tools

package
v0.0.0-...-bd244ef Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 45 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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 that line counts are unavailable.
	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     = 39 << 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, about 9,984 estimated tokens, so a page is never itself externalized to an artifact at the default 10,000-token inline limit; an agent whose requests keep a lower limit lowers the cap with WithPageBytes.

View Source
const OutputDirEnv = "POLLYTOOL_OUTPUT_DIR"

OutputDirEnv names the context's output directory to its processes: the place a worker leaves files for whoever reads its result. The runtime that owns the scratch captures what is there when the work completes.

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 ErrNativeToolsRequired = errors.New("registry has no native tool setup; construct it with WithNativeTools or supply tools through OpenTools")

ErrNativeToolsRequired reports a registry without native tool setup asked to bind an execution context or to build native tools.

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.

View Source
var RexToolNames = []string{
	"rex_inspect",
	"rex_layout",
	"rex_terminal",
	"rex_lua",
	"rex_api",
	"rex_client",
}

RexToolNames lists the opt-in native Rex tool names registered by WithNativeTools. None are loaded into a registry until explicitly selected.

Functions

func CapPageText

func CapPageText(ctx context.Context, text string) string

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

func Coordinates

func Coordinates(tool Tool) bool

Coordinates reports whether tool declares trusted orchestration behavior at the execution gate.

func Error

func Error(message, code string) string

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

func ExclusiveBatch

func ExclusiveBatch(tool Tool) bool

ExclusiveBatch reports whether tool requires being the sole call in a batch.

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 KillProcessGroups

func KillProcessGroups(pgids []int) []int

KillProcessGroups kills every listed group still alive and reports the ones it killed. Callers pass groups detached from a bound registry.

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 OutputDir

func OutputDir(scratch string) string

OutputDir is the output directory of a context with the given scratch.

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 PageBytes

func PageBytes(ctx context.Context) int

PageBytes is the page cap under ctx: PageMaxBytes unless WithPageBytes lowered it.

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 ParentOnly

func ParentOnly(tool Tool) bool

ParentOnly reports whether tool declares itself restricted to the parent session and excluded from derived child registries using DenyParentOnly.

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 ReadArtifactFile

func ReadArtifactFile(ctx context.Context, registry *ToolRegistry, path string, maxBytes int64) (blob artifacts.Blob, err error)

ReadArtifactFile captures the exact bytes of a regular file, resolving path against registry's execution root and enforcing its read policy. maxBytes bounds both the initial size and the bytes read if the file grows. It never silently truncates a capture. The caller owns persistence and publication.

func ReadsOnly

func ReadsOnly(tool Tool) bool

ReadsOnly reports whether tool declares that its calls only read.

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 RestoreArtifact

func RestoreArtifact(ctx context.Context, registry *ToolRegistry, path string, ref artifacts.Ref, source io.ReadCloser) (abs string, err error)

RestoreArtifact streams an already-authorized artifact into a NEW regular file, returning its absolute path. It owns and closes source on every path. The destination directory must exist and permit writes to both the explicit destination and a temporary sibling. The completed file is linked into place only after size, SHA-256, read/close and sync checks succeed. No source mode is preserved: the new file is private (0600, subject to umask), never executable.

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. Wrappers implementing Unwrap() Tool are unwrapped first.

func Untimed

func Untimed(tool Tool) bool

Untimed reports whether tool declares itself exempt from per-tool timeouts.

func ValidateAgentSandboxPreset

func ValidateAgentSandboxPreset(spec string) error

ValidateAgentSandboxPreset validates an explicit child sandbox preset without filesystem access or mutations. Omission is represented by no preset, not an empty string. Filesystem resolution and backend validation happen at child binding.

func WithPageBytes

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

WithPageBytes caps the pages tools return under ctx at n bytes, within PageMaxBytes.

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

func (t *BashTool) BindExecutionContext(bound *ToolRegistry, _ ExecutionContext) (Tool, error)

BindExecutionContext rebuilds bash from the bound registry's own factory, under the context's root and policy.

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. The explicit env is not copied: the sandbox carries the policy env itself, and a sandbox that does not implement ExplicitEnvSandbox would refuse the command.

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 binds a tool to a new execution context: the built-ins and shell tools implement it, and custom Go tools may. A tool that neither rebinds nor declares independence is 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 DenyParentOnly

func DenyParentOnly() DeriveOption

DenyParentOnly hides every inherited parent tool that declares itself parent-only (via ParentOnlyTool, including through ToolWrapper layers) from the derived registry, even if AllowTools matches it or the parent marked it always-allowed or built-in. Tools the derived registry registers directly on itself remain visible.

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:"-"`
	// contains filtered or unexported fields
}

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 {
	// SandboxPresets are ordered restrictions: the operator's child-default
	// floor, then the agent's own preset. Each can only narrow earlier policy.
	// An empty slice preserves ordinary inheritance.
	SandboxPresets []string
	// 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, TMP and TEMP. It is the only
	// writable path of a read-only context. A missing or nested scratch fails
	// closed.
	Scratch string
	// SourceRoot is the workspace the root was made from, such as the
	// checkout a member's worktree copies. An env value a sandbox layer
	// points inside it is rebased into the root, so the context uses its own
	// copy of a workspace path.
	SourceRoot 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 or omitted
	// because the file or the diff exceeded a limit. CountsUnknown marks
	// omitted or approximate line counts.
	Truncated     bool `json:"truncated,omitempty"`
	Binary        bool `json:"binary,omitempty"`
	CountsUnknown bool `json:"counts_unknown,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 string, 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 {
	// ObservedAt orders host-generated workspace reports; per-tool deltas omit it.
	ObservedAt time.Time `json:"observed_at,omitzero"`
	// 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
	ReadOnly    bool
	ParentOnly  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) IsParentOnly

func (f *Func) IsParentOnly() bool

func (*Func) ReadsOnly

func (f *Func) ReadsOnly() bool

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 NewUnsafeMCPClientContext

func NewUnsafeMCPClientContext(ctx context.Context, serverSpec string) (*MCPClient, error)

NewUnsafeMCPClientContext is NewUnsafeMCPClient with cancellable connection and initialization. After success the caller owns the client until Close; cancellation of ctx does not close a successfully opened client.

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

func (*MCPClient) ListToolsContext

func (c *MCPClient) ListToolsContext(ctx context.Context) ([]Tool, error)

ListToolsContext discovers tools using ctx, without transferring ownership of the client or closing it when the request is cancelled.

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 the base policy, an object such as
	// {"allowNetwork":true,"writablePaths":[...]} for overrides, false to
	// opt out.
	Sandbox sandbox.Declaration `json:"sandbox,omitzero"`
}

MCPConfig represents the JSON configuration for an MCP server

func (*MCPConfig) SandboxConfig

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

SandboxConfig returns the server's declared sandbox overrides, or nil when it declared none.

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 a deep copy of 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) IsParentOnly

func (n *NamespacedTool) IsParentOnly() bool

func (*NamespacedTool) ReadsOnly

func (n *NamespacedTool) ReadsOnly() bool

func (*NamespacedTool) RecallStub

func (n *NamespacedTool) RecallStub() string

func (*NamespacedTool) Untimed

func (n *NamespacedTool) Untimed() bool

func (*NamespacedTool) Unwrap

func (n *NamespacedTool) Unwrap() Tool

type NativeOption

type NativeOption func(*nativeOptions)

NativeOption configures NativeOpenTools.

func WithNativeInstructions

func WithNativeInstructions(load func(*ToolRegistry) string) NativeOption

WithNativeInstructions supplies the repository guidance loader a native binding renders into ToolBinding.Instructions, given the bound registry so it reads under the binding's own policy.

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 OpenTools

type OpenTools func(context.Context, ToolScope) (ToolBinding, error)

OpenTools constructs the tools an agent loop runs with, bound to one workspace and one authority. An application supplies the function; the coordinator, the standalone runner, and workflow hosts call it for every binding they need and never choose an implementation themselves. NativeOpenTools builds polly's process-backed tools; another implementation supplies Tool values of its own.

func NativeOpenTools

func NativeOpenTools(source *ToolRegistry, opts ...NativeOption) OpenTools

NativeOpenTools returns the OpenTools that rebinds source's native tools, shell tools, MCP servers, and skills to each scope: the sandbox policy is narrowed to the scope's root and grant, every tool is constructed afresh against that policy, and the skill catalog is rendered into ToolInstructions. The source must have been constructed with WithNativeTools. The caller validates its selection once its own tools are registered (see ToolRegistry.ValidateToolSelection); the binding only reports what it omitted.

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 ParentOnlyTool

type ParentOnlyTool interface {
	Tool
	IsParentOnly() bool
}

ParentOnlyTool is implemented by tools bound to the parent session, UI, or caller identity (such as delegation, session title, theme, sandbox setup, or parent coordination tools) that derived child registries must not inherit when DenyParentOnly is used.

type ReadOnlyTool

type ReadOnlyTool interface {
	Tool
	ReadsOnly() bool
}

ReadOnlyTool is implemented by a tool whose calls only read: they change no file, leave no process running, send nothing to a peer and write no coordination record. Repeating such a call, or never learning that it ran, loses nothing, so a host that journals tool batches for recovery leaves out a batch made only of them. A tool that does not say acts on the world.

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 WithNativeTools

func WithNativeTools() RegistryOption

WithNativeTools installs polly's built-in tools: constructors for bash and the file tools, loaded by name, and view_image, registered at once and marked built-in. Without it a registry serves only the tools registered on it, which is what an independently supplied toolset needs: derivation and execution binding never add native tools of their own.

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 WithSandboxLayer

func WithSandboxLayer(name string, layer SandboxLayer) RegistryOption

WithSandboxLayer adds the named layer to the registry's sandbox policy from the start; SetSandboxLayer says what a layer reaches. Like WithSandboxFactory it prepares the layer when the option is created, and a preparation error surfaces when the registry first builds a process tool's sandbox. A later option with the same name replaces the layer.

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 SandboxChange

type SandboxChange struct {
	// Rebuilt names, once each, the loaded or staged bash and shell tools
	// rebuilt here or in a derived registry under the changed policy.
	Rebuilt []string
	// StaleServers names, by tool namespace, the loaded stdio MCP servers a
	// change to the base did not reach: a running server keeps the policy it
	// started with until it is loaded again. Layers never reach servers, so
	// a layer change leaves it empty.
	StaleServers []string
}

SandboxChange reports how a change to a registry's sandbox policy reached the tools it has loaded.

type SandboxEnvironment

type SandboxEnvironment struct {
	Storage                             SandboxStorage
	Roots                               SandboxStorageRoots
	Env                                 map[string]string
	CheckoutCacheRoot, CheckoutDataRoot string
}

SandboxEnvironment describes the managed part of a layer. The host prepares Roots before publishing it. Env values are allocation references, not paths. Explicit Members settings override these defaults.

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 SandboxLayer

type SandboxLayer struct {
	// Config is merged over the base for the registry's own commands and
	// in-process file checks, and for the registries derived from it.
	Config sandbox.Config
	// Members is what a context bound by ExecutionPolicy takes from the
	// layer; the zero value gives it nothing. ExecutionPolicy judges it the
	// way it judges the base: a read or socket grant the context's denials
	// cover is dropped, write grants reach only a writable context, and an
	// env value inside the context's source root is rebased into its root.
	Members     sandbox.Config
	Environment *SandboxEnvironment
}

SandboxLayer is a named overlay of a registry's sandbox policy that can be set, replaced and removed while the registry runs (see SetSandboxLayer).

type SandboxStorage

type SandboxStorage = envstorage.Spec

type SandboxStorageRoots

type SandboxStorageRoots = envstorage.Roots

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

func (s *ShellTool) BindExecutionContext(bound *ToolRegistry, ec ExecutionContext) (Tool, error)

BindExecutionContext runs the script in the context's root under the context's policy. The script's own sandbox entry may only narrow that policy: its restrictions are kept and its grants dropped.

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

func (t *SkillActivateTool) BindExecutionContext(bound *ToolRegistry, ec ExecutionContext) (Tool, error)

BindExecutionContext installs the rebound skill runtime in bound and returns its copy of this tool.

func (*SkillActivateTool) Execute

func (t *SkillActivateTool) Execute(ctx 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) BindExecutionContext

func (t *SkillReadFileTool) BindExecutionContext(bound *ToolRegistry, ec ExecutionContext) (Tool, error)

BindExecutionContext installs the rebound skill runtime in bound and returns its copy of this tool.

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

func (*SkillReadFileTool) ReadSkillFile

func (t *SkillReadFileTool) ReadSkillFile(skillName, relPath string) (string, error)

ReadSkillFile returns the exact contents of a file inside a discovered skill, under the same catalog and read policy as the tool call. Hosts use it to load a skill's file themselves instead of having a model copy the text.

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

type ToolBinding struct {
	Registry *ToolRegistry
	// Instructions is repository and general guidance for the model;
	// ToolInstructions is guidance about the bound tools and skills. The
	// caller inserts each under its own rules.
	Instructions     string
	ToolInstructions string
	// Omitted names the tools the caller's selection or the binding could
	// not honor, for diagnostics.
	Omitted []string
	// Close releases the binding. It is never nil on success and is safe to
	// call more than once.
	Close func() error
}

ToolBinding is an opened toolset. The caller owns it: agents derive their private views from Registry and close them first, then the caller closes the binding, which releases every resource the binding opened.

type ToolCall

type ToolCall = messages.ToolCall

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 = messages.ToolLoaderInfo

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, err 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. A failure closes the servers already connected, since the caller gets no registry to close.

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. Native tools (bash, the file tools, view_image) come only with WithNativeTools; a registry without it serves the tools registered on it.

func (*ToolRegistry) All

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

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

func (*ToolRegistry) AppendBaseReadPaths

func (r *ToolRegistry) AppendBaseReadPaths(paths ...string) (SandboxChange, error)

AppendBaseReadPaths adds canonical extra read directories to the frozen base sandbox config as read-only grants. The registry freezes the caller-approved base authority once (see preparedBaseSandboxConfig) and never re-prepares the original spellings, so a mid-session add must prepare the new paths on their own and merge: the merged entries are frozen exactly once here, and Config.Merge preserves every identity already frozen. After the call, SandboxReadPolicy, the loaded bash and shell tools (rebuilt, see SandboxChange), every later sandbox, and every registry derived via Derive, before or after, see the new paths; a stdio MCP server already running keeps its snapshot until it is loaded again. Missing paths are dropped by preparation and grant nothing, without error. Without a sandbox factory — or under WithUnsafeNoSandbox — there is no policy to widen, so the call is a documented no-op; the caller still records the list on the session. A derived registry shares its parent's policy and refuses the call. The merged grant list is not re-minimized: overlapping grants are harmless because the deepest rule wins, and the persisted session list is deduplicated by sandbox.MergeExtraReadDirs.

func (*ToolRegistry) BaseSandboxPolicy

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

BaseSandboxPolicy is SandboxReadPolicy without the sandbox layers: the prepared base, which Polly's own processes, such as the worktree package's runtime Git, start from. A registry bound to an execution context returns the context's policy.

func (*ToolRegistry) BeginEnvironmentMaintenance

func (r *ToolRegistry) BeginEnvironmentMaintenance() (func(), error)

BeginEnvironmentMaintenance gates every local execution, including derived agents and bound members. It never waits while an executing tool holds it.

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; the registry's built-ins count. The receiver must have native tool setup. NativeOpenTools is the same binding without the final selection check, which its callers run once their own tools are registered.

func (*ToolRegistry) BindExecutionContextWithContext

func (r *ToolRegistry) BindExecutionContextWithContext(ctx context.Context, ec ExecutionContext, allow []string) (*ToolRegistry, []string, error)

BindExecutionContextWithContext is BindExecutionContext with cancellable MCP setup. Synchronous host-supplied ContextTool constructors must still return before cancellation can be observed. The caller owns a successful binding.

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 detaches owned resources before shutting them down. External shutdown can block its caller, but never holds the tool-map or shared policy lock.

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. The sandbox policy is the parent's own, not a copy: a later change to it (AppendBaseReadPaths or SetSandboxLayer) reaches the derived registry's policy checks and rebuilds its loaded and staged process tools as well as the parent's.

func (*ToolRegistry) DetachProcessGroups

func (r *ToolRegistry) DetachProcessGroups() []int

DetachProcessGroups hands back the process groups the registry's commands left running and forgets them: the caller now owns their reaping, and Close no longer kills them. An unbound registry tracks none.

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. After any wait on the gate it confirms the handle is still the registered, allowed tool for its name and never substitutes another; a replaced, foreign, or newly disallowed handle is not invoked. The returned error is the tool's original error (or an error acquiring the gate or checking the handle); 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, read grants (explicit credential grants included), Unix-socket 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. The member parts of the sandbox layers (see SandboxLayer) count as the base does, and their write grants and env reach the context too: the write grants only when the context may write, and each env value inside the grant's SourceRoot rebased into the root.

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

func (r *ToolRegistry) LoadMCPServerContext(ctx context.Context, serverSpec string) (LoadResult, error)

LoadMCPServerContext connects, initializes and discovers using ctx. Failed or cancelled construction releases partial clients; success transfers ownership to the registry, independently of ctx's subsequent cancellation.

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

func (r *ToolRegistry) LoadMCPServerWithFilterContext(ctx context.Context, serverSpec string, allowedTools []string) error

LoadMCPServerWithFilterContext is the cancellable restoration loader. Like the convenience method, it uses the saved config without context rebinding.

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

func (r *ToolRegistry) LoadMCPServerWithNamespacePrefixContext(ctx context.Context, serverSpec, namespacePrefix string) (LoadResult, error)

LoadMCPServerWithNamespacePrefixContext is the cancellable namespace loader.

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

func (r *ToolRegistry) MarkBuiltin(name string)

MarkBuiltin keeps a registered tool visible through every view derived from this registry and every execution context bound from it, whatever their allow-lists select, and exempts it from skill allowlist filtering. Native setup marks view_image; an independently supplied toolset marks its own equivalents.

func (*ToolRegistry) NewSandbox

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

NewSandbox creates a sandbox with the policy a process tool starts from — the base config and its layers — 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) PlanningReaders

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

PlanningReaders returns just the native text and directory readers selected and allowed on this registry, never a namesake from MCP, a script or a ReadOnly-marked plugin. The private turn registry must not inherit any other handles (including the always-allowed tools of ordinary derived views).

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

func (r *ToolRegistry) RegisterArtifactRestore(tool Tool)

RegisterArtifactRestore is retained for callers installing restore_artifact.

func (*ToolRegistry) RegisterNative

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

RegisterNative registers a native tool factory

func (*ToolRegistry) RegisterPrivateMutation

func (r *ToolRegistry) RegisterPrivateMutation(tool Tool)

RegisterPrivateMutation installs an agent's private mutation without the always-allowed exemption of its recall tools. Unlike ordinary local tool registrations, it remains subject to the source registry's current tool selection and skill policies, even though the source does not own this tool.

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

func (r *ToolRegistry) RestartMCPServer(namespace string) (LoadResult, error)

RestartMCPServer starts the MCP server whose tools carry namespace again and swaps it in for the running one. A stdio server picks up the registry's current sandbox policy that way (a directory added with AppendBaseReadPaths, say), and a hung server gets a fresh process. The server's config is read again, and the registry keeps the tools it holds for the server: one the new process no longer offers is dropped, a new one is not added. The replacement starts before the running server stops, so when it cannot start, or offers none of the tools, the running server stays in place. Only a server this registry loaded itself restarts, and callers serialize a restart with calls to the server's tools.

func (*ToolRegistry) RestartMCPServerContext

func (r *ToolRegistry) RestartMCPServerContext(ctx context.Context, namespace string) (LoadResult, error)

RestartMCPServerContext is RestartMCPServer with cancellable construction. Calls to the old server still need caller serialization; shutdown after a successful swap is synchronous, outside registry locks.

func (*ToolRegistry) RunTrial

func (r *ToolRegistry) RunTrial(ctx context.Context, command string, candidate sandbox.Config) (TrialResult, error)

RunTrial runs command with bash in the registry's execution root under a trial policy, the policy bash starts from (the base and its layers) merged with candidate, and reports what the sandbox denied it. The registry's own policy does not change: the candidate reaches this one command. The command has the trial policy's full reach, like a bash call, so a trial is something the user chose to run. What it observes is evidence of what the command reached for, not proof that a grant is needed or safe (see sandbox.DenialObserver). Where denials cannot be observed the command still runs, and Observation.Incomplete says why nothing was seen.

A command that fails is a result, not an error. RunTrial returns an error when the command could not run at all, including when ctx ends it.

func (*ToolRegistry) SandboxContext

func (r *ToolRegistry) SandboxContext() (string, error)

SandboxContext describes current registry authority for model requests. It contains no environment values and is not an enforcement mechanism. Call it for each request: layers can change during a turn, while bound execution contexts retain their own policy. A registry with no sandbox configuration contributes no context; explicit unsafe mode is reported separately.

func (*ToolRegistry) SandboxPolicyRevision

func (r *ToolRegistry) SandboxPolicyRevision() uint64

SandboxPolicyRevision changes after a successful base or layer update. Derived views share the owner's revision. Reading it does not prepare a sandbox; hosts can invalidate cached bindings without native construction.

func (*ToolRegistry) SandboxReadPolicy

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

SandboxReadPolicy returns the policy in-process reads and writes are checked against, via sandbox.ReadAllowed and sandbox.WriteAllowed, when process sandboxing is active: the prepared base with every sandbox layer merged in name order, which is also the policy a bash or shell tool starts from before its own overlay, so a file tool reaches what a command reaches. A registry bound to an execution context returns the context's policy. 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) SetSandboxLayer

func (r *ToolRegistry) SetSandboxLayer(name string, layer *SandboxLayer) (SandboxChange, error)

SetSandboxLayer replaces the named layer of the registry's sandbox policy, or removes it when layer is nil, then rebuilds the loaded and staged bash and shell tools, including derived registries' own tools, under the result the way AppendBaseReadPaths does. A layer's Config is merged over the base, in name order and before a tool's own overlay, into the sandboxes of bash, shell tools and NewSandbox and into SandboxReadPolicy, which the in-process file tools check, so it can widen or narrow what the registry's commands and file tools reach and be taken back mid-session. Registries derived via Derive share it. Its Members part reaches the contexts ExecutionPolicy binds from then on; a context bound earlier keeps the policy it was bound with. A layer never reaches stdio MCP servers, which a narrowing change could not rebuild, shell-tool schema discovery, or BaseSandboxPolicy. Without a sandbox factory, or under WithUnsafeNoSandbox, the call does nothing.

func (*ToolRegistry) SetSandboxLayerAndCommit

func (r *ToolRegistry) SetSandboxLayerAndCommit(name string, layer *SandboxLayer, commit func() error) (SandboxChange, error)

SetSandboxLayerAndCommit stages the same rebuild as SetSandboxLayer, calls commit, then publishes the rebuilt policy and tools. A commit failure leaves the previous policy and tool instances intact. The callback must not call registry methods: it runs under the policy lock. Without an active sandbox factory the callback is not called, matching SetSandboxLayer's no-op behavior.

func (*ToolRegistry) TryEnvironmentUse

func (r *ToolRegistry) TryEnvironmentUse() (func(), error)

TryEnvironmentUse lets host controls fail promptly instead of blocking their UI event loop behind background cleanup.

func (*ToolRegistry) UnsafeNoSandbox

func (r *ToolRegistry) UnsafeNoSandbox() bool

func (*ToolRegistry) ValidateToolSelection

func (r *ToolRegistry) ValidateToolSelection(allow []string, builtins []string) error

ValidateToolSelection reports the first pattern of a tool selection that names nothing: no tool this registry serves and none of builtins, the names a caller registers privately after binding. A nil or empty selection is valid; an empty one disables tools rather than requiring any. Callers run it once every tool the selection may name is registered.

type ToolScope

type ToolScope struct {
	Root string
	// SourceRoot overrides Grant.SourceRoot when nonempty.
	SourceRoot string
	Grant      ExecutionGrant
	ReadPaths  []string
	// AllowedTools narrows the binding: nil inherits every tool, an empty
	// slice disables tools, and patterns select by name or glob. A binding
	// keeps its built-ins whatever the selection names.
	AllowedTools []string
	// Gate, when set, serialises the binding's tool executions with the
	// owner's exclusive operations. Isolated bindings leave it nil.
	Gate *ExecutionGate
}

ToolScope is what a binding is opened for: the workspace root the tools operate on, the source checkout it was made from (for rebinding operator-selected paths), the authority the coordinator grants beyond reading the root, extra read access such as the owning Git directory, the caller's tool selection, and the execution gate shared with an integrating parent. The deepest rule containing a path decides its access.

type ToolWrapper

type ToolWrapper interface {
	Tool
	Unwrap() Tool
}

ToolWrapper is an optional interface implemented by wrappers that delegate to an inner Tool. Implementing Unwrap allows trait helpers (ReadsOnly, RecallStub, SandboxDetails, ParentOnly, Untimed, ExclusiveBatch, Coordinates) and execution binding to see through arbitrary wrappers.

type TrialResult

type TrialResult struct {
	// ExitCode is the command's exit status, or 128 plus the signal that
	// ended it.
	ExitCode int
	// Output is what the command printed, standard output and error
	// interleaved, bounded like bash's.
	Output string
	// Observation is what the sandbox denied the command, each denial's
	// cause classified against Policy.
	Observation sandbox.Observation
	// Policy is the trial's prepared policy: the one bash starts from merged
	// with the candidate.
	Policy sandbox.Config
}

TrialResult is what one sandbox trial saw.

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