tools

package
v0.0.0-...-0a00bc4 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2026 License: MIT Imports: 35 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ChangeCreated  = "created"
	ChangeModified = "modified"
	ChangeDeleted  = "deleted"
)
View Source
const (
	// ChangeMaxFileBytes bounds one side of a diffed file; larger files
	// report counts only.
	ChangeMaxFileBytes = 1 << 20
	// ChangeMaxTotalBytes bounds the diff bodies one call reports; later
	// files keep their counts and lose their body.
	ChangeMaxTotalBytes = 512 << 10
	// ChangeMaxFiles bounds the files one call lists.
	ChangeMaxFiles = 200
)

Limits shared by every tool that reports file changes.

View Source
const (
	PageDefaultLines = 200
	PageMaxLines     = 500
	PageMaxBytes     = 40 << 10
	// PageScanMaxLine bounds how much of one physical line is held in memory;
	// longer lines page as byte_offset placeholders.
	PageScanMaxLine = 1 << 20
)

The bounded-paging limits shared by every tool that pages text into model context (read_artifact, read_file). Responses stay under PageMaxBytes so a page is never itself externalized to an artifact.

Variables

View Source
var ErrCommandOutputIncomplete = errors.New("command output incomplete")

ErrCommandOutputIncomplete means capture did not reach EOF. The returned output is a partial result, distinct from the bounded buffer's size limit. It is never an ordinary CommandError, even if the process also exited nonzero.

View Source
var ErrPageSizeMismatch = errors.New("content size does not match its declared size")

ErrPageSizeMismatch reports that the content's size did not match the size the caller declared, e.g. because it changed between stat and read. Callers wrap it with their own context.

View Source
var ErrSkillRuntimeUnavailable = errors.New("skill runtime is unavailable")

ErrSkillRuntimeUnavailable is returned when activation or restore is attempted without discovered skills.

Functions

func CapPageText

func CapPageText(text string) string

CapPageText bounds a page response to PageMaxBytes on a rune boundary and keeps it valid UTF-8 (content may contain arbitrary bytes) without increasing its bounded byte size.

func Error

func Error(message, code string) string

Error marshals a tool error as JSON: {"error": message, "code": code}.

func FormatToolError

func FormatToolError(err error) (string, bool)

FormatToolError checks whether err wraps a *ToolError and, if so, returns the JSON-serialized error string. Returns ("", false) otherwise.

func LoadMCPConfigFile

func LoadMCPConfigFile(jsonFile string) (map[string]MCPConfig, error)

LoadMCPConfigFile parses a config file and returns server configs Requires mcpServers format: {"mcpServers": {"name": {...}}}

func MatchesToolPattern

func MatchesToolPattern(pattern, name string) bool

MatchesToolPattern reports whether a tool allow-list entry, a filepath.Match glob or an exact name, matches name.

func PageByteWindow

func PageByteWindow(ctx context.Context, r io.Reader, noun, name string, size, byteOffset int64) (string, error)

PageByteWindow returns a raw byte window of r; paging with the reported next byte_offset recovers any content exactly, regardless of line structure. noun and name identify the content in the window header (e.g. "artifact", its ID), and size is the caller's authoritative content length: a shorter or longer stream returns ErrPageSizeMismatch.

func PageLines

func PageLines(ctx context.Context, r io.Reader, noun string, offset, limit int, query string) (string, error)

PageLines renders numbered lines from r and cannot fail on content shape: physical lines longer than PageScanMaxLine become bounded placeholders that point at their byte_offset instead of aborting the scan, and mid-line response-cap truncation reports the exact continuation byte_offset. noun names the content kind in messages (e.g. "artifact", "file").

func ParseServerSpec

func ParseServerSpec(spec string) (jsonFile string, serverName string)

ParseServerSpec splits a server spec into file path and server name Format: "path/to/config.json" or "path/to/config.json#servername"

func RecallStub

func RecallStub(tool Tool) (string, bool)

RecallStub returns the stub a tool's elided result is replaced with, and whether the tool is a recall tool at all.

func Result

func Result(v any) string

Result marshals v as a JSON string for tool results. Falls back to an error JSON on marshal failure.

func SandboxState

func SandboxState(t Tool) (capable, active bool)

SandboxState reports whether t supports sandboxing and whether it is active. Namespaced wrappers are unwrapped first: NamespacedTool embeds the Tool interface, so methods outside it don't promote.

func WithPipefail

func WithPipefail(ctx context.Context) context.Context

WithPipefail makes bash commands executed under ctx run with pipefail, so a pipeline fails when any stage fails rather than only its last. Workflow exec uses it because scripts gate on exit codes without reading the output.

Types

type Args

type Args map[string]any

Args wraps map[string]any with typed accessors for tool arguments. JSON unmarshals numbers as float64, so direct type assertions on int will panic. Use Args helpers instead.

Usage: args := tools.Args(rawArgs)

func (Args) Bool

func (a Args) Bool(key string) bool

Bool returns the boolean value for key, or false if missing or wrong type.

func (Args) Float

func (a Args) Float(key string, defaultValue float64) float64

Float returns the float64 value for key. Returns defaultValue if missing or wrong type.

func (Args) Int

func (a Args) Int(key string, defaultValue int) int

Int returns the integer value for key, handling float64 (from JSON), int, and int64 types. Returns defaultValue if missing or wrong type.

func (Args) String

func (a Args) String(key string) string

String returns the string value for key, or empty string if missing or wrong type.

func (Args) StringSlice

func (a Args) StringSlice(key string) []string

StringSlice returns a deduplicated string slice for key, handling both []any (from JSON) and []string. Skips empty strings.

type BashTool

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

BashTool executes shell commands via bash -c, or bash -o pipefail -c under a context from WithPipefail.

func NewUnsafeBashTool

func NewUnsafeBashTool(workDir string) *BashTool

NewUnsafeBashTool creates an unsandboxed bash tool. Prefer loading "bash" through a ToolRegistry configured with WithSandboxFactory. This constructor is intentionally explicit because executing model-authored commands without containment grants them the caller's ambient host access.

func (*BashTool) Execute

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

func (*BashTool) ExecuteOutput

func (t *BashTool) ExecuteOutput(ctx context.Context, args map[string]any) (ToolOutput, error)

func (*BashTool) GetName

func (t *BashTool) GetName() string

func (*BashTool) GetSchema

func (t *BashTool) GetSchema() *schema.ToolSchema

func (*BashTool) GetSource

func (t *BashTool) GetSource() string

func (*BashTool) GetType

func (t *BashTool) GetType() string

func (*BashTool) SandboxDetails

func (t *BashTool) SandboxDetails() SandboxInfo

SandboxDetails reports bash sandbox posture and the effective config if known.

func (*BashTool) WithSandbox

func (t *BashTool) WithSandbox(sb sandbox.Sandbox) *BashTool

WithSandbox returns a copy with sandboxing enabled.

type ChangeTracker

type ChangeTracker interface {
	// Snapshot records the state of the workspace containing dir (the
	// process working directory when empty). ok is false, with a reason, when
	// dir is not observable: outside a repository, too large, or disabled.
	Snapshot(ctx context.Context, dir string) (token string, ok bool, reason string, err error)
	// Changes snapshots again and reports what changed since token.
	Changes(ctx context.Context, dir, token string) (FileChanges, error)
}

ChangeTracker observes a workspace around a command so the tool can report what the command changed. Implementations must not modify the workspace or its version-control metadata.

type CommandError

type CommandError struct {
	ExitCode int
	Cause    error
}

CommandError means a command was launched and exited unsuccessfully. Setup, cancellation, timeout and incomplete-capture errors do not have this type.

func (*CommandError) Error

func (e *CommandError) Error() string

func (*CommandError) Unwrap

func (e *CommandError) Unwrap() error

type CommandResult

type CommandResult struct {
	ExitCode int          `json:"exitCode"`
	Changes  *FileChanges `json:"changes,omitempty"`
}

CommandResult records the process outcome without interpreting stderr. Changes is what the command changed in its workspace when the registry has a ChangeTracker, and nil otherwise.

type ContextIndependentTool

type ContextIndependentTool interface {
	Tool
	ContextIndependent() bool
}

ContextIndependentTool is a declaration by trusted Go tool authors. Local process tools still get their own sandbox; declarations never widen it.

type ContextTool

type ContextTool interface {
	Tool
	BindExecutionContext(*ToolRegistry, ExecutionContext) (Tool, error)
}

ContextTool explicitly binds a custom tool to a new execution context. Unknown tools are omitted rather than retaining authority over another cwd.

type CoordinationTool

type CoordinationTool interface {
	Tool
	Coordinates() bool
}

CoordinationTool identifies trusted orchestration that may wait for other executions. It must acquire any filesystem exclusivity inside its runtime operation, rather than holding a shared permit while waiting for that work. A timeout exemption (UntimedTool) does not imply this exemption.

type DeriveOption

type DeriveOption func(*deriveOptions)

DeriveOption narrows a derived registry.

func AllowTools

func AllowTools(patterns ...string) DeriveOption

AllowTools limits the tools a derived registry sees to those matching one of the patterns (filepath.Match globs, or exact names). It bounds the tools the derived registry loads itself as well as the parent's; only its always-allowed built-ins pass regardless. Repeated options accumulate.

func DenyTools

func DenyTools(patterns ...string) DeriveOption

DenyTools hides the parent tools matching any of the patterns from a derived registry, after AllowTools. Repeated options accumulate.

type ExclusiveTool

type ExclusiveTool interface {
	Tool
	ExclusiveBatch() bool
}

ExclusiveTool must be the sole call in a model tool batch. The agent checks the entire batch before dispatching any operation.

type ExecutionContext

type ExecutionContext struct {
	BuiltinTools []string       `json:"-"`
	SourceRoot   string         `json:"-"`
	Root         string         `json:"root"`
	ReadOnly     bool           `json:"readOnly"`
	Scratch      string         `json:"scratch,omitempty"`
	Sandbox      sandbox.Config `json:"-"`
}

ExecutionContext binds filesystem authority to a registry, never to a process-wide chdir. The runtime keeps context identities opaque to scripts.

type ExecutionGate

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

ExecutionGate serializes a runtime's integration writes against parent tool executions. Ownership belongs to the runtime, not to an individual turn.

func NewExecutionGate

func NewExecutionGate() *ExecutionGate

func (*ExecutionGate) Exclusive

func (g *ExecutionGate) Exclusive(ctx context.Context) (func(), error)

func (*ExecutionGate) Shared

func (g *ExecutionGate) Shared(ctx context.Context) (func(), error)

type ExecutionGrant

type ExecutionGrant struct {
	// ReadOnly denies writes to the root. With a Scratch the context may write
	// only there; without one it denies every write.
	ReadOnly     bool
	DeniedReads  []string
	DeniedWrites []string
	// Scratch is an existing directory outside the root, exported to the
	// context's processes as TMPDIR and the Go cache root. It is the only
	// writable path of a read-only context. A missing or nested scratch fails
	// closed.
	Scratch string
}

ExecutionGrant is the authority a context receives beyond reading its root.

type FileChange

type FileChange struct {
	// Path is slash-separated and relative to FileChanges.Root, or absolute
	// when the file lies outside that root.
	Path string `json:"path"`
	// Kind is ChangeCreated, ChangeModified, or ChangeDeleted.
	Kind      string `json:"kind"`
	Additions int    `json:"additions"`
	Deletions int    `json:"deletions"`
	// Diff is the unified diff body: "--- a/x", "+++ b/x", then hunks. It is
	// empty for binary files and for files over the size limits.
	Diff string `json:"diff,omitempty"`
	// Truncated reports that Diff was cut at a hunk boundary or omitted
	// because the file or the diff exceeded a limit. Counts stay complete.
	Truncated bool `json:"truncated,omitempty"`
	Binary    bool `json:"binary,omitempty"`
}

FileChange is one file's difference between two workspace states. Tools that mutate files report it in ToolOutput.Data for the user interface; the model-facing text of those tools does not include it.

func DiffFileChange

func DiffFileChange(path string, old, new []byte, oldExists, newExists bool) FileChange

DiffFileChange describes the change from old to new at path. oldExists and newExists select the kind; a missing side is diffed as empty content. Binary content (a NUL byte on either side) and oversized files carry no body.

type FileChanges

type FileChanges struct {
	// Root is the absolute workspace root that relative Paths resolve against.
	Root string `json:"root"`
	// Changes is sorted by path and never nil in a tracked result.
	Changes []FileChange `json:"changes"`
	// Tracked is false when the workspace could not be observed at all, for
	// example a bash command outside a Git repository. Reason says why.
	Tracked bool   `json:"tracked"`
	Reason  string `json:"reason,omitempty"`
	// Truncated reports that more files changed than fit; Omitted counts them.
	Truncated bool `json:"truncated,omitempty"`
	Omitted   int  `json:"omitted,omitempty"`
}

FileChanges is the Data payload of a file-mutating tool call.

type Func

type Func struct {
	Coordinator bool
	LongRunning bool
	Exclusive   bool
	Name        string
	Desc        string
	Params      schema.Params
	Required    []string
	Strict      bool
	Source      string // defaults to "builtin"
	Run         func(ctx context.Context, args Args) (string, error)
}

Func is a declarative tool definition. It implements Tool.

func (*Func) Coordinates

func (f *Func) Coordinates() bool

func (*Func) ExclusiveBatch

func (f *Func) ExclusiveBatch() bool

func (*Func) Execute

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

func (*Func) GetName

func (f *Func) GetName() string

func (*Func) GetSchema

func (f *Func) GetSchema() *schema.ToolSchema

func (*Func) GetSource

func (f *Func) GetSource() string

func (*Func) GetType

func (f *Func) GetType() string

func (*Func) Untimed

func (f *Func) Untimed() bool

type LoadResult

type LoadResult struct {
	Type    string         // "native", "shell", "mcp"
	Servers []ServerResult // For MCP, one per server loaded; for shell/native, single entry
}

LoadResult contains information about tools that were loaded

type MCPClient

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

MCPClient manages connection to an MCP server

func NewUnsafeMCPClient

func NewUnsafeMCPClient(serverSpec string) (*MCPClient, error)

NewUnsafeMCPClient creates an unsandboxed MCP client from a server spec. Prefer ToolRegistry.LoadMCPServer, which applies the registry sandbox policy before starting stdio servers.

func (*MCPClient) Close

func (c *MCPClient) Close() error

Close closes the MCP client connection. It is safe to call more than once; later calls return the first result.

func (*MCPClient) Closed

func (c *MCPClient) Closed() bool

Closed reports whether Close has been called.

func (*MCPClient) ListTools

func (c *MCPClient) ListTools() ([]Tool, error)

ListTools returns all tools available from the MCP server

type MCPConfig

type MCPConfig struct {
	ContextIndependent bool   `json:"contextIndependent,omitempty"`
	WorkDir            string `json:"-"`
	// Local/stdio transport fields
	Command string            `json:"command,omitempty"`
	Args    []string          `json:"args,omitempty"`
	Env     map[string]string `json:"env,omitempty"`

	// Remote transport fields
	URL       string            `json:"url,omitempty"`       // Remote server URL
	Transport string            `json:"transport,omitempty"` // "stdio" | "sse" | "streamable"
	Headers   map[string]string `json:"headers,omitempty"`   // Auth headers, API keys
	Timeout   string            `json:"timeout,omitempty"`   // Connection timeout (e.g., "30s")

	// Sandboxing (stdio only). true for defaults, or {"allowNetwork":true,"writablePaths":[...]}.
	Sandbox json.RawMessage `json:"sandbox,omitempty"`
}

MCPConfig represents the JSON configuration for an MCP server

func (*MCPConfig) SandboxConfig

func (c *MCPConfig) SandboxConfig() (*sandbox.Config, error)

SandboxConfig returns the parsed sandbox config for merging overrides, or nil when the user didn't specify any sandbox overrides.

func (*MCPConfig) SandboxOptOut

func (c *MCPConfig) SandboxOptOut() bool

SandboxOptOut reports whether this server requested sandbox:false. The registry honors that request only after an explicit WithUnsafeNoSandbox.

type MCPServersConfig

type MCPServersConfig struct {
	MCPServers map[string]MCPConfig `json:"mcpServers"`
}

MCPServersConfig represents the Claude Desktop format with multiple servers

type MCPTool

type MCPTool struct {
	Source string // Server spec that provided this tool
	// contains filtered or unexported fields
}

MCPTool wraps an MCP tool to implement the Tool interface

func (*MCPTool) Execute

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

Execute runs the MCP tool with the given arguments

func (*MCPTool) ExecuteOutput

func (m *MCPTool) ExecuteOutput(ctx context.Context, args map[string]any) (ToolOutput, error)

ExecuteOutput preserves MCP image/audio bytes as typed media so Agent can externalize them rather than embedding base64 in a textual tool result.

func (*MCPTool) GetName

func (m *MCPTool) GetName() string

GetName returns the name of the tool

func (*MCPTool) GetSchema

func (m *MCPTool) GetSchema() *schema.ToolSchema

GetSchema returns the tool's schema (cached after first call)

func (*MCPTool) GetSource

func (m *MCPTool) GetSource() string

GetSource returns the server spec that provided this tool

func (*MCPTool) GetType

func (m *MCPTool) GetType() string

GetType returns "mcp" for MCP tools

func (*MCPTool) SandboxDetails

func (m *MCPTool) SandboxDetails() SandboxInfo

SandboxDetails reports whether the owning MCP server process is sandboxed.

type NamespacedTool

type NamespacedTool struct {
	Tool
	// contains filtered or unexported fields
}

NamespacedTool wraps a tool to provide a namespaced schema

func (*NamespacedTool) Coordinates

func (n *NamespacedTool) Coordinates() bool

func (*NamespacedTool) ExclusiveBatch

func (n *NamespacedTool) ExclusiveBatch() bool

func (*NamespacedTool) ExecuteOutput

func (n *NamespacedTool) ExecuteOutput(ctx context.Context, args map[string]any) (ToolOutput, error)

ExecuteOutput preserves an optional rich result through the namespace wrapper. Without this forwarding method, wrapping an MCP tool would narrow it back to Tool and force image bytes through Execute's textual JSON path.

func (*NamespacedTool) GetName

func (n *NamespacedTool) GetName() string

GetName returns the namespaced name

func (*NamespacedTool) GetSchema

func (n *NamespacedTool) GetSchema() *schema.ToolSchema

GetSchema returns a schema with the namespaced title

func (*NamespacedTool) RecallStub

func (n *NamespacedTool) RecallStub() string

func (*NamespacedTool) Untimed

func (n *NamespacedTool) Untimed() bool

type NativeTool

type NativeTool struct{}

NativeTool provides default GetType and GetSource implementations for native Go tools. Embed it to avoid repeating boilerplate:

type myTool struct {
    tools.NativeTool
    // ...
}

func (NativeTool) GetSource

func (NativeTool) GetSource() string

func (NativeTool) GetType

func (NativeTool) GetType() string

type OutputTool

type OutputTool interface {
	Tool
	ExecuteOutput(ctx context.Context, args map[string]any) (ToolOutput, error)
}

OutputTool is the optional rich-result extension implemented by tools such as MCP. Tool itself intentionally remains unchanged.

func NewViewImageTool

func NewViewImageTool(registry *ToolRegistry) OutputTool

NewViewImageTool creates the view_image tool bound to registry's sandbox policy.

type RecallTool

type RecallTool interface {
	Tool
	RecallStub() string
}

RecallTool is a tool whose result is reproducible on demand: calling it again with the same arguments yields the same information. The agent may therefore elide a completed call's result under context pressure and replace it with RecallStub, which tells the model how to get the content back. An empty stub means the tool is not a recall tool.

type RegistryOption

type RegistryOption func(*registryOptions)

RegistryOption configures a ToolRegistry.

func WithChangeTracker

func WithChangeTracker(tracker ChangeTracker) RegistryOption

WithChangeTracker installs the tracker bash uses to report file changes. SetChangeTracker does the same on an existing registry.

func WithSandboxFactory

func WithSandboxFactory(factory func(sandbox.Config) (sandbox.Sandbox, error), baseCfg sandbox.Config) RegistryOption

WithSandboxFactory sets the sandbox factory and snapshots the prepared base config immediately. Preparation errors surface when the registry first constructs a process sandbox because RegistryOption cannot return an error.

func WithUnsafeNoSandbox

func WithUnsafeNoSandbox() RegistryOption

WithUnsafeNoSandbox explicitly permits process-backed tools to run without an OS sandbox. Without this option, registries that lack a sandbox factory reject bash, shell tools, and stdio MCP servers instead of silently running them with ambient host access.

type SandboxInfo

type SandboxInfo struct {
	Capable  bool
	Active   bool
	OptedOut bool
	Config   *sandbox.Config
}

SandboxInfo describes whether a tool can be sandboxed, whether sandboxing is currently active, and the effective sandbox config when it is known.

func SandboxDetails

func SandboxDetails(t Tool) SandboxInfo

SandboxDetails reports sandbox capability, active state, opt-out state, and the effective config when the tool recorded it at sandbox construction time.

type ServerResult

type ServerResult struct {
	Name      string   // Server/tool name (e.g., "git", "filesystem", "datetime")
	ToolNames []string // Fully namespaced tool names loaded
}

ServerResult contains information about tools loaded from a single source

type ShellTool

type ShellTool struct {
	Command string
	// contains filtered or unexported fields
}

ShellTool wraps external commands/scripts as tools

func NewUnsafeShellTool

func NewUnsafeShellTool(command string) (*ShellTool, error)

NewUnsafeShellTool loads a shell tool without containing its --schema command or future executions. Prefer ToolRegistry.LoadShellTool.

func (*ShellTool) Execute

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

Execute runs the tool with the given arguments

func (*ShellTool) GetName

func (s *ShellTool) GetName() string

GetName returns the name of the tool

func (*ShellTool) GetSchema

func (s *ShellTool) GetSchema() *schema.ToolSchema

GetSchema returns the tool's schema, annotated with [sandboxed] if applicable

func (*ShellTool) GetSource

func (s *ShellTool) GetSource() string

GetSource returns the command/script path

func (*ShellTool) GetType

func (s *ShellTool) GetType() string

GetType returns "shell" for shell tools

func (*ShellTool) SandboxConfig

func (s *ShellTool) SandboxConfig() *sandbox.Config

SandboxConfig returns sandbox override config parsed from the script's schema, or nil if the tool didn't declare any overrides.

func (*ShellTool) SandboxDetails

func (s *ShellTool) SandboxDetails() SandboxInfo

SandboxDetails reports shell tool sandbox posture and the effective config if known.

func (*ShellTool) SandboxOptOut

func (s *ShellTool) SandboxOptOut() bool

SandboxOptOut reports whether the script requested sandbox:false. The registry honors that request only after an explicit WithUnsafeNoSandbox.

func (*ShellTool) WantsSandbox

func (s *ShellTool) WantsSandbox() bool

WantsSandbox reports whether the script's schema declared sandbox overrides.

func (*ShellTool) WithSandbox

func (s *ShellTool) WithSandbox(sb sandbox.Sandbox) *ShellTool

WithSandbox returns a copy with sandboxing enabled.

type SkillActivateTool

type SkillActivateTool struct {
	NativeTool
	// contains filtered or unexported fields
}

SkillActivateTool loads a skill's instructions and registers any executable scripts.

func NewSkillActivateTool

func NewSkillActivateTool(catalog *skills.Catalog, registry *ToolRegistry) *SkillActivateTool

NewSkillActivateTool creates the skill activation tool.

func (*SkillActivateTool) ActivatedSkills

func (t *SkillActivateTool) ActivatedSkills() []string

ActivatedSkills returns the activated skill names in stable order.

func (*SkillActivateTool) Execute

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

func (*SkillActivateTool) GetName

func (t *SkillActivateTool) GetName() string

func (*SkillActivateTool) GetSchema

func (t *SkillActivateTool) GetSchema() *schema.ToolSchema

type SkillReadFileTool

type SkillReadFileTool struct {
	NativeTool
	// contains filtered or unexported fields
}

SkillReadFileTool returns the contents of a file inside a discovered skill. Reads honor the registry's base sandbox read policy so the tool cannot see what a sandboxed command could not.

func NewSkillReadFileTool

func NewSkillReadFileTool(catalog *skills.Catalog, registry *ToolRegistry) *SkillReadFileTool

NewSkillReadFileTool creates the skill file reader tool bound to registry's sandbox policy. A nil registry applies no policy.

func (*SkillReadFileTool) Execute

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

func (*SkillReadFileTool) GetName

func (t *SkillReadFileTool) GetName() string

func (*SkillReadFileTool) GetSchema

func (t *SkillReadFileTool) GetSchema() *schema.ToolSchema

type SkillRuntime

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

SkillRuntime exposes a public API for skill activation, restore, and state export.

func NewSkillRuntime

func NewSkillRuntime(catalog *skills.Catalog, registry *ToolRegistry) (*SkillRuntime, error)

NewSkillRuntime registers the built-in skill tools on the registry and returns a runtime facade.

func (*SkillRuntime) Activate

func (r *SkillRuntime) Activate(name string) (string, error)

Activate activates a skill immediately and commits the resulting tools and policy into the registry.

func (*SkillRuntime) ActivatedSkills

func (r *SkillRuntime) ActivatedSkills() []string

ActivatedSkills returns the currently activated skill names in stable order.

func (*SkillRuntime) Catalog

func (r *SkillRuntime) Catalog() *skills.Catalog

Catalog returns the discovered skill catalog backing the runtime.

func (*SkillRuntime) Derive

func (r *SkillRuntime) Derive(registry *ToolRegistry) (*SkillRuntime, error)

Derive inherits activation state into a registry derived from this runtime's registry. MCP clients remain owned by the parent; no skill files are loaded and no servers are connected again. A skill whose loaded tools the derived registry's allow-list hides is not inherited: the child is refused it, with the hidden tools named, rather than handed instructions for tools it cannot call. The child's policy and future skill activations remain independent, within the derived registry's tool filter.

func (*SkillRuntime) Enabled

func (r *SkillRuntime) Enabled() bool

Enabled reports whether discovered skills are available for activation.

func (*SkillRuntime) Restore

func (r *SkillRuntime) Restore(names []string) error

Restore reactivates previously active skills and commits their tools and policy into the registry.

type Tool

type Tool interface {
	// Execution methods
	GetSchema() *schema.ToolSchema
	Execute(ctx context.Context, args map[string]any) (string, error)

	// Metadata methods
	GetName() string   // Returns the namespaced name (e.g., "script__toolname")
	GetType() string   // Returns the tool type: "shell", "mcp", or "native"
	GetSource() string // Returns the source path/spec (e.g., "/path/to/script.sh")
}

Tool is the generic interface for all tools

func LoadShellToolsWithRegistry

func LoadShellToolsWithRegistry(registry *ToolRegistry, paths []string) ([]Tool, error)

LoadShellToolsWithRegistry prepares every shell tool under registry policy, then registers the whole batch under one lock. A preparation failure leaves the registry unchanged.

func NewEditFileTool

func NewEditFileTool(registry *ToolRegistry) Tool

NewEditFileTool creates the edit_file tool bound to registry's sandbox policy.

func NewListDirTool

func NewListDirTool(registry *ToolRegistry) Tool

NewListDirTool creates the list_dir tool bound to registry's sandbox policy.

func NewReadFileTool

func NewReadFileTool(registry *ToolRegistry) Tool

NewReadFileTool creates the read_file tool bound to registry's sandbox policy.

func NewWriteFileTool

func NewWriteFileTool(registry *ToolRegistry) Tool

NewWriteFileTool creates the write_file tool bound to registry's sandbox policy.

type ToolCall

type ToolCall struct {
	ID   string         // Provider-specific ID (if any)
	Name string         // Tool name
	Args map[string]any // Parsed arguments
}

ToolCall represents a request to execute a tool

type ToolError

type ToolError struct {
	Message string `json:"error"`
	Code    string `json:"code,omitempty"`
}

ToolError is a structured error returned by tools. When a tool returns a *ToolError from Execute, the agent serializes it as JSON with "error" and "code" fields instead of the generic "Error: ..." format.

func NewToolError

func NewToolError(message, code string) *ToolError

NewToolError creates a structured tool error with message and code.

func (*ToolError) Error

func (e *ToolError) Error() string

type ToolExecution

type ToolExecution struct {
	Output     ToolOutput
	Invoked    bool // false when cancellation or the execution gate prevents invocation
	ContextErr error
}

ToolExecution retains the raw output and execution context's outcome so callers can report failures in their own format without losing media or data.

type ToolLoaderInfo

type ToolLoaderInfo struct {
	Name   string `json:"name"`   // Full namespaced tool name
	Type   string `json:"type"`   // "shell", "mcp", or "native"
	Source string `json:"source"` // Path for shell, server spec for MCP, "builtin" for native
}

ToolLoaderInfo stores information needed to reload a specific tool

type ToolMedia

type ToolMedia struct {
	Data      []byte
	MIMEType  string
	Name      string
	Reference string
}

type ToolOutput

type ToolOutput struct {
	Text string
	// Data is a machine-readable result, independent of its display text.
	// Legacy tools leave it nil. Wrappers must preserve it together with Media.
	Data  any
	Media []ToolMedia
}

ToolOutput preserves typed media without forcing it through a base64 JSON string. Agent callers use OutputTool when available; ordinary Tool callers remain source-compatible with Execute's string result.

type ToolRegistry

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

ToolRegistry manages available tools

func LoadRegistry

func LoadRegistry(loaderInfos []ToolLoaderInfo, opts ...RegistryOption) (*ToolRegistry, error)

LoadRegistry builds a registry holding the tools a session persisted: shell tools by path, MCP servers filtered to the named tools, and native tools by name.

func NewToolRegistry

func NewToolRegistry(tools []Tool, opts ...RegistryOption) *ToolRegistry

NewToolRegistry creates a registry. Process-backed tools are rejected unless the registry has a sandbox factory or the caller explicitly selects WithUnsafeNoSandbox; in-process tools can be registered without either.

func (*ToolRegistry) All

func (r *ToolRegistry) All() []Tool

All returns every tool the registry lets the model see, sorted by name.

func (*ToolRegistry) BindExecutionContext

func (r *ToolRegistry) BindExecutionContext(ec ExecutionContext, allow []string) (*ToolRegistry, []string, error)

BindExecutionContext owns fresh native tools and local MCP servers. It never derives a live view of another member's registry. Required tool patterns fail launch when no compatible tool can satisfy them.

func (*ToolRegistry) ChangeTracker

func (r *ToolRegistry) ChangeTracker() ChangeTracker

ChangeTracker returns the registry's tracker, or its nearest ancestor's.

func (*ToolRegistry) Close

func (r *ToolRegistry) Close() error

Close cleans up all resources

func (*ToolRegistry) CommitPendingChanges

func (r *ToolRegistry) CommitPendingChanges()

CommitPendingChanges applies staged skill activations between agent turns.

func (*ToolRegistry) ContextFilePaths

func (r *ToolRegistry) ContextFilePaths(ctx context.Context, root string) ([]string, error)

ContextFilePaths walks the workspace in-process, applying .gitignore files from outer to inner directories. Explicit reads are independent of ignores.

func (*ToolRegistry) Count

func (r *ToolRegistry) Count() int

Count reports how many tools the registry holds; a nil registry holds none.

func (*ToolRegistry) Derive

func (r *ToolRegistry) Derive(opts ...DeriveOption) *ToolRegistry

Derive returns a registry that sees this registry's tools through the options' allow-list and shares its MCP clients and sandbox policy, for a caller that needs a narrower or separately governed tool set (a subagent, say) without starting the servers again. The derived registry is a full registry of its own: tools it registers or loads are private to it and shadow the parent's, its skill policy and always-allowed set are its own, and closing it releases only what it loaded itself. A parent tool stays subject to the parent's policy as well, and the parent closing empties every registry derived from it. The allow-list bounds every tool but the derived registry's own always-allowed built-ins.

func (*ToolRegistry) ExecuteTool

func (r *ToolRegistry) ExecuteTool(ctx context.Context, tool Tool, args map[string]any, timeout time.Duration) (result ToolExecution, err error)

ExecuteTool invokes a tool already resolved and approved by the caller. It owns the per-tool timeout, execution gate, and rich-output dispatch. The returned error is the tool's original error (or an error acquiring the gate); ContextErr separately reports cancellation or timeout, including when a tool returns successfully after its context ends. Panics propagate after releasing the gate and timeout resources.

func (*ToolRegistry) ExecutionPolicy

func (r *ToolRegistry) ExecutionPolicy(root string, grant ExecutionGrant) (ExecutionContext, error)

ExecutionPolicy narrows the parent's grants. Workspace-dependent write roots are replaced; inherited deny rules, non-credential read grants and network policy are retained. A read-only grant with a scratch writes only there; without one it keeps the all-writes-denied policy. An operator's denyWrite base still wins.

func (*ToolRegistry) ExecutionRoot

func (r *ToolRegistry) ExecutionRoot() string

func (*ToolRegistry) ExecutionSkills

func (r *ToolRegistry) ExecutionSkills() *skills.Catalog

func (*ToolRegistry) Get

func (r *ToolRegistry) Get(name string) (Tool, bool)

Get retrieves a tool by name

func (*ToolRegistry) GetActiveToolLoaders

func (r *ToolRegistry) GetActiveToolLoaders() []ToolLoaderInfo

GetActiveToolLoaders returns loader information for all tools This returns one entry per tool to allow selective loading

func (*ToolRegistry) GetIfAllowed

func (r *ToolRegistry) GetIfAllowed(name string) (tool Tool, exists bool, allowed bool)

GetIfAllowed retrieves a tool by name, returning existence and allowance in a single lock acquisition. A derived registry's own tools come first; a parent's tool must pass the parent's policy, then this registry's allow-list and policy.

func (*ToolRegistry) GetSchemas

func (r *ToolRegistry) GetSchemas() []*schema.ToolSchema

GetSchemas returns all tool schemas. Schemas are built after the registry lock is released: a tool's GetSchema may consult the registry (bash cross-references the loaded file tools).

func (*ToolRegistry) GuardExecution

func (r *ToolRegistry) GuardExecution(ctx context.Context, tool Tool) (func(), error)

GuardExecution must surround the actual tool invocation with a deferred release. Callers invoking tools outside llm.Agent can use the same boundary.

func (*ToolRegistry) HasNativeTool

func (r *ToolRegistry) HasNativeTool(name string) bool

HasNativeTool reports whether name is a built-in tool this registry can load, loaded or not. Session restoration uses it to drop a tool that a saved session names but Polly no longer ships.

func (*ToolRegistry) HasSandbox

func (r *ToolRegistry) HasSandbox() bool

HasSandbox reports whether sandboxing is available.

func (*ToolRegistry) LoadMCPServer

func (r *ToolRegistry) LoadMCPServer(serverSpec string) (LoadResult, error)

LoadMCPServer connects to an MCP server and registers its tools with namespace For multi-server configs (mcpServers format), loads ALL servers

func (*ToolRegistry) LoadMCPServerWithFilter

func (r *ToolRegistry) LoadMCPServerWithFilter(serverSpec string, allowedTools []string) error

LoadMCPServerWithFilter connects to an MCP server and only registers specified tools serverSpec format: "path/to/config.json#servername"

func (*ToolRegistry) LoadMCPServerWithNamespacePrefix

func (r *ToolRegistry) LoadMCPServerWithNamespacePrefix(serverSpec, namespacePrefix string) (LoadResult, error)

LoadMCPServerWithNamespacePrefix loads all servers from a config file with an explicit namespace prefix.

func (*ToolRegistry) LoadShellTool

func (r *ToolRegistry) LoadShellTool(path string) (LoadResult, error)

LoadShellTool loads a single shell tool from a file path with the default namespace.

func (*ToolRegistry) LoadShellToolWithNamespace

func (r *ToolRegistry) LoadShellToolWithNamespace(path, namespace string) (LoadResult, error)

LoadShellToolWithNamespace loads a single shell tool from a file path with an explicit namespace; an empty namespace derives one from the path.

func (*ToolRegistry) LoadToolAuto

func (r *ToolRegistry) LoadToolAuto(pathOrServer string) (LoadResult, error)

LoadToolAuto attempts to load a tool, auto-detecting if it's native, shell tool, or MCP server

func (*ToolRegistry) MarkAlwaysAllowed

func (r *ToolRegistry) MarkAlwaysAllowed(name string)

MarkAlwaysAllowed exempts a tool from active skill allowlist filtering.

func (*ToolRegistry) NewSandbox

func (r *ToolRegistry) NewSandbox(overlay *sandbox.Config) (sandbox.Sandbox, error)

NewSandbox creates a sandbox with the base config merged with optional per-tool overrides.

func (*ToolRegistry) NewSandboxDirect

func (r *ToolRegistry) NewSandboxDirect(cfg sandbox.Config) (sandbox.Sandbox, error)

NewSandboxDirect creates a sandbox from an explicit config, ignoring the base config.

func (*ToolRegistry) ReadContextFile

func (r *ToolRegistry) ReadContextFile(ctx context.Context, path string, maxBytes int64) (string, []byte, error)

ReadContextFile reads a complete regular file under the registry's read policy. It fails rather than truncating when the file exceeds maxBytes.

func (*ToolRegistry) Register

func (r *ToolRegistry) Register(tool Tool)

Register adds a tool to the registry

func (*ToolRegistry) RegisterNative

func (r *ToolRegistry) RegisterNative(name string, factory func() Tool)

RegisterNative registers a native tool factory

func (*ToolRegistry) Remove

func (r *ToolRegistry) Remove(namespacedName string)

Remove removes a tool by namespaced name from the registry

func (*ToolRegistry) ResolvePath

func (r *ToolRegistry) ResolvePath(path string) (string, error)

func (*ToolRegistry) SandboxReadPolicy

func (r *ToolRegistry) SandboxReadPolicy() (cfg sandbox.Config, active bool, err error)

SandboxReadPolicy returns the prepared base sandbox config when process sandboxing is active, for checking in-process reads and writes via sandbox.ReadAllowed and sandbox.WriteAllowed. active is false when no sandbox factory is configured, in which case in-process access is unrestricted just like wrapped commands.

func (*ToolRegistry) SetChangeTracker

func (r *ToolRegistry) SetChangeTracker(tracker ChangeTracker)

SetChangeTracker attaches tracker to the registry. Bash tools loaded before the call use it from then on.

func (*ToolRegistry) SetExecutionGate

func (r *ToolRegistry) SetExecutionGate(gate *ExecutionGate)

SetExecutionGate attaches a runtime's gate to its parent registry. Bound execution contexts have independent registries and do not inherit this gate.

func (*ToolRegistry) UnsafeNoSandbox

func (r *ToolRegistry) UnsafeNoSandbox() bool

type UntimedTool

type UntimedTool interface {
	Tool
	Untimed() bool
}

UntimedTool is implemented by tools whose calls outlast any per-tool timeout by design, such as one that runs a whole child agent. The agent loop skips its tool timeout for them; the call still ends with the turn's context.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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