builtin

package
v0.42.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 15, 2026 License: Apache-2.0 Imports: 29 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	SkillToolName          = "read_skill"
	SkillUntrustedToolName = "read_skill_untrusted"
	SkillFileToolName      = "read_skill_file"
)

Names of the tools RegisterSkillTools may register. Exported so adopters running a tools.Selector can pin them without importing internals — see SkillToolNames.

Variables

View Source
var ErrEmptyTitle = errors.New("builtin: GenerateTitle: model returned empty title")

ErrEmptyTitle is returned when the provider produced no usable text. Callers typically fall back to a placeholder like "New conversation".

Functions

func EnsureLimit

func EnsureLimit(sql string, max int) string

EnsureLimit returns sql with a trailing LIMIT N clause when:

  • max > 0
  • the first keyword is SELECT or WITH
  • the statement does not already contain a top-level LIMIT

It is a best-effort lexical transform — it will not touch subquery LIMITs and will not rewrite an already-limited outer query. Comments are stripped for the LIMIT check but preserved in the returned SQL.

func GenerateTitle

func GenerateTitle(ctx context.Context, provider agent.LLMProvider, opts TitleOptions) (string, error)

GenerateTitle asks provider for a one-shot title summarizing opts.Messages. It runs a single GenerateStream round, drains content events, and post- processes the result (strip wrapping quotes, trim trailing punctuation, bound by rune count). Returns an error only when the provider fails or times out; an empty model response yields ErrEmptyTitle.

Pairs with EventTypeSessionCreated: fire the title in your event handler / SSE relay when the session is fresh, store it next to the session metadata, render it in a sidebar.

func HasBareStarProjection

func HasBareStarProjection(sql string) bool

HasBareStarProjection reports whether the outermost SELECT's projection list contains a bare "*" or "<alias>.*" wildcard. Subquery SELECTs at paren depth > 0 are not inspected — only the outer query is enforced, which is where SELECT * causes the practical harm (unbounded row width, hallucinated column references on the model's next turn). Statements whose leading verb is not SELECT or WITH return false unconditionally (EXPLAIN / SHOW / DESCRIBE return plan / metadata rows, not user data).

func RegisterExitPlanMode

func RegisterExitPlanMode(reg tools.Registerer)

RegisterExitPlanMode registers the plan-mode-exit sentinel tool. The AgentLoop intercepts calls to this tool by name while PlanMode is active and routes the plan through ConfirmPlan; the Execute body below is only reached when the loop is NOT in plan mode (e.g. the model called it unnecessarily) and returns a harmless acknowledgement so the run can continue.

Registration pattern uses tools.RegisterFunc for the typed-args path; the tool itself carries no state.

func RegisterFileRead

func RegisterFileRead(reg tools.Registerer, cfg FileReadConfig)

RegisterFileRead registers a read-only file tool sandboxed to cfg.Root. Every read is constrained to that directory — requests whose cleaned absolute path does not live under Root are rejected before the OS is even touched.

Cacheable=true opts identical (path, offset, length) tuples into the agent-loop tool-result cache for the process lifetime; files can change on disk between turns, but the cache is in-memory and short-lived so staleness is bounded.

To pair this with a companion writer, gate that tool behind RequiresConfirmation=true rather than extending this registration.

func RegisterReadURL

func RegisterReadURL(reg tools.Registerer)

RegisterReadURL registers a webpage-scraping tool that fetches HTML and strips it to raw text for the LLM to summarize. SSRF protection is always enabled: private, loopback, and link-local addresses (including 169.254.169.254 cloud metadata endpoints) are blocked at the transport layer.

The http.Client is constructed once at registration time and shared across every call — typical Go HTTP-client lifecycle.

func RegisterShowMedia

func RegisterShowMedia(reg tools.Registerer)

RegisterShowMedia registers the show_media tool. Inline=true marks the tool's output for direct frontend rendering in addition to being fed back to the LLM as a tool result.

func RegisterSkillTools added in v0.36.0

func RegisterSkillTools(reg tools.Registerer, set *skills.Set)

RegisterSkillTools registers the activation tools for set — tiers two and three of progressive disclosure, where the catalog in the system prompt is tier one.

Nothing is registered for a nil or empty set: an agent with no skills should not carry a tool that can only fail, nor pay for its schema.

Which tools appear depends on what the set actually holds:

  • read_skill, whenever a trusted skill exists.
  • read_skill_untrusted, only when an untrusted skill exists. It carries RequiresConfirmation, so the agent loop's HITL gate fires before instructions from an unvouched source reach the model.
  • read_skill_file, only when some skill bundles resource files.

The trust split is two tools rather than one, because RequiresConfirmation is a static field on ToolDescriptor: a single tool serving both would prompt on every activation, including self-authored skills, and confirmation fatigue is how a HITL gate gets switched off. PermissionChecker cannot close the gap either — it can restrict a tool but not escalate one into the gate. The two enums are disjoint, so the model cannot reach an untrusted skill through the ungated tool.

func RegisterTaskTools

func RegisterTaskTools(registry *tools.Registry, store TaskStore)

RegisterTaskTools wires all three task tools into the given registry sharing a single store, so one call enables the entire feature.

store := builtin.NewInMemoryTaskStore()
builtin.RegisterTaskTools(registry, store)

func RegisterWebSearch

func RegisterWebSearch(reg tools.Registerer, apiKey string) error

RegisterWebSearch registers a Tavily-backed web search tool. apiKey is required; pass "" to fall back to the TAVILY_API_KEY environment variable. Returns an error when no key is resolvable so adopters catch misconfiguration at startup instead of on the first call.

The http.Client is built once per registration and shared across every call — typical Go HTTP-client lifecycle.

func SkillToolNames added in v0.36.0

func SkillToolNames() []string

SkillToolNames returns every tool name RegisterSkillTools may register.

Splat it into tools.WithPinned when using a tools.Selector:

sel, _ := tools.NewSelector(ctx, reg, embedder, 8,
    tools.WithPinned(builtin.SkillToolNames()...))

This is not optional hygiene. A Selector replaces the registry per call with its top-K matches, and these tools rank poorly by construction: the Selector embeds a tool's own name and description, but the domain signal lives in the skill descriptions, not in the generic wording of "load a skill". Unpinned, activation disappears on exactly the turns that need it, and the model is left reading a catalog it cannot act on.

func SplitStatements

func SplitStatements(s string) []string

SplitStatements splits s on top-level semicolons. Semicolons inside quoted strings/identifiers are ignored. A trailing semicolon does not produce a final empty statement.

func StripSQLComments

func StripSQLComments(s string) string

StripSQLComments removes -- line comments and /* */ block comments from s. Content inside single-quoted strings, double-quoted identifiers, and backtick-quoted identifiers is preserved verbatim. Doubled quotes inside a string literal (SQL's escape) are respected.

func ValidateReadOnly

func ValidateReadOnly(sql string) error

ValidateReadOnly checks that sql is exactly one read-only statement. Equivalent to `kind, err := ClassifySQL(sql); kind == SQLKindRead`. Returns nil when the input is a single read-only statement; rejects multi-statement input and any non-read verb (including the mutation verbs covered by ClassifySQL — call ClassifySQL directly to permit mutations).

Types

type AssetStorage

type AssetStorage interface {
	Save(ctx context.Context, filename string, data []byte, contentType string) (publicURL string, err error)
}

AssetStorage abstracts how generated media (images, videos) is persisted and made addressable. Implementations turn raw bytes into a public URL the LLM can reference inline. Adopters running on container platforms with ephemeral disk (Cloud Run, Lambda, ECS Fargate) plug in a cloud storage adapter (GCS, S3, Azure Blob) so generated files survive between requests.

Filename is the basename the caller would have used on local disk (e.g. "img-1717531234567890000.png"). Implementations may use it verbatim, namespace it under a tenant prefix, or rewrite it entirely — the returned publicURL is the only contract that matters.

ContentType is the MIME type derived from the source response or the extension; backends that need it for proper Content-Type headers (S3, GCS) should honor it. Pass-through stores (e.g. local disk) may ignore it.

type CallSQLAgentTool

type CallSQLAgentTool struct {
	// contains filtered or unexported fields
}

CallSQLAgentTool converts natural-language questions to SQL by delegating to an isolated sub-agent. The sub-agent sees only the execute_sql tool and a schema-grounded system prompt; the database handle is never exposed to the parent agent.

Hardening applied to every executed statement:

  • multi-statement input is rejected
  • comments are stripped before classification (so "/* SELECT */ DROP" cannot masquerade as read-only)
  • only SELECT / WITH / EXPLAIN / SHOW / DESCRIBE are allowed
  • an implicit LIMIT is appended when MaxRows > 0 and the query lacks one
  • each query runs under an independent QueryTimeout context

Builder methods (OnSQL, WithSchema, WithExamples, WithBusinessRules, WithMaxRows, WithQueryTimeout) are chainable and safe to call in any order; they mutate the receiver and return it.

func NewCallSQLAgentTool

func NewCallSQLAgentTool(db *sql.DB, schemaContext string, sm agent.SessionManager, provider agent.LLMProvider) *CallSQLAgentTool

NewCallSQLAgentTool initializes a tool capable of querying databases. The schemaContext string is used verbatim when no structured Schema is registered via WithSchema — pass an empty string and call WithSchema to use the structured path exclusively.

Defaults: Name() = "call_sql_agent", RequiresConfirmation() = true. Use WithName / WithDisplay / WithRequiresConfirmation to override when registering multiple instances or running unsupervised.

func (*CallSQLAgentTool) Descriptor

func (t *CallSQLAgentTool) Descriptor() tools.ToolDescriptor

Descriptor implements tools.Tool. Reads name / display / requiresConfirmation from the mutable builder fields so the Tool surface reflects the latest configuration without snapshotting.

func (*CallSQLAgentTool) Execute

func (t *CallSQLAgentTool) Execute(ctx context.Context, argsJSON string) (tools.Result, error)

Execute runs the sub-agent loop. The sub-agent sees the schema, examples, and business rules but never the database handle directly — it must call execute_sql to actually touch the DB.

When WithSelfConsistency(n) with n > 1 is configured, n independent sub- agents run in parallel and their execution results are clustered by hash; the answer from the winning cluster is returned.

func (*CallSQLAgentTool) OnSQL

OnSQL registers a callback invoked every time the sub-agent executes a SQL query. Use it for logging, auditing, or streaming SQL to the parent application. Called on both success and failure — ev.Error is non-empty on failure.

func (*CallSQLAgentTool) WithAllowDDL

func (t *CallSQLAgentTool) WithAllowDDL(allow bool) *CallSQLAgentTool

WithAllowDDL toggles whether the sub-agent may emit DDL — CREATE, DROP, ALTER, TRUNCATE, GRANT, REVOKE, COMMENT. Default is false, preserving the schema-immutable contract.

Independent of WithAllowMutations — DDL changes schemas and permissions (irreversible, often unrecoverable without backups), DML changes rows. Adopters opt in to each separately so the trust contract isn't silently widened when only DML was requested.

**Always pair with the HITL gate.** DDL is irreversible in practice: keep RequiresConfirmation at the true default and wire AgentLoop.ConfirmHITL so every CREATE / DROP / ALTER lands in front of a human before it executes. Combine with WithExecuteSQLConfirmation(true) so the exact statement (not just the natural-language intent) is what the operator approves. Auto-approve must be off for DDL-enabled agents.

func (*CallSQLAgentTool) WithAllowMutations

func (t *CallSQLAgentTool) WithAllowMutations(allow bool) *CallSQLAgentTool

WithAllowMutations toggles whether the sub-agent may emit DML — INSERT, UPDATE, DELETE, MERGE — in addition to the read-only verbs. Default is false, preserving the original read-only contract.

DDL (DROP, CREATE, ALTER, TRUNCATE, GRANT, REVOKE, COMMENT) is gated by the separate WithAllowDDL flag — different blast radius, different trust boundary. The existing hardening (multi-statement reject, comment strip, per-query timeout, structured SQLResult envelope) stays in force for the mutation path; mutations execute via ExecContext and surface the affected-row count in SQLResult.RowCount.

**Pair with the HITL gate.** Mutations have side effects you usually want the human in the loop for: leave RequiresConfirmation at the true default and wire AgentLoop.ConfirmHITL so every UPDATE / DELETE is surfaced for explicit user approval. Auto-approve should be off for mutation-enabled agents.

func (*CallSQLAgentTool) WithAllowSelectStar

func (t *CallSQLAgentTool) WithAllowSelectStar(allow bool) *CallSQLAgentTool

WithAllowSelectStar toggles the server-side bare-"*" projection guard. Default is false: the executor rejects statements whose outermost SELECT projects "*" or "<alias>.*", forcing the model to list columns explicitly. Subquery projections (depth > 0) and COUNT(*) are unaffected. Pass true to disable the guard for ad-hoc workbench use.

func (*CallSQLAgentTool) WithBusinessRules

func (t *CallSQLAgentTool) WithBusinessRules(rules ...string) *CallSQLAgentTool

WithBusinessRules registers free-form domain rules (glossary, naming conventions, metric definitions) that are injected into the system prompt. Use short, imperative sentences — "revenue" means NET revenue, exclude refunds; "active" users have login_at in the last 30 days.

func (*CallSQLAgentTool) WithCellRedactor

func (t *CallSQLAgentTool) WithCellRedactor(fn CellRedactor) *CallSQLAgentTool

WithCellRedactor installs a per-cell transform applied to result values before they are serialized into the model's context — a privacy guard for sending SQL results to a third-party LLM. The redactor runs on a deep copy of the (already row-capped) preview only: the OnSQL / SQLQueryEvent hook, the tools.Result.Structured payload, and the host's grid all keep the real values, so the user still sees unmasked data locally while the model sees masked values. Pairs naturally with WithLLMPreviewRows, which bounds how many rows are copied and masked. nil (default) disables redaction with no copying.

func (*CallSQLAgentTool) WithDisplay

WithDisplay overrides the tool display metadata (label, category) shown by integrators in UI surfaces. Pass the zero value to fall back to the auto-derived default.

func (*CallSQLAgentTool) WithExamples

func (t *CallSQLAgentTool) WithExamples(examples ...SQLExample) *CallSQLAgentTool

WithExamples registers few-shot Question→SQL demonstrations that are injected into the sub-agent's system prompt. Even 2–3 examples anchored to the schema materially reduce hallucination on domain-specific queries.

func (*CallSQLAgentTool) WithExecuteSQLConfirmation

func (t *CallSQLAgentTool) WithExecuteSQLConfirmation(b bool) *CallSQLAgentTool

WithExecuteSQLConfirmation toggles HITL on the inner execute_sql tool — the leaf that actually hits the database — rather than (only) on the outer call_sql_agent boundary. When true, every SQL statement the sub-agent generates is surfaced through the parent loop's ConfirmHITL with the rendered SQL (the `sql_query` field of executeSQLArgs) as the argsJSON the host UI shows for approval. Default is false, preserving the original "approve the natural-language request" gate.

**Workbench UX pattern (Phin):** `WithExecuteSQLConfirmation(true). WithRequiresConfirmation(false)` — skip the outer "may I call the sub-agent?" prompt and instead approve the actual SQL the model produced. Pair with WithAllowMutations(true) when the user must see UPDATE/DELETE statements before they run.

**Chatbot pattern (default):** `WithRequiresConfirmation(true). WithExecuteSQLConfirmation(false)` — adopters care about intent, not statements; one approval per request.

**Both true:** double-confirmation. Intent gated, then every SQL re-confirmed.

The parent's ConfirmHITL is propagated to the sub-agent automatically via the tool ctx (no extra wiring required). A nil parent ConfirmHITL will fall back to the EventTypeActionRequired path inside the sub-agent same as on the parent loop.

func (*CallSQLAgentTool) WithLLMPreviewRows

func (t *CallSQLAgentTool) WithLLMPreviewRows(n int) *CallSQLAgentTool

WithLLMPreviewRows caps the number of result rows formatted into the text the sub-agent LLM reads, independent of WithMaxRows. The query still runs and returns up to WithMaxRows rows: the full set is emitted on the OnSQL / SQLQueryEvent hook (so a host grid stays rich) and attached on tools.Result.Structured, while only the first n rows are serialized into the model's context — with the true RowCount preserved and Truncated set so the model knows it saw a sample and should aggregate or ask the host to export rather than assume it read everything.

Use it to keep a large grid (e.g. WithMaxRows(1000)) without paying LLM tokens for 1000 wide rows on every "run it and tell me about it" turn. n <= 0 disables the cap (default): the model sees the full WithMaxRows set, preserving pre-feature behaviour.

func (*CallSQLAgentTool) WithMaxRows

func (t *CallSQLAgentTool) WithMaxRows(n int) *CallSQLAgentTool

WithMaxRows appends "LIMIT n" to any SELECT or WITH statement that does not already contain a LIMIT clause. n <= 0 disables the behaviour (default). Set this to keep accidental "SELECT * FROM large_table" calls from returning millions of rows.

func (*CallSQLAgentTool) WithName

func (t *CallSQLAgentTool) WithName(name string) *CallSQLAgentTool

WithName overrides the tool name reported to the LLM. Use this to register multiple SQL-agent instances (e.g. one per tenant or datalake) in the same registry without wrapping in a shim type. Empty string restores the default "call_sql_agent".

func (*CallSQLAgentTool) WithProviderHint

func (t *CallSQLAgentTool) WithProviderHint(hint string) *CallSQLAgentTool

WithProviderHint appends a free-form addendum to the sub-agent system prompt, immediately after the safety contract and before the schema block. Use this to layer provider-specific guidance on top of the universal contract — Gemini benefits from extra "do NOT" sentences, while Claude/GPT-4 typically need no addendum. Pass an empty string to clear a previously-set hint.

Example (Phin / Gemini 2.5 Pro):

tool.WithProviderHint("Do NOT propose a follow-up DELETE/UPDATE based on rows you just read. The user must literally request the destructive operation in their most recent message.")

func (*CallSQLAgentTool) WithQueryTimeout

func (t *CallSQLAgentTool) WithQueryTimeout(d time.Duration) *CallSQLAgentTool

WithQueryTimeout caps the wall-clock time of each underlying QueryContext call. d <= 0 disables the timeout (default). Separate from the agent's overall request context, which may be much longer.

func (*CallSQLAgentTool) WithRequiresConfirmation

func (t *CallSQLAgentTool) WithRequiresConfirmation(b bool) *CallSQLAgentTool

WithRequiresConfirmation overrides the HITL gate. The default is true so that every SQL invocation flows through the confirmation hook in human-supervised setups. Set to false for autonomous agents where the caller has already vetted the SQL surface (typically read-only DBs paired with WithMaxRows / WithQueryTimeout).

func (*CallSQLAgentTool) WithSchema

func (t *CallSQLAgentTool) WithSchema(s Schema) *CallSQLAgentTool

WithSchema registers a structured schema. When set, its markdown rendering replaces the raw schemaContext passed to NewCallSQLAgentTool in the system prompt. Structured schemas produce tighter, more consistent grounding and are required for downstream features like schema linking.

func (*CallSQLAgentTool) WithSelfConsistency

func (t *CallSQLAgentTool) WithSelfConsistency(n int) *CallSQLAgentTool

WithSelfConsistency enables self-consistency decoding: the tool spawns n independent sub-agent runs in parallel, clusters their final SQL results by execution output, and returns the natural-language answer from the winning (largest) cluster.

Costs scale linearly with n — each run is a full sub-agent invocation — so this is opt-in and intended for high-stakes analytical queries. n <= 1 disables the behaviour (default); odd values (3, 5) break ties naturally.

All candidates share the same schema, examples, and business rules — variation comes from the LLM's own sampling temperature. For stronger diversity, point each run at a slightly-different provider (cheap base + reasoning-tuned) via llm.RouterProvider.

type CallSubAgentTool

type CallSubAgentTool struct {
	Sessions agent.SessionManager
	Tools    *tools.Registry
	LLM      agent.LLMProvider
}

CallSubAgentTool delegates a task to an isolated worker sub-agent with its own session state, preventing context-window pollution in the main agent.

func NewCallSubAgentTool

func NewCallSubAgentTool(sessions agent.SessionManager, registry *tools.Registry, llm agent.LLMProvider) *CallSubAgentTool

NewCallSubAgentTool constructs a CallSubAgentTool wired to the given dependencies.

func (*CallSubAgentTool) Descriptor

func (t *CallSubAgentTool) Descriptor() tools.ToolDescriptor

func (*CallSubAgentTool) Execute

func (t *CallSubAgentTool) Execute(ctx context.Context, inputJSON string) (tools.Result, error)

Execute runs the sub-agent in an isolated session and returns its final report. The worker session is always deleted before returning, regardless of outcome, so no orphan history remains in the backing SessionManager.

When the invoking agent loop has installed a sub-agent emitter on ctx (it does so for every tool invocation), the worker is run in streaming mode and its events — thoughts, tool calls, tool progress, content chunks, errors — are forwarded to the parent stream tagged with Source="subagent:<name>" and ParentID=<parent session key>. This makes the parent no longer look frozen while the sub-agent works, and gives UIs enough metadata to render a nested activity timeline. When no emitter is present (e.g. tests calling Execute directly), Execute falls back to the original non-streaming path.

type CancelAsyncTaskTool

type CancelAsyncTaskTool struct {
	// contains filtered or unexported fields
}

CancelAsyncTaskTool signals a running async task to stop via its CancelFunc. Construct via NewCancelAsyncTaskTool.

func NewCancelAsyncTaskTool

func NewCancelAsyncTaskTool(mgr *agent.AsyncTaskManager) *CancelAsyncTaskTool

NewCancelAsyncTaskTool returns a CancelAsyncTaskTool bound to mgr. Panics if mgr is nil.

func (*CancelAsyncTaskTool) Descriptor

func (t *CancelAsyncTaskTool) Descriptor() tools.ToolDescriptor

func (*CancelAsyncTaskTool) Execute

func (t *CancelAsyncTaskTool) Execute(ctx context.Context, inputJSON string) (tools.Result, error)

type CellRedactor

type CellRedactor func(column string, value any) any

CellRedactor transforms a single result-cell value before it is serialized into the text the sub-agent LLM reads — a privacy guard for sending SQL results to a third-party provider (e.g. mask an email to "j***@***.com"). It receives the column name and the raw cell value and returns the value to expose to the model. It runs ONLY on the model-facing preview: the host-facing rows (OnSQL / SQLQueryEvent and tools.Result.Structured) and the local grid keep full-fidelity values. Return the value unchanged to leave a cell as-is. Returning a mutable value (slice/map) aliases it into the model-facing copy — return a fresh value if the host mutates it later.

type CheckAsyncTaskTool

type CheckAsyncTaskTool struct {
	// contains filtered or unexported fields
}

CheckAsyncTaskTool reports the status or final result of an async task. Construct via NewCheckAsyncTaskTool.

func NewCheckAsyncTaskTool

func NewCheckAsyncTaskTool(mgr *agent.AsyncTaskManager) *CheckAsyncTaskTool

NewCheckAsyncTaskTool returns a CheckAsyncTaskTool bound to mgr. Panics if mgr is nil.

func (*CheckAsyncTaskTool) Descriptor

func (t *CheckAsyncTaskTool) Descriptor() tools.ToolDescriptor

func (*CheckAsyncTaskTool) Execute

func (t *CheckAsyncTaskTool) Execute(ctx context.Context, inputJSON string) (tools.Result, error)

type CodeInterpreterTool

type CodeInterpreterTool struct {
	// contains filtered or unexported fields
}

CodeInterpreterTool runs a short snippet of code in a supported language via a subprocess. It is intended for quick calculations, data shaping, and ad-hoc scripts — NOT for long-running programs or anything that needs network / disk access beyond what the local binary already exposes.

Security posture:

  • Only whitelisted languages (python / python3 / node) are accepted.
  • The operator picks the concrete binary via WithInterpreter — callers cannot inject an arbitrary path.
  • Every run is bounded by a context timeout (default 30s).
  • Output size is capped (default 64 KiB per stream) to prevent a runaway process from blowing up the LLM context.
  • RequiresConfirmation() == true — the HITL layer decides whether to actually execute. Turn it off only in trusted, sandboxed environments.

func NewCodeInterpreterTool

func NewCodeInterpreterTool() *CodeInterpreterTool

NewCodeInterpreterTool returns a tool configured with the default set of language bindings resolved via PATH (python3, node), a 30-second timeout, and a 64 KiB output cap per stream. Tune further with WithInterpreter / WithTimeout / WithMaxBytes / WithWorkingDir.

func (*CodeInterpreterTool) Descriptor

func (t *CodeInterpreterTool) Descriptor() tools.ToolDescriptor

Descriptor returns metadata for code_interpreter. RequiresConfirmation is true because arbitrary code execution is always side-effecting and should never run without a human / policy gate.

func (*CodeInterpreterTool) Execute

func (t *CodeInterpreterTool) Execute(ctx context.Context, argsJSON string) (tools.Result, error)

func (*CodeInterpreterTool) WithInterpreter

func (t *CodeInterpreterTool) WithInterpreter(language, binary string) *CodeInterpreterTool

WithInterpreter maps (or overrides) a language name to an explicit interpreter binary. Pass an absolute path in hardened environments so the resolution is not PATH-dependent.

func (*CodeInterpreterTool) WithMaxBytes

func (t *CodeInterpreterTool) WithMaxBytes(n int) *CodeInterpreterTool

WithMaxBytes caps stdout / stderr per stream. Output past the cap is truncated and a flag is returned to the caller.

func (*CodeInterpreterTool) WithTimeout

WithTimeout sets the max wall-clock duration for a single run.

func (*CodeInterpreterTool) WithWorkingDir

func (t *CodeInterpreterTool) WithWorkingDir(dir string) *CodeInterpreterTool

WithWorkingDir sets the CWD for the subprocess. Defaults to the parent process's CWD. Point this at a scratch directory when running untrusted code.

type ColumnSchema

type ColumnSchema struct {
	Name        string
	Type        string
	Description string
	Nullable    bool
	Examples    []string
}

ColumnSchema describes a single column. Examples should be a short list (3–5) of representative values drawn from the actual table — "value grounding" helps the model match fuzzy natural-language terms to real data (e.g. "active customers" → status='ACTIVE' vs 'active').

type CreateTaskTool

type CreateTaskTool struct{ Store TaskStore }

CreateTaskTool lets the LLM register a new pending task in the session task list as it plans multi-step work.

func NewCreateTaskTool

func NewCreateTaskTool(store TaskStore) *CreateTaskTool

func (*CreateTaskTool) Descriptor

func (t *CreateTaskTool) Descriptor() tools.ToolDescriptor

func (*CreateTaskTool) Execute

func (t *CreateTaskTool) Execute(ctx context.Context, argsJSON string) (tools.Result, error)

type FileReadConfig

type FileReadConfig struct {
	// Root is the absolute directory paths must be contained within.
	// Relative paths in requests are resolved against Root.
	Root string
	// MaxBytes caps how many bytes a single Execute reads. 0 applies
	// the default of 1 MiB.
	MaxBytes int64
}

FileReadConfig tunes the read-only file_read tool registered via RegisterFileRead. Root is required; zero MaxBytes resolves to the 1 MiB default.

type ForeignKey

type ForeignKey struct {
	Column    string
	RefTable  string
	RefColumn string
}

ForeignKey describes a relationship between two tables. The agent uses these to pick JOIN paths without guessing.

type GenerateImageTool

type GenerateImageTool struct {
	// contains filtered or unexported fields
}

func NewGenerateImageTool

func NewGenerateImageTool(apiKey, model string, storage AssetStorage) (*GenerateImageTool, error)

NewGenerateImageTool builds an image generation tool. apiKey defaults to OPENAI_API_KEY; model defaults to dall-e-3. storage is required — pass builtin.NewLocalDiskStorage(saveDir, urlBase) for local-disk persistence, or any AssetStorage implementation for cloud.

func (*GenerateImageTool) Descriptor

func (t *GenerateImageTool) Descriptor() tools.ToolDescriptor

func (*GenerateImageTool) Execute

func (t *GenerateImageTool) Execute(ctx context.Context, argsJSON string) (tools.Result, error)

Execute generates the image, downloads it, saves it to SaveDir, and returns a markdown image tag pointing at URLBase/<filename>.

type GenerateVideoTool

type GenerateVideoTool struct {
	// contains filtered or unexported fields
}

func NewGenerateVideoTool

func NewGenerateVideoTool(apiKey, model string, storage AssetStorage) (*GenerateVideoTool, error)

NewGenerateVideoTool builds a video generation tool. apiKey defaults to GEMINI_API_KEY; model defaults to veo-2.0-generate-001. storage is required — pass builtin.NewLocalDiskStorage(saveDir, urlBase) for local-disk persistence, or any AssetStorage implementation for cloud.

func (*GenerateVideoTool) Descriptor

func (t *GenerateVideoTool) Descriptor() tools.ToolDescriptor

func (*GenerateVideoTool) Execute

func (t *GenerateVideoTool) Execute(ctx context.Context, argsJSON string) (tools.Result, error)

Execute starts a Veo 2 generation job, polls until complete, saves the video, and returns an HTML <video> embed pointing at URLBase/<filename>.

type HTTPRequestTool

type HTTPRequestTool struct {
	// contains filtered or unexported fields
}

HTTPRequestTool performs arbitrary HTTP calls on behalf of the agent. Unlike ReadURLTool, it returns the raw response body (not HTML→text), making it suitable for JSON APIs and webhook calls.

Guardrails layered on every request:

  • SSRF protection (always on): connections to private, loopback, and link-local addresses (incl. 169.254.169.254 cloud metadata) are blocked after DNS resolution to defeat rebinding attacks.
  • an optional host allowlist further restricts which hostnames may be called; hosts in the allowlist also bypass the SSRF IP check.
  • method whitelist: GET / HEAD / POST / PUT / PATCH / DELETE
  • configurable client timeout, body size cap, max redirects

Non-GET/HEAD methods trigger RequiresConfirmation() so the HITL layer can gate mutating calls.

func NewHTTPRequestTool

func NewHTTPRequestTool() *HTTPRequestTool

NewHTTPRequestTool returns a tool configured with sensible defaults: 15s request timeout, 1 MiB response cap, SSRF protection enabled, no host allowlist.

func (*HTTPRequestTool) Descriptor

func (t *HTTPRequestTool) Descriptor() tools.ToolDescriptor

Descriptor returns metadata for http_request. RequiresConfirmation is true because HTTP calls can have side effects (POST/DELETE/etc.) and can exfiltrate data; HITL operators decide. GET-only usage can override by wrapping the tool in middleware.

func (*HTTPRequestTool) Execute

func (t *HTTPRequestTool) Execute(ctx context.Context, argsJSON string) (tools.Result, error)

func (*HTTPRequestTool) WithAllowedHosts

func (t *HTTPRequestTool) WithAllowedHosts(hosts ...string) *HTTPRequestTool

WithAllowedHosts restricts the tool to only call the given hostnames (exact match, case-insensitive). Hosts in the list also bypass the SSRF IP-range check, so you can safely allowlist internal endpoints that would otherwise be blocked (e.g. "127.0.0.1" in tests, or a known internal API). Leaving this unset allows any public host while still blocking private IPs.

func (*HTTPRequestTool) WithMaxBytes

func (t *HTTPRequestTool) WithMaxBytes(n int64) *HTTPRequestTool

WithMaxBytes caps response body size (truncated past the limit). n <= 0 resets to the 1 MiB default.

func (*HTTPRequestTool) WithTimeout

func (t *HTTPRequestTool) WithTimeout(d time.Duration) *HTTPRequestTool

WithTimeout overrides the HTTP client timeout.

type InMemoryStore

type InMemoryStore struct {
	// contains filtered or unexported fields
}

InMemoryStore is a process-local MemoryStore. Lost on restart — fine for short-lived sessions or when the agent is embedded in a longer-running process whose lifetime bounds the memory's usefulness.

func NewInMemoryStore

func NewInMemoryStore() *InMemoryStore

NewInMemoryStore returns a ready-to-use in-memory MemoryStore.

func (*InMemoryStore) Delete

func (s *InMemoryStore) Delete(_ context.Context, sessionKey, key string) error

Delete removes (sessionKey, key). No-op when the key is absent.

func (*InMemoryStore) Get

func (s *InMemoryStore) Get(_ context.Context, sessionKey, key string) (string, bool, error)

Get returns the value for (sessionKey, key) and whether it was present.

func (*InMemoryStore) List

func (s *InMemoryStore) List(_ context.Context, sessionKey string) ([]string, error)

List returns the sorted keys under sessionKey. Empty when the session has no entries.

func (*InMemoryStore) Set

func (s *InMemoryStore) Set(_ context.Context, sessionKey, key, value string) error

Set stores value under (sessionKey, key), replacing any previous value.

type InMemoryTaskStore

type InMemoryTaskStore struct {
	// contains filtered or unexported fields
}

InMemoryTaskStore is a process-local TaskStore. Tasks live as long as the process does; they do not survive restart. Sufficient for planning within a single run of an agent.

func NewInMemoryTaskStore

func NewInMemoryTaskStore() *InMemoryTaskStore

NewInMemoryTaskStore returns a ready-to-use in-memory task store.

func (*InMemoryTaskStore) Create

func (s *InMemoryTaskStore) Create(_ context.Context, sessionKey, title, notes string) (Task, error)

Create adds a new pending task to sessionKey and returns it with a freshly assigned ID ("t1", "t2", ...).

func (*InMemoryTaskStore) List

func (s *InMemoryTaskStore) List(_ context.Context, sessionKey string) ([]Task, error)

List returns a snapshot of tasks for sessionKey in creation order.

func (*InMemoryTaskStore) Update

func (s *InMemoryTaskStore) Update(_ context.Context, sessionKey, id string, status TaskStatus, notes string) (Task, error)

Update mutates the task's status (and optionally notes) and returns the updated record. Passing an empty notes string leaves the existing notes untouched; pass "-" to explicitly clear them.

type ListAsyncTasksTool

type ListAsyncTasksTool struct {
	// contains filtered or unexported fields
}

ListAsyncTasksTool enumerates every async task tracked in the current session. Construct via NewListAsyncTasksTool.

func NewListAsyncTasksTool

func NewListAsyncTasksTool(mgr *agent.AsyncTaskManager) *ListAsyncTasksTool

NewListAsyncTasksTool returns a ListAsyncTasksTool bound to mgr. Panics if mgr is nil.

func (*ListAsyncTasksTool) Descriptor

func (t *ListAsyncTasksTool) Descriptor() tools.ToolDescriptor

func (*ListAsyncTasksTool) Execute

func (t *ListAsyncTasksTool) Execute(ctx context.Context, inputJSON string) (tools.Result, error)

type ListTasksTool

type ListTasksTool struct{ Store TaskStore }

ListTasksTool returns all tasks in the current session. The LLM is expected to consult this every few turns on long multi-step work to re-orient on what's done and what remains.

func NewListTasksTool

func NewListTasksTool(store TaskStore) *ListTasksTool

func (*ListTasksTool) Descriptor

func (t *ListTasksTool) Descriptor() tools.ToolDescriptor

func (*ListTasksTool) Execute

func (t *ListTasksTool) Execute(ctx context.Context, _ string) (tools.Result, error)

type LocalDiskStorage

type LocalDiskStorage struct {
	// contains filtered or unexported fields
}

LocalDiskStorage is the default AssetStorage implementation: writes bytes under saveDir, returns urlBase/<filename>. Suitable for long-lived VMs with persistent disk and an HTTP server fronting saveDir; broken on container platforms with ephemeral disk — use the GCS / S3 / Azure Blob adapter shipped in your integration there.

Construct via NewLocalDiskStorage; the unexported fields prevent the "did my post-construction assignment take effect?" tax that public mutable fields invite.

func NewLocalDiskStorage

func NewLocalDiskStorage(saveDir, urlBase string) (*LocalDiskStorage, error)

NewLocalDiskStorage constructs a LocalDiskStorage that writes files under saveDir and serves them under urlBase. Both arguments are required; passing "" returns an error so misconfiguration surfaces at startup rather than on the first generation. urlBase trailing slashes are tolerated.

func (*LocalDiskStorage) Save

func (s *LocalDiskStorage) Save(_ context.Context, filename string, data []byte, _ string) (string, error)

Save implements AssetStorage by writing data to <saveDir>/<filename> and returning <urlBase>/<filename>.

type MediaAnalyzeTool

type MediaAnalyzeTool struct {
	// contains filtered or unexported fields
}

MediaAnalyzeTool passes a media item (image or video) + instruction to a multimodal model and returns its description. Use it for OCR, chart reading, screenshot understanding, video summarisation, and any other visual or temporal analysis task.

func NewMediaAnalyzeTool

func NewMediaAnalyzeTool(analyzer MediaAnalyzer) *MediaAnalyzeTool

NewMediaAnalyzeTool wires up an analyzer. analyzer must not be nil.

func (*MediaAnalyzeTool) Descriptor

func (t *MediaAnalyzeTool) Descriptor() tools.ToolDescriptor

func (*MediaAnalyzeTool) Execute

func (t *MediaAnalyzeTool) Execute(ctx context.Context, argsJSON string) (tools.Result, error)

type MediaAnalyzer

type MediaAnalyzer interface {
	Analyze(ctx context.Context, media, prompt string) (string, error)
}

MediaAnalyzer is the provider-side dependency injected into MediaAnalyzeTool. Implementations call the underlying multimodal model (Gemini vision/video, OpenAI GPT-4o, Claude vision, etc.) and return a natural-language description.

This interface lives in the tools package (not the llm package) to keep MediaAnalyzeTool decoupled from any specific provider — users wire in a thin adapter over whatever SDK they already use.

media is one of:

  • an absolute http(s) URL pointing to an image or video
  • a Google Cloud Storage URI ("gs://bucket/object") for Gemini video
  • a data URI ("data:image/png;base64,...") for inline images
  • raw base64 (the adapter decides how to interpret it)

Not all providers support video. Gemini 1.5/2.0 accepts video URLs and gs:// URIs natively; OpenAI GPT-4o and Claude 3.x support images only. The adapter is responsible for surfacing a clear error when the media type is unsupported by the underlying model.

prompt is the analysis instruction ("describe the chart", "extract all visible text", "summarise what happens in this video clip").

type MemoryDeleteTool

type MemoryDeleteTool struct {
	Store MemoryStore
}

MemoryDeleteTool removes a key from the current session's memory.

func NewMemoryDeleteTool

func NewMemoryDeleteTool(store MemoryStore) *MemoryDeleteTool

NewMemoryDeleteTool wires a MemoryDeleteTool to the given store.

func (*MemoryDeleteTool) Descriptor

func (t *MemoryDeleteTool) Descriptor() tools.ToolDescriptor

func (*MemoryDeleteTool) Execute

func (t *MemoryDeleteTool) Execute(ctx context.Context, argsJSON string) (tools.Result, error)

type MemoryGetTool

type MemoryGetTool struct {
	Store MemoryStore
}

MemoryGetTool reads a previously saved value from the current session.

func NewMemoryGetTool

func NewMemoryGetTool(store MemoryStore) *MemoryGetTool

NewMemoryGetTool wires a MemoryGetTool to the given store.

func (*MemoryGetTool) Descriptor

func (t *MemoryGetTool) Descriptor() tools.ToolDescriptor

func (*MemoryGetTool) Execute

func (t *MemoryGetTool) Execute(ctx context.Context, argsJSON string) (tools.Result, error)

type MemoryListTool

type MemoryListTool struct {
	Store MemoryStore
}

MemoryListTool returns all keys stored in the current session's memory.

func NewMemoryListTool

func NewMemoryListTool(store MemoryStore) *MemoryListTool

NewMemoryListTool wires a MemoryListTool to the given store.

func (*MemoryListTool) Descriptor

func (t *MemoryListTool) Descriptor() tools.ToolDescriptor

func (*MemoryListTool) Execute

func (t *MemoryListTool) Execute(ctx context.Context, _ string) (tools.Result, error)

type MemorySetTool

type MemorySetTool struct {
	Store MemoryStore
}

MemorySetTool writes a key/value pair into the current session's memory.

func NewMemorySetTool

func NewMemorySetTool(store MemoryStore) *MemorySetTool

NewMemorySetTool wires a MemorySetTool to the given store.

func (*MemorySetTool) Descriptor

func (t *MemorySetTool) Descriptor() tools.ToolDescriptor

func (*MemorySetTool) Execute

func (t *MemorySetTool) Execute(ctx context.Context, argsJSON string) (tools.Result, error)

type MemoryStore

type MemoryStore interface {
	Set(ctx context.Context, sessionKey, key, value string) error
	Get(ctx context.Context, sessionKey, key string) (string, bool, error)
	Delete(ctx context.Context, sessionKey, key string) error
	List(ctx context.Context, sessionKey string) ([]string, error)
}

MemoryStore is the persistence interface behind the memory_* tools. It is keyed by (sessionKey, key) so each agent session gets an isolated namespace.

Implementations must be safe for concurrent use. The default in-memory implementation (InMemoryStore) uses a RWMutex; swap in a Redis / SQL backend by providing your own type that satisfies this interface.

type SQLExample

type SQLExample struct {
	Question string
	SQL      string
	Notes    string
}

SQLExample is a Question → SQL pair used as a few-shot demonstration. Notes is optional free-form reasoning appended after the SQL for chain-of-thought style few-shot prompting.

type SQLKind

type SQLKind int

SQLKind classifies a parsed single SQL statement by its leading verb. Unknown covers anything that doesn't map to a known verb. ClassifySQL never returns Unknown alongside a nil error; the kind/error pair is always consistent. The executor decides which kinds are permitted via WithAllowMutations / WithAllowDDL — classification itself stays neutral.

const (
	SQLKindUnknown SQLKind = iota
	SQLKindRead
	SQLKindMutation
	// SQLKindDDL covers schema- and permission-changing statements
	// (CREATE / DROP / ALTER / TRUNCATE / GRANT / REVOKE / COMMENT).
	// Default-rejected at the executor; opt-in via WithAllowDDL(true).
	SQLKindDDL
)

func ClassifySQL

func ClassifySQL(sql string) (SQLKind, error)

ClassifySQL parses sql, rejects multi-statement input, and returns the kind of the single statement. Comments are stripped before analysis, so "/* update */ SELECT" still classifies as Read. An empty or multi-statement input, or an unrecognised verb, yields SQLKindUnknown with a wrapped error.

type SQLQueryEvent

type SQLQueryEvent struct {
	SessionKey  string
	Query       string
	Error       string           // empty on success
	Columns     []string         // populated on success; nil on early validation failure
	Rows        []map[string]any // populated on success; nil on early validation failure
	RowCount    int              // rows returned (read) or affected (DML/DDL); mirrors SQLResult.RowCount
	ExecutionMs int64            // wall-clock execution time; zero on early validation failure
	Truncated   bool             // true when the MaxRows safety cap clipped output
}

SQLQueryEvent carries metadata about a SQL query executed by the sub-agent. Error is non-empty when the query failed (DB error, DML rejection, or validation failure before execution).

Columns / Rows / RowCount / ExecutionMs / Truncated are populated on successful execution so adopters can flow result sets out of the sub-agent (e.g. into a side-by-side data grid, or a "INSERT executed · N rows" banner) without re-running the query against their own DB handle. RowCount carries rows returned for reads and rows affected for DML/DDL, mirroring SQLResult.RowCount. On early validation failure these fields are zero-valued; partial rows from a mid-iteration error are still surfaced, mirroring the SQLResult returned to the model.

type SQLResult

type SQLResult struct {
	SQL         string           `json:"sql"`
	Columns     []string         `json:"columns,omitempty"`
	Rows        []map[string]any `json:"rows,omitempty"`
	RowCount    int              `json:"row_count"`
	ExecutionMs int64            `json:"execution_ms"`
	Truncated   bool             `json:"truncated,omitempty"`
	Error       string           `json:"error,omitempty"`
}

SQLResult is the structured envelope returned from execute_sql back to the sub-agent. Keeping the result structured (rather than a bare JSON array) makes the model's retry behaviour much more reliable — it can see the row count, truncation flag, and execution time and decide whether the result is complete or needs refinement.

type Schema

type Schema struct {
	Tables []TableSchema
}

Schema is a structured representation of database metadata consumed by CallSQLAgentTool. Keeping the schema structured (rather than a free-form string) unlocks two wins:

  1. Prompt-side grounding — String() renders a compact, consistent markdown block with column types, descriptions, and example values, which large models use as soft constraints to avoid inventing columns.
  2. Server-side schema linking — Filter(tables...) returns a subset so an orchestrator can pre-select the relevant tables before generating SQL, as recommended by Google's text-to-SQL guidance for large schemas.

Schema is zero-value friendly: an empty Schema renders as an empty string and Filter on it is a no-op.

func IntrospectMySQLSchema

func IntrospectMySQLSchema(ctx context.Context, db *sql.DB, schemaName string, tableNames ...string) (Schema, error)

IntrospectMySQLSchema queries INFORMATION_SCHEMA on a live MySQL/MariaDB connection and returns a Schema populated with column metadata for the named tables. It is the deterministic alternative to a hand-maintained schema doc — schema drift between docs and the live DB is the most common cause of "Unknown column" errors from CallSQLAgentTool.

schemaName scopes the lookup; pass "" to use the connection's current database (resolved via DATABASE()). tableNames must be non-empty.

All identifiers are validated against [A-Za-z_][A-Za-z0-9_]* before being inlined into the query. Invalid identifiers are rejected at the boundary, which lets the helper run on any MySQL driver without dialect-specific placeholder syntax. Tables that do not exist in the database are silently omitted from the result.

Column descriptions are populated from MySQL COLUMN_COMMENT when present. PrimaryKey is populated from KEY_COLUMN_USAGE when the table has one. Foreign keys are not currently introspected; declare them via WithSchema if your model needs join hints.

Typical use:

schema, err := builtin.IntrospectMySQLSchema(ctx, db, "",
    "daily_creatives_impressions_v2", "creatives", "apps")
if err != nil { ... }
sqlTool := builtin.NewCallSQLAgentTool(db, "", sm, provider).WithSchema(schema)

func IntrospectPostgresSchema

func IntrospectPostgresSchema(ctx context.Context, db *sql.DB, schemaName string, tableNames ...string) (Schema, error)

IntrospectPostgresSchema queries information_schema and pg_catalog on a live PostgreSQL connection and returns a Schema populated with column metadata for the named tables. Mirrors IntrospectMySQLSchema for the Postgres dialect.

schemaName scopes the lookup; pass "" to use the connection's current_schema(). tableNames must be non-empty. All identifiers are validated against [A-Za-z_][A-Za-z0-9_]* before being inlined into the query — invalid names are rejected at the boundary.

Column descriptions are populated from pg_catalog.pg_description (the COMMENT ON COLUMN ... mechanism). PrimaryKey is populated by joining information_schema.table_constraints / key_column_usage and filtering constraint_type = 'PRIMARY KEY'. Foreign keys are not introspected; use WithSchema(...) to declare them manually if your model needs join hints.

Typical use:

schema, err := builtin.IntrospectPostgresSchema(ctx, db, "",
    "events", "users", "orgs")
if err != nil { ... }
sqlTool := builtin.NewCallSQLAgentTool(db, "", sm, provider).WithSchema(schema)

func (Schema) Filter

func (s Schema) Filter(tables ...string) Schema

Filter returns a new Schema restricted to the named tables. Unknown names are silently skipped. Matching is case-insensitive. The returned order matches the input `tables` slice, with duplicates preserved once.

func (Schema) String

func (s Schema) String() string

String renders the schema as a markdown-formatted prompt block. Tables with no columns are skipped.

func (Schema) Summary

func (s Schema) Summary() string

Summary returns a one-line-per-table overview ("table_name: desc — c1, c2, ...") suitable for a schema-linking picker prompt where the full schema would be too large to fit.

func (Schema) TableNames

func (s Schema) TableNames() []string

TableNames returns all table names in declaration order.

type StartAsyncTaskTool

type StartAsyncTaskTool struct {
	// contains filtered or unexported fields
}

StartAsyncTaskTool spawns a background worker sub-agent and returns a task_id that can be polled, cancelled, or steered via the other async tools. Construct via NewStartAsyncTaskTool — the manager is required.

func NewStartAsyncTaskTool

func NewStartAsyncTaskTool(mgr *agent.AsyncTaskManager) *StartAsyncTaskTool

NewStartAsyncTaskTool returns a StartAsyncTaskTool bound to mgr. Panics if mgr is nil — every async tool needs a manager and a nil panic at startup is strictly better than a nil-pointer deref on the first Execute.

func (*StartAsyncTaskTool) Descriptor

func (t *StartAsyncTaskTool) Descriptor() tools.ToolDescriptor

func (*StartAsyncTaskTool) Execute

func (t *StartAsyncTaskTool) Execute(ctx context.Context, inputJSON string) (tools.Result, error)

type SubAgentInput

type SubAgentInput struct {
	TaskDescription string `json:"task_description"`
	AgentName       string `json:"agent_name"`
}

SubAgentInput is the JSON-decoded argument schema for CallSubAgentTool.

type TableSchema

type TableSchema struct {
	Name        string
	Description string
	Columns     []ColumnSchema
	PrimaryKey  []string
	ForeignKeys []ForeignKey
}

TableSchema describes a single table. Description, PrimaryKey, and ForeignKeys are optional — when present they dramatically reduce hallucination on join-heavy questions.

type Task

type Task struct {
	ID        string     `json:"id"`
	Title     string     `json:"title"`
	Status    TaskStatus `json:"status"`
	Notes     string     `json:"notes,omitempty"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
}

Task is a single planning entry in the per-session task list. Titles are the model's own freeform description; notes are optional detail the model may attach on create/update (subtask list, constraints, acceptance criteria).

type TaskStatus

type TaskStatus string

TaskStatus enumerates the task lifecycle states. The LLM is expected to move a task from pending → in_progress → completed as it does multi-step work; any backward transition is legal (e.g. reopening a completed task).

const (
	TaskPending    TaskStatus = "pending"
	TaskInProgress TaskStatus = "in_progress"
	TaskCompleted  TaskStatus = "completed"
)

type TaskStore

type TaskStore interface {
	Create(ctx context.Context, sessionKey, title, notes string) (Task, error)
	Update(ctx context.Context, sessionKey, id string, status TaskStatus, notes string) (Task, error)
	List(ctx context.Context, sessionKey string) ([]Task, error)
}

TaskStore persists per-session task lists. All methods must be safe for concurrent use.

type TitleOptions

type TitleOptions struct {
	// Messages is the conversation snippet the LLM should summarize.
	// The first user turn (and optionally first assistant reply) is the
	// canonical input — feeding the entire history is fine but wastes
	// tokens on long sessions.
	Messages []history.Message

	// MaxRunes bounds the returned title length AFTER trimming. 0 falls
	// back to 80 — a sane sidebar width.
	MaxRunes int

	// SystemPrompt overrides the library default ("4-7 word title…").
	// Empty string keeps the default; non-empty replaces it entirely.
	SystemPrompt string

	// Timeout caps the underlying GenerateStream call. 0 falls back to
	// 30s — the LLM should produce one short string fast.
	Timeout time.Duration
}

TitleOptions configures GenerateTitle. Messages is the only required field; everything else has a sensible default tuned for "show this conversation in a sidebar" use cases.

type UpdateAsyncTaskTool

type UpdateAsyncTaskTool struct {
	// contains filtered or unexported fields
}

UpdateAsyncTaskTool delivers a steering instruction to a running worker. Construct via NewUpdateAsyncTaskTool.

func NewUpdateAsyncTaskTool

func NewUpdateAsyncTaskTool(mgr *agent.AsyncTaskManager) *UpdateAsyncTaskTool

NewUpdateAsyncTaskTool returns an UpdateAsyncTaskTool bound to mgr. Panics if mgr is nil.

func (*UpdateAsyncTaskTool) Descriptor

func (t *UpdateAsyncTaskTool) Descriptor() tools.ToolDescriptor

func (*UpdateAsyncTaskTool) Execute

func (t *UpdateAsyncTaskTool) Execute(ctx context.Context, inputJSON string) (tools.Result, error)

type UpdateTaskTool

type UpdateTaskTool struct{ Store TaskStore }

UpdateTaskTool changes the status (and optionally notes) of an existing task. The LLM is expected to flip a task to in_progress when starting it and completed when finished, so the list reflects true state.

func NewUpdateTaskTool

func NewUpdateTaskTool(store TaskStore) *UpdateTaskTool

func (*UpdateTaskTool) Descriptor

func (t *UpdateTaskTool) Descriptor() tools.ToolDescriptor

func (*UpdateTaskTool) Execute

func (t *UpdateTaskTool) Execute(ctx context.Context, argsJSON string) (tools.Result, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL