tools

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package tools defines the canonical tool schemas and file I/O executors.

Index

Constants

View Source
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"
)
View Source
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.

View Source
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.

View Source
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.

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

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

func ApplyWrites(writes []FileWrite) error

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

func BashPrefixesFromContext(ctx context.Context) []string

BashPrefixesFromContext returns the bash prefix allowlist stored in ctx, or nil if no restriction was set.

func DirectWriteFromContext

func DirectWriteFromContext(ctx context.Context) bool

DirectWriteFromContext reports whether direct-write mode is enabled in ctx. Returns false if not set (queue writes as proposals — TUI default).

func ExecuteBash

func ExecuteBash(ctx context.Context, command string) string

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

func ExecuteEditFile(ctx context.Context, path, oldString, newString string) (string, string)

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

func ExecuteListDirectory(ctx context.Context, path string, depth int) string

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

func ExecuteRead(ctx context.Context, path string, offset, limit int) string

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

func ExecuteSearchFiles(ctx context.Context, pattern, basePath string) string

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

func ExecuteWebFetch(rawURL string) string

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

func ExecuteWebSearch(query string) string

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

func LoadDisabledTools(path string) (map[string]bool, error)

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

func MaxStepsFromContext(ctx context.Context) int

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

func SaveDisabledTools(path string, disabled map[string]bool) error

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

func SeedFromContext(ctx context.Context) (int64, bool)

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

func SetBashTimeout(d time.Duration)

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

func SubagentDepthFromContext(ctx context.Context) int

SubagentDepthFromContext returns the current sub-agent recursion depth from ctx. Returns 0 if not set (top-level run).

func SystemPromptExtraFromContext

func SystemPromptExtraFromContext(ctx context.Context) (string, bool)

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

func SystemPromptSuffix(ctx context.Context) string

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

func ToolGuidanceMapFromContext(ctx context.Context) map[string]string

ToolGuidanceMapFromContext returns the per-tool guidance map stored in ctx, or nil if no map was set via WithToolGuidanceMap.

func WithActiveTools

func WithActiveTools(ctx context.Context, defs []ToolDef) context.Context

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

func WithBashPrefixes(ctx context.Context, prefixes []string) context.Context

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

func WithDirectWrites(ctx context.Context, enabled bool) context.Context

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

func WithMCPDispatchers(ctx context.Context, dispatchers map[string]MCPDispatcher) context.Context

WithMCPDispatchers returns a context carrying the MCP dispatcher table. Called at startup after MCP servers are launched.

func WithMaxSteps

func WithMaxSteps(ctx context.Context, n int) context.Context

WithMaxSteps returns a context carrying the given max steps limit. Adapter loops call MaxStepsFromContext to enforce the limit.

func WithSeed

func WithSeed(ctx context.Context, seed int64) context.Context

WithSeed returns a context carrying the given seed value. Adapters call SeedFromContext to retrieve it for API calls.

func WithSubagentDepth

func WithSubagentDepth(ctx context.Context, depth int) context.Context

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

func WithSystemPromptExtra(ctx context.Context, s string) context.Context

WithSystemPromptExtra returns a context carrying the given system prompt extra text. Adapters read this via SystemPromptSuffix.

func WithToolGuidanceMap

func WithToolGuidanceMap(ctx context.Context, m map[string]string) context.Context

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

func WithWorkDir(ctx context.Context, dir string) context.Context

WithWorkDir returns a context carrying the given working directory override. Executor functions resolve paths relative to this directory instead of os.Getwd().

func WorkDirFromContext

func WorkDirFromContext(ctx context.Context) string

WorkDirFromContext returns the working directory override stored in ctx, or "" if no override was set (fall back to os.Getwd()).

func WriteFileDirect

func WriteFileDirect(ctx context.Context, path, content string) string

WriteFileDirect writes content to path, resolving against WorkDirFromContext. Creates intermediate directories as needed. Returns "" on success, "[error: ...]" on failure.

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

type MCPDispatcher func(args map[string]string) string

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

func ActiveDefinitions(disabled map[string]bool) []ToolDef

ActiveDefinitions returns the subset of Definitions not in disabled. An empty or nil disabled map returns all Definitions unchanged.

func ActiveToolsFromContext

func ActiveToolsFromContext(ctx context.Context) []ToolDef

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

func ApplyDescriptions(defs []ToolDef, descs map[string]string) []ToolDef

ApplyDescriptions returns a copy of defs with descriptions replaced from descs. Tool names not present in descs are left unchanged.

func DefinitionsAllowed

func DefinitionsAllowed(allowlist []string, disabled map[string]bool) []ToolDef

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

func FilterDefs(defs []ToolDef, disabled map[string]bool) []ToolDef

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

func ToolsForRole(role string, parentDefs []ToolDef) []ToolDef

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

func (d ToolDef) JSONSchemaProps() (props map[string]any, required []string)

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.

type ToolParam

type ToolParam struct {
	Type        string
	Description string
}

ToolParam is a provider-agnostic tool property description.

Jump to

Keyboard shortcuts

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