tool

package
v0.1.0-alpha.1 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

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

View Source
const (
	ToolNameLoadMCPTools = "LoadMcpTools"
	ToolNameCallMCPTool  = "CallMcpTool"
)
View Source
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.

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

View Source
const (
	StatusPending    = "pending"
	StatusInProgress = "in_progress"
	StatusCompleted  = "completed"
)

Valid todo statuses.

View Source
const DefaultLimit = 1000

DefaultLimit is the default number of lines returned when limit is not specified.

View Source
const (
	// MaxContentRunes is the maximum runes of fetched content before truncation.
	MaxContentRunes = 200_000
)

Variables

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

func GatewayTools

func GatewayTools(reg *mcp.Registry) []llm.Tool

GatewayTools returns LoadMcpTools and CallMcpTool bound to reg.

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 NewBash

func NewBash(workspaceRoot string) *Bash

NewBash creates a Bash tool that runs commands under the given workspace root.

func (*Bash) CheckArgs

func (b *Bash) CheckArgs(args map[string]any) llm.ToolAction

CheckArgs implements llm.ArgChecker.

Decision order (each step short-circuits):

  1. Catastrophic patterns (rm -rf /, raw dd, mkfs on device) — always Deny.
  2. 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

func (b *Bash) Description() string

Description returns a short description so the LLM knows when to use this tool.

func (*Bash) Execute

func (b *Bash) Execute(ctx context.Context, args map[string]any) (string, error)

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

func (b *Bash) Name() string

Name returns the tool name for the LLM.

func (*Bash) Parameters

func (b *Bash) Parameters() any

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

func NewEditFile(workspaceRoot string) *EditFile

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

func (e *EditFile) Description() string

Description returns a short description so the LLM knows when to use this tool.

func (*EditFile) Execute

func (e *EditFile) Execute(ctx context.Context, args map[string]any) (string, error)

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

func (e *EditFile) Name() string

Name returns the tool name for the LLM.

func (*EditFile) Parameters

func (e *EditFile) Parameters() any

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 NewGlob

func NewGlob(workspaceRoot string) *Glob

NewGlob creates a Glob tool that searches for files under the given workspace root.

func (*Glob) Description

func (g *Glob) Description() string

Description returns a short description so the LLM knows when to use this tool.

func (*Glob) Execute

func (g *Glob) Execute(ctx context.Context, args map[string]any) (string, error)

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

func (g *Glob) Name() string

Name returns the tool name for the LLM.

func (*Glob) Parameters

func (g *Glob) Parameters() any

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

func NewGrep(workspaceRoot string) *Grep

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

func (g *Grep) Description() string

Description returns a short description so the LLM knows when to use this tool.

func (*Grep) Execute

func (g *Grep) Execute(ctx context.Context, args map[string]any) (string, error)

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

func (g *Grep) Name() string

Name returns the tool name for the LLM.

func (*Grep) Parameters

func (g *Grep) Parameters() any

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

func NewReadFile(workspaceRoot string) *ReadFile

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

func (r *ReadFile) Description() string

Description returns a short description so the LLM knows when to use this tool.

func (*ReadFile) Execute

func (r *ReadFile) Execute(ctx context.Context, args map[string]any) (string, error)

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

func (r *ReadFile) Name() string

Name returns the tool name for the LLM.

func (*ReadFile) Parameters

func (r *ReadFile) Parameters() any

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

func NewSkill(searchPaths []string) *SkillTool

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

func (s *SkillTool) Description() string

Description returns a static preamble followed by a dynamic listing of discovered skills.

func (*SkillTool) Execute

func (s *SkillTool) Execute(ctx context.Context, args map[string]any) (string, error)

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

func (s *SkillTool) Name() string

Name returns the tool name for the LLM.

func (*SkillTool) Parameters

func (s *SkillTool) Parameters() any

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

func (t *TaskTool) Description() string

Description returns a dynamically built description listing all available agent types.

func (*TaskTool) Execute

func (t *TaskTool) Execute(ctx context.Context, args map[string]any) (string, error)

Execute spawns a sub-agent of the requested type, runs the prompt, and returns the reply.

func (*TaskTool) Name

func (t *TaskTool) Name() string

Name returns the tool name for the LLM.

func (*TaskTool) Parameters

func (t *TaskTool) Parameters() any

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 NewTodoWrite

func NewTodoWrite() *TodoWrite

NewTodoWrite creates a TodoWrite tool.

func (*TodoWrite) Description

func (t *TodoWrite) Description() string

Description returns a short description so the LLM knows when to use this tool.

func (*TodoWrite) Execute

func (t *TodoWrite) Execute(ctx context.Context, args map[string]any) (string, error)

Execute parses and validates todos from args, then returns a formatted list for the LLM.

func (*TodoWrite) Name

func (t *TodoWrite) Name() string

Name returns the tool name for the LLM.

func (*TodoWrite) Parameters

func (t *TodoWrite) Parameters() any

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

func NewWebFetch(llmClient llm.LLMClient, cacheTTL time.Duration) *WebFetch

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

func (w *WebFetch) Description() string

Description returns a short description so the LLM knows when to use this tool.

func (*WebFetch) Execute

func (w *WebFetch) Execute(ctx context.Context, args map[string]any) (string, error)

Execute fetches the URL, converts HTML to markdown, optionally calls the LLM with content+prompt, and returns the result.

func (*WebFetch) Name

func (w *WebFetch) Name() string

Name returns the tool name for the LLM.

func (*WebFetch) Parameters

func (w *WebFetch) Parameters() any

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

func NewWriteFile(workspaceRoot string) *WriteFile

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

func (w *WriteFile) Description() string

Description returns a short description so the LLM knows when to use this tool.

func (*WriteFile) Execute

func (w *WriteFile) Execute(ctx context.Context, args map[string]any) (string, error)

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

func (w *WriteFile) Name() string

Name returns the tool name for the LLM.

func (*WriteFile) Parameters

func (w *WriteFile) Parameters() any

Parameters returns the OpenAI-style JSON schema for the tool arguments.

Jump to

Keyboard shortcuts

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