tools

package
v0.56.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package tools provides the tool registry and execution framework.

Index

Constants

View Source
const (
	// ApprovedByRule: the policy let the call run without asking (read-only
	// or agent-state tool, approval auto, an MCP rule).
	ApprovedByRule = "rule"
	// ApprovedByUser: the person was asked and allowed it.
	ApprovedByUser = "user"
	// ApprovedAlways: the person had answered "always" for this tool.
	ApprovedAlways = "always"
	// AskedAndDenied: the person was asked and refused.
	AskedAndDenied = "user_denied"
	// ApprovedByTrust: trust mode let an ask through without a person (not
	// emitted until the trust tier is wired in).
	ApprovedByTrust = "trust"
)

Approval sources (ApprovalReport.Source).

View Source
const (
	// DefaultInlineOutputBytes is the default inline threshold: a tool result
	// larger than this is not kept whole in the session (tools.max_output_bytes).
	DefaultInlineOutputBytes = 8000
	// DefaultRawOutputBytes is the default cap on the raw output one tool call
	// may produce before the output layer sees it (tools.max_spill_bytes).
	DefaultRawOutputBytes = 1 << 20

	// OutputMetaKey is the ToolResult.Metadata key the output layer writes its
	// OutputInfo under (a nested map, so tool-defined keys are never touched).
	OutputMetaKey = "output"
)
View Source
const (

	// DefaultSearchLimit and MaxSearchLimit bound tool_search results.
	DefaultSearchLimit = 5
	MaxSearchLimit     = 10
)
View Source
const (
	SearchEventSearch   = "tool_search"
	SearchEventAutoLoad = "auto_load"
)

Search event kinds reported through Visibility's event callback.

View Source
const ApprovedResultNote = "[已经人工批准执行]"

ApprovedResultNote goes after (annotateApproved) the model-visible tool result of a call a person approved this time (ApprovalReport.Answered, the ACP allow/allow_always answer and the chat y/a answer). It tells the model truth about who let the call run; it is never added for a rule- or remembered-always allowed call.

View Source
const (
	// OriginWindow is the shortest verbatim piece that counts as copied. 12 bytes
	// (until suga-we1v) matched common phrases a model writes on its own
	// ("API definitions", " credentials: ") once a spec had been fetched; a
	// copied command or script is usually far longer than 40 bytes.
	OriginWindow = 40
)

External-origin tracking (suga-42m8): text a web or MCP tool brought into the context is remembered as hashes of its 40-byte windows, so an approval can tell that the arguments of a write or exec call carry a verbatim piece of it (the practical prompt-injection signal: the model copies a fetched command straight into shell_exec or file_write).

View Source
const ToolCallName = "tool_call"

ToolCallName is the always-registered proxy tool through which the model calls a deferred native tool that is loaded but not in the tool table yet (tools.deferred_apply: segment). The provider probe of 2026-10-23 showed that models do not call tools missing from the request's tools field, so the segment mode needs this proxy (design Q9).

Variables

View Source
var DefaultNativeDeferredTools = []string{
	"agent",
	"file_symbols",
	"memory",
	"recall",
	"session_search",
	"session_message",
	"skill",
	"suga_manifest",
	"web_fetch",
}

DefaultNativeDeferredTools is the built-in deferred set of tools.deferred_native: auto (design 2026-10-23 section 2.1). The list is chosen by call frequency, not schema size: these tools cost ~13.4k characters of every request and are used a handful of times per session at most.

View Source
var ErrAborted = errors.New("tool approval aborted")

ErrAborted marks an approval that could not be completed (the approver was cancelled or the turn context ended). Unlike ErrDenied it must end the turn: the runner's tool policy fails the turn instead of turning it into a tool result.

View Source
var ErrCannotAsk = errors.New("no interactive terminal to ask for approval")

ErrCannotAsk means nobody can be asked (no interactive terminal, or the asker is not bound yet). Approvers turn it into a refusal (fail closed).

View Source
var ErrDenied = errors.New("tool call denied")

ErrDenied is the sentinel for a tool call refused by a permission layer (approval gate, read-only mode ...). The observe layer uses it to tell a denial from an ordinary tool failure.

Functions

func Denied

func Denied(msg string) error

Denied returns an error that prints as msg and satisfies errors.Is(err, ErrDenied).

func InvocationID

func InvocationID(ctx context.Context) string

InvocationID returns the id of the tool invocation running with ctx, or "" when ctx carries none (outside a tool call). The id is stable for the whole call - hooks before and after the tool, the tool itself - and unique within a session: the runtime builds it from the run id and the provider's call id.

func IsMCP

func IsMCP(t api.Tool) bool

IsMCP reports whether t is backed by an MCP server.

func MCPServerOf

func MCPServerOf(t api.Tool) string

MCPServerOf returns the configured server name of an MCP tool, or "".

func NativePurpose

func NativePurpose(name, description string) string

NativePurpose returns the listing line text of a deferred native tool: the built-in purpose for the default list, else a shortened schema description.

func ParseNativeDeferred

func ParseNativeDeferred(raw any) ([]string, error)

ParseNativeDeferred parses a tools.deferred_native value: unset or "never" defers no native tool, "auto" selects DefaultNativeDeferredTools, and a YAML list (or a single name) is taken as the explicit set.

func ReportApproval

func ReportApproval(ctx context.Context, source string, wait time.Duration)

ReportApproval records the source and the person's answer time in ctx's report, if any.

func ReportApprovalAnswer

func ReportApprovalAnswer(ctx context.Context, source string, wait time.Duration)

ReportApprovalAnswer is ReportApproval plus Answered: the person answered a prompt in this very call and let it run (allow once or allow always; either way the model-visible result gets the human-approved note, see annotateApproved). Later calls with ReportApproval(ApprovedAlways, 0) come from a remembered session rule, not from a fresh answer, and stay unmarked.

func ReportDanger

func ReportDanger(ctx context.Context, reason string)

ReportDanger records in ctx's report why the call is dangerous.

func ReportOriginJudge added in v0.55.0

func ReportOriginJudge(ctx context.Context, decision, reason string, tokens int)

ReportOriginJudge records the external-origin judge's verdict ("allow", "deny", "ask" or "error"), its reason and the tokens it spent in ctx's report.

func ReportRule

func ReportRule(ctx context.Context, summary, scope string)

ReportRule records the stable rule summary and optional session scope in the current approval report. Empty values deliberately mean that no matching rule or session scope was available.

func TruncateHeadTail

func TruncateHeadTail(s string, limit int) string

TruncateHeadTail keeps the head and tail of s within limit bytes (UTF-8 safe) and notes how many bytes were omitted in between. The tail usually holds errors and exit status, so both ends are kept. limit <= 0 returns s.

func WithInvocationID

func WithInvocationID(ctx context.Context, id string) context.Context

WithInvocationID returns a context carrying id as the id of the tool call that is about to run. The runtime sets it once per call, before the BeforeTool hooks, so a hook, the tool itself and the AfterTool hooks all read the same value (InvocationID). A host's in-process tool (wiring.Options. ExtraTools) reads it the same way and may use it as the idempotency key of its own side-effect ledger (see pkg/sugasdk).

Types

type Approval

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

Approval is the permission layer of the tool registry stack (order: observe -> visibility -> approval -> base). Every call that reaches it is resolved against the base registry and handed to the Approver before it runs. Unloaded deferred tools never get here (visibility answers them first), so they never trigger an approval prompt.

func NewApproval

func NewApproval(inner interface {
	api.ToolRegistry
	Lookup
}, approver Approver) *Approval

NewApproval wraps inner with approver. A nil approver denies every call (fail closed), so a runtime opened without a policy cannot run tools.

func (*Approval) ExecuteTool

func (a *Approval) ExecuteTool(ctx context.Context, call api.ToolCall) (*api.ToolResult, error)

func (*Approval) Get

func (a *Approval) Get(name string) (api.Tool, error)

Get passes tool lookup through so outer layers can still classify tools.

func (*Approval) ListTools

func (a *Approval) ListTools(ctx context.Context) ([]api.ToolSchema, error)

func (*Approval) SetDisabled

func (a *Approval) SetDisabled(hints map[string]string)

SetDisabled names the known tools that are off in this runtime (write tools in read-only mode, web_search without a key) with an enable hint. A call to one of them is refused with ErrDenied, so repeated attempts count toward the denial limit; any other unknown name is a plain error that does not count.

func (*Approval) SetOnApproved

func (a *Approval) SetOnApproved(fn ApprovedCallFunc)

SetOnApproved installs the callback that runs after the approval decision allowed a call and before the tool executes. A refused call never reaches it, and neither does a decision cancelled or timed out at the prompt (those abort the turn instead of producing a result). It has to be set before the first turn runs.

func (*Approval) SetRewriter

func (a *Approval) SetRewriter(rewriter CallRewriter)

SetRewriter installs the pre-decision rewriter (chat's PreToolUse hook). It narrows a call before the policy sees it; it never replaces the decision, so a rewriter cannot let a call through that the approver refuses.

type ApprovalMode added in v0.55.0

type ApprovalMode string

ApprovalMode is the approval tier an entry point starts with. It only ever comes from a start-up flag or an SDK option, never from a config file.

const (
	// ApprovalModeDefault ("") keeps each entry point's own behaviour.
	ApprovalModeDefault ApprovalMode = ""
	// ApprovalModeAsk asks for every call the policy does not allow.
	ApprovalModeAsk ApprovalMode = "ask"
	// ApprovalModeAuto allows native calls without asking.
	ApprovalModeAuto ApprovalMode = "auto"
	// ApprovalModeTrust is auto plus letting unprotected asks through.
	ApprovalModeTrust ApprovalMode = "trust"
)

func ParseApprovalMode added in v0.55.0

func ParseApprovalMode(s string) (ApprovalMode, error)

ParseApprovalMode validates s: "", "ask", "auto" or "trust" (exact, no trimming or case folding, so a typo cannot silently pick a tier).

type ApprovalReport

type ApprovalReport struct {
	Source string
	Wait   time.Duration
	// Danger is why the call needed a stricter decision (a dangerous delete
	// command), "" for an ordinary call.
	Danger string
	// Rule is the stable summary of the representative approval rule. An empty
	// value means no declarative rule matched the call (the policy default ran).
	Rule string
	// Scope is the session rule's scope key; it is empty for user, project and
	// legacy rules, and for calls without a representative rule.
	Scope string
	// Answered marks a call the person was asked about in this very call and
	// allowed (allow_once, and the allow_always of the same prompt: the person
	// did approve this call). Later calls a remembered "always" rule lets
	// through are not Answered, so the model-visible note is not added there.
	Answered bool
	// OriginJudge is the verdict of the external-origin judge ("allow", "deny",
	// "ask"), "" when the call was not judged. OriginJudgeReason is its
	// redacted, truncated reason; OriginJudgeTokens the tokens it spent
	// (input + output).
	OriginJudge       string
	OriginJudgeReason string
	OriginJudgeTokens int
}

ApprovalReport says how a call was approved: who decided and how long the person took to answer. The observing layer puts one in the context (WithApprovalReport) and reads it after the call; approvers that ask a person fill it in (ReportApproval); a call the Approver let through without reporting is ApprovedByRule.

func WithApprovalReport

func WithApprovalReport(ctx context.Context) (context.Context, *ApprovalReport)

WithApprovalReport returns ctx carrying a fresh report.

type ApprovedCallFunc

type ApprovedCallFunc func(ctx context.Context, call api.ToolCall, tool api.Tool)

ApprovedCallFunc is the callback of the approval layer that runs once a call passed the decision and right before the tool executes (SetOnApproved). It is the seam for a host's record of what is about to have effects (the admit ledger of internal/personal), so that record is never written for a call the person refused or a prompt that was cancelled. It cannot refuse the call: a failure to record must not stop the tool.

type Approver

type Approver interface {
	Decide(ctx context.Context, call api.ToolCall, tool api.Tool) error
}

Approver decides whether one tool call may run.

Decide returns nil to allow the call. An error matching ErrDenied (see Denied) refuses it: the model gets the message as a tool error and the turn continues. Any other error (typically context.Canceled from a cancelled approval prompt) aborts the turn; it is returned wrapped so it matches both ErrAborted and the original cause.

type ApproverFunc

type ApproverFunc func(ctx context.Context, call api.ToolCall, tool api.Tool) error

ApproverFunc adapts a function to Approver.

func (ApproverFunc) Decide

func (f ApproverFunc) Decide(ctx context.Context, call api.ToolCall, tool api.Tool) error

type Asker

type Asker interface {
	Ask(ctx context.Context, q Question) (string, error)
}

Asker asks the person a question and returns the typed answer line. ErrCannotAsk means nobody can answer; any other error (the person pressed Ctrl-C, the turn was cancelled) aborts the turn.

type BindableAsker

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

BindableAsker is an Asker whose implementation is bound after the runtime is assembled (chat binds its terminal input once it exists). Unbound, it answers ErrCannotAsk, so every question is refused until a terminal is bound.

func NewBindableAsker

func NewBindableAsker() *BindableAsker

NewBindableAsker returns an unbound asker.

func (*BindableAsker) Ask

func (b *BindableAsker) Ask(ctx context.Context, q Question) (string, error)

Ask forwards to the bound asker, or returns ErrCannotAsk when none is bound.

func (*BindableAsker) Bind

func (b *BindableAsker) Bind(asker Asker)

Bind sets the asker that answers from now on; nil unbinds it.

type CallExpander

type CallExpander interface {
	ExpandCall(ctx context.Context, call api.ToolCall) (api.ToolCall, bool)
}

CallExpander is a tool layer that expands a proxy tool call (tool_call) into the real tool call. It is structural (the runtime asserts it on the outermost registry), so every wrapper between the runtime and Visibility has to forward it, otherwise a proxied call would reach approval/repo layers as tool_call.

type CallRewriter

type CallRewriter interface {
	Rewrite(ctx context.Context, call api.ToolCall, tool api.Tool) (api.ToolCall, error)
}

CallRewriter is an optional extension of an Approver: it reprocesses a call before the permission decision (a hook rewrites the arguments). The approval layer runs it first and then decides on the rewritten call, so a change can never be approved on the arguments it replaced.

type Category

type Category string

Category is a protocol-neutral class of what a tool does. Hosts map it onto their own vocabulary (e.g. ACP tool kinds) and approval prompts.

const (
	CategoryRead Category = "read"
	CategoryEdit Category = "edit"
	// CategoryDelete removes files (file_remove).
	CategoryDelete  Category = "delete"
	CategoryExecute Category = "execute"
	CategorySearch  Category = "search"
	CategoryFetch   Category = "fetch"
	CategoryThink   Category = "think"
	// CategoryOther is the default for tools that declare nothing.
	CategoryOther Category = "other"
)

type DeferredApplyMode

type DeferredApplyMode string

DeferredApplyMode is the tools.deferred_apply setting: when a loaded native tool joins the tool table. MCP tools keep the immediate behaviour.

const (
	// DeferredApplySegment folds loaded tools into the table at a segment
	// boundary only, so the tool prefix stays byte-identical within a segment.
	DeferredApplySegment DeferredApplyMode = "segment"
	// DeferredApplyImmediate lists a tool as soon as it is loaded.
	DeferredApplyImmediate DeferredApplyMode = "immediate"
)

func ParseDeferredApplyMode

func ParseDeferredApplyMode(s string) (DeferredApplyMode, error)

ParseDeferredApplyMode validates a tools.deferred_apply value; empty means segment (the default of the setting).

type DeferredMode

type DeferredMode string

DeferredMode is the tools.deferred setting.

const (
	// DeferredAuto defers MCP tools only when their schemas are large relative
	// to the context window.
	DeferredAuto DeferredMode = "auto"
	// DeferredAlways always defers MCP tools.
	DeferredAlways DeferredMode = "always"
	// DeferredNever sends every tool directly.
	DeferredNever DeferredMode = "never"
)

func ParseDeferredMode

func ParseDeferredMode(s string) (DeferredMode, error)

ParseDeferredMode validates a tools.deferred value; empty means auto.

type Describer

type Describer interface {
	ToolMeta() Meta
}

Describer is the optional interface a tool implements to declare its Meta.

type ExternalOrigin added in v0.53.0

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

ExternalOrigin remembers the text of external tool results per session. The zero value is not usable; use NewExternalOrigin. It is safe for concurrent use.

func NewExternalOrigin added in v0.53.0

func NewExternalOrigin() *ExternalOrigin

NewExternalOrigin returns an empty tracker.

func (*ExternalOrigin) Find added in v0.53.0

func (o *ExternalOrigin) Find(session string, args map[string]any) (OriginHit, bool)

Find looks for a piece of at least OriginWindow bytes of a remembered result in the string values of args (nested maps and lists included). Whitespace runs are compared as one space.

func (*ExternalOrigin) FindIgnoringURLs added in v0.54.8

func (o *ExternalOrigin) FindIgnoringURLs(session string, args map[string]any) (OriginHit, bool)

FindIgnoringURLs is Find with every http(s) URL in args left out of the comparison (suga-we1v): a file write that names a fetched page's URL in a comment or a config is not a copied instruction, while a command that runs a fetched URL is still checked with Find.

func (*ExternalOrigin) Record added in v0.53.0

func (o *ExternalOrigin) Record(session, tool, text string)

Record remembers text, the result of tool, for session.

type Kind

type Kind string

Kind classifies the runtime type of a tool.

const (
	KindNative Kind = "native"
	KindMCP    Kind = "mcp"
)

func KindOf

func KindOf(t api.Tool) Kind

KindOf returns the runtime kind of t: its Kind() when it implements Kinded, KindNative otherwise (including a nil tool).

type Kinded

type Kinded interface {
	Kind() Kind
}

Kinded is implemented by tools that report their runtime kind. It is optional: a tool without it is native (see KindOf).

type LoadedStore

type LoadedStore interface {
	LoadedTools(ctx context.Context) ([]string, error)
	SaveLoadedTools(ctx context.Context, names []string) error
}

LoadedStore persists the session's loaded deferred tool names. The session is identified by ctx, so this package stays independent of the session layer.

type Lookup

type Lookup interface {
	Get(name string) (api.Tool, error)
}

Lookup is the query capability wrapping registry layers (observe, visibility, approval) pass through so permission code can still resolve a tool's Kind and MCP server name behind them.

type MCPServerNamer

type MCPServerNamer interface {
	MCPServer() string
}

MCPServerNamer is implemented by MCP-backed tools so permission checks know which configured server a tool came from.

type Meta

type Meta struct {
	Category Category
	// ReadOnly marks tools without side effects outside the session (reading
	// files, searching, fetching, updating the plan): approval layers may run
	// them without asking, and read-only tool sets keep only them.
	ReadOnly bool
	// External marks tools whose results come from outside the workspace
	// (web pages, search results): the session is flagged as tainted once such
	// a result enters the context.
	External bool
	// Rereadable marks tools that paginate on their own (the model can re-read
	// the rest by calling again): output wrapping layers neither truncate nor
	// externalise their results.
	Rereadable bool
	// AgentState marks tools that only change the agent's own state (e.g.
	// memory). Approval layers let them through without asking; the tool
	// itself decides whether a write is allowed in the current run mode
	// (e.g. read-only). Never honoured for MCP tools.
	AgentState bool
	// Prefetchable marks tools that only read local files and keep no state,
	// so a reply's calls to them may run ahead concurrently (Registry.Prefetch).
	// Never honoured for MCP tools.
	Prefetchable bool
	// Hidden marks a tool that stays registered and callable by name but is not
	// listed in the tool table (ListTools), the manifest or tool_search: an alias
	// of another tool kept for one version, so old sessions and name-based
	// configuration keep working (view_image, design 2026-10-23 Q4).
	Hidden bool
}

Meta describes a tool for permission decisions.

func MetaOf

func MetaOf(t api.Tool) Meta

MetaOf returns t's declared Meta. A tool without Describer, a nil tool and every MCP tool get {CategoryOther, ReadOnly: false, AgentState: false, Rereadable: false}; MCP results are always External. MCP tools are never trusted as read-only, agent-state or rereadable by name or declaration, so an MCP tool cannot pose as a built-in to bypass approval.

type ModelTexts

type ModelTexts struct {
	// ApprovedNote ends the result of a call a person approved right now
	// (ApprovedResultNote when empty).
	ApprovedNote string
	// OutputSavedRef heads an oversized result stored under a ref:
	// %d bytes, %d lines, %s ref.
	OutputSavedRef string
	// OutputCondensed opens the note replacing a result by its tidied text:
	// %d bytes, %d lines.
	OutputCondensed string
	// OutputCondensedRef continues that note with the ref of the original: %s ref.
	OutputCondensedRef string
}

ModelTexts is the model-facing wording the tool stack appends to results and hints, for the host to inject by language (i18n phase 1b). The zero value is the historical Chinese text, so a run that injects nothing — and a run with language: zh — keeps its model requests byte-identical; a host resolving language: en fills the fields from its catalog (internal/i18n/catalog/*/model.ini, see internal/wiring).

The values carry the format verbs of their line, which a translation must keep: the layer formats the line with fmt.Sprintf. Names of tools, arguments and ref markers are part of the model's protocol and stay as is.

func DefaultModelTexts

func DefaultModelTexts() ModelTexts

DefaultModelTexts returns the historical Chinese wording.

type OriginHit added in v0.53.0

type OriginHit struct {
	// Tool is the tool whose result held the text.
	Tool string
	// Snippet is the start of the copied piece, as found in the arguments.
	Snippet string
}

OriginHit is a verbatim piece of an external result found in call arguments.

type Output

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

Output is the output-governance layer of the tool registry stack (order: observe -> output -> visibility -> approval -> base). Results up to InlineBytes pass unchanged; larger ones are replaced by a ref line plus a head/tail snippet, with the full text handed to the Spiller. Tools that paginate on their own (Meta.Rereadable) pass through untouched, and errors are never rewritten, so denial accounting in outer layers is unaffected.

func NewOutput

func NewOutput(inner api.ToolRegistry, cfg OutputConfig) *Output

NewOutput wraps inner with output governance.

func (*Output) ExecuteTool

func (o *Output) ExecuteTool(ctx context.Context, call api.ToolCall) (*api.ToolResult, error)

ExecuteTool runs the wrapped stack and then notes a call the person approved: the note is added here, above output governance, so a minimizer or a truncation cannot drop it from the result the model reads.

func (*Output) ExpandCall

func (o *Output) ExpandCall(ctx context.Context, call api.ToolCall) (api.ToolCall, bool)

ExpandCall forwards the proxy-call expansion (tool_call) of the wrapped layer, so the runtime still sees the real tool call.

func (*Output) Get

func (o *Output) Get(name string) (api.Tool, error)

Get passes tool lookup through to the wrapped layers.

func (*Output) ListTools

func (o *Output) ListTools(ctx context.Context) ([]api.ToolSchema, error)

type OutputConfig

type OutputConfig struct {
	// InlineBytes is the largest result kept whole (<=0 = DefaultInlineOutputBytes).
	InlineBytes int
	// Spiller stores oversized results; nil means they are only truncated.
	Spiller Spiller
	// Sanitize, when set, cleans an oversized result (e.g. redacts secrets)
	// before its OutputInfo is computed, it is spilled and the snippet is cut,
	// so the recorded hash matches the stored file.
	Sanitize func(string) string
	// Minimize, when set, may return a tidied version of a successful result
	// (test summaries, collapsed repeats, no colour codes). The original is
	// then spilled and the result carries the tidy text plus its ref, so
	// nothing is lost; ok=false leaves the result alone.
	Minimize func(call api.ToolCall, content string) (tidy string, ok bool)
	// Texts is the model-facing wording of the layer (the approved note and
	// the ref/condensed headers). The zero value is the historical Chinese
	// text; a host injects another language's wording (see ModelTexts).
	Texts ModelTexts
}

OutputConfig configures NewOutput.

type OutputInfo

type OutputInfo struct {
	Ref    string // empty when the output was only truncated
	Bytes  int
	Lines  int
	SHA256 string
	// Minimized marks a result replaced by OutputConfig.Minimize's tidy text.
	Minimized bool
}

OutputInfo describes the raw output behind a shortened result. Bytes, Lines and SHA256 are computed over the raw text after OutputConfig.Sanitize, i.e. exactly what the Spiller stored.

func OutputInfoOf

func OutputInfoOf(md map[string]any) (OutputInfo, bool)

OutputInfoOf reads the OutputInfo the output layer recorded in md. It accepts both in-memory values (int) and JSON round-tripped ones (float64).

type PrefetchExempt

type PrefetchExempt interface {
	// SkipPrefetch reports whether this call must not run ahead.
	SkipPrefetch(args map[string]any) bool
}

PrefetchExempt is the optional interface a Prefetchable tool implements to skip the run-ahead for a single call: it stays Prefetchable for its other calls. Registry.Prefetch asks it after the static Meta filter, once per call with that call's arguments (file_read reads pictures, and decoding one for a step that is cut away is wasted work - design 2026-10-23-file-read-images).

type Question

type Question struct {
	// Tool is the name of the tool to approve.
	Tool string
	// Details are the full key arguments (command, path, query), already
	// redacted and never truncated; one entry per item, may span lines.
	Details []string
	// Prompt is the line the answer is typed on.
	Prompt string
}

Question is one approval prompt for the person at the terminal.

type Registry

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

Registry holds all registered tools and dispatches calls.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty Registry.

func (*Registry) ExecuteTool

func (r *Registry) ExecuteTool(ctx context.Context, call api.ToolCall) (*api.ToolResult, error)

ExecuteTool dispatches a public tool call to a registered tool.

func (*Registry) Get

func (r *Registry) Get(name string) (api.Tool, error)

Get returns the tool with the given name, or an error if not found.

func (*Registry) List

func (r *Registry) List() []string

List returns the names of all registered tools.

func (*Registry) ListTools

func (r *Registry) ListTools(context.Context) ([]api.ToolSchema, error)

ListTools exposes registered schemas through the agentcore tool-registry contract.

func (*Registry) MustRegister

func (r *Registry) MustRegister(t api.Tool)

MustRegister is like Register but does not panic — it overwrites.

func (*Registry) Prefetch

func (r *Registry) Prefetch(ctx context.Context, calls []api.ToolCall)

Prefetch starts the Prefetchable calls of one model reply concurrently (agentcore.Config.PrefetchTools). Every call still goes through the whole registry stack in order - hooks, approval, taint tracking, observation, output wrapping - and only on reaching ExecuteTool here takes the result run ahead, provided its arguments are unchanged; a call refused on the way just leaves its result unused. Only side-effect-free local tools are prefetchable, so running one that is then refused changes nothing. Runs of an earlier reply that were never taken are forgotten. Fewer than two prefetchable calls start nothing.

func (*Registry) Register

func (r *Registry) Register(t api.Tool)

Register adds a tool to the registry. Panics on duplicate name.

func (*Registry) Remove

func (r *Registry) Remove(name string)

Remove drops the tool with the given name; an unregistered name is ignored. The host uses it for a policy the model must not even see (a disabled tool is missing from Schemas and from ToolSearch, not merely refused on call).

func (*Registry) Schemas

func (r *Registry) Schemas() []api.ToolSchema

Schemas returns the ToolSchema list for all registered tools in deterministic order. A Hidden tool (view_image, an alias of file_read's picture branch) is left out: it stays callable by name, but the model is not offered it (design 2026-10-23 Q4).

func (*Registry) TryRegister

func (r *Registry) TryRegister(t api.Tool) bool

TryRegister adds a tool unless the name is already taken; it never overwrites and reports whether the tool was added. Earlier registrations win.

type SearchEvent

type SearchEvent struct {
	Kind        string // SearchEventSearch or SearchEventAutoLoad
	Query       string
	Hits        []string
	NewlyLoaded []string
	// CacheInvalidated is true when the loaded set changed (the tool prefix of
	// the next model request differs, so the provider cache is invalidated).
	CacheInvalidated bool
}

SearchEvent describes one load action for the observe layer.

type SearchHit

type SearchHit struct {
	Name        string
	Description string
	// Params is the compact parameter list ("a(integer), b(string)") so the model
	// can call the tool with the right arguments without seeing the full schema.
	Params        string
	AlreadyLoaded bool // loaded before this search
}

SearchHit is one tool_search match.

type SearchResult

type SearchResult struct {
	Hits        []SearchHit
	NewlyLoaded []string
	// Missing lists names a select: query asked for that are not deferred tools.
	Missing []string
}

SearchResult is the outcome of Visibility.Search.

type Spiller

type Spiller interface {
	Spill(ctx context.Context, call api.ToolCall, content string) (ref string, err error)
}

Spiller stores the full text of an oversized tool result outside the session history and returns a ref the model can use to read it back. Implementations take the session/turn from ctx; an error makes the output layer fall back to plain head/tail truncation.

type ToolCallProxy

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

ToolCallProxy is the always-registered proxy tool of the segment apply mode: it lets the model call a deferred native tool that is already loaded while the tool table stays unchanged (design Q9, provider probe 2026-10-23).

The runtime expands a proxy call into the real tool call before execution (agentcore.CallExpander), so approval, the PreToolUse hook, taint handling and the trace all see the real tool name. Execute keeps the same path as a fallback for a caller that does not expand: it runs the real tool through the inner layers, never around them.

func NewToolCallProxy

func NewToolCallProxy(v *Visibility) *ToolCallProxy

NewToolCallProxy creates tool_call backed by v.

func (*ToolCallProxy) Description

func (t *ToolCallProxy) Description() string

func (*ToolCallProxy) Execute

func (t *ToolCallProxy) Execute(ctx context.Context, call api.ToolCall) (*api.ToolResult, error)

Execute expands the proxy call and runs the real tool through the inner layers. An unknown or not-yet-loaded target is an error result listing the deferred tools, so the model can correct itself in the next step.

func (*ToolCallProxy) Name

func (t *ToolCallProxy) Name() string

func (*ToolCallProxy) Schema

func (t *ToolCallProxy) Schema() api.ToolSchema

func (*ToolCallProxy) ToolMeta

func (*ToolCallProxy) ToolMeta() Meta

ToolMeta marks the proxy as read-only: the real tool is approved under its own name and meta by the execution layers, so the proxy itself must not ask.

type Visibility

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

Visibility is the registry layer deciding which tools the model sees (order: observe -> visibility -> approval -> base). Direct tools are always listed; deferred tools (MCP and the configured native names) are listed only once loaded. Executing an unloaded deferred tool loads it and returns a tool error carrying its schema, without calling the inner layer, so no approval is requested for it.

func NewVisibility

func NewVisibility(inner lookupRegistry, opts VisibilityOptions) *Visibility

NewVisibility classifies the inner registry's tools once. The deferred set is fixed for the lifetime of the layer, which keeps the prompt listing and the tool prefix stable within a session.

func (*Visibility) Active

func (v *Visibility) Active() bool

Active reports whether any tool is deferred.

func (*Visibility) Bind

func (v *Visibility) Bind(store LoadedStore, onEvent func(context.Context, SearchEvent))

Bind connects the persistent loaded set and the event sink. Either may be nil.

func (*Visibility) ClearLoaded added in v0.52.0

func (v *Visibility) ClearLoaded(ctx context.Context) error

ClearLoaded forgets every loaded deferred tool of the session and empties the segment tool table, so a later segment (a --clear-ctx break) starts from the deferred set as if nothing had been loaded. The persisted set is saved empty before the table follows it, so a resumed process sees the same cleared state; a failed save is returned and leaves the table untouched.

func (*Visibility) DeferredList

func (v *Visibility) DeferredList(ctx context.Context) (native, mcp, loaded []string)

DeferredList returns the deferred tool names by source (native, MCP) and the loaded subset, all sorted. The manifest note and the diagnosis of "the model never found a tool" use it (design Q7).

func (*Visibility) DeferredStats

func (v *Visibility) DeferredStats(ctx context.Context) (native, loaded int)

DeferredStats reports how many native tools are deferred and how many deferred tools the session has loaded (design Q7, the context event).

func (*Visibility) ExecuteTool

func (v *Visibility) ExecuteTool(ctx context.Context, call api.ToolCall) (*api.ToolResult, error)

ExecuteTool runs loaded or direct tools through the inner layers. An unloaded deferred tool is loaded and answered with a tool error holding its schema.

func (*Visibility) ExpandCall

func (v *Visibility) ExpandCall(ctx context.Context, call api.ToolCall) (api.ToolCall, bool)

ExpandCall turns a tool_call proxy call into the real tool call, so the execution path (approval, hooks, taint, trace) sees the real tool name. ok is false for every other call and for a proxy call naming a tool that is not a loaded deferred tool: the proxy tool itself then answers with an error.

func (*Visibility) FoldLoaded

func (v *Visibility) FoldLoaded(ctx context.Context)

FoldLoaded folds the loaded deferred tools into the tool table (segment boundary). The caller invokes it when a new segment snapshot is built: the prompt prefix is rebuilt anyway, so adding the tools costs no extra cache write. It is a no-op when nothing is deferred or nothing new is segment-mode.

func (*Visibility) Get

func (v *Visibility) Get(name string) (api.Tool, error)

Get passes tool lookup through to the inner layers.

func (*Visibility) HasSegmentNative

func (v *Visibility) HasSegmentNative() bool

HasSegmentNative reports whether a deferred native tool waits for the next segment boundary to join the tool table. The wiring registers the tool_call proxy only then: with immediate apply the tool is listed as soon as loaded.

func (*Visibility) KindOfDeferred

func (v *Visibility) KindOfDeferred(name string) string

KindOfDeferred reports the source of a deferred tool ("native" or "mcp"), or "" for a name that is not deferred here. It feeds the newly_loaded_kinds field of the tool_search event (design Q7).

func (*Visibility) ListTools

func (v *Visibility) ListTools(ctx context.Context) ([]api.ToolSchema, error)

ListTools returns direct tools followed by the loaded deferred tools sorted by name. A native tool with tools.deferred_apply: segment is listed only after the loaded set was folded into the table (FoldLoaded), so the list stays byte-identical inside a segment.

func (*Visibility) PromptSection

func (v *Visibility) PromptSection() string

PromptSection lists the deferred tools for the system prompt: the native tools first, then each MCP server, sorted by name, so it is stable for the whole session. It is empty when nothing is deferred.

func (*Visibility) Search

func (v *Visibility) Search(ctx context.Context, query string, limit int) (SearchResult, error)

Search finds deferred tools and loads the hits. A query starting with "select:" picks exact names (comma separated); otherwise names and descriptions are tokenized and scored (name hits outweigh description hits).

type VisibilityOptions

type VisibilityOptions struct {
	Mode DeferredMode
	// ContextWindow is the model window in tokens (<=0 uses 128000).
	ContextWindow int
	// PinnedMCPTools are MCP tool names that stay directly visible even when
	// the selected deferred mode would otherwise hide them.
	PinnedMCPTools []string
	// NativeTools are native tool names to defer in addition to the MCP tools
	// (tools.deferred_native). Names that are not registered, are hidden or are
	// reserved (tool_search, tool_call) are ignored with a log line.
	NativeTools []string
	// Apply tells when a loaded native tool joins the tool table. It applies to
	// the native tools only: MCP tools keep the immediate behaviour (design Q5,
	// the conservative option). Empty means immediate.
	Apply DeferredApplyMode
}

VisibilityOptions configures NewVisibility.

type VisionGate

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

VisionGate is the live "the current model can see images" switch of one runtime. The tool set is built once, but chat can switch the main model between turns (:model) and the runtime lists the tools at every step, so the capability cannot be baked into the tool instances: the host updates the gate on a model switch and the observers/tools consult it per call.

A nil gate means "can see": a host that does not track the capability (tests, the examples) keeps the previous behavior.

func NewVisionGate

func NewVisionGate(vision bool) *VisionGate

NewVisionGate returns a gate for a model with the given vision capability.

func (*VisionGate) CanSee

func (g *VisionGate) CanSee() bool

CanSee reports whether the current model accepts images (a nil gate: yes).

func (*VisionGate) SetVision

func (g *VisionGate) SetVision(vision bool)

SetVision records whether the current model accepts images.

Directories

Path Synopsis
Package mcp implements a JSON-RPC 2.0 client for MCP (Model Context Protocol) servers.
Package mcp implements a JSON-RPC 2.0 client for MCP (Model Context Protocol) servers.
Package native provides built-in tool implementations.
Package native provides built-in tool implementations.
Package rules contains the approval-rule model and matcher.
Package rules contains the approval-rule model and matcher.

Jump to

Keyboard shortcuts

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