tool

package
v0.4.2-rc.2 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: Apache-2.0 Imports: 52 Imported by: 0

Documentation

Overview

The apply_patch tool: a multi-file patch envelope (add, update, move, delete) validated up front and applied after one permission check that covers every file it touches.

The bash tool: runs a command in the workspace shell, enforces its timeout, and turns the exit into a tool result with the output capped and spilled.

The edit tool: exact string replacement backed by a ladder of progressively more lenient matchers, tried in order until exactly one match is found.

The glob tool: file-name matching through `rg --files`, newest first, capped at globResultLimit entries.

The grep tool: content search through `rg --json`, grouped by file and ordered newest first.

Path confinement: every tool path resolves inside the workspace unless the registry allows external directories, in which case it asks first.

The read tool: files with line-number prefixes, directories as entry lists, images and PDFs as attachments, plus nested instruction reminders.

Package tool is the workspace-bound tool registry: the tools the model can call, each confined to a single workspace and gated by the permission rules.

Ripgrep is the one external binary the search tools depend on, and it is never fetched at run time: a sealed or offline deployment could not download it anyway.

A missing rg is not a cosmetic loss. grep and glob are how the agent reads a codebase, so without them a run does not degrade gracefully — it fails tool call after tool call and never gets to the work. This file keeps the existing ripgrepRunner seam and answers in process instead, so the engine is self-contained. rg stays authoritative whenever it is installed: the fallback is selected only when exec.LookPath("rg") misses, which means an existing deployment's behaviour is untouched.

Fidelity notes (the deliberate gaps, so nobody has to rediscover them):

  • Inside a git work tree the file list comes from `git ls-files --cached --others --exclude-standard`, which reproduces rg's default .gitignore behaviour exactly. Outside one, every regular file is walked: rg would also honour .ignore/.rgignore files there, and this does not.
  • Patterns are compiled with Go's regexp (RE2), the same family as rg's default engine, so ordinary patterns behave the same. Anything relying on Rust-regex-only syntax will not compile here.
  • Results are emitted in lexicographic order. rg emits in traversal order; both are arbitrary as far as the callers are concerned, and a stable order makes the 100-result cap deterministic instead of filesystem dependent.

The deterministic shell core shared by executors: shell identification and the permission scan that extracts paths and command patterns from a command line. Process execution lives in bash.go.

The write tool: whole-file writes that preserve an existing BOM, run the configured formatter, and report a unified diff of the change.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AcquireShellScratch

func AcquireShellScratch(sessionID string) func()

AcquireShellScratch registers one active user of a session's private build caches. The returned release removes the cache after the last user exits.

func BlockAnchorReplacer

func BlockAnchorReplacer(content string, find string) []string

BlockAnchorReplacer matches a block by its first and last lines and scores the lines between them by similarity; a lone candidate is accepted outright, competing candidates must clear multipleCandidatesSimilarityThreshold.

func ContextAwareReplacer

func ContextAwareReplacer(content string, find string) []string

ContextAwareReplacer matches a block of the same length by its first and last lines when at least half of the inner lines agree.

func EscapeNormalizedReplacer

func EscapeNormalizedReplacer(content string, find string) []string

EscapeNormalizedReplacer matches after unescaping backslash sequences in the search text, for a model that sent an escaped string.

func FilterDefinitions

func FilterDefinitions(
	definitions []steploop.ToolDefinition,
	input FilterInput,
) []steploop.ToolDefinition

FilterDefinitions narrows the advertised tool list to what the provider and model can use: websearch needs a search backend, and GPT-family models get apply_patch in place of edit/write. It is separate from Registry so plugin/custom definitions can pass through the same seam.

func IndentationFlexibleReplacer

func IndentationFlexibleReplacer(content string, find string) []string

IndentationFlexibleReplacer matches after removing the common indentation from both the search text and the candidate block.

func LineTrimmedReplacer

func LineTrimmedReplacer(content string, find string) []string

LineTrimmedReplacer matches line by line, ignoring leading and trailing whitespace on each line.

func MultiOccurrenceReplacer

func MultiOccurrenceReplacer(content string, find string) []string

MultiOccurrenceReplacer returns one candidate per exact occurrence, which is what lets replaceAll act on every one. It assumes find != "": the edit tool rejects an empty search before the ladder runs.

func Replace

func Replace(content string, oldString string, newString string, replaceAll bool) (string, error)

Replace runs the replacer ladder in order and substitutes the first unique match, or every match of the first successful replacer when replaceAll is set.

func ShellAcceptable

func ShellAcceptable(file string) bool

ShellAcceptable reports whether a shell may run tool commands; fish and nu are refused.

func ShellName

func ShellName(file string) string

ShellName returns the lowercase executable basename, without its extension on Windows.

func ShellPowerShell

func ShellPowerShell(file string) bool

ShellPowerShell reports whether a shell uses PowerShell syntax.

func SimpleReplacer

func SimpleReplacer(_ string, find string) []string

SimpleReplacer matches the search text exactly.

func TeardownShellScratch

func TeardownShellScratch(sessionID string)

TeardownShellScratch releases one leaf's private build caches. Shared-cache mode never creates these directories, so removal remains a best-effort no-op.

func TrimDiff

func TrimDiff(diff string) string

TrimDiff removes the common leading indentation from a unified diff's content lines so the model-visible diff is not dominated by nesting.

func TrimmedBoundaryReplacer

func TrimmedBoundaryReplacer(content string, find string) []string

TrimmedBoundaryReplacer matches the search text with its surrounding whitespace trimmed away.

func WebSearchEnabled

func WebSearchEnabled(providerID string, flags WebSearchFlags) bool

WebSearchEnabled reports whether a search backend is available: the senior-dev provider, or an Exa or Parallel flag.

func WhitespaceNormalizedReplacer

func WhitespaceNormalizedReplacer(content string, find string) []string

WhitespaceNormalizedReplacer matches after collapsing every run of whitespace to a single space.

func WithWebHTTPClient

func WithWebHTTPClient(ctx context.Context, client *http.Client) context.Context

WithWebHTTPClient injects the HTTP seam used by webfetch and websearch. Production calls use http.DefaultClient, which follows redirects.

func WithWebHostResolver

func WithWebHostResolver(
	ctx context.Context, resolver func(context.Context, string) ([]net.IP, error),
) context.Context

WithWebHostResolver injects redirect-boundary DNS resolution for hermetic tests. Production uses net.DefaultResolver.

func WithWebOutputDir

func WithWebOutputDir(ctx context.Context, directory string) context.Context

WithWebOutputDir redirects the shared 50 KiB/2000-line truncation spill.

func WithWebSearchEndpoints

func WithWebSearchEndpoints(ctx context.Context, exaURL, parallelURL string) context.Context

WithWebSearchEndpoints redirects the provider MCP endpoints. It exists so tests can exercise the complete registry path without external network I/O.

Types

type FilterInput

type FilterInput struct {
	ProviderID string
	ModelID    string
	Flags      WebSearchFlags
}

FilterInput carries the provider, model and search flags that decide which tools are advertised for a turn.

type PermissionEvaluator

type PermissionEvaluator interface {
	Evaluate(permission.AskInput) error
}

PermissionEvaluator decides one permission request; mutation requests carry the proposed diff in their metadata.

type PermissionRules

type PermissionRules func(context.Context, steploop.ToolCall) permission.Ruleset

PermissionRules resolves the agent and instance rules for one tool call.

type Registry

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

Registry is a collection of tools whose file operations are confined to a single workspace.

func New

func New(workDir string) *Registry

New returns a registry bound to workDir.

func NewWithOptions

func NewWithOptions(workDir string, options RegistryOptions) *Registry

NewWithOptions returns a configured registry bound to workDir.

func (*Registry) ClearInstructionClaims

func (r *Registry) ClearInstructionClaims(ctx context.Context, messageID string)

ClearInstructionClaims releases one assistant turn's in-flight nested-path claims. Persisted read metadata remains the cross-turn loaded-path memory.

func (*Registry) CloseShellProcesses

func (r *Registry) CloseShellProcesses()

CloseShellProcesses ends background jobs left in the process groups that the run's bash tool started before the run releases its workspace.

func (*Registry) Definitions

func (r *Registry) Definitions() []steploop.ToolDefinition

Definitions returns the provider declarations for all workspace tools.

func (*Registry) DefinitionsFor

func (r *Registry) DefinitionsFor(input FilterInput) []steploop.ToolDefinition

DefinitionsFor applies the registry's provider and model-family visibility rules.

func (*Registry) Execute

func (r *Registry) Execute(ctx context.Context, call steploop.ToolCall) (steploop.ToolResult, error)

Execute dispatches an already-validated call to its named tool.

func (*Registry) IDs

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

IDs returns builtin tool IDs in registry insertion order.

func (*Registry) SetSubmitFreezer

func (r *Registry) SetSubmitFreezer(freeze SubmitFreezer)

SetSubmitFreezer installs the submission handler after construction. The registry is built inside the runtime, before the pipeline that owns the freeze exists; this is the seam between them. Setting it also advertises the submit tool, so it must be called before the first turn is configured.

func (*Registry) SystemInstructions

func (r *Registry) SystemInstructions(ctx context.Context) []string

SystemInstructions returns the root/global instruction blocks used by the engine system prompt for the same workspace-bound service as read tools.

type RegistryOptions

type RegistryOptions struct {
	Permission               PermissionEvaluator
	PermissionRules          PermissionRules
	Instructions             []string
	Config                   *config.Service
	AllowExternalDirectories bool
	// ConfineWrites refuses every file write outside the workspace, whatever
	// AllowExternalDirectories says of reads: codeaf keeps only what a program
	// changes in the folder it is handed, so a write anywhere else is work that
	// no run owns and a change made to somebody else's folder (path.go).
	ConfineWrites bool
	// HardConfineShellPaths rejects parsed external shell operands instead of
	// asking permission, for an embedder that must not prompt. senior-dev leaves it
	// disabled and asks.
	HardConfineShellPaths bool
	// ClientIdentity names the kind of client driving the registry (app, cli,
	// desktop) and decides whether the question tool is advertised. The senior-dev
	// binary supplies "cli" unless SENIOR_DEV_CLIENT overrides it; embedders that
	// omit it are not assumed to have an interactive client.
	ClientIdentity string
	Question       *question.Service
	// SubmitFreeze installs the submit tool and receives the candidate at the
	// moment the model submits. See submit.go.
	SubmitFreeze SubmitFreezer
}

RegistryOptions supplies the host services used by live tool execution.

type ShellPermissionScan

type ShellPermissionScan struct {
	Dirs     []string `json:"dirs"`
	Patterns []string `json:"patterns"`
	Always   []string `json:"always"`
}

ShellPermissionScan is the ordered permission material gathered from a parsed shell command.

func ScanShellPermissions

func ScanShellPermissions(command string, opts ShellScanOptions) ShellPermissionScan

ScanShellPermissions extracts the permission material from a command line: directories it touches outside the workspace, the simple-command patterns, and their arity prefixes. It keeps shell source strings and token boundaries intact and skips dynamic path expressions rather than guess at them.

type ShellScanOptions

type ShellScanOptions struct {
	CWD       string
	Shell     string
	Workspace string
	Home      string
	Env       map[string]string
	IsDir     func(string) bool
}

ShellScanOptions supplies the path context used by the permission scanner.

type Submission

type Submission struct {
	Reason             string
	Evidence           string
	ChecklistSatisfied bool
	SessionID          string
}

Submission is what the model claimed when it submitted. The claim is recorded verbatim and separately from what senior-dev verifies itself afterwards -- a run that says "all tests pass" and did not run them must leave both facts in the record, not one reconciled story.

type SubmitFreezer

type SubmitFreezer func(ctx context.Context, submission Submission) (string, error)

SubmitFreezer captures the candidate at submit time. It returns a short human-readable description of what was frozen (a patch size, a sha) that is echoed back to the model so the transcript records the handoff, or an error if there was nothing to freeze.

The freeze happens inside the tool call rather than after the turn returns because that is the only placement where "no later stage may reopen the implementation" is structural instead of aspirational.

type WebSearchFlags

type WebSearchFlags struct {
	Exa      bool
	Parallel bool
}

WebSearchFlags are the two feature flags consulted by webSearchEnabled.

func CurrentWebSearchFlags

func CurrentWebSearchFlags() WebSearchFlags

CurrentWebSearchFlags reads the search-backend switches: SENIOR_DEV_EXPERIMENTAL (which enables Exa), SENIOR_DEV_ENABLE_EXA or SENIOR_DEV_EXPERIMENTAL_EXA, and SENIOR_DEV_ENABLE_PARALLEL or SENIOR_DEV_EXPERIMENTAL_PARALLEL. API keys are intentionally not feature flags.

Jump to

Keyboard shortcuts

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