Documentation
¶
Overview ¶
Package tools provides TaskSmith's generic tool execution container, typed tool specification builder, custom workspace command tool adapter, and session permission and policy evaluation gate.
Index ¶
- Constants
- Variables
- func ActivationBlocks(container Container, cat *workspace.Catalog, resolvedTools []*warp.Tool) []message.Block
- func CheckMCPResourceAllowed(ws *workspace.Workspace, serverName, uri string) error
- func ReadMCPResource(ctx context.Context, ws *workspace.Workspace, caller MCPCaller, ...) (api.MCPResourceResponse, error)
- func ReadOnlyExecutionFromContext(ctx context.Context) bool
- func Spill(ctx context.Context, text string) string
- func TruncateSkillInstructions(rendered, skillPath string) (string, bool)
- func UnsandboxedExecutionFromContext(ctx context.Context) bool
- func WithPlanReviewOutcome(ctx context.Context, outcome PlanReviewOutcome) context.Context
- func WithReadOnlyExecution(ctx context.Context, readOnly bool) context.Context
- func WithSpiller(ctx context.Context, s Spiller) context.Context
- func WithUnsandboxedExecution(ctx context.Context, unsandboxed bool) context.Context
- type AccessDecision
- type CommandRunner
- type Config
- type Container
- type Handler
- type MCPCaller
- type MCPProhibitedError
- type Metadata
- type Plan
- type PlanReviewOutcome
- type SafeWriter
- type Spec
- type SpillWriter
- type Spiller
- type SpillerConfig
- type Tool
Constants ¶
const ( DefaultSpillMaxBytes = 32 * 1024 // 32 KB DefaultSpillMaxLines = 500 // 500 lines DefaultSpillHeadLines = 100 // 100 lines DefaultSpillTailLines = 100 // 100 lines DefaultSpillMaxDiskBytes = 16 * 1024 * 1024 // 16 MB safety cap on spilled file size )
Default thresholds and slice sizes for tool output spilling.
Variables ¶
var ( ErrInvalidConfig = errors.New("tools: invalid configuration") ErrToolNotFound = errors.New("tools: tool not found") ErrPermissionDenied = errors.New("tools: permission denied") )
Sentinel errors returned by the tools package.
Functions ¶
func ActivationBlocks ¶
func ActivationBlocks(container Container, cat *workspace.Catalog, resolvedTools []*warp.Tool) []message.Block
ActivationBlocks activates a command or skill's policy-allowed tools into the model's context: a ToolReferenceBlock for each deferred tool registered in container, and an inline ToolDefinitionBlock for any policy-allowed tool in cat that is not registered in container. Tools are deduplicated by name.
func CheckMCPResourceAllowed ¶
CheckMCPResourceAllowed verifies that serverName does not prohibit uri under its current spec.policies.resources filter. It returns nil when ws or the server is unresolved so Prepare can defer unknown-server diagnostics to Execute while blocking prohibited resources before permission prompts.
func ReadMCPResource ¶
func ReadMCPResource(ctx context.Context, ws *workspace.Workspace, caller MCPCaller, serverName, uri string, allowProhibited bool) (api.MCPResourceResponse, error)
ReadMCPResource reads one resource URI from a named MCP server through ws's attached runtime. Unless allowProhibited is set — which only a user acting interactively may do, never the agent — a resource the server manifest's spec.policies.resources blocks is rejected with an *MCPProhibitedError naming the manifest. A missing runtime, unknown server, or blank argument is reported as a descriptive error.
func ReadOnlyExecutionFromContext ¶
ReadOnlyExecutionFromContext reports whether ctx was tagged for read-only child-process execution.
func Spill ¶
Spill applies output spilling via the Spiller in ctx, or returns text unchanged if no Spiller is registered.
func TruncateSkillInstructions ¶
TruncateSkillInstructions caps rendered skill instructions at the default spill line/byte budget and appends navigational guidance when truncated.
func UnsandboxedExecutionFromContext ¶
UnsandboxedExecutionFromContext reports whether ctx was tagged for unsandboxed child-process execution.
func WithPlanReviewOutcome ¶
func WithPlanReviewOutcome(ctx context.Context, outcome PlanReviewOutcome) context.Context
WithPlanReviewOutcome attaches the resolved plan review outcome to ctx.
func WithReadOnlyExecution ¶
WithReadOnlyExecution marks ctx so tools that spawn child processes request a per-command read-only kernel profile. Passing false returns ctx unchanged.
func WithSpiller ¶
WithSpiller binds a Spiller into the context.
func WithUnsandboxedExecution ¶
WithUnsandboxedExecution marks ctx so execution-capable tools skip the kernel sandbox wrapper for the child process of this tool call. Passing false returns ctx unchanged. The harness tags this only from a plan the permission engine approved as unsandboxed (bypass_sandbox, an excludedCommands match, or a direct user shell command).
Types ¶
type AccessDecision ¶
type AccessDecision string
AccessDecision represents the policy evaluation outcome.
const ( AccessAllow AccessDecision = "allow" AccessAsk AccessDecision = "ask" AccessDeny AccessDecision = "deny" )
type CommandRunner ¶
type CommandRunner interface {
Exec(ctx context.Context, req std.ExecRequest) (*std.ExecResult, error)
}
CommandRunner executes a program inside the session environment without shell interpretation and synchronizes external file changes afterwards. Satisfied by *std.Std, mirroring how the harness narrows Std.Bash behind BashRunner; custom tools depend only on this seam.
type Config ¶
type Config struct {
Tools []Tool
Sandbox sandbox.Sandbox
Workspace *workspace.Workspace
Logger log.Interface
Spiller Spiller
AllowedTools []string
// Agent is the active agent definition, injected into custom tool render
// options so command and instruction templates can reference
// {{.Agent.Name}} and {{.Agent.Description}}. It may be nil for agentless
// sessions, in which case those template fields resolve to empty values.
Agent *warp.Agent
// DeferredTools is the set of tool names that should be withheld from the
// initial model context (DeferLoading: true) and instead discovered via
// tool_search. Deferred tools must also appear in AllowedTools so that they
// are constructed and registered in the container; they are merely held back
// from the first request's tool definitions.
DeferredTools []string
// ToolSearchFactory constructs the built-in tool_search tool from the
// deferred tools' definitions. It is invoked (and tool_search registered)
// only when there is at least one deferred tool.
ToolSearchFactory func(defs []tool.Definition) Tool
// MCPCaller is the MCP runtime used to execute tools discovered on MCP
// servers. When nil, no MCP tool is registered: the servers stay discoverable
// in listings but nothing can invoke their tools.
MCPCaller MCPCaller
// CommandRunner is the execution surface command-backed custom tools run
// through (satisfied by the session's *std.Std), so process output
// synchronizes external file changes into the change journal like the
// built-in bash tool.
CommandRunner CommandRunner
// Tasks is the session's background task registry. Command-backed custom
// tools run as tasks so a slow tool auto-backgrounds at the wait window
// instead of blocking the turn indefinitely.
Tasks tasks.Store
}
Config holds the mandatory dependencies required to construct a Container.
type Container ¶
type Container interface {
Definitions() []tool.Definition
List() []Tool
Get(name string) (Tool, bool)
Prepare(ctx context.Context, tc *message.ToolCall) (*Plan, error)
Execute(ctx context.Context, tc *message.ToolCall) (*message.Tool, error)
}
Container manages registered Tool instances, custom workspace command tools, and two-phase Prepare/Execute orchestration.
type Handler ¶
type Handler[In, Out any] interface { Prepare(ctx context.Context, in In) (*Plan, error) Execute(ctx context.Context, in In) (Out, error) }
Handler is implemented by strongly typed tools with two-phase Prepare and Execute methods.
type MCPCaller ¶
type MCPCaller interface {
// CallMCPTool executes rawToolName on the named server and streams its
// result. rawToolName is the server's own tool name, not the materialized
// "<server>__<tool>" name the agent calls.
CallMCPTool(ctx context.Context, serverName, rawToolName string, args map[string]any) (tool.ToolStream, error)
// ReadMCPResource reads one resource URI from the named server.
ReadMCPResource(ctx context.Context, serverName, uri string, allowProhibited bool) (api.MCPResourceResponse, error)
// GetMCPPrompt renders one prompt discovered on the named server. It backs
// daemon-side `/mcp:<server>:<prompt>` execution so every client gets the
// same prompt rendering through a single `Send`.
GetMCPPrompt(ctx context.Context, serverName, prompt string, args map[string]string, allowProhibited bool) (api.MCPPromptResponse, error)
// HasAllowedMCPResources reports whether any server exposes a resource that
// spec.policies permits.
HasAllowedMCPResources() bool
}
MCPCaller is the transport contract the tools package needs from an MCP manager. It is deliberately narrower than the workspace MCPService surface: a tool container only invokes tools and reads resources, never manages connections, so the MCP manager satisfies it through a small adapter without the tools package depending on the manager implementation.
Implementations must be safe for concurrent use.
type MCPProhibitedError ¶
type MCPProhibitedError struct {
Kind string // "tool" or "resource"
Item string
Section string // e.g. "spec.policies.tools"
ManifestPath string
}
MCPProhibitedError reports an MCP item that a server manifest's spec.policies prohibits. It is a hard block for the agent: the message names the manifest so the user can relax the policy, and the container surfaces it to the model as an error result.
func (*MCPProhibitedError) Error ¶
func (e *MCPProhibitedError) Error() string
type Metadata ¶
type Metadata struct {
Title string
Description string
Annotation tool.Annotation
DeferLoading bool
InputSchema map[string]any
}
Metadata provides display and permission metadata for a tool.
type Plan ¶
type Plan struct {
ToolCallID string `json:"tool_call_id"`
ToolName string `json:"tool_name"`
Action api.ActionType `json:"action"`
Safety api.SafetyLevel `json:"safety"`
Target string `json:"target,omitempty"`
// Paths holds the additional workspace-relative, slash-separated target paths
// touched by the invocation (e.g. a bash command's CWD and file operands, or
// the paths surfaced by a search/listing result). It is used by rule
// matching to evaluate triggers.globs against every path in play, not just
// the primary Target.
Paths []string `json:"paths,omitempty"`
Summary string `json:"summary"`
Diff string `json:"diff,omitempty"`
ReadOnly bool `json:"read_only,omitempty"`
// Reversible marks a mutating or deleting plan whose prior state is
// snapshotted by the daemon so /revert can restore it cleanly.
Reversible bool `json:"reversible,omitempty"`
// InsideWorkspace reports whether a file-targeted plan resolves inside the
// workspace root. Nil when the plan does not target a single file path.
InsideWorkspace *bool `json:"inside_workspace,omitempty"`
// ProtectedPath reports whether the plan targets or references a protected
// control-plane, secret, XDG policy, or sensitive host path.
ProtectedPath bool `json:"protected_path,omitempty"`
// ScriptPaths holds local script paths referenced by a shell plan for
// bounded review inspection.
ScriptPaths []string `json:"script_paths,omitempty"`
// Unsandboxed marks a plan whose child process runs directly on the host
// instead of inside the kernel sandbox (bash bypass_sandbox or an
// excludedCommands match). The harness tags their execution context
// accordingly.
Unsandboxed bool `json:"unsandboxed,omitempty"`
// BypassSandbox distinguishes a model-requested bypass_sandbox plan from
// a trusted excludedCommands match: bypass plans are isolated into the
// bash_unsandboxed(...) rule namespace so regular bash(...) allow rules
// can never auto-approve an unsandboxed retry, while excluded matches
// flow through normal bash(...) rules and modes.
BypassSandbox bool `json:"bypass_sandbox,omitempty"`
// PlanReview carries the validated plan path and Markdown preview when
// exit_plan_mode prepares a plan review interrupt.
PlanReview *api.PlanReviewRequest `json:"-"`
}
Plan describes the pre-flight impact and unified diff preview of a validated tool invocation produced by Tool.Prepare or Container.Prepare.
func PlanFromAnnotation ¶
func PlanFromAnnotation(name string, ann tool.Annotation, target, defaultSummary string) *Plan
PlanFromAnnotation derives a Plan from a manifest's safety annotations and the invocation's target. It is exported so built-in tools whose effect depends on an external server can share the exact mapping command-backed and MCP tools use, instead of restating the annotation precedence.
type PlanReviewOutcome ¶
type PlanReviewOutcome struct {
Approved bool
Mode api.PermissionMode
Feedback string
}
PlanReviewOutcome carries the user's review decision when resuming an exit_plan_mode interrupt in the harness.
func PlanReviewOutcomeFromContext ¶
func PlanReviewOutcomeFromContext(ctx context.Context) (PlanReviewOutcome, bool)
PlanReviewOutcomeFromContext retrieves the plan review outcome from ctx, if set.
type SafeWriter ¶
type SafeWriter struct {
// contains filtered or unexported fields
}
SafeWriter guards an io.WriteCloser against writes that race a late Close: backgrounded tasks can still be flushing process output when the tool call that launched them finishes and closes the underlying spill writer. Writes after Close are counted but discarded instead of failing or panicking.
func NewSafeWriter ¶
func NewSafeWriter(w io.WriteCloser) *SafeWriter
NewSafeWriter wraps a spill writer so task goroutines can keep writing after the owning tool call closes it.
func (*SafeWriter) Close ¶
func (sw *SafeWriter) Close()
type Spec ¶
type Spec[In, Out any] struct { Name string Title string Description string Annotation tool.Annotation DeferLoading bool InputSchema map[string]any Prepare func(ctx context.Context, in In) (*Plan, error) Execute func(ctx context.Context, in In) (Out, error) }
Spec defines a strongly typed Tool backed by Go input and output types.
type SpillWriter ¶
type SpillWriter interface {
io.WriteCloser
// String returns the full output if within limits, or the truncated
// head + notice + tail preview if spilled to disk.
String() string
// Spilled reports whether the output exceeded thresholds and was written to disk.
Spilled() bool
// Path returns the path to the spilled file on disk, or "" if not spilled.
Path() string
}
SpillWriter streams tool output, spilling to disk if limits are exceeded, and produces a truncated preview.
func NewSpillWriter ¶
func NewSpillWriter(ctx context.Context) SpillWriter
NewSpillWriter returns a streaming SpillWriter bound to the Spiller in ctx, or an in-memory passthrough writer if no Spiller is registered.
type Spiller ¶
type Spiller interface {
Spill(ctx context.Context, text string) string
NewWriter(ctx context.Context) SpillWriter
}
Spiller intercepts large tool output and spills the full content to disk, returning a truncated preview with navigational guidance.
func NewSpiller ¶
func NewSpiller(cfg SpillerConfig) (Spiller, error)
NewSpiller constructs a new Spiller from cfg.
type SpillerConfig ¶
type SpillerConfig struct {
BaseDir string // base directory (e.g. from xdg.WorkspaceDir(rootDir)); required if Workspace is nil
Workspace *workspace.Workspace
MaxBytes int
MaxLines int
HeadLines int
TailLines int
MaxDiskBytes int
}
SpillerConfig configures the Spiller.
type Tool ¶
type Tool interface {
Name() string
Definition() tool.Definition
Prepare(ctx context.Context, args map[string]any) (*Plan, error)
Execute(ctx context.Context, call *message.ToolCall) (*message.Tool, error)
// SetDeferLoading marks the tool for deferred loading. Deferred tools are
// withheld from the initial model context until discovered via tool_search.
SetDeferLoading(deferLoading bool)
}
Tool is an executable LLM-callable tool with two-phase Prepare and Execute lifecycle hooks.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package builtin provides the embedded WARP tool manifests (*.tool.md), generated tool-name constants, and standard library adapters for Tasksmith's built-in system tools (view, ls, glob, grep, write, edit, remove, bash, web_fetch, and download).
|
Package builtin provides the embedded WARP tool manifests (*.tool.md), generated tool-name constants, and standard library adapters for Tasksmith's built-in system tools (view, ls, glob, grep, write, edit, remove, bash, web_fetch, and download). |