tool

package
v0.42.5 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: MIT Imports: 35 Imported by: 0 modules, 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

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool

func Bool(p map[string]any, key string) 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 Int

func Int(p map[string]any, key string, def int) int

Int reads an integer param, tolerating JSON float64 and numeric strings.

func Str

func Str(p map[string]any, key string) string

Str reads a string param (JSON values arrive as any), coercing non-strings via fmt. Missing → "".

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

type Approver interface {
	Approve(kind, detail string) bool
}

Approver answers an interactive permission prompt for a policy "ask" decision.

type Args

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

Args is a typed accessor over the (already validated) params handed to a handler.

func (Args) Bool

func (a Args) Bool(k string) bool

func (Args) Has

func (a Args) Has(k string) bool

func (Args) Int

func (a Args) Int(k string, def int) int

func (Args) Str

func (a Args) Str(k string) string

type CmdWrapper added in v0.30.0

type CmdWrapper func(name string, args []string) (string, []string)

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) Actions

func (d *Domain) Actions() []string

func (*Domain) Call

func (d *Domain) Call(ctx context.Context, action string, params map[string]any) Result

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

func (d *Domain) Description() string

Description is generated from the action declarations.

func (*Domain) InferAction added in v0.35.1

func (d *Domain) InferAction(params map[string]any) string

InferAction guesses a read-only action from the params when the model omitted "action". Returns "" when the spec has no inference or nothing fits.

func (*Domain) Mutates

func (d *Domain) Mutates(action string) bool

Mutates reports whether the named action is declared as state-changing.

func (*Domain) Name

func (d *Domain) Name() string

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

type MCPListFunc func(ctx context.Context) string

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

type MCPSchemaFunc func(ctx context.Context, server, tool string) string

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.

func Opt

func Opt(name, typ, def string) Param

func Req

func Req(name, typ string) Param

Req and Opt are concise constructors for declaring params.

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

func NewRegistry(ts ...Tool) *Registry

NewRegistry indexes tools by name and their actions by owning tool(s).

func (*Registry) Actions added in v0.40.3

func (r *Registry) Actions(name string) []string

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

func (r *Registry) Dispatch(ctx context.Context, name, action string, params map[string]any) Result

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

func (r *Registry) Mutates(name, action string) bool

Mutates reports whether (name, action) changes state — the gate plan mode uses.

func (*Registry) OpenAITools

func (r *Registry) OpenAITools() []map[string]any

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.

func (*Registry) Usage

func (r *Registry) Usage(name string) string

Usage returns a tool's self-describing contract (its Description), or "" if no such tool — used to lead the model back to correct usage after an error.

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.

func Err

func Err(s string) Result

Err is a model-recoverable failure (bad input, denied, not found) — text only.

func Fail

func Fail(tool, action, msg string, cause error) Result

Fail is a host/infra failure: the model sees msg, the host gets a typed *ToolError via Result.Err.

func Ok

func Ok(s string) Result

Ok is a successful result.

type SkillSource

type SkillSource interface {
	Index() string
	Body(name string) (string, error)
}

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

type SpawnFunc func(ctx context.Context, profile, task, dir string) (string, error)

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

func NewAgent(spawn, spawnBg SpawnFunc) Tool

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 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

func NewGit(p *policy.Engine, ap Approver) Tool

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.

func NewHelp

func NewHelp(kb *knowledge.KB, usage func(domain string) string) Tool

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, 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

func NewWeb(hc *http.Client, offline bool) Tool

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.

type ToolError

type ToolError struct {
	Tool   string
	Action string
	Err    error
}

ToolError wraps a host-level tool failure.

func (*ToolError) Error

func (e *ToolError) Error() string

func (*ToolError) Unwrap

func (e *ToolError) Unwrap() error

Jump to

Keyboard shortcuts

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