Documentation
¶
Overview ¶
Package tool provides concrete agent tools (Read, Write, Edit, Glob, Grep, Bash, WebFetch, TodoWrite, Skill, Task, and MCP gateway tools).
Package tools provides concrete agent tools (e.g. read_file, write_file, webfetch, todowrite).
Package tools provides concrete agent tools (e.g. read_file, write_file, webfetch).
Index ¶
- Constants
- Variables
- func GatewayTools(reg *mcp.Registry) []llm.Tool
- type AgentTypeConfig
- type Bash
- type BuiltinSubAgentDef
- type EditFile
- type Glob
- type Grep
- type ReadFile
- type SkillEntry
- type SkillTool
- type SubAgentDef
- type SubAgentRunOpts
- type SubAgentRunner
- type SubAgentRunnerOption
- type TaskTool
- type TodoWrite
- type WebFetch
- type WriteFile
Constants ¶
const ( ToolNameLoadMCPTools = "LoadMcpTools" ToolNameCallMCPTool = "CallMcpTool" )
const ( ToolNameRead = "Read" ToolNameWrite = "Write" ToolNameEdit = "Edit" ToolNameGlob = "Glob" ToolNameGrep = "Grep" ToolNameBash = "Bash" ToolNameWebFetch = "WebFetch" ToolNameTodoWrite = "TodoWrite" ToolNameSkill = "Skill" ToolNameTask = "Task" )
Tool name constants — single source of truth for every tool's Name(). Use camelCase for LLM-facing names.
const ( GeneralSubAgentPrompt = `` /* 234-byte string literal not displayed */ ExploreSubAgentPrompt = `` /* 242-byte string literal not displayed */ ShellSubAgentPrompt = `` /* 194-byte string literal not displayed */ )
Built-in sub-agent system prompts.
const ( StatusPending = "pending" StatusInProgress = "in_progress" StatusCompleted = "completed" )
Valid todo statuses.
const DefaultLimit = 1000
DefaultLimit is the default number of lines returned when limit is not specified.
const (
// MaxContentRunes is the maximum runes of fetched content before truncation.
MaxContentRunes = 200_000
)
Variables ¶
var BuiltinSubAgentDefs = []BuiltinSubAgentDef{ { Name: "general", ToolNames: nil, SystemPrompt: GeneralSubAgentPrompt, Description: "General-purpose agent with all tools for multi-step tasks.", }, { Name: "explore", ToolNames: []string{ToolNameRead, ToolNameGlob, ToolNameGrep}, SystemPrompt: ExploreSubAgentPrompt, Description: "Read-only agent for fast codebase exploration (Read, Glob, Grep).", }, { Name: "shell", ToolNames: []string{ToolNameBash}, SystemPrompt: ShellSubAgentPrompt, Description: "Command execution specialist (Bash only).", }, }
BuiltinSubAgentDefs defines the built-in sub-agent types in display order.
Functions ¶
Types ¶
type AgentTypeConfig ¶
type AgentTypeConfig struct {
Tools []llm.Tool // tools available to this agent type
SystemPrompt string // system prompt for the sub-agent
Description string // LLM-readable description of this agent type
Model string // model name to use; "" = runner default
MaxIterations int // iteration cap; 0 = defaultSubAgentMaxIter (50)
}
AgentTypeConfig holds the configuration for one agent type (built-in or user-defined).
type Bash ¶
type Bash struct {
// contains filtered or unexported fields
}
Bash runs a shell command in the workspace (one command per call).
func (*Bash) CheckArgs ¶
func (b *Bash) CheckArgs(args map[string]any) llm.ToolAction
CheckArgs implements llm.ArgChecker.
Decision order (each step short-circuits):
- Catastrophic patterns (rm -rf /, raw dd, mkfs on device) — always Deny.
- Risky patterns (curl, npm, sudo, …) — Ask, unless auto-allow applies.
Auto-allow demotes Ask → Allow when:
- the sandbox is enabled,
- its mode is auto_allow (config.auto_allow_bash_if_sandboxed),
- the command would actually be sandboxed (not in excluded_commands),
- the caller did not pass dangerously_disable_sandbox=true.
Matches Claude Code's documented behavior in /sandboxing: catastrophic destructive commands still prompt even in auto-allow mode; everything else is contained by the OS sandbox boundary.
func (*Bash) Description ¶
Description returns a short description so the LLM knows when to use this tool.
func (*Bash) Execute ¶
Execute runs the command in b.root with the given timeout, captures combined stdout+stderr, and returns the result (truncated if needed). On success (exit 0) returns output and nil error. On non-zero exit or timeout returns a clear message and nil error so the LLM receives a readable result. Returns error only for argument validation (missing or empty command).
func (*Bash) Parameters ¶
Parameters returns the OpenAI-style JSON schema for the tool arguments.
func (*Bash) WithSandbox ¶
func (b *Bash) WithSandbox(v agent.SandboxView) *Bash
WithSandbox returns a copy of b that wraps spawned commands through the given SandboxView. Pass agent.NoopSandbox{} (or nil) to disable. Returning a copy keeps Bash safe to share across goroutines.
type BuiltinSubAgentDef ¶
type BuiltinSubAgentDef struct {
Name string
ToolNames []string // nil ⇒ all base tools
SystemPrompt string
Description string
}
BuiltinSubAgentDef describes a built-in sub-agent type declaratively. ToolNames lists tool names resolved at runtime; nil means all base tools.
type EditFile ¶
type EditFile struct {
// contains filtered or unexported fields
}
EditFile performs exact string replacements in a file under a workspace root.
func NewEditFile ¶
NewEditFile creates an EditFile tool that edits files under the given workspace root.
func (*EditFile) CheckArgs ¶
func (e *EditFile) CheckArgs(args map[string]any) llm.ToolAction
CheckArgs implements llm.ArgChecker. Editing a sensitive file (credentials, private keys) triggers Ask so the user can confirm intent in interactive sessions.
func (*EditFile) Description ¶
Description returns a short description so the LLM knows when to use this tool.
func (*EditFile) Execute ¶
Execute performs string replacement(s) in the file at args["file_path"]. Reads the file, validates old_string uniqueness when replace_all=false, performs replacement(s), and writes back.
func (*EditFile) Parameters ¶
Parameters returns the OpenAI-style JSON schema for the tool arguments.
type Glob ¶
type Glob struct {
// contains filtered or unexported fields
}
Glob lists files matching a glob pattern under a workspace root. Symlinks: doublestar.Glob with WithFilesOnly does not follow symlinks to directories; symlinks to files are included as matches.
func (*Glob) Description ¶
Description returns a short description so the LLM knows when to use this tool.
func (*Glob) Execute ¶
Execute lists files under the search directory that match the pattern, sorted by modification time (newest first). Returns one absolute path per line, or "No files matched the pattern.", or an error for validation/system failures.
func (*Glob) Parameters ¶
Parameters returns the OpenAI-style JSON schema for the tool arguments.
type Grep ¶
type Grep struct {
// contains filtered or unexported fields
}
Grep searches file contents by regex pattern under a workspace root.
func NewGrep ¶
NewGrep creates a Grep tool that searches file contents under the given workspace root.
func (*Grep) CheckArgs ¶
func (g *Grep) CheckArgs(args map[string]any) llm.ToolAction
CheckArgs implements llm.ArgChecker. Grepping inside a sensitive file (credentials, private keys) triggers Ask so the user can confirm intent in interactive sessions.
func (*Grep) Description ¶
Description returns a short description so the LLM knows when to use this tool.
func (*Grep) Execute ¶
Execute searches file contents under the tool's root for the given regex pattern. Returns formatted results based on output_mode, or "No matches found.", or an error.
func (*Grep) Parameters ¶
Parameters returns the OpenAI-style JSON schema for the tool arguments.
type ReadFile ¶
type ReadFile struct {
// contains filtered or unexported fields
}
ReadFile reads a local file under a workspace root.
func NewReadFile ¶
NewReadFile creates a ReadFile tool that reads files under the given workspace root.
func (*ReadFile) CheckArgs ¶
func (r *ReadFile) CheckArgs(args map[string]any) llm.ToolAction
CheckArgs implements llm.ArgChecker. Reading a sensitive file (credentials, private keys) triggers Ask so the user can confirm intent in interactive sessions.
func (*ReadFile) Description ¶
Description returns a short description so the LLM knows when to use this tool.
func (*ReadFile) Execute ¶
Execute reads the file at args["file_path"] if it is under the tool's root. File contents are returned as UTF-8 text; invalid UTF-8 in the file is passed through as-is.
func (*ReadFile) Parameters ¶
Parameters returns the OpenAI-style JSON schema for the tool arguments.
type SkillEntry ¶
type SkillEntry struct {
Name string // skill identifier (directory name)
Description string // short description extracted from SKILL.md
Path string // absolute path to the SKILL.md file
}
SkillEntry holds metadata for one discovered skill.
func DiscoverSkillEntries ¶
func DiscoverSkillEntries(searchPaths []string) []SkillEntry
DiscoverSkillEntries scans search paths for subdirectories containing SKILL.md. First-path-wins on name conflicts. Returns skills sorted alphabetically by name. This is the single discovery implementation used by NewSkill and other callers that need a listing (e.g. TUI /skills).
type SkillTool ¶
type SkillTool struct {
// contains filtered or unexported fields
}
SkillTool is an agent tool that discovers and invokes skills from disk. It implements agent.Tool.
func NewSkill ¶
NewSkill creates a SkillTool that discovers skills from the given search paths. Each search path is scanned one level deep for subdirectories containing a SKILL.md file. Missing directories are silently skipped. If multiple search paths contain a skill with the same name, the first one found wins (search paths are priority-ordered).
func NewSkillFromEntries ¶
func NewSkillFromEntries(entries []SkillEntry) *SkillTool
NewSkillFromEntries creates a SkillTool from pre-discovered skill entries. The provided entries are copied so callers can treat the returned tool as immutable.
func (*SkillTool) Description ¶
Description returns a static preamble followed by a dynamic listing of discovered skills.
func (*SkillTool) Execute ¶
Execute looks up the requested skill, reads its SKILL.md file, and returns the content. If args is provided, it is prepended as context.
func (*SkillTool) Parameters ¶
Parameters returns the OpenAI-style JSON schema for the tool arguments.
type SubAgentDef ¶
type SubAgentDef struct {
Name string // agent type name (used as subagent_type value)
Description string // LLM-readable description
ToolNames []string // tool names parsed from the "tools" field
SystemPrompt string // body text used as the sub-agent system prompt
Model string // model name to use for this agent type; "" = runner default
MaxIterations int // iteration cap; 0 = defaultSubAgentMaxIter (50)
Color string // color hint (parsed, reserved for UI)
}
SubAgentDef represents one parsed sub-agent definition file. The file uses YAML-like frontmatter (between --- delimiters) for metadata and the body after the closing --- as the system prompt.
func LoadAgentDefs ¶
func LoadAgentDefs(dir string) ([]SubAgentDef, error)
LoadAgentDefs reads all files from dir, parses each as an agent definition, and returns the valid definitions sorted alphabetically by Name. If dir does not exist, returns (nil, nil) — not an error. Individual files that fail to parse are skipped with a log warning.
func LoadAgentDefsFromPaths ¶
func LoadAgentDefsFromPaths(dirs []string) ([]SubAgentDef, error)
LoadAgentDefsFromPaths loads agent definitions from multiple directories in priority order. Directories are scanned in order; if two directories contain a definition with the same Name, the first one wins (project-level overrides global-level). Missing directories are gracefully skipped (same behavior as LoadAgentDefs). Returns the merged list sorted alphabetically by Name.
type SubAgentRunOpts ¶
type SubAgentRunOpts struct {
Tools []llm.Tool
SystemPrompt string
Description string
MaxIter int // 0 = defaultSubAgentMaxIter
Model string // "" = use runner default client
}
SubAgentRunOpts configures one sub-agent invocation.
type SubAgentRunner ¶
type SubAgentRunner interface {
RunSubAgent(ctx context.Context, opts SubAgentRunOpts, prompt string) (reply string, err error)
}
SubAgentRunner runs a sub-agent with the given options and prompt. It is implemented by agentapp and injected when building the Task tool so that tools do not depend on a concrete runner; tests can inject a mock.
func NewDefaultSubAgentRunner ¶
func NewDefaultSubAgentRunner(llmClient llm.LLMClient, policy coreagent.ToolPolicy, modelResolver func(string) (llm.LLMClient, error), opts ...SubAgentRunnerOption) (SubAgentRunner, error)
NewDefaultSubAgentRunner returns a SubAgentRunner backed by the given LLM client. policy is inherited from the parent agent run (nil = AllowAll). modelResolver looks up an LLM client by model name for agent types that specify a model; nil means always use client regardless of the model field.
type SubAgentRunnerOption ¶
type SubAgentRunnerOption func(*defaultSubAgentRunner)
SubAgentRunnerOption configures a SubAgentRunner.
func WithSubAgentHooks ¶
func WithSubAgentHooks(h coreagent.HookRunner) SubAgentRunnerOption
WithSubAgentHooks attaches a parent hook runner so subagent runs honor the same PreToolUse / PostToolUse / lifecycle hooks as the parent agent. Nil disables hooks.
type TaskTool ¶
type TaskTool struct {
// contains filtered or unexported fields
}
TaskTool is an agent tool that spawns sub-agents to handle complex subtasks. It implements llm.Tool.
func NewTask ¶
func NewTask(runner SubAgentRunner, agentTypes map[string]AgentTypeConfig) (*TaskTool, error)
NewTask creates a TaskTool with the given sub-agent runner and agent type configurations. runner must not be nil; agentTypes must have at least one entry.
func (*TaskTool) Description ¶
Description returns a dynamically built description listing all available agent types.
func (*TaskTool) Execute ¶
Execute spawns a sub-agent of the requested type, runs the prompt, and returns the reply.
func (*TaskTool) Parameters ¶
Parameters returns the OpenAI-style JSON schema with a dynamic enum for subagent_type.
type TodoWrite ¶
type TodoWrite struct{}
TodoWrite is a tool that formats a task list for the LLM to trace progress. It does not store state; it validates the given todos and returns a formatted list. It implements the agent.Tool interface.
func (*TodoWrite) Description ¶
Description returns a short description so the LLM knows when to use this tool.
func (*TodoWrite) Execute ¶
Execute parses and validates todos from args, then returns a formatted list for the LLM.
func (*TodoWrite) Parameters ¶
Parameters returns the OpenAI-style JSON schema for the tool arguments.
type WebFetch ¶
type WebFetch struct {
// contains filtered or unexported fields
}
WebFetch is a tool that fetches a URL, converts HTML to markdown, optionally processes content with the LLM using a prompt, and returns the result. It implements the llm.Tool interface.
func NewWebFetch ¶
NewWebFetch creates a WebFetch tool with the given LLM client and cache TTL. llmClient may be nil: fetching without a "prompt" argument still works; if "prompt" is set, Execute returns an error until a non-nil client is provided.
func (*WebFetch) Description ¶
Description returns a short description so the LLM knows when to use this tool.
func (*WebFetch) Execute ¶
Execute fetches the URL, converts HTML to markdown, optionally calls the LLM with content+prompt, and returns the result.
func (*WebFetch) Parameters ¶
Parameters returns the OpenAI-style JSON schema for the tool arguments.
func (*WebFetch) WithSandbox ¶
func (w *WebFetch) WithSandbox(v agent.SandboxView) *WebFetch
WithSandbox installs v as the host filter on w and returns w. Mutates in place because WebFetch holds shared cache state behind a mutex — copying would split the cache. Pass agent.NoopSandbox{} (or nil) to disable enforcement.
type WriteFile ¶
type WriteFile struct {
// contains filtered or unexported fields
}
WriteFile writes content to a local file under a workspace root.
func NewWriteFile ¶
NewWriteFile creates a WriteFile tool that writes files under the given workspace root.
func (*WriteFile) CheckArgs ¶
func (w *WriteFile) CheckArgs(args map[string]any) llm.ToolAction
CheckArgs implements llm.ArgChecker. Writing to a sensitive file (credentials, private keys) triggers Ask so the user can confirm intent in interactive sessions.
func (*WriteFile) Description ¶
Description returns a short description so the LLM knows when to use this tool.
func (*WriteFile) Execute ¶
Execute writes args["content"] to the file at args["file_path"] if the path is under the tool's root. Creates parent directories if needed; overwrites if the file exists. Returns a short success message or error.
func (*WriteFile) Parameters ¶
Parameters returns the OpenAI-style JSON schema for the tool arguments.