Documentation
¶
Overview ¶
Package tools defines the canonical tool schemas and file I/O executors.
Index ¶
- Constants
- Variables
- func ApplyWrites(writes []FileWrite) error
- func BashPrefixesFromContext(ctx context.Context) []string
- func DirectWriteFromContext(ctx context.Context) bool
- func ExecuteBash(ctx context.Context, command string) string
- func ExecuteEditFile(ctx context.Context, path, oldString, newString string) (string, string)
- func ExecuteListDirectory(ctx context.Context, path string, depth int) string
- func ExecuteRead(ctx context.Context, path string, offset, limit int) string
- func ExecuteSearchCode(ctx context.Context, pattern, path, fileGlob string, contextLines int) string
- func ExecuteSearchFiles(ctx context.Context, pattern, basePath string) string
- func ExecuteWebFetch(rawURL string) string
- func ExecuteWebSearch(query string) string
- func LoadDisabledTools(path string) (map[string]bool, error)
- func MCPDispatchersFromContext(ctx context.Context) map[string]MCPDispatcher
- func MaxStepsFromContext(ctx context.Context) int
- func RestoreSnapshots(snaps []FileSnapshot) error
- func SaveDisabledTools(path string, disabled map[string]bool) error
- func SeedFromContext(ctx context.Context) (int64, bool)
- func SetAllowLocalFetch(b bool)
- func SetBashTimeout(d time.Duration)
- func SetWebSearchAPIBase(u string)
- func SubagentDepthFromContext(ctx context.Context) int
- func SystemPromptExtraFromContext(ctx context.Context) (string, bool)
- func SystemPromptGuidance() string
- func SystemPromptSuffix(ctx context.Context) string
- func ToolGuidanceMapFromContext(ctx context.Context) map[string]string
- func WithActiveTools(ctx context.Context, defs []ToolDef) context.Context
- func WithBashPrefixes(ctx context.Context, prefixes []string) context.Context
- func WithDirectWrites(ctx context.Context, enabled bool) context.Context
- func WithMCPDispatchers(ctx context.Context, dispatchers map[string]MCPDispatcher) context.Context
- func WithMaxSteps(ctx context.Context, n int) context.Context
- func WithSeed(ctx context.Context, seed int64) context.Context
- func WithSubagentDepth(ctx context.Context, depth int) context.Context
- func WithSubagentDispatcher(ctx context.Context, d SubagentDispatcher) context.Context
- func WithSystemPromptExtra(ctx context.Context, s string) context.Context
- func WithToolGuidanceMap(ctx context.Context, m map[string]string) context.Context
- func WithWorkDir(ctx context.Context, dir string) context.Context
- func WorkDirFromContext(ctx context.Context) string
- func WriteFileDirect(ctx context.Context, path, content string) string
- type FileSnapshot
- type FileWrite
- type MCPDispatcher
- type SubagentDispatcher
- type ToolDef
- func ActiveDefinitions(disabled map[string]bool) []ToolDef
- func ActiveToolsFromContext(ctx context.Context) []ToolDef
- func ApplyDescriptions(defs []ToolDef, descs map[string]string) []ToolDef
- func DefinitionsAllowed(allowlist []string, disabled map[string]bool) []ToolDef
- func FilterDefs(defs []ToolDef, disabled map[string]bool) []ToolDef
- func ToolsForRole(role string, parentDefs []ToolDef) []ToolDef
- type ToolParam
Constants ¶
const ( ReadToolName = "read_file" WriteToolName = "write_file" EditToolName = "edit_file" ListDirToolName = "list_directory" SearchFilesName = "search_files" SearchCodeName = "search_code" BashToolName = "bash" WebFetchToolName = "web_fetch" WebSearchToolName = "web_search" SpawnAgentToolName = "spawn_agent" )
const ( // RoleExplorer provides read-only search, file, and web tools. // Use for tasks that only need to gather information. RoleExplorer = "explorer" // RolePlanner provides explorer tools plus bash. // Use for tasks that need to explore and run commands but not write files. RolePlanner = "planner" // RoleCoder provides all active parent tools (default role). // The sub-agent can propose file writes that bubble up to the parent. RoleCoder = "coder" // RoleFull is an alias for RoleCoder. RoleFull = "full" )
Sub-agent role names control which tools a spawned sub-agent can access.
const HooksEnabled = false
HooksEnabled gates lifecycle event hooks. When false, the config panel omits the hooks section and hook execution is skipped. Recipe parsing is unaffected. Set to true to activate.
const RemindersEnabled = false
RemindersEnabled gates conditional mid-conversation system reminders. When false, the config panel omits the reminders section and reminder state is not initialised. Recipe parsing is unaffected. Set to true to activate.
const SubagentEnabled = false
SubagentEnabled gates all user-facing sub-agent functionality. When false, spawn_agent is excluded from Definitions, the config panel omits the sub-agent section, and dispatcher wiring is skipped. Set to true to re-enable the feature.
Variables ¶
var Definitions = []ToolDef{ { Name: ReadToolName, Description: "Read the contents of a file relative to the current working directory. " + "Use offset and limit to read a specific line range for large files. " + "Returns a truncation notice when there are more lines to read.", Properties: map[string]ToolParam{ "path": {Type: "string", Description: "Relative path to the file"}, "offset": {Type: "integer", Description: "First line to return, 1-indexed (default 1)"}, "limit": {Type: "integer", Description: "Maximum lines to return (default and max 2000)"}, }, Required: []string{"path"}, }, { Name: WriteToolName, Description: "Propose writing content to a file relative to the current working directory. " + "Use only for new files or complete rewrites — use edit_file for targeted changes to existing files. " + "The write will be applied only if the user selects this model's response.", Properties: map[string]ToolParam{ "path": {Type: "string", Description: "Relative path to the file"}, "content": {Type: "string", Description: "Full file content to write"}, }, Required: []string{"path", "content"}, }, { Name: EditToolName, Description: "Propose a targeted edit to an existing file by replacing an exact string. " + "old_string must appear exactly once in the file — add enough surrounding context to make it unique. " + "More efficient than write_file for small changes. " + "The edit is queued and applied only if the user selects this model's response.", Properties: map[string]ToolParam{ "path": {Type: "string", Description: "Relative path to the file to edit"}, "old_string": {Type: "string", Description: "The exact string to replace (must appear exactly once)"}, "new_string": {Type: "string", Description: "The replacement string"}, }, Required: []string{"path", "old_string", "new_string"}, }, { Name: ListDirToolName, Description: "List files and directories recursively from a path relative to the current " + "working directory. Returns an indented tree; directories end with /. Use this to " + "explore the project structure before reading specific files.", Properties: map[string]ToolParam{ "path": {Type: "string", Description: "Relative path to the directory to list"}, "depth": {Type: "integer", Description: "How many levels deep to recurse (default 2, max 5)"}, }, Required: []string{"path"}, }, { Name: SearchFilesName, Description: "Find files whose names match a glob pattern within the project. " + "Use ** for recursive matching (e.g. **/*.go). Returns matching paths relative to the base.", Properties: map[string]ToolParam{ "pattern": {Type: "string", Description: "Glob pattern, e.g. '**/*.go' or 'internal/**/*.go'"}, "base_path": {Type: "string", Description: "Directory to search from, relative to cwd (default '.')"}, }, Required: []string{"pattern"}, }, { Name: SearchCodeName, Description: "Search file contents for a regex pattern. Returns matching file paths, " + "line numbers, and the matching lines. Use file_glob to filter by file type. " + "Use context_lines to include surrounding lines for context.", Properties: map[string]ToolParam{ "pattern": {Type: "string", Description: "Regex pattern to search for"}, "path": {Type: "string", Description: "File or directory to search, relative to cwd (default '.')"}, "file_glob": {Type: "string", Description: "Optional filename filter, e.g. '*.go'"}, "context_lines": {Type: "integer", Description: "Lines of context before and after each match (default 0)"}, }, Required: []string{"pattern"}, }, { Name: BashToolName, Description: "Execute a shell command and return its combined stdout+stderr output. " + "Use for running tests, builds, linters, git commands, or any shell operation. " + "Commands run with a 2-minute timeout. Provide a brief description of what the command does.", Properties: map[string]ToolParam{ "command": {Type: "string", Description: "The shell command to execute"}, "description": {Type: "string", Description: "One-line summary of what this command does"}, }, Required: []string{"command", "description"}, }, { Name: WebFetchToolName, Description: "Fetch the content of a public URL and return its text. " + "HTML pages are stripped to plain text. Use for reading documentation, " + "GitHub issues, READMEs, or any publicly accessible web page.", Properties: map[string]ToolParam{ "url": {Type: "string", Description: "The http:// or https:// URL to fetch"}, }, Required: []string{"url"}, }, { Name: WebSearchToolName, Description: "Search DuckDuckGo for factual information and return instant answers. " + "Best for definitions, Wikipedia-style summaries, and quick facts. " + "Limited to knowledge-panel results — not a full web index. " + "For specific documentation pages or URLs, use web_fetch instead.", Properties: map[string]ToolParam{ "query": {Type: "string", Description: "The search query"}, }, Required: []string{"query"}, }, { Name: SpawnAgentToolName, Description: "Spawn a sub-agent to complete a specific task. The sub-agent runs its own " + "agentic loop and returns its final response. Any file writes the sub-agent proposes " + "are automatically included in the current run's proposals and shown in the diff view.", Properties: map[string]ToolParam{ "task": {Type: "string", Description: "The specific task for the sub-agent to complete."}, "role": {Type: "string", Description: "Tool access role: 'explorer' (read-only search/file/web), 'planner' (explorer + bash), 'coder' (full tools, can propose writes). Default: coder"}, "model_id": {Type: "string", Description: "Model to use. Defaults to the current model."}, }, Required: []string{"task"}, }, }
Definitions is the canonical set of tools available to all agents.
Functions ¶
func ApplyWrites ¶
ApplyWrites writes each FileWrite to disk, creating parent directories as needed. Deletion entries (fw.Delete) remove the file instead of writing it. All paths are validated against the current working directory; writes that would escape it via ".." sequences are rejected with an error.
func BashPrefixesFromContext ¶
BashPrefixesFromContext returns the bash prefix allowlist stored in ctx, or nil if no restriction was set.
func DirectWriteFromContext ¶
DirectWriteFromContext reports whether direct-write mode is enabled in ctx. Returns false if not set (queue writes as proposals — TUI default).
func ExecuteBash ¶
ExecuteBash runs command via the system shell (sh -c) with a 2-minute timeout. stdout and stderr are combined; output is capped at bashOutputLimit bytes. If ctx carries a bash prefix allowlist (via WithBashPrefixes), the command must match one of the allowed prefixes or an error string is returned instead. If ctx carries a sandbox Config (via sandbox.WithConfig), the subprocess is wrapped with OS-level sandboxing appropriate for the current platform.
func ExecuteEditFile ¶
ExecuteEditFile reads path, replaces exactly one occurrence of oldString with newString, and returns (newContent, ""). Returns ("", errorMessage) on failure. The caller is responsible for queuing the result as a ProposedWrite or writing directly. Refuses paths that escape the working directory.
func ExecuteListDirectory ¶
ExecuteListDirectory lists a directory tree up to depth levels deep. path is relative to the working directory (from context or cwd). Returns an indented tree string, or an error message. Directories are suffixed with /. depth is clamped to [1, 5]. File entries include a human-readable size hint (e.g. "handlers.go (12 KB)").
DERIVED: BFS indented-tree design from codex list_dir.rs
func ExecuteRead ¶
ExecuteRead reads a file relative to the working directory (from context or cwd). offset is 1-indexed (0 or 1 both mean "start at line 1"). limit is the max lines to return (0 means use maxReadLines). Returns the file content, or an error string the model can see. Refuses paths that escape the working directory.
func ExecuteSearchCode ¶
func ExecuteSearchCode(ctx context.Context, pattern, path, fileGlob string, contextLines int) string
ExecuteSearchCode searches file contents for pattern using pure Go (filepath.WalkDir + regexp). Skips .git/ directories and binary files. path and fileGlob are optional; path defaults to ".". contextLines adds N lines of context before and after each match. Returns grep-compatible output (path:line:content format) or an error message.
func ExecuteSearchFiles ¶
ExecuteSearchFiles finds files matching a glob pattern relative to basePath. basePath is relative to the working directory (from context or cwd). Returns newline-separated matching paths, or an error message.
func ExecuteWebFetch ¶
ExecuteWebFetch fetches a URL and returns cleaned text content. HTML pages are stripped to plain text. Output is capped at webFetchOutputLimit bytes. Concurrent calls for the same URL are deduplicated via singleflight — only one HTTP request goes out, and all callers receive the identical result.
func ExecuteWebSearch ¶
ExecuteWebSearch queries the DuckDuckGo instant answers API and returns a formatted plain-text result. Best for factual/definition queries. Not a full web index — for specific URLs, callers should prefer ExecuteWebFetch.
func LoadDisabledTools ¶
LoadDisabledTools reads the disabled-tool set from path. Returns an empty map and nil error if path is empty or the file does not exist (all tools enabled).
func MCPDispatchersFromContext ¶
func MCPDispatchersFromContext(ctx context.Context) map[string]MCPDispatcher
MCPDispatchersFromContext returns the MCP dispatcher table stored in ctx, or nil if no dispatchers were registered (MCP not configured).
func MaxStepsFromContext ¶
MaxStepsFromContext returns the max steps limit stored in ctx. Returns 0 if no limit was set (unlimited).
func RestoreSnapshots ¶
func RestoreSnapshots(snaps []FileSnapshot) error
RestoreSnapshots restores files to their snapshotted state. DidNotExist entries are removed. Best-effort: continues on individual errors and returns the first error encountered.
func SaveDisabledTools ¶
SaveDisabledTools persists the disabled-tool set to path. If path is empty, disabled is nil, or disabled is empty, any existing file is removed.
func SeedFromContext ¶
SeedFromContext returns the seed stored in ctx and true, or (0, false) if no seed was set.
func SetAllowLocalFetch ¶
func SetAllowLocalFetch(b bool)
SetAllowLocalFetch enables or disables web_fetch for localhost URLs.
func SetBashTimeout ¶
SetBashTimeout overrides the default bash tool timeout. Pass 0 to reset to the default.
func SetWebSearchAPIBase ¶
func SetWebSearchAPIBase(u string)
SetWebSearchAPIBase overrides the DuckDuckGo API base URL (for tests). Pass "" to reset to the default.
func SubagentDepthFromContext ¶
SubagentDepthFromContext returns the current sub-agent recursion depth from ctx. Returns 0 if not set (top-level run).
func SystemPromptExtraFromContext ¶
SystemPromptExtraFromContext returns the system prompt extra text stored in ctx. The bool is false if no value was set via WithSystemPromptExtra.
func SystemPromptGuidance ¶
func SystemPromptGuidance() string
SystemPromptGuidance returns the fixed tool-use guidance text. This is the same guidance as in SystemPromptSuffix but without the user-authored extra. Returns full unfiltered guidance (no context).
func SystemPromptSuffix ¶
SystemPromptSuffix returns guidance text appended to each adapter's system prompt so models understand how to use the available tool set effectively. When ctx carries an active tool set (via WithActiveTools), only guidance lines relevant to those tools are included. If no active tools are in context, the full unfiltered guidance is returned for backward compatibility. If WithSystemPromptExtra was called on ctx, that text is appended after the built-in guidance so project-specific context reaches every model.
func ToolGuidanceMapFromContext ¶
ToolGuidanceMapFromContext returns the per-tool guidance map stored in ctx, or nil if no map was set via WithToolGuidanceMap.
func WithActiveTools ¶
WithActiveTools returns a context carrying the given tool definitions. Adapters call ActiveToolsFromContext to retrieve the set for this run. Passing nil is a no-op (nil means "not set"); pass an empty slice to explicitly indicate zero active tools.
func WithBashPrefixes ¶
WithBashPrefixes returns a context carrying the given bash prefix allowlist. When set, ExecuteBash will only run commands whose prefix matches one of these patterns (e.g. "go test *", "go build *"). nil or empty means unrestricted.
func WithDirectWrites ¶
WithDirectWrites returns a context that enables direct-write mode. When enabled, write_file and edit_file write to disk immediately instead of queuing proposals. Used in headless mode with per-model worktrees.
func WithMCPDispatchers ¶
WithMCPDispatchers returns a context carrying the MCP dispatcher table. Called at startup after MCP servers are launched.
func WithMaxSteps ¶
WithMaxSteps returns a context carrying the given max steps limit. Adapter loops call MaxStepsFromContext to enforce the limit.
func WithSeed ¶
WithSeed returns a context carrying the given seed value. Adapters call SeedFromContext to retrieve it for API calls.
func WithSubagentDepth ¶
WithSubagentDepth returns a context with the given sub-agent recursion depth. The top-level run always starts at depth 0.
func WithSubagentDispatcher ¶
func WithSubagentDispatcher(ctx context.Context, d SubagentDispatcher) context.Context
WithSubagentDispatcher returns a context carrying the given SubagentDispatcher. Called when building the run context before passing to runner.RunAll.
func WithSystemPromptExtra ¶
WithSystemPromptExtra returns a context carrying the given system prompt extra text. Adapters read this via SystemPromptSuffix.
func WithToolGuidanceMap ¶
WithToolGuidanceMap returns a context carrying the per-tool guidance map. effectiveGuidanceForCtx reads this to override code-default guidance per tool. A nil map means "use code defaults for all tools."
func WithWorkDir ¶
WithWorkDir returns a context carrying the given working directory override. Executor functions resolve paths relative to this directory instead of os.Getwd().
func WorkDirFromContext ¶
WorkDirFromContext returns the working directory override stored in ctx, or "" if no override was set (fall back to os.Getwd()).
Types ¶
type FileSnapshot ¶
type FileSnapshot struct {
Path string // absolute path
Content string // original content (empty for new files)
DidNotExist bool // true = file was created by write; rewind should delete it
}
FileSnapshot captures the on-disk state of a file before a write operation. Used by /rewind to restore files to their previous state.
func SnapshotFiles ¶
func SnapshotFiles(writes []FileWrite) ([]FileSnapshot, error)
SnapshotFiles reads the current on-disk content for each path in writes. Files that don't exist get DidNotExist: true. Paths are validated against the current working directory. For deletion entries (fw.Delete), the file's current content is captured so /rewind can restore it. If the file already doesn't exist, it is skipped.
type FileWrite ¶
type FileWrite struct {
Path string `json:"path"`
Content string `json:"content"`
Delete bool `json:"delete,omitempty"`
}
FileWrite is a proposed file write intercepted from an agent's tool call. It lives here (not in models) to break the import cycle: tools → (stdlib only), models → tools.
type MCPDispatcher ¶
MCPDispatcher is a function that executes one MCP tool call. args values are strings to match Errata's DispatchTool convention.
type SubagentDispatcher ¶
type SubagentDispatcher func(ctx context.Context, args map[string]string) (text string, writes []FileWrite, errMsg string)
SubagentDispatcher is a function that spawns a sub-agent to complete a task. args contains the spawn_agent tool arguments (task, role, model_id). It returns the sub-agent's text response, any proposed writes to bubble up, and an error message string (empty on success).
func SubagentDispatcherFromContext ¶
func SubagentDispatcherFromContext(ctx context.Context) SubagentDispatcher
SubagentDispatcherFromContext returns the SubagentDispatcher stored in ctx, or nil if no dispatcher was registered.
type ToolDef ¶
type ToolDef struct {
Name string
Description string
Properties map[string]ToolParam
Required []string
}
ToolDef is the canonical, provider-agnostic tool definition. Each adapter translates this into its own SDK format.
func ActiveDefinitions ¶
ActiveDefinitions returns the subset of Definitions not in disabled. An empty or nil disabled map returns all Definitions unchanged.
func ActiveToolsFromContext ¶
ActiveToolsFromContext returns the tool definitions stored in ctx, or Definitions if no active set was provided. An empty slice means zero tools are active.
func ApplyDescriptions ¶
ApplyDescriptions returns a copy of defs with descriptions replaced from descs. Tool names not present in descs are left unchanged.
func DefinitionsAllowed ¶
DefinitionsAllowed returns tool definitions filtered by allowlist (if non-nil) and minus any disabled tools. A nil allowlist means all Definitions are candidates; a non-nil empty allowlist means zero tools (the section was present but empty). This combines recipe-level tool allowlist filtering with session-level disabling.
func FilterDefs ¶
FilterDefs returns the subset of defs not in disabled. Used to apply the same disabled-tool filter to MCP or other dynamic tool sets.
func ToolsForRole ¶
ToolsForRole returns the subset of tool definitions allowed for the given role. parentDefs is the active tool set from the parent context (returned as-is for coder/full or unknown roles). Explorer and planner roles filter from the canonical Definitions list so they always get the read-only or read+bash sets, regardless of what the parent has enabled.
func (ToolDef) JSONSchemaProps ¶
JSONSchemaProps returns a JSON-Schema-compatible properties map and required list for this tool definition. Used by adapter tool-building functions to avoid duplicating the property-extraction loop.