native

package
v0.53.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 59 Imported by: 0

Documentation

Overview

Package native provides built-in tool implementations.

Index

Constants

View Source
const (
	AgentExplore  = "explore"  // workspace read-only tools
	AgentResearch = "research" // explore plus web_fetch and web_search
)

Sub-agent types (the agent tool's type argument).

View Source
const (
	// DefaultShellTimeout is used when the call gives no timeout.
	DefaultShellTimeout = 120 * time.Second
	// DefaultShellBackgroundAfter is the foreground grace period before a
	// long-running command is handed to the task manager.
	DefaultShellBackgroundAfter = 120 * time.Second
	// DefaultShellTimeoutMax caps the timeout a call may ask for
	// (tools.shell_timeout_max).
	DefaultShellTimeoutMax = 600 * time.Second
	// DefaultTaskTimeoutMax caps background shell tasks.
	DefaultTaskTimeoutMax = time.Hour
)
View Source
const (
	LedgerScopeCurrent   = "current"
	LedgerScopeWorkspace = "workspace"
	LedgerScopeAll       = "all"
)

Ledger search scopes (session_search scope argument).

View Source
const (
	MemoryActionAdd     = "add"
	MemoryActionReplace = "replace"
	MemoryActionRemove  = "remove"
	MemoryActionGet     = "get"
	MemoryActionSearch  = "search"
)

Actions of the memory tool.

View Source
const (
	PlanPending    = "pending"
	PlanInProgress = "in_progress"
	PlanCompleted  = "completed"
)

Plan step statuses accepted by update_plan.

View Source
const (
	// RemoveMaxFiles is the most files one file_remove call may move to the
	// trash. Ignored directories (see FileRemoveTool) are neither counted nor
	// moved.
	RemoveMaxFiles = 1000
	// TrashRetention is how long removed paths are kept in the trash.
	TrashRetention = 7 * 24 * time.Hour
)
View Source
const (
	// DefaultShellLimitMemory is the memory limit when tools.shell_limits.memory
	// is not set (4 GiB).
	DefaultShellLimitMemory uint64 = 4 << 30
	// DefaultShellLimitProcesses is the process limit when
	// tools.shell_limits.processes is not set (256).
	DefaultShellLimitProcesses = 256
)

Defaults of tools.shell_limits: generous enough for a full Go build, small enough that one runaway command cannot take the machine down.

View Source
const (
	SnapshotKindFile   SnapshotKind = "file"
	SnapshotKindAbsent SnapshotKind = "absent"
	SnapshotKindTrash  SnapshotKind = "trash"
	SnapshotKindPurged SnapshotKind = "purged"

	SnapshotStatusComplete        = "complete"
	SnapshotStatusIncomplete      = "incomplete"
	SnapshotUnrecoverableOversize = "oversize"
	SnapshotUnrecoverablePurged   = "purged"
)
View Source
const BuiltinSource = "builtin"

BuiltinSource marks a rule that ships with the binary (the embedded rule files); a user or project rule file carries its path instead.

View Source
const (
	// DefaultImageMaxSide is the long side an image is scaled down to
	// (images.max_side). 1568 is what both Anthropic and OpenAI recommend as an
	// upper bound for a single picture.
	DefaultImageMaxSide = 1568
)

Image input, first phase (design 0.3): view_image reads a local picture and hands it to the model as an image part of the tool result.

The bytes never stay in the message: the store writes them to the session's images directory and keeps a reference (internal/personal). The tool itself is read-only and never marked Prefetchable: a prefetch would decode, scale and encode a picture a cut-away step never used, all of that wasted (the bytes are only written by AppendMessages, so a prefetch leaves no file behind). file_read reads pictures through this pipeline too and exempts its picture calls from the prefetch for the same reason (tools.PrefetchExempt).

View Source
const DefaultMaxOutputBytes = tools.DefaultInlineOutputBytes

DefaultMaxOutputBytes is the default inline threshold (tools.max_output_bytes): file_read pages its own output to this size, and the output layer (tools.NewOutput) externalises any other result larger than it.

View Source
const DefaultRawOutputBytes = tools.DefaultRawOutputBytes

DefaultRawOutputBytes is the default cap on the raw output of every other native tool (tools.max_spill_bytes). It bounds what the output layer may save to the session directory, not what enters the context.

View Source
const (

	// DefaultReadPageBytes is the default page cap of one file_read
	// (tools.read_page_bytes): most source files fit in one read, so the model
	// does not page through files it just wrote (suag-jz0l review).
	DefaultReadPageBytes = 32 << 10
)
View Source
const OutputRefPrefix = "out:"

OutputRefPrefix starts every ref to an externalised tool output (out:<session_id>:<16 hex>); other refs point at ledger messages (<session_id>/<seq>).

View Source
const PowerShellQuoteAdvice = "参数含 , = . @ 时整体加引号,例如 \"-Dtest=A,B\"、\"-Dincludes=g:a\"。"

PowerShellQuoteAdvice is appended to shell_exec's description when the shell is PowerShell: there a bare , = . @ inside an argument is syntax (a comma builds an array, an unquoted space splits it), so such an argument must be quoted as a whole (suga-cfeq: "-Dincludes=a,b" was split into an array).

View Source
const WriteScriptAdvice = "多行文本处理、复杂引号、JSON/正则处理时,先用 file_write 把脚本写到工作区 tmp/ 下再用解释器执行," +
	"不要在 shell 一行里拼复杂引号。"

WriteScriptAdvice asks for a script file instead of a heavily quoted shell line. It is appended to the environment section and to shell_exec's description (PowerShell) whenever an interpreter is available.

Variables

This section is empty.

Functions

func ApplyEdit

func ApplyEdit(content string, args map[string]any) (string, int, error)

ApplyEdit applies file_edit's arguments (old_string, new_string, replace_all, or the edits list) to content and returns the new content and the number of replacements. Edits apply in order to the previous result and any failure aborts the whole call. When the file uses CRLF and the strings use bare LF, the strings are converted so the file keeps CRLF. Exported so ACP can preview the exact result as a diff.

func BuildTools

func BuildTools(env Env, allowWrite bool) []api.Tool

BuildTools returns the catalog tools available in env, in catalog order. Tools that are not read-only (tools.MetaOf) are skipped unless allowWrite is set.

func CanonicalPath

func CanonicalPath(path string) string

CanonicalPath returns path in the one spelling a location has on this system: only Windows spells one directory two ways (8.3 short names), so nothing is looked up and resolved here and the Unix behaviour is unchanged. It cleans like the Windows version, so no caller has to know which system it runs on.

func DangerousDelete

func DangerousDelete(command string, powershell bool, workspace string) string

DangerousDelete reports why command looks like a catastrophic delete, or "" when it does not. powershell selects PowerShell syntax (else POSIX sh); relative paths resolve against workspace.

func DangerousDeleteKind added in v0.52.0

func DangerousDeleteKind(command string, powershell bool, workspace string, rw ...string) (reason string, hard bool)

DangerousDeleteKind is DangerousDelete that also says whether the target is one nobody may confirm away (hard): the user's home directory, the file system root (a drive root included), a parent directory of the workspace, or a path outside the workspace. The outside check applies to recursive deletes only and reads the path lexically (a symlink inside the workspace that points out is not followed). rw lists the session's read-write --add-dir directories: a path strictly inside one counts as inside the workspace (no finding), while the directory itself and its parents stay hard. The caller refuses a hard hit whatever the approval mode; other hits (the workspace itself, a variable-led path) may still be confirmed by the person.

func EditList

func EditList(args map[string]any) ([]map[string]any, error)

EditList returns file_edit's replacements as a list: the edits argument, or the single old_string/new_string pair. edits may arrive as a JSON string (some models encode nested arrays that way); mixing both forms is an error. An empty value of the form not used counts as absent: models with strict tool schemas fill every optional field, sending edits: [] next to an old_string/new_string pair, or old_string: "" next to edits.

func FormatByteSize

func FormatByteSize(n uint64) string

FormatByteSize renders a byte count the way the limits are configured ("4GiB", "512MiB", "64KiB").

func InterpreterHint

func InterpreterHint(list []Interpreter) string

InterpreterHint is the environment-section line that advertises the detected interpreters, e.g.

可用解释器:python 3.12.4(python)、node 22.6.0(node)。…

and asks the model to write a script file instead of quoting complex text on one shell line. It is "" when no interpreter was found: the model then stays with the system shell.

The text is generated per segment (the environment section travels in the segment context, not the stable system prompt), so a change here cannot invalidate the provider prefix cache.

func IsHardLinked

func IsHardLinked(path string, info os.FileInfo) bool

IsHardLinked reports whether a regular file has another directory entry. Undo refuses such targets because writing one link would mutate the other.

func MemoryCallID

func MemoryCallID(ctx context.Context) string

MemoryCallID returns the id of the memory tool call whose write is in progress (set for the store's Write, so a confirmation can refer to it).

func MinimizeToolOutput

func MinimizeToolOutput(call api.ToolCall, content string) (string, bool)

MinimizeToolOutput tidies with the built-in rules only.

func ModeSuffix

func ModeSuffix(writable bool) string

ModeSuffix names a directory mode as the --add-dir suffix: ":rw" when the directory is writable, ":ro" otherwise.

func MovePath

func MovePath(src, dst string) error

MovePath moves src to dst with the same-volume rename and cross-volume copy-then-remove fallback used by file_remove. Undo uses this helper to restore a trash entry without maintaining a second copy of the algorithm.

func NewFileTools

func NewFileTools(workspace string) []api.Tool

NewFileTools returns the three file tools scoped to workspace.

func NotedDirs

func NotedDirs(dirs []string) string

NotedDirs names the first few directories of dirs and how many more.

func ParseFetchProxy

func ParseFetchProxy(proxy string) (*url.URL, error)

ParseFetchProxy validates tools.web_fetch.proxy; empty means no proxy.

func ParseMemorySize

func ParseMemorySize(s string) (uint64, error)

ParseMemorySize reads tools.shell_limits.memory: a plain byte count ("1073741824") or a size with a unit ("4GiB", "512MiB", "1.5G"). "" and "off" (also "0") mean no limit; an unknown unit is an error, so a typo is a startup warning rather than a silently ignored limit.

func PrepareImage

func PrepareImage(data []byte, name string, maxSide int) (api.ImagePart, string, error)

PrepareImage identifies and scales a loaded picture the view_image way and returns the image part for a message plus its text description. Chat's :image and the clipboard paste reuse the tool's pipeline through it.

func ReadImageFile

func ReadImageFile(workspace string, readRoots []string, addDirs *AddDirs, arg string) ([]byte, string, error)

ReadImageFile loads a picture for a chat-side command (:image, Alt+V paste) with exactly the rules view_image applies: the same path resolution (workspace, read-only roots, added directories) and input size limits.

func ReadPathList

func ReadPathList(args map[string]any) ([]string, error)

ReadPathList returns file_read's paths: path, then the entries of paths (duplicates dropped), each without its line-span suffix. paths may arrive as a JSON-encoded string, as some models encode arrays that way, or as a single plain string. The callers beyond file_read (the outside-directory check and the ACP location) get the file itself, never a "file:120-180" argument.

func ReportSnapshot

func ReportSnapshot(ctx context.Context, report SnapshotReport)

ReportSnapshot replaces the current context report with a snapshot summary. Native tools call this only after the snapshot outcome is known; callers without an observing context are intentionally ignored.

func ResolveSandboxedPath

func ResolveSandboxedPath(workspace, rel string) (string, error)

ResolveSandboxedPath is the path rule shared by the file tools. A relative rel is joined under workspace; an absolute rel is accepted only when it lies inside workspace (Windows compares volume and names case-insensitively) and is otherwise rejected. Either way the result must not escape workspace. Exported so ACP reports exactly the path the tool writes.

func RootPaths

func RootPaths(roots []ReadRoot) []string

RootPaths returns the paths of roots, in order.

func ShellName

func ShellName(explicit string) string

ShellName reports the shell shell_exec uses for the given tools.shell value (empty = OS default), for the system prompt.

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; limit <= 0 uses DefaultMaxOutputBytes. See tools.TruncateHeadTail.

func TruncateLines

func TruncateLines(s string, limit int) (string, int, bool)

TruncateLines keeps whole lines of s while they fit in limit bytes. It returns the kept text, the number of kept lines and whether anything was dropped. A single line longer than limit is cut on a UTF-8 boundary so at least some content comes back.

Types

type AddDir

type AddDir struct {
	Path     string
	Writable bool
}

AddDir is one additional directory of the session (--add-dir): the read tools may read it and, when Writable (:rw), the write tools may change it too. Path is absolute and cleaned.

type AddDirs

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

AddDirs is the additional-directory set of the session being served. The runtime and its tools are assembled before the session is opened, so the front end fills the set once the session is known and the tools read it at every call. A nil *AddDirs means "no additional directory" everywhere.

func NewAddDirs

func NewAddDirs() *AddDirs

NewAddDirs returns an empty set.

func (*AddDirs) List

func (a *AddDirs) List() []string

List renders the set as "path:ro" / "path:rw" entries, in order. The turn_context event records it so a trace shows what the session could reach.

func (*AddDirs) ReadPaths

func (a *AddDirs) ReadPaths() []string

ReadPaths returns the directories the read tools may read: every added directory, the read-write ones included.

func (*AddDirs) Set

func (a *AddDirs) Set(dirs []AddDir)

Set replaces the set: paths are cleaned and a path named twice keeps its first entry (the front end resolves path conflicts before setting them).

func (*AddDirs) Snapshot

func (a *AddDirs) Snapshot() []AddDir

Snapshot returns the set in order.

func (*AddDirs) WritePaths

func (a *AddDirs) WritePaths() []string

WritePaths returns the directories the write tools may write: only :rw ones.

type AgentReport

type AgentReport struct {
	SessionID string
	Report    string
	// Stop is why it ended: final, max_steps, max_tokens, timeout, cancelled
	// or failed.
	Stop      string
	Steps     int
	ToolCalls int
	Usage     api.Usage
	Duration  time.Duration
	// Tainted: the sub-agent read external content.
	Tainted bool
}

AgentReport is the outcome of a sub-agent run.

type AgentRequest

type AgentRequest struct {
	Type, Description, Prompt string
	// ParentSession, ParentTurn and CallID name the turn's tool call that
	// started it (SubAgents.Scope fills the first two at the call).
	ParentSession, ParentTurn, CallID string
	// Background: it runs as a task; the host marks the parent session
	// tainted itself when the sub-agent read external content (the report
	// reaches the model through a notice or the task tool, not this result).
	Background bool
}

AgentRequest is one sub-agent run.

type AgentTool

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

AgentTool hands a task to a sub-agent: a model run in a session of its own with read-only tools; only its final report comes back, so exploring many files does not fill this conversation.

func NewAgentTool

func NewAgentTool(agents SubAgents) *AgentTool

NewAgentTool returns the agent tool over agents.

func (*AgentTool) Description

func (t *AgentTool) Description() string

Description skips the type restatement: the type parameter's own description names both values and what each gets (docs/research/ 2026-10-23-fixed-prefix-tools-report.md 三 #21).

func (*AgentTool) Execute

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

func (*AgentTool) Name

func (t *AgentTool) Name() string

func (*AgentTool) Schema

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

func (*AgentTool) SetTasks

func (t *AgentTool) SetTasks(m *tasks.Manager)

SetTasks enables background: true (the host owns m).

func (*AgentTool) ToolMeta

func (*AgentTool) ToolMeta() tools.Meta

ToolMeta: it only reads (through its sub-agent), so it needs no approval and is available in read-only sessions.

type BuiltinRuleFile

type BuiltinRuleFile struct {
	// Name is the file's embedded path, e.g. outrules/go.yaml.
	Name string
	// YAML is the file's raw content, so `suga inspect rules --builtin` prints
	// exactly what ships and a template can be written from it.
	YAML []byte
}

BuiltinRuleFile is one embedded rule file as the binary carries it.

func BuiltinOutputRuleFiles

func BuiltinOutputRuleFiles() []BuiltinRuleFile

BuiltinOutputRuleFiles returns the embedded output rule files in the order they are read in, so a rule writer sees the shipped rules verbatim.

type Env

type Env struct {
	// Workspace confines file tools and is the shell working directory.
	Workspace string
	// TrashDir is where file_remove moves removed paths (kept TrashRetention);
	// empty leaves file_remove unavailable.
	TrashDir string
	// ReadRoots are directories outside the workspace the read-only file tools
	// may read too (dependency sources, tools.read_roots). Writes never go there.
	ReadRoots []string
	// AddDirs are the additional directories of the session being served
	// (--add-dir): the tools read the set at every call, because the runtime is
	// assembled before the session is opened. nil = no additional directory.
	AddDirs *AddDirs
	// Snapshots receives before/after notifications for file-writing tools.
	// nil disables snapshotting.
	Snapshots Snapshotter
	// InlineBytes is the inline threshold (tools.max_output_bytes). Tools
	// leave the inline cut to the output layer (tools.NewOutput); file_read
	// pages by itself with ReadPageBytes instead.
	InlineBytes int
	// ReadPageBytes caps one file_read page (tools.read_page_bytes);
	// 0 = DefaultReadPageBytes.
	ReadPageBytes int
	// RawBytes caps the raw result of every other tool (tools.max_spill_bytes),
	// i.e. how much the output layer may save to the session directory.
	RawBytes int
	// SerpAPIKey enables web_search; empty leaves it unavailable.
	SerpAPIKey string
	// Shell overrides the shell_exec shell (tools.shell); empty = OS default.
	Shell string
	// Interpreters are the script interpreters detected on PATH
	// (tools.interpreters, see DetectInterpreters); empty = none, no hint.
	Interpreters []Interpreter
	// ShellTimeoutMax caps a shell_exec timeout (tools.shell_timeout_max).
	ShellTimeoutMax time.Duration
	// TaskTimeoutMax caps a background shell task (tools.task_timeout_max).
	TaskTimeoutMax time.Duration
	// ShellBackgroundAfter is the foreground grace period before a shell is
	// transferred to the task manager; zero disables transfer.
	ShellBackgroundAfter time.Duration
	// ShellLimits caps the memory, process count and CPU time of a command and
	// its process tree (tools.shell_limits); the zero value is no limit.
	ShellLimits ShellLimits
	// FetchAllowPrivate lets web_fetch reach private and local addresses
	// (tools.web_fetch.allow_private).
	FetchAllowPrivate bool
	// FetchProxy routes web_fetch through a proxy (tools.web_fetch.proxy);
	// wiring validates it at startup with ParseFetchProxy. It only applies when
	// NetworkProxy is nil.
	FetchProxy string
	// NetworkProxy is the global network.proxy selector used by web_fetch and
	// web_search; nil keeps their previous behavior (web_fetch ignores the
	// environment proxies, web_search follows them).
	NetworkProxy *netproxy.Selector
	// FetchUserAgent is the User-Agent web_fetch sends
	// (tools.web_fetch.user_agent); empty keeps the tool's default.
	FetchUserAgent string
	// ImagesDir is the session's images directory (view_image accepts a ref to
	// one of its files); empty = only ordinary paths.
	ImagesDir string
	// Vision is the live capability of the current model (nil = can see):
	// view_image explains how to switch instead of reading a picture nobody can
	// see. The host updates the gate on a model switch.
	Vision *tools.VisionGate
	// ImageMaxSide is the long side view_image scales a picture to when the call
	// names none (images.max_side); 0 = DefaultImageMaxSide.
	ImageMaxSide int
	// ExtraEnv adds the variables suga exports to a subprocess (the session, its
	// short name and the turn); the tools and chat's local commands call it at
	// every run, so it may still be nil or return nothing when they are built.
	ExtraEnv func(context.Context) []string
	// SessionMessenger is the host side of the session_message tool (the running
	// chat sessions of this SUGA_HOME); nil keeps the tool out of the catalog
	// (tools.session_message.enabled, SUGA_SESSION_MESSAGE=off).
	SessionMessenger SessionMessenger
	// TurnID names the turn ctx belongs to ("" outside a turn): the per-turn send
	// limit of session_message resets with every turn.
	TurnID func(context.Context) string
	// ProtectChangedFiles makes file_write and file_edit refuse a file that was
	// changed on disk since this tool set last read or wrote it
	// (tools.protect_changed_files); BuildTools gives the tools one shared
	// FileGuard, so each tool set (a sub-agent's included) has its own table.
	ProtectChangedFiles bool
	// Guard is that table; BuildTools fills it when ProtectChangedFiles is set.
	Guard *FileGuard
}

Env carries the settings native tools are built with. Zero values fall back to each tool's defaults.

type FileEditTool

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

FileEditTool replaces exact strings in a workspace file (or a file under a directory the session added as read-write): one replacement (old_string/new_string) or several in one call (edits).

func (*FileEditTool) Description

func (t *FileEditTool) Description() string

Description skips the "prefer this over file_write" sentence: the stable system prompt already says it (docs/research/ 2026-10-23-fixed-prefix-tools-report.md 三 #20).

func (*FileEditTool) Execute

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

func (*FileEditTool) Name

func (t *FileEditTool) Name() string

func (*FileEditTool) Schema

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

func (*FileEditTool) ToolMeta

func (*FileEditTool) ToolMeta() tools.Meta

ToolMeta marks the tool as an edit: it changes workspace files.

type FileFindTool

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

FileFindTool finds files by glob pattern in the workspace.

func (*FileFindTool) Description

func (t *FileFindTool) Description() string

func (*FileFindTool) Execute

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

func (*FileFindTool) Name

func (t *FileFindTool) Name() string

func (*FileFindTool) Schema

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

func (*FileFindTool) ToolMeta

func (*FileFindTool) ToolMeta() tools.Meta

ToolMeta marks the tool as a read-only search.

type FileGrepTool

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

FileGrepTool searches file contents in the workspace with a regular expression, in pure Go (no external rg).

func (*FileGrepTool) Description

func (t *FileGrepTool) Description() string

Description keeps the result shape and the skip defaults; the parameter restatement (glob/exclude/context/literal sentences) went, each parameter's own description is the one place that text lives (docs/research/ 2026-10-23-fixed-prefix-tools-report.md 三 #12-#13).

func (*FileGrepTool) Execute

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

func (*FileGrepTool) Name

func (t *FileGrepTool) Name() string

func (*FileGrepTool) Schema

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

func (*FileGrepTool) ToolMeta

func (*FileGrepTool) ToolMeta() tools.Meta

ToolMeta marks the tool as a read-only search.

type FileGuard added in v0.52.0

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

FileGuard remembers the stamp of every file a session's file_read, file_write and file_edit last saw, and refuses a write over a file that changed since (tools.protect_changed_files): the model would be writing from stale content. A file never read or written in the session is not guarded - creating a file or writing one the model never looked at keeps working. One FileGuard belongs to one tool set (BuildTools makes one per call), so a sub-agent has its own table; the mutex covers tools running in parallel.

func GuardOf added in v0.52.0

func GuardOf(t api.Tool) *FileGuard

GuardOf returns the FileGuard a file tool of a tool set works with (nil when the tool is not a file tool or the guard is off), so the host can Forget the files it changes itself.

func NewFileGuard added in v0.52.0

func NewFileGuard() *FileGuard

NewFileGuard returns an empty guard.

func (*FileGuard) Forget added in v0.52.0

func (g *FileGuard) Forget(paths ...string)

Forget drops the records of paths, so the next write of them is judged as for a file never read. Suga calls it for files it changed itself outside the file tools (:undo restoring a checkpoint): without it the guard would take its own restore for an outside change. A nil guard does nothing.

type FileListTool

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

FileListTool lists files in a workspace directory, optionally recursively.

func (*FileListTool) Description

func (t *FileListTool) Description() string

Description skips the "the result says which" parenthetical: the no_ignore parameter and the result's own note carry it (docs/research/ 2026-10-23-fixed-prefix-tools-report.md 三 #22).

func (*FileListTool) Execute

func (t *FileListTool) Execute(_ context.Context, call api.ToolCall) (*api.ToolResult, error)

func (*FileListTool) Name

func (t *FileListTool) Name() string

func (*FileListTool) Schema

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

func (*FileListTool) ToolMeta

func (*FileListTool) ToolMeta() tools.Meta

ToolMeta marks the tool as a read-only read.

type FileReadTool

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

FileReadTool reads files within the workspace (or a read root), a window of lines at a time.

func (*FileReadTool) Description

func (t *FileReadTool) Description() string

Description keeps the window/multi-path/image contract; the outline restatement went (its parameter is the one place the trigger and the 300-line threshold are stated) with the "cannot see images" note, which the tool result itself shows when it happens (docs/research/ 2026-10-23-fixed-prefix-tools-report.md 三 #14-#15).

func (*FileReadTool) Execute

func (t *FileReadTool) Execute(_ context.Context, call api.ToolCall) (*api.ToolResult, error)

func (*FileReadTool) Name

func (t *FileReadTool) Name() string

func (*FileReadTool) Schema

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

func (*FileReadTool) SetImagePipeline

func (t *FileReadTool) SetImagePipeline(img *ViewImageTool) *FileReadTool

SetImagePipeline binds file_read to the picture pipeline it shares with view_image: the same instance, so the runtime's live vision gate (:model) and the session images directory resolver (:resume, :new) apply to both.

func (*FileReadTool) SkipPrefetch

func (t *FileReadTool) SkipPrefetch(args map[string]any) bool

SkipPrefetch implements tools.PrefetchExempt: a call naming a picture or a session image ref is not run ahead. Decoding, scaling and encoding a picture for a step that is cut away is wasted work (design 2026-10-23 section 7), and view_image never prefetched either. The guess is by extension and ref form only: a picture without one of those extensions keeps being prefetched (one extra decode, no visible effect).

func (*FileReadTool) ToolMeta

func (*FileReadTool) ToolMeta() tools.Meta

ToolMeta marks the tool as a read-only read.

type FileRefsTool

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

FileRefsTool answers "who calls X / where is X used" for one name (design docs/design/2026-10-18-symbol-refs-design.md): one "path:line class text" line per use, across a file, a directory or the workspace. Go is classified by go/parser without type checking; the other supported languages are matched word-bounded with comments and strings masked and marked approx. It is read-only, parses in memory only, and no index or cache is involved: every call reads the files again.

func (*FileRefsTool) Description

func (t *FileRefsTool) Description() string

Description keeps the call contract (what goes in, what a result line looks like, how a qualified name is narrowed) and drops the parser/language mechanics: the result still marks every match approx/class/pkg:, so the model learns the difference from one answer instead of ones in the prefix (docs/research/2026-10-23-fixed-prefix-tools-report.md 三 #1-#4).

func (*FileRefsTool) Execute

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

func (*FileRefsTool) Name

func (t *FileRefsTool) Name() string

func (*FileRefsTool) Schema

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

func (*FileRefsTool) ToolMeta

func (*FileRefsTool) ToolMeta() tools.Meta

ToolMeta marks the tool as a read-only search by name, like file_grep: it reports positions, it does not read a target's whole content.

type FileRemoveTool

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

FileRemoveTool removes a file or directory inside the workspace, or under a directory the session added as read-write (--add-dir ...:rw). Regular content is moved into the trash (kept TrashRetention, then purged) so it can be restored; ignored directories (node_modules, vendor, dist and directories matched by the .gitignore files, e.g. tmp/) are regenerable and deleted for good without being walked, so large caches neither slow the call down nor fill the trash. Ignored single files (.env, local config) still go to the trash: they are often not regenerable. It refuses the workspace root, the workspace's own .git, the user's home directory and anything outside the workspace, never expands wildcards, needs recursive for a directory and moves at most RemoveMaxFiles files to the trash per call.

func NewFileRemoveTool

func NewFileRemoveTool(workspace, trashDir string) *FileRemoveTool

NewFileRemoveTool builds file_remove; trashDir must be an absolute directory outside the workspace (e.g. <SUGA_HOME>/trash).

func (*FileRemoveTool) Description

func (t *FileRemoveTool) Description() string

Description skips the "instead of shell rm" sentence: the stable system prompt already names file_remove for every delete (docs/research/ 2026-10-23-fixed-prefix-tools-report.md 三 #19).

func (*FileRemoveTool) Execute

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

func (*FileRemoveTool) Name

func (t *FileRemoveTool) Name() string

func (*FileRemoveTool) Schema

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

func (*FileRemoveTool) ToolMeta

func (*FileRemoveTool) ToolMeta() tools.Meta

ToolMeta marks the tool as a deletion: it changes workspace files.

type FileSymbolsTool

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

FileSymbolsTool lists the declarations of a source file, or of every source file under a directory (design docs/design/2026-10-18-explore-efficiency-design.md, CAP-02): "which declarations are in this package, and on which line" is what the model answered by guessing file_grep patterns before. It is read-only and parses in memory only.

func (*FileSymbolsTool) Description

func (t *FileSymbolsTool) Description() string

Description keeps the listing contract and the file_refs pointer, and drops the per-language parser details: an approx result line carries the same information, and the caps (config key levels, 200 declarations) only matter when a result they explain appears (docs/research/ 2026-10-23-fixed-prefix-tools-report.md 三 #5-#9).

func (*FileSymbolsTool) Execute

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

func (*FileSymbolsTool) Name

func (t *FileSymbolsTool) Name() string

func (*FileSymbolsTool) Schema

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

func (*FileSymbolsTool) ToolMeta

func (*FileSymbolsTool) ToolMeta() tools.Meta

ToolMeta marks the tool as a read-only read of the sources. It pages its own result (limit), so it is not Rereadable: the output layer may wrap it.

type FileWriteTool

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

FileWriteTool writes/creates a file within the workspace, or under a directory the session added as read-write (--add-dir ...:rw).

func (*FileWriteTool) Description

func (t *FileWriteTool) Description() string

func (*FileWriteTool) Execute

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

func (*FileWriteTool) Name

func (t *FileWriteTool) Name() string

func (*FileWriteTool) Schema

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

func (*FileWriteTool) ToolMeta

func (*FileWriteTool) ToolMeta() tools.Meta

ToolMeta marks the tool as an edit: it changes workspace files.

type FoldBlock

type FoldBlock struct {
	Start string `yaml:"start"`
	Body  string `yaml:"body"`
	Text  string `yaml:"text"`
}

FoldBlock collapses a run of lines repeating the same noise into one line: start matches its first line, body every following line of the run, and text is what replaces the run ({lines} = the number of lines folded, {1}/{name} = a capture group of the start line; empty text drops the whole run). Maven's effective-model warnings are the case it was added for.

type Interpreter

type Interpreter struct {
	Name    string
	Path    string
	Version string
}

Interpreter is one script interpreter found on PATH and confirmed to work: Name is the command that was looked up (or the name the configuration gave), Path the resolved binary and Version the version string it printed for --version.

func DetectInterpreters

func DetectInterpreters(setting any) []Interpreter

DetectInterpreters returns the interpreters to advertise for a tools.interpreters value (see ParseInterpreterSetting). Every candidate is probed at most once per process: results are cached per setting, so a turn never pays for the probe again.

type InterpreterSetting

type InterpreterSetting struct {
	// Enabled is false when detection is switched off: nothing is probed and no
	// hint is written, so the model stays with the system shell.
	Enabled bool
	// Auto probes the built-in candidate list; when false, Names holds the
	// commands and paths the configuration named.
	Auto  bool
	Names []string
}

InterpreterSetting is a parsed tools.interpreters value (see ParseInterpreterSetting).

func ParseInterpreterSetting

func ParseInterpreterSetting(raw any) InterpreterSetting

ParseInterpreterSetting reads a tools.interpreters config value:

  • unset, true or "auto": probe the built-in candidates (default);
  • false or "off": no detection;
  • a command name, an absolute path, or a list of either: probe exactly those (an absolute path is taken as the user's own choice, so the Windows store-alias check does not apply to it).

An empty list or an unusable value (a number, a map) keeps the default.

type LedgerHit

type LedgerHit struct {
	// Ref locates the match: <session_id>/<seq> for a message, the out:...
	// ref for a line of an externalised output.
	Ref string
	// Role is the entry type of a message hit (user, assistant, tool,
	// compaction, handoff); empty for line hits.
	Role string
	// Line is the 1-based line number of a hit inside an externalised output;
	// 0 for message hits.
	Line int
	// Snippet is a short excerpt around the match.
	Snippet string
}

LedgerHit is one search match.

type LedgerQuery

type LedgerQuery struct {
	// Query is split on whitespace; every term must occur (AND). Terms are
	// literal text, never search syntax.
	Query string
	// Scope is current, workspace or all ("" = workspace).
	Scope string
	// Ref, when set, is an out:... ref: the search then scans that one
	// externalised output line by line and Scope is ignored.
	Ref string
	// Limit caps the hits (<= 0 = the implementation default).
	Limit int
	// Cursor resumes a process-local search snapshot returned by next_cursor.
	Cursor string
	// Kinds restrict message hits to the indexed entry roles.
	Kinds []string
	// Since is inclusive and Until is exclusive; zero means no bound.
	Since time.Time
	Until time.Time
}

LedgerQuery is one session_search request.

type LedgerSearchResult

type LedgerSearchResult struct {
	Hits       []LedgerHit
	NextCursor string
	Notice     string
	// HistoryEmpty is set by the searcher when the query's scope holds no
	// searchable entry at all: the search found nothing because there is nothing
	// there, so another wording cannot match either. It is never set for a
	// narrowed query (cursor, kind or a time bound) or for a ref search, where a
	// scope with no hit still holds history (suag-hpu7).
	HistoryEmpty bool
}

LedgerSearchResult is one page of ledger hits and its optional continuation metadata. Notice explains a stale cursor or a bounded snapshot without making an otherwise valid search fail.

type LedgerSearcher

type LedgerSearcher interface {
	Search(ctx context.Context, q LedgerQuery) (LedgerSearchResult, error)
	// Fetch returns a readable window: for <session_id>/<seq> the messages
	// from seq on (offset skips messages, limit counts them); for out:... the
	// lines starting at line offset (1-based; 0 = 1), limit lines.
	Fetch(ctx context.Context, ref string, offset, limit int) (string, error)
}

LedgerSearcher reads the session ledger and externalised tool outputs. The host implements it (one real implementation, so the interface is declared here at the consumer, like PlanSink and ToolSearcher).

type LocalCommand

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

LocalCommand runs one command a person typed at the chat prompt (a "!cmd" or "!!cmd" line, chat's local command). It runs exactly the way shell_exec runs one: the same shell (tools.shell, else the OS default), the workspace as the working directory, the same environment (suga's own settings removed) and the same promise that the whole process tree dies with the run - the person's Ctrl-C and the timeout both go through it. The output is streamed to the caller as it is produced (the person watches the command run) and the same text is handed back, tidied by the tool output minimizer and cut to the inline limit, for the next model message.

It is deliberately not a tool: a local command never goes through approval, the tool list or a turn. shell_exec's "[stderr]" marker is the one difference from a tool call: stdout and stderr share the stream the person watches, so the text is their interleaving.

func NewLocalCommand

func NewLocalCommand(opts LocalCommandOptions) *LocalCommand

NewLocalCommand returns the runner of a front end's local commands.

func (*LocalCommand) Run

func (c *LocalCommand) Run(ctx context.Context, command string, stream io.Writer) (LocalCommandResult, error)

Run runs command, streaming its output to stream (nil: the output is only collected) and killing the whole process tree when ctx ends or the timeout is reached. An error is returned only when the command could not be started (or the shell itself failed): a cancellation, a timeout and a non-zero exit code are reported on the result.

func (*LocalCommand) ShellName

func (c *LocalCommand) ShellName() string

ShellName names the shell this runner uses (for the banner and the usage hint); it is the shell shell_exec would use for the same configuration.

type LocalCommandOptions

type LocalCommandOptions struct {
	// Workspace is the directory the command runs in (the session's workspace).
	Workspace string
	// Shell is tools.shell: a command name or path ("", the OS default).
	Shell string
	// Timeout caps one run (tools.shell_timeout_max: 0 = DefaultShellTimeoutMax).
	Timeout time.Duration
	// RawBytes caps the output kept (tools.max_spill_bytes).
	RawBytes int
	// InlineBytes caps the block handed to the model (tools.max_output_bytes).
	InlineBytes int
	// Minimize is the tool result tidier (wiring's minimizeOutput); nil keeps
	// the output as it is.
	Minimize func(api.ToolCall, string) (string, bool)
	// ExtraEnv adds the variables suga exports to a command (native.Env.ExtraEnv).
	ExtraEnv func(context.Context) []string
}

LocalCommandOptions configures a LocalCommand runner; every zero value falls back to shell_exec's own default.

type LocalCommandResult

type LocalCommandResult struct {
	// ExitCode is the shell's exit code (-1 when it was killed before exiting).
	ExitCode int
	// Duration is how long the command ran.
	Duration time.Duration
	// Bytes is how much output the command wrote.
	Bytes int
	// TimedOut is true when the run hit its timeout (the process tree was killed).
	TimedOut bool
	// Cancelled is true when ctx ended the run (the person's Ctrl-C or Esc, or
	// chat leaving).
	Cancelled bool
	// ModelText is the block the next model message carries for a "!!" command:
	// the command, its exit code and its output (tidied like a shell_exec result
	// and cut to the inline limit). Empty when the command never ran or wrote
	// nothing at all.
	ModelText string
}

LocalCommandResult is what one run produced.

type MemoryChange

type MemoryChange struct {
	Action string // add, replace or remove
	Scope  string // scope kind: project or user
	ID     string
	Title  string
}

MemoryChange is a successful memory write as reported in the tool result, parsed back by ParseMemoryResult (chat shows "已记住:..." from it).

func ParseMemoryResult

func ParseMemoryResult(content string) (MemoryChange, bool)

ParseMemoryResult reads the first line of a successful memory write result.

type MemoryTexts

type MemoryTexts struct {
	// ReadOnly refuses a write in a read-only run: %s action.
	ReadOnly string
	// NeedsConfirmation refuses a write of a tainted session that cannot ask.
	NeedsConfirmation string
	// Denied is a write whose confirmation was not given: %v cause.
	Denied string
	// Tombstoned is a write equal to a removed entry: %v cause.
	Tombstoned string
	// OverBudget is a full index: %s scope, %v cause.
	OverBudget string
	// NotFound is a missing id: %s scope, %q id.
	NotFound string
	// NoBackend is a scope without a backend: %s scope.
	NoBackend string
	// Invalid is a bad request: %v cause.
	Invalid string
	// Failed wraps any other store error: %s action, %s scope, %w cause.
	Failed string
}

MemoryTexts is the model-facing wording of the memory tool's refusals and errors, 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 keep the format verbs of their line, which are what the tool formats with fmt.Errorf. Actions (add/replace/remove/get/search) and scopes are part of the call shape and stay untranslated.

func DefaultMemoryTexts

func DefaultMemoryTexts() MemoryTexts

DefaultMemoryTexts returns the historical Chinese wording.

type MemoryTool

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

MemoryTool reads and writes long-term memory through a memory.Store (normally memory.Governed over a Router). It only changes the agent's own state, so it is AgentState: approval layers let it through and the tool enforces the read-only mode itself.

func NewMemoryTool

func NewMemoryTool(store memory.Store, opts MemoryToolOptions) *MemoryTool

NewMemoryTool creates the memory tool over store.

func (*MemoryTool) Description

func (t *MemoryTool) Description() string

Description is the tool contract for the model (design D5): what is worth storing and actions vs summary rules. The four kinds and the do-not-store list are not restated here: the memory-index note every segment context carries already states both (internal/personal/memory.go), and the two texts had started to drift (docs/research/2026-10-23-fixed-prefix-tools-report.md 三 #10-#11).

func (*MemoryTool) Execute

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

func (*MemoryTool) Name

func (t *MemoryTool) Name() string

func (*MemoryTool) Schema

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

func (*MemoryTool) ToolMeta

func (*MemoryTool) ToolMeta() tools.Meta

ToolMeta: an agent-state write tool (memory is suga's own state, not the workspace); read-only mode is enforced inside Execute.

type MemoryToolOptions

type MemoryToolOptions struct {
	// Writable allows add/replace/remove. false (read-only runs) refuses every
	// write before the store is called; get/search stay available.
	Writable bool
	// ProjectKey is the key of the project scope (scope=project); empty
	// means the project scope is unavailable.
	ProjectKey string
	// Backend names the backend serving a scope ("files", "gofer", "exec").
	// Results read from any backend other than files are marked external so
	// the host flags the session as tainted. nil or an unknown name counts as
	// external (fail closed).
	Backend func(memory.Scope) string
	// ProvenanceFrom returns the session/turn of the call from ctx (set by
	// the host); nil leaves the provenance empty apart from Source.
	ProvenanceFrom func(ctx context.Context) memory.Provenance
	// Texts is the model-facing wording of the refusals and errors; the zero
	// value is the historical Chinese text (see MemoryTexts).
	Texts MemoryTexts
}

MemoryToolOptions configures the memory tool.

type OutputMinimizer

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

OutputMinimizer tidies successful shell_exec results for the model (tools.OutputConfig.Minimize): colour codes and carriage-return progress are dropped, runs of identical lines folded, and the output of a command an OutputRule matches (go test, cargo test, jest, pytest, maven, ...) is reduced to what matters - a summary when everything passed, the failures with their messages otherwise (the omp shell minimizer and pi-go's compactor do the same). Lines no rule recognises are kept. The output layer keeps the original under a ref.

func NewOutputMinimizer

func NewOutputMinimizer(rules []OutputRule) *OutputMinimizer

NewOutputMinimizer returns a minimizer applying rules (see LoadOutputRules).

func (*OutputMinimizer) Minimize

func (m *OutputMinimizer) Minimize(call api.ToolCall, content string) (string, bool)

Minimize returns the tidied content; ok is false when nothing worth it changed.

type OutputRule

type OutputRule struct {
	Name    string `yaml:"name"`
	Enabled *bool  `yaml:"enabled"` // nil = on
	Match   string `yaml:"match"`
	// MatchOutput, when set, requires the output to hold this pattern as well: a
	// rule written for one output shape (the header of a git diff, say) then
	// stays out of the way of the same command printing something else.
	MatchOutput string   `yaml:"match_output"`
	Drop        []string `yaml:"drop"`
	Block       struct {
		Start string `yaml:"start"`
		Body  string `yaml:"body"`
		Pass  string `yaml:"pass"`
		Fail  string `yaml:"fail"`
	} `yaml:"block"`
	Failure []string          `yaml:"failure"`
	Count   map[string]string `yaml:"count"`
	Sum     map[string]string `yaml:"sum"`
	Fold    []FoldBlock       `yaml:"fold"`
	// Replace rewrites what the rule keeps (after drop/fold/block, before
	// group_by); see ReplaceBlock.
	Replace []ReplaceBlock `yaml:"replace"`
	// GroupBy is a regexp with a capture group holding a group key: neighbouring
	// lines sharing the key merge into one header line and the rest of every
	// line, indented (a grep hit's file path is printed once).
	GroupBy string `yaml:"group_by"`
	// Head and Tail keep the first/last N lines of the rule's result, the lines
	// in between go; they act before the global line cap (minimize.go).
	Head int `yaml:"head"`
	Tail int `yaml:"tail"`
	// MinBytes and MinSaving lower the global gates for this rule (of all rules
	// matching a command the most permissive value wins); nil = global default.
	MinBytes  *int     `yaml:"min_bytes"`
	MinSaving *float64 `yaml:"min_saving"`
	Summary   string   `yaml:"summary"`

	// Source is the layer the rule came from (\"builtin\", or the rule file's
	// path); the loaders fill it and the manifest and `suga inspect rules`
	// report it.
	Source string `yaml:"-"`
	// contains filtered or unexported fields
}

OutputRule tidies the output of the shell commands it matches; see outrules/README.md for the fields. Rules are data so new tools and languages are added without code (omp's shell minimizer works the same way).

func DefaultOutputRules

func DefaultOutputRules() []OutputRule

DefaultOutputRules returns the built-in rules (go build/vet/test, cargo test, TypeScript/ESLint, Ruff/Mypy, Jest/Vitest, pytest, maven, gradle and the command-line tool families), read from the embedded rule files in builtinRuleFileOrder. A rule file that does not parse is a build error: the rules ship with the binary.

func LoadOutputRules

func LoadOutputRules(paths ...string) ([]OutputRule, []error)

LoadOutputRules returns the built-in rules merged with the rule files in order (later files win): a rule with the name of an earlier one replaces it, a new name is appended. Missing files are skipped; a file that does not parse or holds a broken rule is reported and skipped as a whole.

type OutsideDir

type OutsideDir struct {
	// Path is the canonical absolute path of the directory to authorize: the
	// target itself when it is an existing directory, the directory of an
	// existing file, else the nearest existing ancestor. It is derived from the
	// path the tool would really resolve (symlinks followed), never from words
	// the model wrote about the call.
	Path string
	// Target is the call's path argument, cleaned but otherwise as given, for
	// the question's detail line.
	Target string
	// Writable reports that the call would change files under Path (a write
	// tool), so authorizing it read-only would not be enough.
	Writable bool
}

OutsideDir is a directory a file tool call wants to reach that lies outside the workspace, the configured read roots and the session's added directories. The chat approver asks the person to authorize such a directory before the call runs (chat.ask_outside_dirs).

func OutsideOf

func OutsideOf(workspace string, readRoots []string, dirs *AddDirs, tool string, args map[string]any) (OutsideDir, bool)

OutsideOf reports the directory a file tool call reaches outside the workspace, the read roots and dirs. Only the absolute path arguments of the file tools count: a relative path can only ever name a place inside the workspace, and a path that is already reachable needs no authorization. ok is false when nothing has to be authorized (an unknown tool, no path argument, a reachable path, or a target with no authorizable directory such as the volume root).

readRoots are the tool's static read-only roots (native.RootPaths); dirs is the session's live added-directory set. A write call is checked against the read-write directories only, exactly like the write tools themselves, so a write into a read-only added directory is offered as an authorization too.

type Plan

type Plan struct {
	Explanation string     `json:"explanation,omitempty"`
	Steps       []PlanStep `json:"plan"`
}

Plan is the full task list; every update replaces the previous one.

type PlanSink

type PlanSink interface {
	RecordPlan(ctx context.Context, plan Plan) error
}

PlanSink persists and publishes a validated plan. It is injected when the tool is built, so this package never depends on the session layer.

type PlanStep

type PlanStep struct {
	Step   string `json:"step"`
	Status string `json:"status"`
}

PlanStep is one item of the task list.

type ReadRoot

type ReadRoot struct {
	Label string // what the directory holds, e.g. "Go modules"
	Path  string // absolute and cleaned
}

ReadRoot is a directory outside the workspace that the read-only file tools (file_read, file_list, file_grep, file_find) may read. Writes stay confined to the workspace.

func ConfiguredReadRoots

func ConfiguredReadRoots(entries []string) ([]ReadRoot, []error)

ConfiguredReadRoots turns tools.read_roots entries into read roots: "~" is expanded, the path must be absolute and an existing directory. Rejected entries are returned as errors so the caller can report them.

func DeduplicateReadRoots

func DeduplicateReadRoots(roots []ReadRoot) []ReadRoot

DeduplicateReadRoots keeps the first label and path for each root. Windows path comparison follows the same case-insensitive rule as native path access.

func DependencyRoots

func DependencyRoots() []ReadRoot

DependencyRoots detects the local dependency caches and repositories of every declared language, in Languages() order: the Go module cache, the Go standard library sources, the Rust crate sources, the Maven local repository and the Gradle module cache. Only directories holding dependency files are returned, never a whole tool home (~/.cargo, ~/.gradle and ~/.m2 hold credentials or build state too). Directories that do not exist are left out. It runs no external command: the go env file, environment variables and the go binary location in PATH are enough.

A pathless file_grep / file_find only searches the workspace, so these large roots are walked only when the model passes one of them as the search path (such a walk stops at searchTimeout and at the tool's result limit).

func ExistingReadRoot

func ExistingReadRoot(label, dir string) (ReadRoot, bool)

ExistingReadRoot reports the read root for dir (absolute, existing directory only), matching the safety boundary used by configured and dependency roots.

func StandardsRoots

func StandardsRoots(workspace string) []ReadRoot

StandardsRoots detects the idev-std release and workspace loading roots. The roots are read-only: file tools may read them, while writes and shell commands continue to use the workspace.

type RecallTool

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

RecallTool reads a window of earlier history or of an externalised output by ref. It pages on its own (Rereadable): its result is capped at the inline threshold here, so the output layer never externalises it again.

func NewRecallTool

func NewRecallTool(searcher LedgerSearcher, maxOut int) *RecallTool

NewRecallTool creates recall backed by searcher; maxOut caps one result (normally the inline threshold, tools.max_output_bytes).

func (*RecallTool) Description

func (t *RecallTool) Description() string

func (*RecallTool) Execute

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

func (*RecallTool) Name

func (t *RecallTool) Name() string

func (*RecallTool) Schema

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

func (*RecallTool) ToolMeta

func (*RecallTool) ToolMeta() tools.Meta

ToolMeta: read-only, pages on its own, results are external content.

type RemovePlan

type RemovePlan struct {
	Abs, Rel string
	// Base is the directory Abs was resolved in: the workspace, or an added
	// read-write directory.
	Base         string
	Dir          bool
	Files, Bytes int64
	// Purge: the path is (inside) an ignored directory and is deleted for
	// good as a whole; nothing goes to the trash.
	Purge bool
	// PurgeDirs are the ignored directories below the path deleted for good
	// (workspace-relative, slash-separated) before the rest goes to the trash.
	PurgeDirs []string
}

RemovePlan is what file_remove would do: the absolute path and its path relative to Base, the files and bytes going to the trash, and the ignored directories deleted for good (Purge: all of the path is). Exported for approval prompts.

func PlanRemove

func PlanRemove(workspace string, args map[string]any) (RemovePlan, error)

PlanRemove checks a file_remove call against the workspace.

func PlanRemoveWithDirs

func PlanRemoveWithDirs(workspace string, writeRoots []string, args map[string]any) (RemovePlan, error)

PlanRemoveWithDirs is PlanRemove against the workspace and the session's read-write directories (--add-dir ...:rw), which are treated the same way: the same delete guards apply inside them. writeRoots are absolute.

type ReplaceBlock

type ReplaceBlock struct {
	Pattern string `yaml:"pattern"`
	With    string `yaml:"with"`
}

ReplaceBlock is one `replace` item: pattern is a Go regexp compiled in multi-line mode (so ^/$ anchor on a line while a pattern may still cross lines with \n) and with replaces every match of it, with $1 / ${name} standing for a capture group.

type SessionMessageTool

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

SessionMessageTool lets the model list and message the other chat sessions of this machine (design 2026-10-21 session_message): one tool with the actions list and send.

func (*SessionMessageTool) Description

func (t *SessionMessageTool) Description() string

func (*SessionMessageTool) Execute

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

func (*SessionMessageTool) Name

func (t *SessionMessageTool) Name() string

func (*SessionMessageTool) Schema

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

func (*SessionMessageTool) ToolMeta

func (*SessionMessageTool) ToolMeta() tools.Meta

ToolMeta: it only messages processes of this machine, so it is available in read-only sessions and needs no approval.

type SessionMessenger

type SessionMessenger interface {
	// Peers lists the running chat sessions, the caller's own excluded.
	Peers(ctx context.Context) ([]SessionPeer, error)
	// Send delivers text to the session `to` names (a short name, a full session
	// ID or an ID prefix). mode is "follow_up" or "steer".
	Send(ctx context.Context, to, text, mode string) (SessionSendResult, error)
	// Status answers the state of one message ID a former send to `to` produced
	// (queued|steered|processed|failed|held|discarded); the empty state means the
	// receiver never saw that ID (it restarted) or knows nothing of it.
	Status(ctx context.Context, to, id string) (string, error)
}

SessionMessenger is the host side of session_message: the running chat processes of this SUGA_HOME (native.Env.SessionMessenger). The suga layering keeps the tool out of internal/*; the host resolves short names, the caller's session and the hop depth of the current turn.

type SessionPeer

type SessionPeer struct {
	// Name is the short name `suga send --session <name>` accepts.
	Name      string
	SessionID string
	CWD       string
	// State is idle or busy: an idle chat starts a turn for a follow-up message at once.
	State string
	// HopsCapable is false for a peer of an older version, whose chat has no
	// automatic-reply limit: a message to it always starts a turn.
	HopsCapable bool
}

SessionPeer is one running chat session of this machine and SUGA_HOME, as session_message lists it.

type SessionSearchTool

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

SessionSearchTool searches earlier conversation history and externalised outputs. Results are old, possibly external content: the tool is External so the session is flagged as tainted when it is used.

func NewSessionSearchTool

func NewSessionSearchTool(searcher LedgerSearcher) *SessionSearchTool

NewSessionSearchTool creates session_search backed by searcher.

func (*SessionSearchTool) Description

func (t *SessionSearchTool) Description() string

func (*SessionSearchTool) Execute

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

func (*SessionSearchTool) Name

func (t *SessionSearchTool) Name() string

func (*SessionSearchTool) Schema

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

func (*SessionSearchTool) ToolMeta

func (*SessionSearchTool) ToolMeta() tools.Meta

ToolMeta: read-only search; results are external content (taint).

type SessionSendResult

type SessionSendResult struct {
	// Queued is true when the message waited for the next turn of a busy peer,
	// false when the peer started a turn for it at once.
	Queued bool
	// Steered is true when the message went into the turn the peer runs right now.
	Steered bool
	// Warning is what the receiver did to accept the message (the model cannot see
	// pictures, so they became a note).
	Warning string
	// Legacy is true when the peer runs a version without the automatic-reply
	// limit: the message was delivered and starts its turn whenever it arrives.
	Legacy bool
	// MessageID is the ID the receiver dedupes on and a receipt or a status query
	// names (empty for a peer of an older version).
	MessageID string
}

SessionSendResult is what delivering one session message produced.

type ShellExecTool

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

ShellExecTool runs a shell command inside the workspace directory. A call either completes within its foreground timeout or, when tasks are enabled, transfers a long-running process tree to the task manager without dropping output; the configured maximum remains a hard kill deadline.

func NewShellExecTool

func NewShellExecTool(workspace string, timeout time.Duration) *ShellExecTool

NewShellExecTool returns a ShellExecTool scoped to workspace using the OS default shell. timeout is the default per call (0 = DefaultShellTimeout).

func (*ShellExecTool) DangerousDelete

func (t *ShellExecTool) DangerousDelete(command string) string

DangerousDelete is DangerousDelete with this tool's shell and workspace.

func (*ShellExecTool) DangerousDeleteKind added in v0.52.0

func (t *ShellExecTool) DangerousDeleteKind(command string) (reason string, hard bool)

DangerousDeleteKind is DangerousDeleteKind with this tool's shell and workspace.

func (*ShellExecTool) Description

func (t *ShellExecTool) Description() string

func (*ShellExecTool) Execute

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

func (*ShellExecTool) Name

func (t *ShellExecTool) Name() string

func (*ShellExecTool) Schema

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

func (*ShellExecTool) SetExtraEnv

func (t *ShellExecTool) SetExtraEnv(extra func(context.Context) []string)

SetExtraEnv adds the environment entries extra returns for a call (native.Env.ExtraEnv): the session and turn a command runs for.

func (*ShellExecTool) SetTasks

func (t *ShellExecTool) SetTasks(m *tasks.Manager)

SetTasks enables background: true (the host owns m and its lifetime).

func (*ShellExecTool) ToolMeta

func (*ShellExecTool) ToolMeta() tools.Meta

ToolMeta marks the tool as an execute: it runs commands.

type ShellLimits

type ShellLimits struct {
	// MemoryBytes caps the memory of one process and of the tree; 0 = no cap.
	MemoryBytes uint64
	// Processes caps how many processes the tree may have; 0 = no cap.
	Processes int
	// CPUTime caps the CPU time of one process; 0 = no cap.
	CPUTime time.Duration
}

ShellLimits caps what one shell_exec command and every process it starts may use (tools.shell_limits). It is not a sandbox: a command can still write every file its user can write and reach the network; it only stops a runaway build or test run from eating the machine.

Windows sets every field on the process tree's job object. Unix sets them with setrlimit: memory per process and CPU time per process work as expected, while the process count is RLIMIT_NPROC - a per-user limit, which suga therefore raises by the user's current process count (a command may add roughly processes more, and the limit is left off on a Unix without /proc).

func (ShellLimits) Empty

func (l ShellLimits) Empty() bool

Empty reports that no limit is set: a command runs the way it always did.

type SkillTool

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

SkillTool returns a skill's instructions (SKILL.md body) or another file of the skill's directory. Skill directories may lie outside the workspace, so reads go through os.OpenRoot(skillDir): nothing outside that directory.

func NewSkillTool

func NewSkillTool(reg *skills.Registry, maxOut int) *SkillTool

NewSkillTool serves the skills in reg.

func (*SkillTool) Description

func (t *SkillTool) Description() string

func (*SkillTool) Execute

func (t *SkillTool) Execute(_ context.Context, call api.ToolCall) (*api.ToolResult, error)

func (*SkillTool) Name

func (t *SkillTool) Name() string

func (*SkillTool) Schema

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

func (*SkillTool) ToolMeta

func (*SkillTool) ToolMeta() tools.Meta

ToolMeta marks the tool as a read-only read.

type SnapshotBefore

type SnapshotBefore struct {
	Unrecoverable string
	Notice        string
}

SnapshotBefore is the non-fatal outcome of creating a before-image. A non-empty Unrecoverable value means the write may continue, but the caller must tell the model that this call cannot be undone. Other failures are returned as errors and must stop the write.

type SnapshotKind

type SnapshotKind = string

SnapshotKind identifies what the write tool found before it changed a path. The strings are persisted by the personal snapshot store, so keep them stable across native and host layers.

type SnapshotPath

type SnapshotPath struct {
	Root    string
	Rel     string
	RealRel string
	Abs     string
}

SnapshotPath is the checked identity of a snapshot target. Abs keeps the lexical path used by the write tool; RealRel is checked against the current resolved location before undo performs any I/O on the target.

func ResolveSnapshotPath

func ResolveSnapshotPath(root, rel, realRel string) (SnapshotPath, error)

ResolveSnapshotPath validates the root-relative identity recorded by a write tool. It rejects non-canonical or escaping paths and detects a changed symlinked parent/target by comparing the current real relative path.

type SnapshotReport

type SnapshotReport struct {
	Kind          SnapshotKind
	Status        string
	Bytes         int64
	Unrecoverable string
}

SnapshotReport is the small, non-sensitive snapshot summary attached to a tool event. It deliberately contains no before-image bytes or filesystem contents.

func WithSnapshotReport

func WithSnapshotReport(ctx context.Context) (context.Context, *SnapshotReport)

WithSnapshotReport returns a context carrying a fresh report. The observing tool layer reads the report after the native tool has finished.

type SnapshotRequest

type SnapshotRequest struct {
	CallID  string
	Tool    string
	Root    string
	Rel     string
	RealRel string
	Kind    SnapshotKind
	Before  []byte
}

SnapshotRequest carries the path and original bytes to the snapshot owner. Root and Rel describe the lexical path used by the tool; RealRel is the resolved path below the same root and lets the undo layer re-check links.

type SnapshotResult

type SnapshotResult struct {
	CallID        string
	Tool          string
	Root          string
	Rel           string
	RealRel       string
	Kind          SnapshotKind
	AfterSHA256   string
	Size          int64
	Status        string
	Unrecoverable string
	TrashEntries  []string
	PurgedDirs    []string
}

SnapshotResult completes a snapshot after the native write. An incomplete result is sent when the write itself fails, so the store does not leave a pending record that looks complete.

type Snapshotter

type Snapshotter interface {
	BeforeCall(ctx context.Context, req SnapshotRequest) (SnapshotBefore, error)
	AfterCall(ctx context.Context, result SnapshotResult) error
}

Snapshotter is implemented by the session snapshot store. Native tools only know this contract; they do not depend on session storage or personal-agent packages. A nil Snapshotter disables snapshots and preserves old behavior.

type Spec

type Spec struct {
	Name string
	// New builds the tool, or returns nil when env lacks what it needs
	// (web_search without a key).
	New func(env Env) api.Tool
}

Spec is one entry of the native tool catalog. Whether a tool writes is its own tools.Meta (ToolMeta), not a catalog flag.

func Catalog

func Catalog() []Spec

Catalog lists every native tool. run, chat and ACP all register from this one list; update_plan and tool_search are wired separately because they depend on session state, not on Env.

type SubAgents

type SubAgents interface {
	// Scope returns the session and turn of the tool call ctx belongs to.
	Scope(ctx context.Context) (session, turn string)
	// RunAgent runs req and returns its report; an error comes with the
	// report so far (its SessionID set when the session was created).
	RunAgent(ctx context.Context, req AgentRequest) (AgentReport, error)
}

SubAgents runs sub-agents for the agent tool; the host implements it.

type TaskTool

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

TaskTool manages the session's background tasks (started by shell_exec or agent with background: true): list, read output, wait, kill.

func NewTaskTool

func NewTaskTool(m *tasks.Manager, maxWait time.Duration) *TaskTool

NewTaskTool returns the task tool over m; maxWait caps a wait timeout (0 = DefaultShellTimeoutMax).

func (*TaskTool) Description

func (t *TaskTool) Description() string

func (*TaskTool) Execute

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

func (*TaskTool) Name

func (t *TaskTool) Name() string

func (*TaskTool) Schema

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

func (*TaskTool) ToolMeta

func (*TaskTool) ToolMeta() tools.Meta

ToolMeta: it only acts on tasks this session started, so it is agent state (no approval), like update_plan.

type ToolSearchTool

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

ToolSearchTool lets the model load deferred MCP tools. It is registered only when some tools are deferred; with nothing deferred it would be a useless entry in every request's tool prefix.

func NewToolSearchTool

func NewToolSearchTool(searcher ToolSearcher) *ToolSearchTool

NewToolSearchTool creates tool_search backed by searcher.

func (*ToolSearchTool) Description

func (t *ToolSearchTool) Description() string

func (*ToolSearchTool) Execute

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

func (*ToolSearchTool) Name

func (t *ToolSearchTool) Name() string

func (*ToolSearchTool) Schema

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

func (*ToolSearchTool) ToolMeta

func (*ToolSearchTool) ToolMeta() tools.Meta

ToolMeta marks the tool as a read-only search.

type ToolSearcher

type ToolSearcher interface {
	Search(ctx context.Context, query string, limit int) (tools.SearchResult, error)
}

ToolSearcher finds deferred tools and loads the matches (tools.Visibility).

type UpdatePlanTool

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

UpdatePlanTool lets the model keep a structured task list. It never touches the workspace, so it is available in read-only modes too.

func NewUpdatePlanTool

func NewUpdatePlanTool(sink PlanSink) *UpdatePlanTool

NewUpdatePlanTool creates the update_plan tool writing through sink.

func (*UpdatePlanTool) Description

func (t *UpdatePlanTool) Description() string

func (*UpdatePlanTool) Execute

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

func (*UpdatePlanTool) Name

func (t *UpdatePlanTool) Name() string

func (*UpdatePlanTool) Schema

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

func (*UpdatePlanTool) ToolMeta

func (*UpdatePlanTool) ToolMeta() tools.Meta

ToolMeta marks the tool read-only: it only updates the session plan.

type ViewImageTool

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

ViewImageTool returns a picture as an image part of its tool result, so a model that can see gets to look at it.

func NewViewImageTool

func NewViewImageTool(workspace string, readRoots []string, addDirs *AddDirs, imagesDir string) *ViewImageTool

NewViewImageTool returns the tool for a workspace and the session's images directory ("" when the session has none).

func (*ViewImageTool) Description

func (t *ViewImageTool) Description() string

func (*ViewImageTool) Execute

func (t *ViewImageTool) Execute(_ context.Context, call api.ToolCall) (*api.ToolResult, error)

func (*ViewImageTool) Name

func (t *ViewImageTool) Name() string

func (*ViewImageTool) Schema

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

func (*ViewImageTool) SetImagesDirResolver

func (t *ViewImageTool) SetImagesDirResolver(fn func() string) *ViewImageTool

SetImagesDirResolver binds a function that resolves the served session's images directory at call time, so view_image works across the session a chat opens later (:resume, :new). Function may return "" while no session is open.

func (*ViewImageTool) SetVision

func (t *ViewImageTool) SetVision(gate *tools.VisionGate) *ViewImageTool

SetVision binds the tool to the runtime's live vision gate, so the check follows a model switch instead of the model the tool was built with.

func (*ViewImageTool) ToolMeta

func (*ViewImageTool) ToolMeta() tools.Meta

ToolMeta marks the tool as a read-only read. It is not Prefetchable: its bytes would be stored even when the step is cut away (design 0.3). It is Hidden: file_read reads pictures now, so view_image stays only as an alias one version longer - callable by name for old sessions and name-based configuration, never listed (design 2026-10-23 Q4).

type WebFetchTool

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

WebFetchTool downloads a web page and returns its readable text.

func NewWebFetchTool

func NewWebFetchTool(allowPrivate bool, proxy string) (*WebFetchTool, error)

NewWebFetchTool builds the tool without a global proxy. Unless allowPrivate is set, private and local addresses are refused. Without a proxy every connection is checked at dial time against the IP actually connected to, which also covers redirects and DNS rebinding; environment proxies are ignored so the check sees the real target. With proxy (http, https or socks5 URL) connections go only to the proxy, and the target host is resolved and checked before the request and on every redirect instead (the proxy may still resolve a name differently: a weaker guarantee, accepted to reach sites that need one).

func NewWebFetchToolWithSelector

func NewWebFetchToolWithSelector(allowPrivate bool, proxy string, selector *netproxy.Selector) (*WebFetchTool, error)

NewWebFetchToolWithSelector builds the tool with the global network proxy selector (network.proxy). A non-nil selector decides per target URL between the proxy and a direct connection and takes precedence over the legacy proxy argument; a nil one keeps the legacy tools.web_fetch.proxy behavior described in NewWebFetchTool. Because the dial check cannot tell the proxy's own address from a target, a selector always checks every request by name (checkHost) and keeps the dial check for direct connections.

func (*WebFetchTool) Description

func (t *WebFetchTool) Description() string

Description drops the untrusted-data sentence: the stable system prompt carries that convention for every tool that brings content in (suga-eygi; docs/research/2026-10-23-fixed-prefix-tools-report.md 三 #18).

func (*WebFetchTool) Execute

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

func (*WebFetchTool) Name

func (t *WebFetchTool) Name() string

func (*WebFetchTool) Schema

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

func (*WebFetchTool) ToolMeta

func (*WebFetchTool) ToolMeta() tools.Meta

ToolMeta marks the tool as a read-only fetch.

type WebSearchTool

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

WebSearchTool performs web searches via SerpAPI (serpapi_key). It only reads, so it is registered in read-only mode too.

func NewWebSearchTool

func NewWebSearchTool(apiKey string) *WebSearchTool

NewWebSearchTool creates a WebSearchTool with the given SerpAPI key. Its client follows the environment proxies unless a network proxy is set (see SetNetworkProxy).

func (*WebSearchTool) Description

func (t *WebSearchTool) Description() string

func (*WebSearchTool) Execute

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

func (*WebSearchTool) Name

func (t *WebSearchTool) Name() string

func (*WebSearchTool) Schema

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

func (*WebSearchTool) SetNetworkProxy

func (t *WebSearchTool) SetNetworkProxy(selector *netproxy.Selector)

SetNetworkProxy routes web_search through the global network.proxy selector: a matched host uses the proxy, every other host stays direct. A nil selector (no global proxy configured) keeps the default client, which reads HTTP_PROXY/HTTPS_PROXY/NO_PROXY.

func (*WebSearchTool) ToolMeta

func (*WebSearchTool) ToolMeta() tools.Meta

ToolMeta marks the tool as a read-only search.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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