Documentation
¶
Index ¶
- Constants
- Variables
- func AskUserNonInteractiveMessage() string
- func BuildToolSearchDescription(deferred []Tool) string
- func DeferredSource(t Tool) string
- func DeferredToolDiscoveryLine(t Tool) string
- func FormatAskUserAnswers(questions []AskUserQuestion, answers []string) string
- func HashContent(content []byte) string
- func HostExecCommandShellGuidance() string
- func HostShellCommand(command string) (string, []string)
- func HostShellEnvironmentGuidance() string
- func IsBuiltInApplyPatch(tool Tool) bool
- func IsDeferralEligible(t Tool) bool
- func IsDeferred(t Tool) bool
- func ModelVisible(tool Tool) bool
- func MsysProneCommandName(name string) bool
- func MutationTargets(workspaceRoot string, name string, args map[string]any) []string
- func NewAskUserTool() *askUserTool
- func NewHostShellCommandContext(ctx context.Context, commandText string) *exec.Cmd
- func NewSkillTool(dir string) *skillTool
- func NewUpdatePlanTool() *updatePlanTool
- func NormalizeBrowserOpenURL(rawURL string) (string, error)
- func NormalizeResourcePath(path string) string
- func NormalizedBrowserActionCommand(command string) (string, bool)
- func PrepareFreeformApplyPatchArguments(tool Tool, patch string) (map[string]any, error)
- func ToolAdvertisedForPermissionMode(tool Tool, permissionMode string) bool
- func UnknownExecSessionError(sessionID int) string
- func ValidateBuiltinCatalog(workspaceRoot string) []string
- func ValidateCapabilities(name string, caps ToolCapabilities) []string
- type ArgsPermissioner
- type AskUserQuestion
- type CapabilityProvider
- type Display
- type EffectClass
- type ExecSessionController
- type ExecSessionSnapshot
- type FileDiff
- type FileTracker
- func (tracker *FileTracker) CheckConflict(absPath string, currentContent []byte) error
- func (tracker *FileTracker) CreatedFiles() []string
- func (tracker *FileTracker) Forget(absPath string)
- func (tracker *FileTracker) Record(absPath string, content []byte, info os.FileInfo)
- func (tracker *FileTracker) RecordCreated(absPath string)
- func (tracker *FileTracker) RecordEdit(absPath string, before, after []byte, info os.FileInfo)
- func (tracker *FileTracker) RecordHash(absPath string, hash string, info os.FileInfo)
- func (tracker *FileTracker) RecordSeenBytes(absPath string, start, end, total int)
- func (tracker *FileTracker) RecordSeenRange(absPath string, start, end, total int)
- func (tracker *FileTracker) SeenBytes(absPath string, start, end int) bool
- func (tracker *FileTracker) SeenRange(absPath string, start, end int) bool
- func (tracker *FileTracker) SeenWhole(absPath string) bool
- func (tracker *FileTracker) Version(absPath string) (FileVersion, bool)
- type FileVersion
- type LocalControlArtifactOptions
- type OutcomeDiagnostics
- type PathScope
- type Permission
- type PlanItem
- type PrePermissionRejecter
- type PropertySchema
- type Registry
- func (registry *Registry) All() []Tool
- func (registry *Registry) Capabilities(name string) ToolCapabilities
- func (registry *Registry) Clone() *Registry
- func (registry *Registry) CommitFileObservation(result Result, tracker *FileTracker) Result
- func (registry *Registry) Get(name string) (Tool, bool)
- func (registry *Registry) RebudgetAfterHook(toolName string, args map[string]any, result Result) Result
- func (registry *Registry) Register(tool Tool)
- func (registry *Registry) RegisterBatch(batch []Tool)
- func (registry *Registry) Run(ctx context.Context, name string, args map[string]any) Result
- func (registry *Registry) RunWithOptions(ctx context.Context, name string, args map[string]any, options RunOptions) (result Result)
- func (registry *Registry) Snapshot() RegistrySnapshot
- type RegistrySnapshot
- type Result
- type RunOptions
- type Safety
- type SandboxPermissionOverride
- type ScaffoldOptions
- type ScaffoldResult
- type ScaffoldRuntime
- type Schema
- type SideEffect
- type Status
- type Tool
- func BuiltinCatalog(workspaceRoot string) []Tool
- func CoreNetworkTools() []Tool
- func CoreReadOnlyToolsScoped(workspaceRoot string, scope PathScope) []Tool
- func CoreShellToolsScoped(workspaceRoot string, scope PathScope) []Tool
- func CoreToolsScoped(workspaceRoot string, scope PathScope) []Tool
- func CoreWriteToolsScoped(workspaceRoot string, scope PathScope) []Tool
- func NewBashTool(workspaceRoot string) Tool
- func NewEscalateModelTool() Tool
- func NewExecCommandTool(workspaceRoot string, manager *execSessionManager) Tool
- func NewGlobTool(workspaceRoot string) Tool
- func NewGoalTools(store *sessions.Store, sessionID string) []Tool
- func NewGrepTool(workspaceRoot string) Tool
- func NewListDirectoryTool(workspaceRoot string) Tool
- func NewLocalBrowserTools(options localcontrol.BrowserOptions) []Tool
- func NewLocalControlArtifactTools(options LocalControlArtifactOptions) []Tool
- func NewLocalDesktopTools(options localcontrol.DesktopOptions) []Tool
- func NewLocalTerminalTools(options localcontrol.TerminalOptions) []Tool
- func NewPeerReplyTool(service peerSessionService) Tool
- func NewPeerSessionTools(service peerSessionService) []Tool
- func NewReadFileTool(workspaceRoot string) Tool
- func NewReadMinifiedFileTool(workspaceRoot string) Tool
- func NewRequestPermissionsTool() Tool
- func NewScopedApplyPatchTool(workspaceRoot string, scope PathScope) Tool
- func NewScopedBashTool(workspaceRoot string, scope PathScope) Tool
- func NewScopedEditFileTool(workspaceRoot string, scope PathScope) Tool
- func NewScopedExecCommandTool(workspaceRoot string, scope PathScope, manager *execSessionManager) Tool
- func NewScopedGlobTool(workspaceRoot string, scope PathScope) Tool
- func NewScopedGrepTool(workspaceRoot string, scope PathScope) Tool
- func NewScopedLSPNavigateTool(workspaceRoot string, scope PathScope) Tool
- func NewScopedListDirectoryTool(workspaceRoot string, scope PathScope) Tool
- func NewScopedReadFileTool(workspaceRoot string, scope PathScope) Tool
- func NewScopedReadMinifiedFileTool(workspaceRoot string, scope PathScope) Tool
- func NewScopedViewImageTool(workspaceRoot string, scope PathScope) Tool
- func NewScopedWriteFileTool(workspaceRoot string, scope PathScope) Tool
- func NewToolSearchTool(registry *Registry) Tool
- func NewViewImageTool(workspaceRoot string) Tool
- func NewWebFetchTool() Tool
- func NewWebSearchTool() Tool
- func NewWriteStdinTool(manager *execSessionManager) Tool
- type ToolArtifact
- type ToolCapabilities
- type ToolOutcome
Constants ¶
const ( ExecCommandToolName = "exec_command" WriteStdinToolName = "write_stdin" )
const ( ResourceKeyFile = "file:" ResourceKeyDirectory = "directory:" ResourceKeyRepository = "repository:" // reserved ResourceKeyProcess = "process:" ResourceKeyPTY = "pty:" // reserved ResourceKeyBrowser = "browser:" // reserved ResourceKeyEndpoint = "endpoint:" ResourceKeySession = "session:" ResourceKeyWorkspace = "workspace:" )
Resource-key prefixes used for future conflict detection. Keys are pure metadata in this PR — no locks or scheduling are applied.
Unused prefixes (repository/pty/browser) are reserved for follow-up classifiers so PR6 conflict keys stay vocabulary-stable.
const ( PlanMode = "plan" SpecDraftMode = "spec-draft" )
PlanMode and SpecDraftMode are the string values of agent.PermissionModePlan and agent.PermissionModeSpecDraft. RunOptions.PermissionMode is already a plain string (set from agent.PermissionMode via string(permissionMode)), so this package owns the literals rather than importing the agent type (which would create an import cycle). agent.ToolAdvertised delegates plan/spec-draft decisions here so tool_search and the dispatch gate stay identical.
const ( SandboxLikelyDeniedMeta = "sandbox_likely_denied" SandboxDenialKindMeta = "sandbox_denial_kind" SandboxDenialReasonMeta = "sandbox_denial_reason" SandboxDenialKeywordMeta = "sandbox_denial_keyword" )
const ( SandboxDenialKindSandbox = "sandbox" SandboxDenialKindNetwork = "network" )
const RequestPermissionsToolName = "request_permissions"
const ToolSearchToolName = "tool_search"
ToolSearchToolName is the canonical registry name of the deferred-tool loader. It is exported so the agent loop, CLI filter validation, and the partition can reference the loader without re-stating the literal (keeping all the gates that must treat it specially in agreement).
const ViewImageToolName = "view_image"
ViewImageToolName is the canonical registry name of the image viewer.
Variables ¶
var ErrFileChangedOnDisk = errors.New("the file changed on disk since you last read it")
ErrFileChangedOnDisk is returned by CheckConflict when a file's current on-disk content no longer matches what a tool last read or wrote in this session — i.e. it was modified outside Zero. The write tools surface it with guidance to re-read before retrying, so a stale overwrite cannot silently clobber an external edit.
Functions ¶
func AskUserNonInteractiveMessage ¶
func AskUserNonInteractiveMessage() string
AskUserNonInteractiveMessage exposes the shared graceful-degradation message so the agent loop and the tool fallback stay in lock-step.
func BuildToolSearchDescription ¶
BuildToolSearchDescription renders the model-facing discovery instructions for deferred tools. This belongs on the tool_search tool definition, not as an extra user message, so the model can discover tools without treating discovery metadata as something to answer or acknowledge.
func DeferredSource ¶
DeferredSource reports the compact source label used in tool_search's dynamic description. MCP tools use their configured server name; other deferred tools fall back to the first name segment so families such as swarm_* are grouped.
func DeferredToolDiscoveryLine ¶
DeferredToolDiscoveryLine renders the compact name/source entry used in tool_search's dynamic description. It intentionally omits descriptions and schemas; those are revealed only after tool_search loads a matching tool.
func FormatAskUserAnswers ¶
func FormatAskUserAnswers(questions []AskUserQuestion, answers []string) string
FormatAskUserAnswers renders question/answer pairs into a clear, model-readable block. Missing answers are surfaced explicitly so the model never silently treats an unanswered question as answered.
It distinguishes two shapes of "empty" the model would otherwise conflate: a wholesale dismissal (the user closed the prompt without answering ANYTHING) is flagged up front as a skip, so the model doesn't invent a default; a single blank field amid other answers is marked "(left blank)".
func HashContent ¶
HashContent returns the hex-encoded SHA-256 of content. Exported so the write tools and tests share one definition of a file's identity.
func HostExecCommandShellGuidance ¶
func HostExecCommandShellGuidance() string
HostExecCommandShellGuidance returns the shell guidance appended to exec_command's description on this host, or "" where none is appended.
Exported for the per-turn token ratchet in internal/agent. That budget has to separate what every host pays for the tool schemas from what THIS host pays for its shell guidance, because the guidance varies by shell and by PowerShell version, and a single number covering both silently means a different thing on each machine.
func HostShellCommand ¶
HostShellCommand returns the shell executable and argv used for a command on this host. Keeping this in one place makes agent tools and the user-typed TUI shell escape use the same Windows shell and fallback behavior.
func HostShellEnvironmentGuidance ¶
func HostShellEnvironmentGuidance() string
HostShellEnvironmentGuidance returns the concise, model-facing shell rule for the current host.
func IsBuiltInApplyPatch ¶
IsBuiltInApplyPatch reports whether tool is Zero's scoped patch tool. The marker method is package-private so external and MCP tools cannot claim this identity merely by sharing the public name "apply_patch".
func IsDeferralEligible ¶
IsDeferralEligible reports whether a tool counts toward the DeferThreshold. A currently-deferred tool always counts. A tool may ALSO opt in via DeferralEligible() to keep counting while exposed eagerly (see above). This is the count partitionTools uses for the active-gate; whether a tool is actually hidden is still decided by IsDeferred.
func IsDeferred ¶
IsDeferred reports whether a tool opts into deferred loading. A tool is deferred-eligible only if it implements deferredTool and its Deferred() method returns true; tools that do not implement the interface are eager.
func ModelVisible ¶
ModelVisible reports whether a registered tool is advertised to an agent. Every registered tool is visible. edit_file (exact search/replace with a uniqueness guard, CRLF and fuzzy fallbacks) was hidden for a while in favour of apply_patch; head-to-head benchmarking showed that when a model misses the patch grammar it degrades to whole-file rewrites, so both edit tools are advertised and the prompt steers between them.
func MsysProneCommandName ¶
MsysProneCommandName reports whether a bare command name commonly resolves to a Git-for-Windows MSYS binary that fails under the Windows restricted sandbox.
func MutationTargets ¶
MutationTargets returns the workspace-relative paths a tool call will write to, so the session layer can snapshot their before-state for safe rewind. It is a pure helper (no I/O beyond path resolution) and returns nil for read-only tools and for bash (whose affected paths are not knowable before execution).
func NewAskUserTool ¶
func NewAskUserTool() *askUserTool
NewAskUserTool builds the ask_user tool. It is read-only (it gathers input, never mutates the workspace). The agent loop intercepts ask_user calls and routes them to an interactive front-end when one exists; this tool's Run() is the fallback used when nothing intercepts the call (e.g. headless runs).
func NewHostShellCommandContext ¶
NewHostShellCommandContext constructs a direct host-shell command. The cmd.exe fallback needs a Windows-specific raw command line, while PowerShell and POSIX shells use normal argv handling.
func NewSkillTool ¶
func NewSkillTool(dir string) *skillTool
NewSkillTool builds the skill tool. An empty dir resolves to the standard skills data directory (skills.DefaultDir); pass an explicit dir in tests.
func NewUpdatePlanTool ¶
func NewUpdatePlanTool() *updatePlanTool
func NormalizeBrowserOpenURL ¶
NormalizeBrowserOpenURL applies the browser_open URL rules before execution. Keeping this exported within the internal package lets permission displays describe the same destination the browser helper will open.
func NormalizeResourcePath ¶
NormalizeResourcePath produces a deterministic path token for resource keys. It never touches the filesystem (no EvalSymlinks / Stat) so it cannot cause side effects or panic on missing paths. Empty input returns "".
Rules:
- Trim space
- filepath.Clean
- Convert separators to '/'
- On Windows, lower-case for case-insensitive comparison
- Strip a leading "./"
- Never include credentials or query fragments (paths only)
func NormalizedBrowserActionCommand ¶
NormalizedBrowserActionCommand returns the exact action that browser_action will execute after normalizing its command argument. ACP uses it only for a permission title, so an unrecognised command is never reflected as text that the tool would reject.
func PrepareFreeformApplyPatchArguments ¶
PrepareFreeformApplyPatchArguments converts native structured-patch input into the ordinary apply_patch argument map used by permission checks and tool execution. Absolute patch-header paths select a granted write root and are rewritten relative to that root; relative-only patches keep workspace-root behavior.
func ToolAdvertisedForPermissionMode ¶
ToolAdvertisedForPermissionMode is the single source of truth for whether a tool may be advertised under a given permission mode string. agent.ToolAdvertised calls this for plan/spec-draft after its own PermissionDeny short-circuit; tool_search applies it to deferred candidates so a mutator cannot leak through load_tools. Modes other than plan/spec-draft only apply the PermissionDeny gate here (auto/member-auto/ask/unsafe advertisement rules stay in agent).
func UnknownExecSessionError ¶
UnknownExecSessionError is the result returned when write_stdin targets a session_id with no live exec session. The stable recovery guidance leads and the numeric id trails on purpose: the agent's repeated-failure guard keys on a normalized, truncated prefix of the error string, so keeping the id out of that prefix makes a model probing ids 1, 2, 3, … produce ONE signature that finally trips the halt instead of a fresh signature per id — while also telling the model how to actually recover. See TestUnknownExecSessionErrorSignatureIsIDInvariant in internal/agent, which pins this invariant against the real guard.
func ValidateBuiltinCatalog ¶
ValidateBuiltinCatalog returns diagnostics for every catalog tool that is missing or inconsistently classified. Empty means full coverage.
Duplicate builtin names are always rejected: ResourceKeys is a function and cannot be compared, so partial metadata comparison would miss conflict-scope drift between two same-name tools.
Validation uses constructor-declared capabilities (before ThreadSafe normalization) so a mutator wired with ThreadSafe=true is still reported. Runtime callers continue to use CapabilitiesOf, which normalizes.
func ValidateCapabilities ¶
func ValidateCapabilities(name string, caps ToolCapabilities) []string
ValidateCapabilities checks a single capability record for consistency. It returns a non-empty slice of human-readable problems when invalid. Note: CapabilitiesOf already normalizes ThreadSafe away for non-ReadOnly effects; validation still rejects the raw combination so catalog tests catch mis-declared constructors.
Types ¶
type ArgsPermissioner ¶
type ArgsPermissioner interface {
PermissionForArgs(args map[string]any) Permission
}
ArgsPermissioner is an optional interface a Tool can implement to refine its permission for a SPECIFIC call based on its arguments. When a tool implements it, the agent loop consults PermissionForArgs(args) instead of the static Safety().Permission when deciding whether the call needs approval. It exists to safely RELAX a prompt to allow for arguments the tool can prove are harmless (e.g. delegating to a read-only sub-agent); a tool must return its static, stricter permission whenever it cannot prove the call is safe.
type AskUserQuestion ¶
type AskUserQuestion struct {
Question string
Header string
Options []string
OptionDescriptions []string
Recommended string
MultiSelect bool
}
AskUserQuestion is one clarifying question the agent wants the user to answer. Options/MultiSelect are presentation hints for an interactive front-end; the tool itself never blocks on input.
func ParseAskUserQuestions ¶
func ParseAskUserQuestions(args map[string]any) ([]AskUserQuestion, error)
ParseAskUserQuestions extracts the questionnaire from raw tool arguments. It is shared by the tool's Run() fallback and the agent loop's interactive path so both validate identically.
type CapabilityProvider ¶
type CapabilityProvider interface {
Capabilities() ToolCapabilities
}
CapabilityProvider is the optional interface tools implement to declare effect metadata. Tools that do not implement it are treated as EffectUnknown and not thread-safe (fail-closed).
type Display ¶
type Display struct {
Summary string
Kind string // e.g. file, diff, search, shell
// Preview is a multi-line, card-only body (e.g. a unified diff or file head)
// for the TUI. It is NEVER sent to the model — Output stays the short summary
// the model sees — so a rich code preview costs zero model tokens.
Preview string
}
Display carries a short, structured summary of a tool result for the TUI/stream.
type EffectClass ¶
type EffectClass int
EffectClass classifies a tool's side effects for concurrency safety. Concurrent execution (a later PR) must only consider tools that are both ThreadSafe and EffectReadOnly; this package only declares metadata. ThreadSafe is force-cleared for every non-ReadOnly effect at read time (see normalizeCapabilities).
const ( // EffectUnknown is the fail-closed default for unclassified tools. // Never concurrency-eligible; always serialized. EffectUnknown EffectClass = iota // EffectReadOnly reads local or remote state without mutating it. // The only effect class that may set ThreadSafe=true after audit. EffectReadOnly // EffectProcessRead observes a retained process, PTY, or terminal. EffectProcessRead // EffectWorkspaceWrite mutates the local repository or workspace. // Includes one-shot shell commands that can rewrite the workspace. EffectWorkspaceWrite // EffectExternalWrite mutates state outside the local workspace. EffectExternalWrite // EffectInteractive uses browser, PTY/terminal, prompts, or other // session-bound interaction where ordering matters. EffectInteractive )
func (EffectClass) String ¶
func (e EffectClass) String() string
String returns a stable diagnostic name for the effect class.
func (EffectClass) Valid ¶
func (e EffectClass) Valid() bool
Valid reports whether e is one of the defined effect classes.
type ExecSessionController ¶
type ExecSessionSnapshot ¶
type ExecSessionSnapshot = execution.ProcessSnapshot
type FileDiff ¶
type FileDiff struct {
// Path is the canonical absolute path required by ACP diff content. The
// separate ChangedFiles result remains workspace-relative for local UI use.
Path string
// OldExists and NewExists distinguish an empty file from a missing side of a
// create/delete/move. Empty strings alone cannot encode that difference.
OldExists bool
NewExists bool
OldText string
NewText string
}
FileDiff is a human-facing before/after file change. Registry-boundary redaction applies to both sides before any caller receives it.
type FileTracker ¶
type FileTracker struct {
// contains filtered or unexported fields
}
FileTracker records, per absolute path, the version of each file a tool read or wrote within a single session. A later write compares the current on-disk content against this baseline to detect a modification made outside Zero.
Construct with NewFileTracker. A nil *FileTracker is a valid no-op — every method tolerates it — so a caller that has not wired the feature (tests, MCP) needs no nil guards.
func NewFileTracker ¶
func NewFileTracker() *FileTracker
func (*FileTracker) CheckConflict ¶
func (tracker *FileTracker) CheckConflict(absPath string, currentContent []byte) error
CheckConflict reports ErrFileChangedOnDisk when absPath has a recorded baseline and currentContent (the bytes the caller just read from disk) no longer matches it. An untracked path returns nil: with no baseline there is nothing to conflict against, so a first-touch write is always allowed.
func (*FileTracker) CreatedFiles ¶
func (tracker *FileTracker) CreatedFiles() []string
CreatedFiles returns the absolute paths of every brand-new file recorded via RecordCreated during this session, in first-created order. The caller owns the returned slice.
func (*FileTracker) Forget ¶
func (tracker *FileTracker) Forget(absPath string)
Forget drops any recorded version for absPath, so the next read re-establishes the baseline. Used after a tool rewrites a file by a path other than its own (e.g. apply_patch) where the new content is not cheaply available to Record.
func (*FileTracker) Record ¶
func (tracker *FileTracker) Record(absPath string, content []byte, info os.FileInfo)
Record stores the version of absPath given its content and optional stat info.
func (*FileTracker) RecordCreated ¶
func (tracker *FileTracker) RecordCreated(absPath string)
RecordCreated notes that absPath is a brand-new file a tool just created in this session (as opposed to an overwrite of something that already existed).
func (*FileTracker) RecordEdit ¶
func (tracker *FileTracker) RecordEdit(absPath string, before, after []byte, info os.FileInfo)
RecordEdit re-baselines absPath after an edit THIS SESSION made, keeping the reads the edit did not disturb.
WHY THIS EXISTS RATHER THAN Record. RecordHash drops every recorded range when the content hash moves, which is right for a change we did not make: we cannot say which lines still hold what was read. After our own edit we can say exactly. The content before the first changed line is byte-identical and sits at the same line numbers; the content after the last changed line is byte-identical and has moved by a known delta. Only the lines the edit actually spans stop describing the file.
Dropping the lot instead cost a real run. A 371-line file was read in three pieces (40-45, 85-260, 260-371) and one two-line edit at line 92 erased the credit for all three: the next six edits — into regions that had been read, that the edit did not touch, in a file whose line count had not changed — were each refused as content "not read in this session", and the repeated-failure guard halted the run. The error even told the model to re-read, which would have been undone by its next successful edit. The guard is right that a model must not edit what it has not seen; it was wrong about what it had seen.
func (*FileTracker) RecordHash ¶
func (tracker *FileTracker) RecordHash(absPath string, hash string, info os.FileInfo)
RecordHash stores the version of absPath when the caller already computed the same HashContent-compatible SHA-256 while reading the file.
func (*FileTracker) RecordSeenBytes ¶
func (tracker *FileTracker) RecordSeenBytes(absPath string, start, end, total int)
RecordSeenBytes records an exact, non-elided byte interval returned to the model. Byte intervals make oversized single-line files recoverable without crediting the model for the omitted middle of a truncated line read.
func (*FileTracker) RecordSeenRange ¶
func (tracker *FileTracker) RecordSeenRange(absPath string, start, end, total int)
RecordSeenRange records exact, non-elided source lines returned to the model. Ranges accumulate while the content hash remains unchanged.
func (*FileTracker) SeenBytes ¶
func (tracker *FileTracker) SeenBytes(absPath string, start, end int) bool
SeenBytes reports whether every byte in [start, end) was returned exactly to the model for the currently tracked version.
func (*FileTracker) SeenRange ¶
func (tracker *FileTracker) SeenRange(absPath string, start, end int) bool
SeenRange reports whether every line in the requested range was returned exactly to the model for the currently tracked version.
func (*FileTracker) SeenWhole ¶
func (tracker *FileTracker) SeenWhole(absPath string) bool
func (*FileTracker) Version ¶
func (tracker *FileTracker) Version(absPath string) (FileVersion, bool)
Version returns the recorded version for absPath and whether one exists.
type FileVersion ¶
FileVersion is what a tool last observed for a file: an authoritative content hash plus cheap stat metadata kept for diagnostics.
type LocalControlArtifactOptions ¶
type LocalControlArtifactOptions struct {
Browser localcontrol.BrowserOptions
Desktop localcontrol.DesktopOptions
Terminal localcontrol.TerminalOptions
ArtifactsDir string
}
type OutcomeDiagnostics ¶
type OutcomeDiagnostics struct {
Category string
OriginalBytes int
ModelBytes int
EstimatedOriginalTokens int
EstimatedModelTokens int
Truncated bool
Redacted bool
Reason string
}
OutcomeDiagnostics describes how the model-facing representation differs from the redacted output received by the registry boundary.
type PathScope ¶
type PathScope interface {
Roots() []string
}
PathScope is the multi-root write scope shared with the sandbox engine. *sandbox.Scope satisfies it; nil means workspace-only (today's behavior). Roots()[0] must be the workspace root (sandbox.Scope guarantees this ordering); relative paths and error messages key off it.
type Permission ¶
type Permission string
const ( PermissionAllow Permission = "allow" PermissionPrompt Permission = "prompt" PermissionDeny Permission = "deny" )
type PrePermissionRejecter ¶
PrePermissionRejecter lets a tool reject a call that cannot safely or validly run before any permission prompt is shown. Implementations must be purely local and deterministic: no filesystem, process, DNS, or network access.
type PropertySchema ¶
type PropertySchema struct {
Type string `json:"type"`
Description string `json:"description,omitempty"`
Enum []string `json:"enum,omitempty"`
Default any `json:"default,omitempty"`
Items *PropertySchema `json:"items,omitempty"`
Minimum *int `json:"minimum,omitempty"`
Maximum *int `json:"maximum,omitempty"`
MinLength *int `json:"minLength,omitempty"`
MaxLength *int `json:"maxLength,omitempty"`
MinItems *int `json:"minItems,omitempty"`
// Properties/Required describe nested object fields (for Type "object" or an
// object-typed Items).
Properties map[string]PropertySchema `json:"properties,omitempty"`
Required []string `json:"required,omitempty"`
}
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
func NewRegistry ¶
func NewRegistry() *Registry
func (*Registry) Capabilities ¶
func (registry *Registry) Capabilities(name string) ToolCapabilities
Registry.Capabilities looks up a registered tool's capabilities by name. Unknown tools return the fail-closed default (not an error) so callers can treat missing tools as non-concurrent without panicking.
func (*Registry) Clone ¶
Clone returns an independent registry containing exactly one source snapshot.
func (*Registry) CommitFileObservation ¶
func (registry *Registry) CommitFileObservation(result Result, tracker *FileTracker) Result
CommitFileObservation grants exact-read credit only when the tool's complete output remains intact at the final boundary that will be sent to the model.
func (*Registry) RebudgetAfterHook ¶
func (registry *Registry) RebudgetAfterHook(toolName string, args map[string]any, result Result) Result
RebudgetAfterHook reapplies the registry's redaction and output limits after an afterTool hook appends model-visible feedback to a completed result. The initial registry pass has already run; this second pass is limited to the newly combined result so hooks cannot bypass the established safety ceiling.
func (*Registry) RegisterBatch ¶
RegisterBatch publishes a group of tools as one registry generation. Readers observe either the complete prior generation or the complete new one.
func (*Registry) RunWithOptions ¶
func (*Registry) Snapshot ¶
func (registry *Registry) Snapshot() RegistrySnapshot
Snapshot returns a stable, sorted view of the registry at one generation.
type RegistrySnapshot ¶
RegistrySnapshot is one immutable registry generation. Tools is a detached, name-sorted slice: later registrations cannot change the snapshot observed by an in-flight agent turn.
type Result ¶
type Result struct {
Status Status
Output string
Truncated bool
Meta map[string]string
SandboxDecision *sandbox.Decision `json:"-"`
// ExecutionRequest and ExecutionOutcome are the typed command protocol used
// by command-oriented tools. Legacy Output and Meta fields remain populated
// while callers migrate away from parsing text and string metadata.
ExecutionRequest *execution.Request `json:"-"`
ExecutionOutcome *execution.Outcome `json:"-"`
// Images are pictures the tool is handing the model — a screenshot it just
// captured, a file it was asked to look at. Text-only tools leave it nil.
//
// They are NOT delivered on this result's own tool-result message. Every
// provider drops images there: Anthropic maps a tool result to a tool_result
// block whose content is a string, Gemini to a functionResponse, and OpenAI
// guards its image content-parts to the user role. The agent loop therefore
// emits them as a following user message, which is also the only shape that
// keeps one tool result per tool call.
Images []zeroruntime.ImageBlock `json:"-"`
// Redacted is set when secret scrubbing altered Output before it left the
// tool-execution boundary.
Redacted bool
// ChangedFiles lists workspace-relative paths a mutating tool wrote;
// entries under a granted extra write root are absolute, since
// workspace-relative would be ambiguous there.
ChangedFiles []string
// FileDiffs carries exact, bounded before/after text for built-in file
// mutations. A missing entry means the client must fall back to ChangedFiles
// rather than inventing a partial diff.
FileDiffs []FileDiff
// ChangeSummaries contains bounded generated-tree changes. These are shown
// in session evidence and the Files panel but are never treated as files to
// open or diagnose individually.
ChangeSummaries []execution.Change
// Display carries a short, structured summary for the TUI / stream.
Display Display
// Outcome is the finalized, typed representation produced at the registry
// seam. ModelView, HumanView, and Artifact deliberately serve different
// consumers; Output, Display, and spill metadata remain synchronized for
// compatibility with direct tool callers and persisted sessions.
Outcome ToolOutcome
// contains filtered or unexported fields
}
func ScrubResultSecrets ¶
ScrubResultSecrets applies the registry's transcript boundary to a result that was produced before Registry.RunWithOptions could own it, such as a local pre-permission rejection in the agent loop.
func (Result) HumanDisplay ¶
HumanDisplay returns the finalized presentation, falling back to the legacy display for direct Tool.Run callers.
func (Result) ModelOutput ¶
ModelOutput returns the finalized provider-facing text, falling back to the legacy field for direct Tool.Run callers that have not crossed the registry.
type RunOptions ¶
type RunOptions struct {
PermissionGranted bool
PermissionMode string
Autonomy string
Sandbox *sandbox.Engine
ToolCallID string
SessionID string
Model string
ReasoningEffort string
Depth int
Cwd string
// FileTracker, when set, records the version of each file read or written this
// session so write_file/edit_file can refuse to clobber a file that changed on
// disk outside Zero since it was last read. nil disables the feature entirely
// (the read/write tools behave exactly as before).
FileTracker *FileTracker
// DeferFileObservationCommit lets a caller with an additional output layer
// commit exact-read credit after that final layer has run.
DeferFileObservationCommit bool
// EnabledTools / DisabledTools carry the run's operator tool filters so a
// filter-aware tool (tool_search) never discloses or loads an operator-hidden
// tool. They use the same allow/deny semantics as the agent's filter gate:
// denied if listed in DisabledTools; if EnabledTools is non-empty, allowed
// only when listed in it.
EnabledTools []string
DisabledTools []string
// Progress, when set, is called with each stream-json event emitted by a
// specialist child process while it runs. Used by the TUI to show live
// tool-call progress in the specialist card. nil is a no-op (the default
// for every non-Task tool).
Progress func(streamjson.Event)
// Diagnostics, when set, returns a formatted language-diagnostics block for
// a file a mutating tool just wrote ("" when clean or no server available).
// edit_file/write_file append it to their output so the model sees an error
// it introduced in the same turn instead of waiting for a later verification
// pass. nil disables inline diagnostics.
Diagnostics func(ctx context.Context, absPath string) string
// contains filtered or unexported fields
}
type Safety ¶
type Safety struct {
SideEffect SideEffect
Permission Permission
Reason string
// AdvertiseInAuto allows selected non-allow tools to be visible in auto mode
// while still requiring the normal permission flow before execution.
AdvertiseInAuto bool
}
type SandboxPermissionOverride ¶
type SandboxPermissionOverride string
const ( SandboxPermissionsUseDefault SandboxPermissionOverride = "use_default" SandboxPermissionsRequireEscalated SandboxPermissionOverride = "require_escalated" SandboxPermissionsWithAdditionalPermissions SandboxPermissionOverride = "with_additional_permissions" )
type ScaffoldOptions ¶
type ScaffoldOptions struct {
// Name is the tool/plugin id (a single path segment).
Name string
// Dir is the toolbox directory to create the plugin under (typically the user
// plugins root).
Dir string
// Description is an optional human description; a default is used when empty.
Description string
// Runtime selects the entry-stub language; defaults to RuntimeShell.
Runtime ScaffoldRuntime
}
ScaffoldOptions configures a single tool scaffold.
type ScaffoldResult ¶
type ScaffoldResult struct {
Name string `json:"name"`
PluginDir string `json:"pluginDir"`
ManifestPath string `json:"manifestPath"`
EntryPath string `json:"entryPath"`
}
ScaffoldResult reports the generated layout.
func Scaffold ¶
func Scaffold(options ScaffoldOptions) (ScaffoldResult, error)
Scaffold generates a plugin-tool skeleton under options.Dir/<name>/ and returns the created paths. It refuses an invalid name, a missing dir, or an existing target so it never clobbers prior work.
type ScaffoldRuntime ¶
type ScaffoldRuntime string
ScaffoldRuntime selects the entry-stub language. The default is a POSIX shell stub, which has no interpreter install dependency; node/python are offered for authors who prefer them. Runtimes are deliberately model-provider-agnostic.
const ( RuntimeShell ScaffoldRuntime = "shell" RuntimeNode ScaffoldRuntime = "node" RuntimePython ScaffoldRuntime = "python" )
type Schema ¶
type Schema struct {
Type string `json:"type"`
Properties map[string]PropertySchema `json:"properties,omitempty"`
Required []string `json:"required,omitempty"`
AdditionalProperties bool `json:"additionalProperties"`
}
type SideEffect ¶
type SideEffect string
const ( // SideEffectNone marks a control-only tool that neither reads nor mutates // state — no read/write/shell/network/out-of-workspace effect. Examples: // tool_search (only reports already-registered tool schemas) and // escalate_model (only requests a loop-level model switch). SideEffectNone SideEffect = "none" SideEffectRead SideEffect = "read" SideEffectWrite SideEffect = "write" SideEffectShell SideEffect = "shell" SideEffectNetwork SideEffect = "network" SideEffectLocalControl SideEffect = "local_control" SideEffectLocalBrowser SideEffect = "local_browser" SideEffectLocalDesktop SideEffect = "local_desktop" SideEffectLocalTerminal SideEffect = "local_terminal" SideEffectOutOfWorkspace SideEffect = "out_of_workspace" )
type Tool ¶
type Tool interface {
Name() string
Description() string
Parameters() Schema
Safety() Safety
Run(ctx context.Context, args map[string]any) Result
}
func BuiltinCatalog ¶
BuiltinCatalog returns every built-in tool that Zero can expose to the model from this package (core + control + optional local-control helpers).
It is the source of truth for metadata coverage tests: every tool returned here must declare an explicit Effect other than EffectUnknown.
Not included (fail-closed EffectUnknown by design):
- MCP tools (internal/mcp registryTool)
- Plugin tools (internal/plugins pluginTool)
- Specialist tools registered outside this package (Task, Generate, …)
workspaceRoot is used only to construct path-scoped tools; it need not exist.
func CoreNetworkTools ¶
func CoreNetworkTools() []Tool
func CoreReadOnlyToolsScoped ¶
func CoreShellToolsScoped ¶
func CoreToolsScoped ¶
func CoreWriteToolsScoped ¶
func NewBashTool ¶
func NewEscalateModelTool ¶
func NewEscalateModelTool() Tool
NewEscalateModelTool builds the tool with the default model registry. If the default registry cannot be built the tool degrades gracefully: every run then reports "no escalation available" rather than failing.
func NewExecCommandTool ¶
func NewGlobTool ¶
func NewGoalTools ¶
NewGoalTools returns goal lifecycle tools bound to one captured session. The binding prevents a late tool call from mutating a different session after a resume or session switch.
func NewGrepTool ¶
func NewListDirectoryTool ¶
func NewLocalBrowserTools ¶
func NewLocalBrowserTools(options localcontrol.BrowserOptions) []Tool
func NewLocalControlArtifactTools ¶
func NewLocalControlArtifactTools(options LocalControlArtifactOptions) []Tool
func NewLocalDesktopTools ¶
func NewLocalDesktopTools(options localcontrol.DesktopOptions) []Tool
func NewLocalTerminalTools ¶
func NewLocalTerminalTools(options localcontrol.TerminalOptions) []Tool
func NewPeerReplyTool ¶
func NewPeerReplyTool(service peerSessionService) Tool
NewPeerReplyTool exposes send_message eagerly for a turn that originated from another session. Ordinary turns keep the same tool deferred so sessions that never use peer messaging pay no schema cost.
func NewPeerSessionTools ¶
func NewPeerSessionTools(service peerSessionService) []Tool
NewPeerSessionTools exposes live-session discovery and messaging through the canonical tool registry. The peer runtime still owns resolution, transport, framing, and delivery policy.
func NewReadFileTool ¶
func NewReadMinifiedFileTool ¶
func NewRequestPermissionsTool ¶
func NewRequestPermissionsTool() Tool
func NewScopedApplyPatchTool ¶
func NewScopedBashTool ¶
func NewScopedEditFileTool ¶
func NewScopedGlobTool ¶
func NewScopedGrepTool ¶
func NewScopedLSPNavigateTool ¶
NewScopedLSPNavigateTool builds the tool with its own lazily-started LSP manager (servers spin up on first use and are reused across calls within a session). The model-supplied path is resolved through the same scoped confinement the sibling read-only tools use, so a `..` or absolute path cannot read or open a file outside the workspace (or an extra granted root).
func NewScopedReadFileTool ¶
func NewScopedViewImageTool ¶
NewScopedViewImageTool builds the image viewer bound to a path scope.
The scope is not optional decoration. imageinput.LoadFile resolves a relative path by joining it to the workspace root and otherwise takes the path as given, so on its own it would happily read outside the workspace. Every path goes through resolveScopedReadPath first, exactly like read_file, so this tool grants no reach that read_file does not already have.
func NewScopedWriteFileTool ¶
func NewToolSearchTool ¶
NewToolSearchTool builds the tool_search tool over the given registry. The tool is informational/no-side-effect and is advertised even in auto mode so the model can always discover withheld tools.
func NewViewImageTool ¶
NewViewImageTool builds the workspace-scoped image viewer.
func NewWebFetchTool ¶
func NewWebFetchTool() Tool
func NewWebSearchTool ¶
func NewWebSearchTool() Tool
NewWebSearchTool builds the web_search tool with the env-configured backend.
func NewWriteStdinTool ¶
func NewWriteStdinTool(manager *execSessionManager) Tool
type ToolArtifact ¶
ToolArtifact identifies recoverable output saved by the tool boundary. CompleteAtBoundary means the artifact contains every redacted byte received by that boundary; an underlying process may already have applied its own capture limit before producing the result.
type ToolCapabilities ¶
type ToolCapabilities struct {
Effect EffectClass
ThreadSafe bool
ResourceKeys func(args map[string]any) []string
}
ToolCapabilities is the concurrency-safety contract for a tool. ResourceKeys, when set, returns deterministic conflict keys for a call's arguments. Returning no keys does NOT make a tool parallel-safe.
func CapabilitiesOf ¶
func CapabilitiesOf(tool Tool) ToolCapabilities
CapabilitiesOf returns a tool's declared capabilities, or the fail-closed unknown default when the tool does not implement CapabilityProvider.
func UnknownCapabilities ¶
func UnknownCapabilities() ToolCapabilities
UnknownCapabilities is the fail-closed default for tools without metadata.
type ToolOutcome ¶
type ToolOutcome struct {
ModelView string
HumanView Display
Artifact *ToolArtifact
Diagnostics OutcomeDiagnostics
// contains filtered or unexported fields
}
ToolOutcome is the canonical post-execution representation of one tool result. It separates the bounded provider payload from the human-facing presentation and the recoverable output retained outside model context.
func (ToolOutcome) Finalized ¶
func (outcome ToolOutcome) Finalized() bool
Finalized reports whether the outcome crossed the registry boundary. Direct Tool.Run results deliberately return false and use their legacy fields.
func (ToolOutcome) MarshalJSON ¶
func (outcome ToolOutcome) MarshalJSON() ([]byte, error)
MarshalJSON preserves the private finalized marker without making outcome state mutable to callers.
func (*ToolOutcome) UnmarshalJSON ¶
func (outcome *ToolOutcome) UnmarshalJSON(data []byte) error
UnmarshalJSON restores the finalized marker used to select canonical views.
Source Files
¶
- apply_patch.go
- args.go
- argtolerance.go
- ask_user.go
- bash.go
- bash_proc_unix.go
- builtin_catalog.go
- capabilities.go
- deferred.go
- diff_preview.go
- edit_file.go
- edit_replacers.go
- escalate_model.go
- exec_command.go
- file_commit.go
- file_tracker.go
- format_on_write.go
- glob.go
- goal.go
- grep.go
- inline_diagnostics.go
- line_reader.go
- list_directory.go
- local_browser.go
- local_capture.go
- local_desktop.go
- local_terminal.go
- lsp_navigate.go
- model_visibility.go
- mutation_targets.go
- output_boundary.go
- output_budget.go
- output_ceiling.go
- output_policies.go
- path_hint.go
- peer_sessions.go
- preview.go
- read_exclusions.go
- read_file.go
- read_minified_file.go
- registry.go
- request_permissions.go
- resource_keys.go
- rooted_file.go
- sandbox_denial.go
- scaffold.go
- search_cancel.go
- shell_output_reducer.go
- shell_runtime.go
- skill.go
- spill.go
- spill_owner_unix.go
- structured_patch.go
- tool_outcome.go
- tool_search.go
- types.go
- unified_patch.go
- update_plan.go
- view_image.go
- web_fetch.go
- web_fetch_aimlapi.go
- web_fetch_markdown.go
- web_search.go
- web_search_aimlapi.go
- workspace.go
- write_file.go