Documentation
¶
Overview ¶
Package tool defines the fat-tool abstraction the agent exposes to the model: one tool per domain, each taking an (action, params) pair. It also holds the shared helpers — argument validation, parameter coercion, and the typed ToolError used for host-level failures.
Index ¶
- func Ask(ctx context.Context, ap Approver, kind, detail string) (ok bool, unanswered string)
- func AskWith(ctx context.Context, kind, detail string, ...) (ok bool, unanswered string)
- func Bool(p map[string]any, key string) bool
- func Int(p map[string]any, key string, def int) int
- func NoAnswer(ctx context.Context)
- func OutputBudget(ctxWindow int) int
- func Str(p map[string]any, key string) string
- type Action
- type Approver
- type Args
- type CmdWrapper
- type Domain
- type DomainSpec
- type HistorySource
- type MCPCallFunc
- type MCPListFunc
- type MCPSchemaFunc
- type Param
- type Registry
- func (r *Registry) Actions(name string) []string
- func (r *Registry) Dispatch(ctx context.Context, name, action string, params map[string]any) Result
- func (r *Registry) Mutates(name, action string) bool
- func (r *Registry) Normalize(name, action string, params map[string]any) (string, map[string]any)
- func (r *Registry) OpenAITools() []map[string]any
- func (r *Registry) Usage(name string) string
- type Result
- type Shell
- type SkillSource
- type Snapshotter
- type SpawnFunc
- type Tool
- func NewAgent(spawn, spawnBg SpawnFunc) Tool
- func NewCalc() Tool
- func NewDone() Tool
- func NewFile(p *policy.Engine, ap Approver, snap Snapshotter) Tool
- func NewGit(p *policy.Engine, ap Approver, ctxWindow int, offline bool) Tool
- func NewGitLive(p *policy.Engine, ap Approver, ctxWindow int, offline func() bool, ...) Tool
- func NewHelp(kb *knowledge.KB, usage func(domain string) string) Tool
- func NewHistory(src HistorySource) Tool
- func NewMCP(list MCPListFunc, call MCPCallFunc, schema MCPSchemaFunc) Tool
- func NewRun(p *policy.Engine, ap Approver, defaultTimeout time.Duration, ctxWindow int, ...) Tool
- func NewSkill(src SkillSource) Tool
- func NewWeb(hc *http.Client, offline bool) Tool
- func NewWebLive(hc *http.Client, offline func() bool) Tool
- type ToolError
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Ask ¶ added in v0.67.1
Ask is ap.Approve, plus — when the no was nobody's answer — what the call reports instead of "denied by user", or "" when someone did answer.
func AskWith ¶ added in v0.67.1
func AskWith(ctx context.Context, kind, detail string, approve func(ctx context.Context, kind, detail string) bool) (ok bool, unanswered string)
AskWith is Ask for an approval asked some other way.
A refusal and a prompt that ran out read alike to the model as "denied by user", so it took the user to be against the call — dropping it, or working around a no nobody gave. What it needs instead is that the user is away: go on without it, and leave it for them.
func Bool ¶
Bool reads a boolean param, tolerating the string and numeric forms weak models emit ("true"/"yes"/"1", or a non-zero number) instead of a real JSON bool. Missing or unrecognized → false.
func NoAnswer ¶ added in v0.67.1
NoAnswer is how an Approver marks the no it is about to return as nobody's: the prompt ran out unanswered. A no under an Ask is otherwise reported as the user's.
func OutputBudget ¶ added in v0.46.2
OutputBudget is the per-call output cap for the run and git tools, scaled to the active model's context window. A zero or unknown window keeps the old absolute cap — better to behave exactly as before than to guess.
Types ¶
type Action ¶
type Action struct {
Name string
Note string // optional one-line note appended to the generated help
Mutates bool // changes state (write/run/git) — blocked in plan mode
Params []Param
Run func(ctx context.Context, a Args) Result
}
Action is one operation: its declared params and its handler. The handler runs only after the required params have been validated.
type Approver ¶
Approver answers an interactive permission prompt for a policy "ask" decision. ctx is the caller's own context (a job's, for a background sub-agent) — an implementation that blocks on a human answer must also honor ctx.Done(), so a job's own cancellation (not just a process-wide abort) can free it.
type Args ¶
type Args struct {
// contains filtered or unexported fields
}
Args is a typed accessor over the (already validated) params handed to a handler.
type CmdWrapper ¶ added in v0.30.0
CmdWrapper rewrites the exec (name, args) before it runs — used to wrap a command in an OS sandbox. It knows nothing about the sandbox itself; the app injects a closure. nil means run the command directly.
type Domain ¶
type Domain struct {
// contains filtered or unexported fields
}
Domain is the universal tool object (MCP-style): standard methods — schema/help (Description), action list, and dispatch (Call) — generated from a declarative spec. Adding a tool or action is data, not a switch statement, and the schema can't fall out of sync with the handlers.
func NewDomain ¶
func NewDomain(spec DomainSpec) *Domain
NewDomain builds a Domain from its spec. *Domain implements Tool.
func (*Domain) Call ¶
Call validates the action's required params (from its declaration) and then runs the handler. The registry already guarantees the action exists.
func (*Domain) Description ¶
Description is generated from the action declarations.
func (*Domain) InferAction ¶ added in v0.35.1
InferAction guesses a read-only action from the params when the model omitted "action". Returns "" when the spec has no inference or nothing fits.
type DomainSpec ¶
type DomainSpec struct {
Name string
Summary string
Details string // optional extra lines after the action list
NotHere string
Actions []Action
// Infer recovers a likely action from the params when a model omits "action"
// (some models violate the required+enum schema). It MUST only ever return a
// read-only action — never guess a mutation — so a wrong guess is harmless and
// self-correcting. "" = can't tell, surface the normal "no action" error.
Infer func(params map[string]any) string
}
DomainSpec declares a fat tool: a name, a one-line summary, optional extra details, a "NOT here" routing note, and its actions.
type HistorySource ¶ added in v0.40.0
type HistorySource interface {
// Recent returns up to n of the most recently archived entries, oldest
// first. n<=0 means the source's own default.
Recent(n int) []string
// Search returns archived entries whose goal or answer contains query
// (case-insensitive substring), oldest match first, capped at a small
// count so a broad query can't flood the model's context.
Search(query string) []string
}
HistorySource is the read-only view of the session's durable task record — every (goal, final answer + actions digest) this session has ever produced, kept in full even after auto-compact folds the live session memory into a short recap. It lets the model recover a fact compaction has since paraphrased away, instead of guessing.
type MCPCallFunc ¶ added in v0.10.0
type MCPCallFunc func(ctx context.Context, server, tool string, args map[string]any) (string, error)
MCPListFunc returns a human-readable catalog of the configured MCP servers and their tools (the host owns the connections). MCPCallFunc invokes one tool; MCPSchemaFunc returns a tool's input schema on demand. The host gates calls with approval.
type MCPListFunc ¶ added in v0.10.0
MCPListFunc returns a human-readable catalog of the configured MCP servers and their tools (the host owns the connections). MCPCallFunc invokes one tool; MCPSchemaFunc returns a tool's input schema on demand. The host gates calls with approval.
type MCPSchemaFunc ¶ added in v0.10.0
MCPListFunc returns a human-readable catalog of the configured MCP servers and their tools (the host owns the connections). MCPCallFunc invokes one tool; MCPSchemaFunc returns a tool's input schema on demand. The host gates calls with approval.
type Param ¶
type Param struct {
Name string
Type string // str | int | bool | number | list
Required bool
Default string // shown in the generated help when set (e.g. "." or "15")
}
Param declares one action parameter. It is the single source for BOTH the schema shown to the model and the required-arg validation, so help and behaviour can never drift apart.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry holds the active tools and routes calls, applying cross-tool action correction so a misrouted action returns a hint naming the right tool.
func NewRegistry ¶
NewRegistry indexes tools by name and their actions by owning tool(s).
func (*Registry) Actions ¶ added in v0.40.3
Actions returns a tool's action names, or nil if no such tool — used to scope a past-run hint to the action it was actually learned for.
func (*Registry) Dispatch ¶
Dispatch routes (name, action) to its tool. Unknown tool, or an action owned by a different tool, returns a self-correcting Result the model can act on.
func (*Registry) Mutates ¶
Mutates reports whether (name, action) changes state — the gate plan mode uses.
func (*Registry) Normalize ¶ added in v0.68.0
Normalize is the action and params Dispatch will actually run a call with, by the same recovery of a missing or garbled action. Anything that judges a call before it runs — the risk score, plan mode, the call gate — must see it this way, or a call recovered here runs unjudged: "touch x" dumped into run's action field was scored and gated as nothing, then run as a command (found by review). A call nothing recovers comes back as given, for Dispatch to refuse.
func (*Registry) OpenAITools ¶
OpenAITools renders the catalog as OpenAI function definitions — one function per tool, with the action enum and a freeform params object. Kept tiny on purpose so small models prefill it fast.
type Result ¶
type Result struct {
Content string
IsError bool
Err error
Diff string // optional unified diff to display (set by file edits)
}
Result is a tool's outcome as the model sees it. Content is always model- facing text. IsError marks a failure the model should react to. Err is set only for host/infra failures (a *ToolError) so the host can log the typed cause while the model still just reads Content.
type Shell ¶ added in v0.62.6
type Shell string
Shell picks the shell `run` uses on Windows (see shell_windows.go). Elsewhere it is always sh, and the setting is ignored.
func (Shell) CleanOutput ¶ added in v0.62.7
CleanOutput turns what the shell printed into plain text; sh needs nothing.
func (Shell) Interactive ¶ added in v0.62.6
Interactive is the shell /shell opens: the user's own.
func (Shell) InteractiveCommand ¶ added in v0.62.7
InteractiveCommand opens Interactive.
func (Shell) PromptNote ¶ added in v0.62.7
PromptNote tells the model which shell its commands run in, for the system prompt — the sh actually installed: on Debian/Ubuntu it is dash, where bash syntax fails.
type SkillSource ¶
SkillSource is the read-only view of the skill store the model is allowed to touch: see the catalog of enabled skills and load one's full instructions. Installing and toggling skills is a human action (the /skills command), so it is deliberately NOT reachable from here.
type Snapshotter ¶ added in v0.12.0
type Snapshotter func(absPath string)
Snapshotter is called with the absolute path of a file about to be modified, BEFORE the change, so a checkpoint can capture its prior content (for /rewind).
type SpawnFunc ¶ added in v0.6.0
SpawnFunc runs a delegated task on a sub-agent — a fresh LLM session for the named profile (which carries the provider+model), in a given directory — and returns its final answer. The host provides it because it owns the profiles, provider resolution, approval, and the agent build. It errors on an unknown profile, a missing key, a bad directory, or a denied spawn.
type Tool ¶
type Tool interface {
Name() string
Description() string
Actions() []string
Call(ctx context.Context, action string, params map[string]any) Result
// Mutates reports whether an action changes state (writes a file, runs a
// command, alters git). Plan mode blocks these; read-only actions stay open.
Mutates(action string) bool
}
Tool is one fat domain tool.
func NewAgent ¶ added in v0.6.0
NewAgent is the `agent` fat tool: delegate a self-contained task to one of the configured profiles (each a model the user curated) — a second opinion, or another model's strength (e.g. reviewing the same code across models), optionally in another directory. Sub-agents can't spawn their own sub-agents (the host gives them a catalog without this tool). Issue several calls in one turn to fan a task out across profiles; they run in parallel.
spawnBg is the fire-and-forget variant: it starts the task as a detached background job and returns an immediate acknowledgement; the host delivers the job's result to the model at the start of a later turn.
func NewCalc ¶
func NewCalc() Tool
NewCalc returns the calc tool: safe arithmetic evaluation, so small models don't have to do unreliable mental math.
func NewDone ¶ added in v0.44.49
func NewDone() Tool
NewDone returns the done tool: a bare, parameter-less signal a model can call, instead of a real action, to end the run. Reported live: a weak/ tool-trained local model can be so habituated to always calling SOMETHING that it never produces the plain no-tool-call reply the loop treats as a clean finish — instead it invents a workaround, like repeatedly running a shell echo of "TASK COMPLETE" or "EXIT 0". The model was genuinely trying to say it was done, just through the wrong channel. This gives it a real, correct one: the agent loop (see Agent.Run's isDoneOnly) treats a turn whose ONLY tool call is done exactly like a plain no-tool-call finalize, using the same reply's own Content as the answer — done itself is never actually dispatched. It does NOT confirm the goal met on its own: the goal judge (a separate, independent mechanism) still decides that regardless of how the model signaled it thought it was finished.
func NewFile ¶
func NewFile(p *policy.Engine, ap Approver, snap Snapshotter) Tool
NewFile returns the file tool, gated by the policy engine and (for "ask" decisions) the approver. snap (may be nil) is notified before each file change.
func NewGit ¶
NewGit returns the git tool. It runs git directly (argv, no shell) in the workspace; read-only actions run freely, mutating ones ask for approval. When offline is true the actions that need a server refuse, the same way the web tool does.
func NewGitLive ¶ added in v0.62.2
func NewGitLive(p *policy.Engine, ap Approver, ctxWindow int, offline func() bool, wrap ...CmdWrapper) Tool
NewGitLive is NewGit with offline mode read on every networked call, for the same reason as NewWebLive.
wrap, when given, confines git as the run tool's commands are: a read action still runs what the repository's config names — a clean filter, a textconv — and a read-only run wants that sandboxed too.
func NewHelp ¶
NewHelp returns the help tool: an explicit escape hatch the model can call to see a domain's REAL usage (its current schema) plus the lessons learned for it. usage is the live contract lookup (e.g. Registry.Usage); it may be nil.
func NewHistory ¶ added in v0.40.0
func NewHistory(src HistorySource) Tool
NewHistory exposes the session's full task-by-task record to the model, so it can recall something the compacted session summary no longer states — e.g. which files an earlier task actually created. Only registered once there's something archived to recall (see the caller) — it costs nothing in the catalog for a session that doesn't need it yet.
func NewMCP ¶ added in v0.10.0
func NewMCP(list MCPListFunc, call MCPCallFunc, schema MCPSchemaFunc) Tool
NewMCP is the `mcp` proxy fat tool: ONE tool that fronts every configured MCP server, so the prompt catalog doesn't balloon with each server's schemas. The model calls list to discover tools, schema to see a tool's inputs, and call to run one. Only present when at least one MCP server is configured.
func NewRun ¶
func NewRun(p *policy.Engine, ap Approver, defaultTimeout time.Duration, ctxWindow int, shell Shell, wrap ...CmdWrapper) Tool
NewRun returns the run tool: a single `shell` action gated by the policy engine, executed with a timeout and a jail-confined working directory. The default timeout comes from config (run.timeout_seconds); 0 falls back to 60s.
func NewSkill ¶
func NewSkill(src SkillSource) Tool
NewSkill exposes enabled skills to the model. It is only registered when at least one skill is enabled, so it costs nothing in the catalog otherwise.
func NewWeb ¶
NewWeb returns the web tool. A nil client builds one with a 30s timeout — task contexts have no deadline of their own, so without this a slow/hostile server could hang fetch/search/stackexchange indefinitely; pass http. DefaultClient explicitly if you really want that (unbounded). When offline is true, every action refuses with offlineMsg instead of touching the network.
func NewWebLive ¶ added in v0.62.2
NewWebLive is NewWeb with offline mode read on every call. A tool built once — a background sub-agent's — must see /offline on when it happens, not keep egressing on the value it was built with (found by review).