Documentation
¶
Overview ¶
tools/bash_executor.go: user bash execution (!cmd, RPC bash, SDK ExecuteBash).
Upstream reference:
.upstream/current/packages/coding-agent/src/core/bash-executor.ts executeBashWithOperations.
The LLM bash tool does not use this path: like upstream it feeds raw output to an OutputAccumulator (shell_tool.go). User bash sanitizes each decoded chunk for display and storage.
Shell process execution shared by the bash and powershell tools and user bash.
Mirrors upstream core/tools/bash.ts BashOperations and createLocalShellOperations, plus utils/child-process.ts waitForChildProcess for the post-exit stdio grace.
Package tools: edit-diff helpers.
Mirrors upstream packages/coding-agent/src/core/tools/edit-diff.ts: line-ending detection, BOM stripping, fuzzy matching, and the position-based multi-file edit application algorithm.
Image format detection for the read tool.
upstream: coding-agent/src/utils/mime.ts detectSupportedImageMimeTypeFromFile
Streaming output accumulator for the shell tools.
Mirrors upstream packages/coding-agent/src/core/tools/output-accumulator.ts.
Path resolution utilities for all file tools.
Mirrors upstream path-utils.ts: ~ expansion, @ prefix stripping, unicode space normalization, macOS filename variants (NFD, curly quotes, AM/PM screenshot paths).
upstream: coding-agent/src/core/tools/path-utils.ts (94 LOC)
Package tools implements the built-in LLM-callable tools. Mirrors pi-coding-agent's tools: bash, read, write, edit, grep, find, ls.
fd/rg auto-install: upstream's tools-manager.ts download/extraction pipeline is ported in tools_manager.go (ToolsManager.EnsureTool). It looks up <agentDir>/bin/<binary> first, then PATH, and downloads from GitHub Releases as a last resort. The lookup-only fast path remains available via lookupSystemToolPath for callers that don't want to do any network work (e.g. early startup).
Package tools: fd/rg installer.
This file ports the download/extract pipeline from upstream packages/coding-agent/src/utils/tools-manager.ts. The pipeline ensures that fd and rg are available even when the user has not installed them via the system package manager:
- EnsureTool first checks <agentDir>/bin/<binary> (local install),
- then PATH (system install),
- then, if neither is found and we're online and not on Android/Termux, downloads the appropriate platform asset from GitHub Releases, extracts it, and installs the binary into <agentDir>/bin.
The asset table selects platform-specific release archives. On darwin/x64, fd uses a pinned release.
Extraction divergence (D14: documented in DIVERGENCES.md): upstream spawns `tar`, `unzip`, and PowerShell. pig uses Go stdlib (archive/tar + compress/gzip + archive/zip) on all platforms. The extracted binary is byte-identical; only the error message text on extraction failure differs.
Index ¶
- Constants
- Variables
- func BuiltinToolActive(name string, active, allowed map[string]struct{}) bool
- func BuiltinToolDescription(name string) string
- func BuiltinToolNames() []string
- func CreateAllTools(cwd string, settings BashSettingsView, agentBinDir string) []agent.AgentTool
- func CreateCodingTools(cwd string, settings BashSettingsView, agentBinDir string) []agent.AgentTool
- func CreateReadOnlyTools(cwd string, settings BashSettingsView, agentBinDir string) []agent.AgentTool
- func DefaultToolGuidelines() map[string][]string
- func FormatJSNumber(v float64) string
- func FormatSize(bytes int) string
- func FormatTruncationWarning(tr TruncationResult) string
- func GenerateDiffString(oldContent, newContent string) (diff string, firstChangedLine int)
- func GenerateUnifiedPatch(path, oldStr, newStr string) string
- func GetShellEnv(binDir string) []string
- func IsOfflineModeEnabled() bool
- func LookupToolPath(tool, agentBinDir string) string
- func NormalizeWindowsShellPath(filePath string) string
- func SanitizeBinaryOutput(s string) string
- func SelectBuiltinTools(all []agent.AgentTool, active, allowed map[string]struct{}) []agent.AgentTool
- func StripANSI(b []byte) []byte
- func SupportedImageMime(data []byte) string
- func TruncateLine(line string, maxChars int) (string, bool)
- type BashDetails
- type BashExecOptions
- type BashOperations
- type BashOperationsExecOptions
- type BashOperationsResult
- type BashResult
- type BashSettingsView
- type BashTool
- type EditTool
- func (t *EditTool) Execute(ctx context.Context, _ string, rawParams json.RawMessage, ...) (agent.AgentToolResult, error)
- func (t *EditTool) ExecutionMode() agent.ToolExecutionMode
- func (t *EditTool) Label() string
- func (t *EditTool) Name() string
- func (t *EditTool) PrepareArguments(raw json.RawMessage) (json.RawMessage, error)
- func (t *EditTool) ReserveMutationOrder(rawParams json.RawMessage) (*agent.MutationTicket, bool)
- func (t *EditTool) Schema() ai.ToolSchema
- type EditToolDetails
- type FileMutationQueue
- type FindDetails
- type FindTool
- type GrepDetails
- type GrepTool
- type LocalShellOperations
- type LsDetails
- type LsTool
- type MutationTicket
- type OutputAccumulator
- type OutputSnapshot
- type PowerShellTool
- func (t *PowerShellTool) Execute(ctx context.Context, _ string, rawParams json.RawMessage, ...) (agent.AgentToolResult, error)
- func (t *PowerShellTool) ExecutionMode() agent.ToolExecutionMode
- func (t *PowerShellTool) Label() string
- func (t *PowerShellTool) Name() string
- func (t *PowerShellTool) Schema() ai.ToolSchema
- type ReadDetails
- type ReadTool
- type SettingsView
- type ShellConfig
- type ToolStatus
- type ToolsManager
- type TruncationResult
- type WriteDetails
- type WriteTool
- func (t *WriteTool) Execute(ctx context.Context, _ string, rawParams json.RawMessage, ...) (agent.AgentToolResult, error)
- func (t *WriteTool) ExecutionMode() agent.ToolExecutionMode
- func (t *WriteTool) Label() string
- func (t *WriteTool) Name() string
- func (t *WriteTool) ReserveMutationOrder(rawParams json.RawMessage) (*agent.MutationTicket, bool)
- func (t *WriteTool) Schema() ai.ToolSchema
Constants ¶
const ( DefaultMaxBytes = 50 * 1024 // upstream: packages/coding-agent/src/core/tools/truncate.ts:DEFAULT_MAX_BYTES DefaultMaxLines = 2_000 // upstream: packages/coding-agent/src/core/tools/truncate.ts:DEFAULT_MAX_LINES )
upstream: coding-agent/src/core/tools/truncate.ts:DEFAULT_MAX_BYTES
const ( DefaultMaxBytesUpstream = 50 * 1024 // 50 KB: upstream DEFAULT_MAX_BYTES DefaultMaxLinesUpstream = 2000 // upstream DEFAULT_MAX_LINES GrepMaxLineLengthUpstream = 500 // upstream GREP_MAX_LINE_LENGTH )
Mirrors upstream defaults exactly. These supersede the older 200_000 figure that lived in tools.go.
const GrepMaxLineLength = GrepMaxLineLengthUpstream
GrepMaxLineLength matches upstream truncate.ts GREP_MAX_LINE_LENGTH.
const PowerShellPromptSnippet = "Execute PowerShell commands"
PowerShellPromptSnippet mirrors upstream powershellToolSystemPromptContribution.snippet.
Variables ¶
var PowerShellArgs = []string{"-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command"}
PowerShellArgs mirrors upstream POWERSHELL_ARGS (utils/shell.ts): no profile, non-interactive, a process-local execution policy bypass, and the command as the final argument.
Functions ¶
func BuiltinToolActive ¶
BuiltinToolActive reports whether the registered built-in name is active. A non-nil active set is explicit. A nil active set means PiG's full default: every built-in except the opt-in ones, which stay inactive unless the allowed tool list names them.
func BuiltinToolDescription ¶
BuiltinToolDescription returns short host-action metadata without creating a tool instance.
func BuiltinToolNames ¶
func BuiltinToolNames() []string
BuiltinToolNames returns the canonical built-in names in registry order. The returned slice is a copy and cannot mutate future host callbacks.
func CreateAllTools ¶
func CreateAllTools(cwd string, settings BashSettingsView, agentBinDir string) []agent.AgentTool
CreateAllTools returns every registered built-in tool, mirroring upstream createAllTools (tools/index.ts): CreateCodingTools plus the opt-in powershell tool, in upstream registry order. Callers select the active subset with SelectBuiltinTools.
func CreateCodingTools ¶
func CreateCodingTools(cwd string, settings BashSettingsView, agentBinDir string) []agent.AgentTool
CreateCodingTools returns the default set of LLM-callable coding tools. Edit and write share one FileMutationQueue.
settings is consulted by BashTool to resolve shellPath and commandPrefix. nil falls through to the upstream defaults (getShellConfig, no prefix).
agentBinDir, when non-empty, is <agentDir>/bin: grep and find resolve rg and fd there first, then on PATH, and download them when missing (upstream ensureTool); bash puts it on PATH. Pass "" for PATH-only lookup and no downloads.
func CreateReadOnlyTools ¶
func CreateReadOnlyTools(cwd string, settings BashSettingsView, agentBinDir string) []agent.AgentTool
CreateReadOnlyTools returns read-only tools (read, bash, grep, find, ls).
agentBinDir: see CreateCodingTools for semantics.
func DefaultToolGuidelines ¶
DefaultToolGuidelines returns the prompt guidelines from each built-in tool's Schema(). Used by prompt builders that don't have access to the full tool instances (e.g. interactive mode where tools are constructed later). Mirrors upstream agent-session.ts:2273-2276.
func FormatJSNumber ¶
FormatJSNumber mirrors JavaScript String(number) for a finite number.
func FormatSize ¶
FormatSize renders a byte count as "123B" / "12.3KB" / "1.2MB". Mirrors upstream `formatSize`.
func FormatTruncationWarning ¶
func FormatTruncationWarning(tr TruncationResult) string
FormatTruncationWarning returns the upstream-format `[Truncated: ...]` warning string for a TruncationResult, or "" if not truncated. Mirrors upstream's render-layer formatting in `read.ts:108-116` and `bash.ts:247-263`. Producers that don't have a separate render layer (pig grep / find / etc.) append the warning directly to the LLM-visible content.
func GenerateDiffString ¶
GenerateDiffString returns the line-numbered display diff and the first changed line number in the new file, byte-identical to upstream generateDiffString with the default 4 lines of context. A returned firstChangedLine of 0 means there was no change (upstream `undefined`).
func GenerateUnifiedPatch ¶
GenerateUnifiedPatch returns a unified diff for path byte-identical to upstream's generateUnifiedPatch with the default 4 lines of context.
func GetShellEnv ¶
GetShellEnv mirrors upstream getShellEnv: the process environment with binDir (upstream getBinDir, <agentDir>/bin, where managed rg and fd live) prepended to PATH unless PATH already lists it. The PATH key is matched case-insensitively, as on Windows. An empty binDir leaves PATH unchanged.
func IsOfflineModeEnabled ¶
func IsOfflineModeEnabled() bool
IsOfflineModeEnabled mirrors the env-var check used elsewhere in pig. Duplicated here (instead of imported from cmd/pig) because tools is a lower-level package that cannot depend on the CLI.
func LookupToolPath ¶
LookupToolPath resolves a tool to a usable binary path. Search order:
- agentBinDir (if non-empty): the auto-install location used by ToolsManager.downloadTool.
- exec.LookPath over systemBinaryNames (fd has "fdfind" fallback for Debian/Ubuntu).
Returns "" if nothing is found. On Windows, returns the bare command name (matches upstream behavior so cmd.exe expansion works).
func NormalizeWindowsShellPath ¶
NormalizeWindowsShellPath converts a Git Bash, MSYS, Cygwin or WSL drive path to the form native Windows APIs accept.
upstream: utils/paths.ts normalizeWindowsShellPath
func SanitizeBinaryOutput ¶
SanitizeBinaryOutput mirrors upstream shell.ts sanitizeBinaryOutput: drop control characters other than tab, newline and carriage return, and the Unicode format characters U+FFF9..U+FFFB (they crash string-width). Invalid UTF-8 bytes become U+FFFD, as upstream's decoder would have produced before sanitizing.
func SelectBuiltinTools ¶
func SelectBuiltinTools(all []agent.AgentTool, active, allowed map[string]struct{}) []agent.AgentTool
SelectBuiltinTools keeps the tools BuiltinToolActive reports active.
func StripANSI ¶
StripANSI mirrors upstream stripAnsi: remove every ansiRegex match. Anything the pattern does not cover (a lone ESC, ESC + letter outside the final-byte set) is left for SanitizeBinaryOutput.
func SupportedImageMime ¶
SupportedImageMime returns the supported still-image MIME type of a file's contents, or "" when it is not one. Like upstream detectSupportedImageMimeTypeFromFile it looks only at the first IMAGE_TYPE_SNIFF_BYTES.
The read tool is one of only two producers of image bytes that later reach the image decoders, so this allowlist is what keeps formats outside it out of them.
func TruncateLine ¶
TruncateLine mirrors upstream truncateLine: a line longer than maxChars UTF-16 code units (JavaScript string length) is cut to maxChars units plus "... [truncated]". A cut inside a surrogate pair leaves U+FFFD, as the lone surrogate JavaScript would keep serializes to.
Types ¶
type BashDetails ¶
type BashDetails struct {
Truncation *TruncationResult
FullOutputPath string
}
BashDetails is attached to a BashTool result. The renderer reads Truncation to format the warning row (e.g. `[Showing lines 1001-3000 of 3000. Full output: /tmp/...]`) and FullOutputPath to surface the temp file containing the full (untruncated) output.
Either field may be zero/nil; both nil means the bash output fit fully in the rolling buffer.
func (*BashDetails) ToolResultDetails ¶
func (d *BashDetails) ToolResultDetails() any
ToolResultDetails maps bash result details to extension.BashToolDetails. Upstream attaches details only when output was truncated (bash.ts:354).
type BashExecOptions ¶
type BashExecOptions struct {
// OnChunk receives each sanitized chunk as it arrives. Nil = disabled.
OnChunk func(chunk string)
// BinDir is prepended to PATH (upstream getShellEnv's getBinDir).
BinDir string
}
BashExecOptions mirrors upstream BashExecutorOptions; cancellation comes from the context.
type BashOperations ¶
type BashOperations = extension.BashOperations
BashOperationsExecOptions, BashOperationsResult and BashOperations are the public extension contract (coding/extension), so an extension's operations plug straight into the shell tools and user bash.
type BashOperationsExecOptions ¶
type BashOperationsExecOptions = extension.BashOperationsExecOptions
BashOperationsExecOptions, BashOperationsResult and BashOperations are the public extension contract (coding/extension), so an extension's operations plug straight into the shell tools and user bash.
type BashOperationsResult ¶
type BashOperationsResult = extension.BashOperationsResult
BashOperationsExecOptions, BashOperationsResult and BashOperations are the public extension contract (coding/extension), so an extension's operations plug straight into the shell tools and user bash.
type BashResult ¶
type BashResult struct {
// Output is combined stdout+stderr after sanitize + truncate.
Output string
// ExitCode is the process exit code, or nil if killed/cancelled.
ExitCode *int
// Cancelled is true when the context was cancelled mid-run.
Cancelled bool
// Truncated is true when Output is shorter than the full process output.
Truncated bool
// FullOutputPath, when non-empty, is a temp-file path holding the
// untruncated output. Caller is responsible for deletion.
FullOutputPath string
}
BashResult mirrors upstream BashResult (bash-executor.ts).
func ExecuteBash ¶
func ExecuteBash(ctx context.Context, command, cwd string, shell ShellConfig, opts BashExecOptions) (BashResult, error)
ExecuteBash runs command under shell in cwd through local shell operations. ctx cancellation kills the process group.
func ExecuteBashWithOperations ¶
func ExecuteBashWithOperations(ctx context.Context, command, cwd string, operations BashOperations, opts BashExecOptions) (BashResult, error)
ExecuteBashWithOperations mirrors upstream executeBashWithOperations: each chunk is decoded with a streaming UTF-8 decoder, ANSI-stripped, sanitized, and stripped of carriage returns; a rolling window of chunks is kept, and a temp file receives the sanitized text once the output passes the byte limit. A cancelled run returns its output with Cancelled set; any other operations error is returned.
type BashSettingsView ¶
type BashSettingsView interface {
SettingsView
GetCommandPrefix() string
}
SettingsView (in shell_config.go) is the inner shell-only subset.
type BashTool ¶
type BashTool struct {
CWD string
// Settings is consulted via GetShellConfig to resolve shellPath. nil
// falls through to the platform default.
Settings SettingsView
// CommandPrefix prepended (with \n) to every command. Empty = no prefix.
CommandPrefix string
// BinDir (<agentDir>/bin) is prepended to the command's PATH, mirroring
// upstream getShellEnv. Empty leaves PATH unchanged.
BinDir string
// HideSessionEnvironment turns off upstream's exposeSessionEnvironment:
// commands then see no PI_* session variables, and the prompt omits the
// guideline that mentions them.
HideSessionEnvironment bool
}
BashTool executes shell commands.
Contract (mirrors upstream tools/bash.ts):
- One-shot spawn per call. cwd does NOT persist between calls.
- Resolved command = CommandPrefix + "\n" + command (when prefix set).
- Spawn via getShellConfig: settings shellPath, else /bin/bash, bash on PATH, then sh (always with -c).
- Stream chunks: ANSI strip, binary sanitize, drop \r.
- Tempfile overflow at DEFAULT_MAX_BYTES (50 KB); rolling buffer 2x.
- On exit ≠ 0: append "Command exited with code N", return as IsError. A signal-killed shell reports 128 + the signal number.
- On context cancel: append "Command aborted", return as IsError.
- Details: BashDetails{Truncation, FullOutputPath} on a truncated success; error results carry none (upstream throws).
func (*BashTool) Execute ¶
func (t *BashTool) Execute(ctx context.Context, _ string, rawParams json.RawMessage, onUpdate agent.ToolUpdateCallback) (agent.AgentToolResult, error)
Execute runs the command through the shared shell tool execution (upstream createShellToolDefinition with the bash config: getShellConfig-resolved bash, the settings command prefix, and pig-bash temp files).
func (*BashTool) ExecutionMode ¶
func (t *BashTool) ExecutionMode() agent.ToolExecutionMode
ExecutionMode is parallel: upstream's shell tool definition sets no executionMode.
func (*BashTool) Schema ¶
func (t *BashTool) Schema() ai.ToolSchema
type EditTool ¶
type EditTool struct {
CWD string
Queue *FileMutationQueue // serialises concurrent edits
}
EditTool performs exact-text-replacement edits on files. Mirrors upstream packages/coding-agent/src/core/tools/edit.ts.
func (*EditTool) Execute ¶
func (t *EditTool) Execute(ctx context.Context, _ string, rawParams json.RawMessage, _ agent.ToolUpdateCallback) (agent.AgentToolResult, error)
Execute mirrors upstream edit.ts execute: inside the file mutation queue it checks access, reads, applies the edits, and writes, checking for an abort after each step so the queue is never released mid-write.
func (*EditTool) ExecutionMode ¶
func (t *EditTool) ExecutionMode() agent.ToolExecutionMode
ExecutionMode is parallel: upstream's edit definition sets no executionMode, and the file mutation queue serialises edits to one file.
func (*EditTool) PrepareArguments ¶
func (t *EditTool) PrepareArguments(raw json.RawMessage) (json.RawMessage, error)
PrepareArguments implements agent.ArgumentPreparer, mirroring upstream edit.ts `prepareArguments: prepareEditArguments`: models that send edits as a JSON string, as a single edit object, or in the legacy top-level {oldText, newText} shape reach the schema validator as {path, edits:[…]}. Anything else passes through unchanged.
func (*EditTool) ReserveMutationOrder ¶
func (t *EditTool) ReserveMutationOrder(rawParams json.RawMessage) (*agent.MutationTicket, bool)
ReserveMutationOrder implements agent.QueueOrderable: the parallel dispatcher calls this synchronously, in tool-call order, before spawning this call's goroutine, so this edit's place in the shared file mutation queue is fixed before goroutine scheduling can reorder it. Returns ok=false whenever Execute would not reach the queue either (invalid params or no edits), so no reservation is ever left un-awaited.
func (*EditTool) Schema ¶
func (t *EditTool) Schema() ai.ToolSchema
type EditToolDetails ¶
type EditToolDetails struct {
// Diff is the display-oriented, line-numbered diff (generateDiffString).
Diff string `json:"diff"`
// Patch is the standard unified patch (generateUnifiedPatch).
Patch string `json:"patch"`
// FirstChangedLine is the new-file line of the first change, 0 when
// there is no change (upstream `firstChangedLine?: number`, omitted).
FirstChangedLine int `json:"firstChangedLine,omitempty"`
}
EditToolDetails is attached to an EditTool result. It is the upstream SDK contract (edit.ts:61 `EditToolDetails`): a display-oriented diff, a standard unified patch, and the new-file line of the first change (for editor navigation). The TUI renders Diff directly; extensions and PostToolUse hooks receive this exact JSON shape.
type FileMutationQueue ¶
type FileMutationQueue struct {
// contains filtered or unexported fields
}
FileMutationQueue serialises concurrent mutations targeting the same canonical file path, in the order callers entered With. Operations on different files proceed in parallel.
Mirrors upstream core/tools/file-mutation-queue.ts::withFileMutationQueue, which chains a per-file Promise so mutations for one file apply in the order withFileMutationQueue was called, and drops the map entry once the chain drains. Upstream additionally serialises the async key-resolution step itself through a package-level registrationQueue so that admission order matches call order even though realpath is async; pig's key resolution (canonicalKey) is synchronous, so admission and key resolution happen inside the same lock/unlock section below, giving the same call-order guarantee without a separate queue.
A single per-key sync.Mutex is not equivalent: two goroutines that both see the mutex missing (or unlocked) race, unsynchronised, to acquire it, so a goroutine that entered With later can still win and run its callback before an earlier caller. The chain below removes that race by deciding each caller's position atomically, under q.mu, and having callers wait on a channel handed to them at that moment rather than a second Lock() race.
func NewFileMutationQueue ¶
func NewFileMutationQueue() *FileMutationQueue
NewFileMutationQueue returns a ready-to-use queue.
func (*FileMutationQueue) Reserve ¶
func (q *FileMutationQueue) Reserve(filePath string) (*MutationTicket, error)
Reserve registers filePath's next queue position, synchronously, without waiting for the previous holder. Call Wait for this ticket's turn, then Release exactly once, after the mutation completes. Reserve lets a caller (for example the parallel tool dispatcher, via QueueOrderable) establish admission order itself, in its own call-ordered loop, decoupled from when the reserving goroutine actually runs its mutation.
func (*FileMutationQueue) With ¶
func (q *FileMutationQueue) With(filePath string, fn func() error) error
With runs fn once every mutation registered earlier for the same canonical path has completed, then hands the path to the next queued caller and returns fn's error. filePath is resolved to its canonical form before keying (matching upstream realpath behaviour: symlinks to the same file share one queue slot). If q is nil (e.g. in tests that construct tools directly), fn is called without serialisation: safe for single-threaded test contexts.
type FindDetails ¶
type FindDetails struct {
Truncation *TruncationResult
ResultLimitReached int
}
FindDetails mirrors upstream FindToolDetails (find.ts:32): a truncation object when the byte limit was hit and the result-limit cap when reached.
func (*FindDetails) ToolResultDetails ¶
func (d *FindDetails) ToolResultDetails() any
ToolResultDetails maps find result details to extension.FindToolDetails.
type FindTool ¶
type FindTool struct {
CWD string
FdPath string
Tools *ToolsManager
}
FindTool searches for files with fd, mirroring upstream find.ts.
FdPath, when non-empty, pins the fd binary. Otherwise fd is resolved on every call through Tools (upstream ensureTool: <agentDir>/bin, PATH, then a download); with no Tools, PATH only.
func (*FindTool) Execute ¶
func (t *FindTool) Execute(ctx context.Context, _ string, rawParams json.RawMessage, _ agent.ToolUpdateCallback) (agent.AgentToolResult, error)
Execute mirrors upstream find.ts execute over fd.
func (*FindTool) ExecutionMode ¶
func (t *FindTool) ExecutionMode() agent.ToolExecutionMode
func (*FindTool) Schema ¶
func (t *FindTool) Schema() ai.ToolSchema
type GrepDetails ¶
type GrepDetails struct {
Truncation *TruncationResult
MatchLimitReached int
LinesTruncated bool
}
GrepDetails mirrors upstream GrepToolDetails (grep.ts:41): a truncation object when the byte limit was hit, the match-limit cap when reached, and a flag when individual lines were truncated to the max length.
func (*GrepDetails) ToolResultDetails ¶
func (d *GrepDetails) ToolResultDetails() any
ToolResultDetails maps grep result details to extension.GrepToolDetails.
type GrepTool ¶
type GrepTool struct {
CWD string
RgPath string
Tools *ToolsManager
}
GrepTool runs ripgrep to search files, mirroring upstream grep.ts.
RgPath, when non-empty, pins the ripgrep binary. Otherwise rg is resolved on every call through Tools (upstream ensureTool: <agentDir>/bin, PATH, then a download); with no Tools, PATH only.
func (*GrepTool) Execute ¶
func (t *GrepTool) Execute(ctx context.Context, _ string, rawParams json.RawMessage, _ agent.ToolUpdateCallback) (agent.AgentToolResult, error)
Execute mirrors upstream grep.ts execute: resolve the path, stream `rg --json` events with no line-length cap (upstream reads with readline), stop rg at the match limit, surface rg's stderr on failure, then format matches (with context lines read from the files) and apply byte truncation and upstream's notices.
func (*GrepTool) ExecutionMode ¶
func (t *GrepTool) ExecutionMode() agent.ToolExecutionMode
func (*GrepTool) Schema ¶
func (t *GrepTool) Schema() ai.ToolSchema
type LocalShellOperations ¶
type LocalShellOperations struct {
ShellName string
ResolveShell func() (ShellConfig, error)
// WrapCommand, when set, rewrites the command before execution.
WrapCommand func(string) string
// BinDir is prepended to PATH when the caller passes no environment
// (upstream getShellEnv's getBinDir).
BinDir string
}
LocalShellOperations mirrors upstream createLocalShellOperations(shellName, resolveShellConfig), with PowerShell's command wrapper (createLocalPowerShellOperations) as an optional hook.
func NewLocalBashOperations ¶
func NewLocalBashOperations(settings SettingsView, binDir string) *LocalShellOperations
NewLocalBashOperations mirrors upstream createLocalBashOperations: local execution through getShellConfig(settings.getShellPath()), read when a command runs, so an invalid shell path fails that command.
func (*LocalShellOperations) Exec ¶
func (o *LocalShellOperations) Exec(ctx context.Context, command, cwd string, opts BashOperationsExecOptions) (BashOperationsResult, error)
Exec runs command through the resolved shell, streaming output to opts.OnData, and waits for the shell (not its background descendants).
type LsDetails ¶
type LsDetails struct {
Truncation *TruncationResult
EntryLimitReached int
}
LsDetails is attached to a LsTool result. It carries the upstream SDK contract (ls.ts:23 LsToolDetails): a truncation object when the byte limit was hit and the entry-limit cap when reached. The TUI has no dedicated ls renderer; this exists only for the extension wire.
func (*LsDetails) ToolResultDetails ¶
ToolResultDetails maps ls result details to extension.LsToolDetails.
type LsTool ¶
type LsTool struct {
CWD string
}
LsTool lists directory contents.
func (*LsTool) Execute ¶
func (t *LsTool) Execute(ctx context.Context, _ string, rawParams json.RawMessage, _ agent.ToolUpdateCallback) (agent.AgentToolResult, error)
Execute mirrors upstream ls.ts execute.
func (*LsTool) ExecutionMode ¶
func (t *LsTool) ExecutionMode() agent.ToolExecutionMode
func (*LsTool) Schema ¶
func (t *LsTool) Schema() ai.ToolSchema
type MutationTicket ¶
type MutationTicket struct {
// contains filtered or unexported fields
}
MutationTicket is a reserved position in a FileMutationQueue, obtained via Reserve. It lets a caller fix its place in call order before starting any concurrent work, rather than only being able to register and wait in one inseparable step (With).
func (*MutationTicket) Release ¶
func (t *MutationTicket) Release()
Release signals this ticket's completion to the next queued caller, and drops the queue's bookkeeping for this path if no later caller has registered behind it. Callers must call Release exactly once, regardless of whether the mutation succeeded.
func (*MutationTicket) Wait ¶
func (t *MutationTicket) Wait()
Wait blocks until every earlier-registered mutation for this ticket's canonical path has completed.
type OutputAccumulator ¶
type OutputAccumulator struct {
// contains filtered or unexported fields
}
OutputAccumulator incrementally tracks streaming output with bounded memory. It decodes chunks with a streaming UTF-8 decoder (so a character split across reads survives), keeps only a decoded tail for snapshots, and writes the raw bytes to a temp file once the full output must be kept. Methods are safe for concurrent use.
func NewOutputAccumulator ¶
func NewOutputAccumulator(tempFilePrefix string) *OutputAccumulator
NewOutputAccumulator mirrors `new OutputAccumulator({ tempFilePrefix })` with the default line and byte limits. An empty prefix means "pi-output".
func (*OutputAccumulator) Append ¶
func (a *OutputAccumulator) Append(data []byte)
Append adds a raw output chunk.
func (*OutputAccumulator) CloseTempFile ¶
func (a *OutputAccumulator) CloseTempFile() error
CloseTempFile closes the full-output file, if one was opened.
func (*OutputAccumulator) Finish ¶
func (a *OutputAccumulator) Finish()
Finish flushes the decoder; later appends are ignored.
func (*OutputAccumulator) LastLineBytes ¶
func (a *OutputAccumulator) LastLineBytes() int
LastLineBytes mirrors upstream getLastLineBytes.
func (*OutputAccumulator) Snapshot ¶
func (a *OutputAccumulator) Snapshot(persistIfTruncated bool) OutputSnapshot
Snapshot mirrors upstream snapshot({ persistIfTruncated }).
type OutputSnapshot ¶
type OutputSnapshot struct {
Content string
Truncation TruncationResult
FullOutputPath string
}
OutputSnapshot mirrors upstream OutputSnapshot.
type PowerShellTool ¶
type PowerShellTool struct {
CWD string
// BinDir (<agentDir>/bin) is prepended to the command's PATH.
BinDir string
// HideSessionEnvironment turns off upstream's exposeSessionEnvironment.
HideSessionEnvironment bool
}
PowerShellTool executes PowerShell commands. It mirrors upstream tools/powershell.ts: the shared shell tool definition with the PowerShell config (name/label "powershell", shell name "PowerShell", prompt "PS>"), local operations that resolve PowerShell through GetPowerShellConfig and prefix each command with the UTF-8 output switch, and no command prefix or shell path setting (PowerShellToolOptions picks only operations, exposeSessionEnvironment, and spawnHook from BashToolOptions).
func (*PowerShellTool) Execute ¶
func (t *PowerShellTool) Execute(ctx context.Context, _ string, rawParams json.RawMessage, onUpdate agent.ToolUpdateCallback) (agent.AgentToolResult, error)
func (*PowerShellTool) ExecutionMode ¶
func (t *PowerShellTool) ExecutionMode() agent.ToolExecutionMode
ExecutionMode is parallel: upstream's shell tool definition sets no executionMode.
func (*PowerShellTool) Label ¶
func (t *PowerShellTool) Label() string
func (*PowerShellTool) Name ¶
func (t *PowerShellTool) Name() string
func (*PowerShellTool) Schema ¶
func (t *PowerShellTool) Schema() ai.ToolSchema
type ReadDetails ¶
type ReadDetails struct {
Path string
StartLine int // 1-indexed line number of the first emitted line
TotalLines int // total lines in the file (before truncation)
Truncated bool
// Truncation is the upstream-shaped truncation object for the extension SDK
// contract and the TUI warning. It is nil unless truncation occurred.
Truncation *TruncationResult
}
ReadDetails is attached to a ReadTool result. The TUI uses the path for syntax highlighting and the truncation details for the warning shown after the complete expanded body.
func (*ReadDetails) ToolResultDetails ¶
func (d *ReadDetails) ToolResultDetails() any
ToolResultDetails maps read result details to extension.ReadToolDetails.
type ReadTool ¶
type ReadTool struct {
CWD string
AutoResizeImages *bool
ResizeOptions *ai.ModelImageResizeOptions
}
ReadTool reads file contents.
func (*ReadTool) Execute ¶
func (t *ReadTool) Execute(ctx context.Context, _ string, rawParams json.RawMessage, _ agent.ToolUpdateCallback) (agent.AgentToolResult, error)
Execute mirrors upstream read.ts execute: resolve the path, check it is readable, return a supported image as an attachment, and otherwise decode the text (invalid UTF-8 becomes U+FFFD, as Buffer.toString does) and apply offset, limit and head truncation.
func (*ReadTool) ExecutionMode ¶
func (t *ReadTool) ExecutionMode() agent.ToolExecutionMode
func (*ReadTool) Schema ¶
func (t *ReadTool) Schema() ai.ToolSchema
type SettingsView ¶
SettingsView is the minimum settings surface needed to resolve a ShellConfig. Defining it here (rather than importing internal/codingagent) keeps the tools package free of upward dependencies.
type ShellConfig ¶
type ShellConfig = shellconfig.Config
ShellConfig is the resolved (binary, leading-args) pair used to invoke shell commands. The actual command string is appended as the final argument when spawning, unless CommandTransport is "stdin".
func GetPowerShellConfig ¶
func GetPowerShellConfig() (ShellConfig, error)
GetPowerShellConfig resolves PowerShell on Windows, preferring PowerShell 7 (pwsh.exe) over Windows PowerShell (powershell.exe). Mirrors upstream getPowerShellConfig: on any other platform it reports that the tool is Windows-only.
func GetShellConfig ¶
func GetShellConfig(settings SettingsView) (ShellConfig, error)
GetShellConfig returns the shell binary + leading args. settings may be nil; resolution then uses the platform default (defaultShellConfig).
type ToolStatus ¶
ToolStatus mirrors upstream ToolStatus: progress and failures EnsureTool reports instead of printing. Type is "info" or "warning".
type ToolsManager ¶
type ToolsManager struct {
// contains filtered or unexported fields
}
ToolsManager provides the download/install pipeline for fd and rg. It is parameterised on the agent dir so tests can use a tempdir.
Concurrent EnsureTool calls for the same tool deduplicate downloads via the singleflight in-flight map.
func NewToolsManager ¶
func NewToolsManager(agentDir string) *ToolsManager
NewToolsManager constructs a manager rooted at agentDir.
func (*ToolsManager) BinDir ¶
func (m *ToolsManager) BinDir() string
BinDir returns <agentDir>/bin (mirrors upstream getBinDir).
func (*ToolsManager) EnsureTool ¶
func (m *ToolsManager) EnsureTool(ctx context.Context, tool string, onStatus func(ToolStatus)) string
EnsureTool mirrors upstream ensureTool: it returns the tool's path, or "" when unavailable. It reports progress and failures through onStatus (nil discards them), never writes to the console, and includes up to five distinct cause messages in download warnings.
func (*ToolsManager) GetToolPath ¶
func (m *ToolsManager) GetToolPath(tool string) string
GetToolPath mirrors upstream getToolPath (tools-manager.ts:80). Returns the path to the tool, or "" if not found.
Lookup order:
- <agentDir>/bin/<binary>[.exe] (local install)
- systemBinaryNames in PATH
type TruncationResult ¶
type TruncationResult struct {
Content string
Truncated bool
TruncatedBy string // "lines" | "bytes" | ""
TotalLines int
TotalBytes int
OutputLines int
OutputBytes int
// LastLinePartial: the last line of the original output is the
// only one that fit (and was truncated from its end). Bash-only
// edge case.
LastLinePartial bool
// FirstLineExceedsLimit: head-truncation case where the first line
// alone exceeds maxBytes. We return empty content and let the
// caller decide.
FirstLineExceedsLimit bool
MaxLines int
MaxBytes int
}
TruncationResult captures every fact a renderer needs to format the "[Showing lines X-Y of Z. Full output: <path>]" warning row.
Layout matches upstream TruncationResult:
{ content, truncated, truncatedBy, totalLines, totalBytes,
outputLines, outputBytes, lastLinePartial, firstLineExceedsLimit,
maxLines, maxBytes }
func TruncateHead ¶
func TruncateHead(content string, maxBytes, maxLines int) TruncationResult
TruncateHead keeps the FIRST lines/bytes of content. Used for grep output, find results, etc.: anywhere we want to see the beginning. Mirrors upstream `truncateHead` at `.upstream/current/packages/coding-agent/src/core/tools/truncate.ts:67-149`.
Never returns partial lines: if the first line alone exceeds maxBytes, the result is empty content with `FirstLineExceedsLimit` set so the caller can emit the upstream `[First line exceeds N limit]` warning.
func TruncateTail ¶
func TruncateTail(content string, maxBytes, maxLines int) TruncationResult
TruncateTail keeps the last lines/bytes of content. Used for bash output (errors and final results live at the end).
maxBytes and maxLines are used as given, like upstream's options (only an omitted option falls back to a default there); callers pass the defaults.
type WriteDetails ¶
type WriteDetails struct {
Path string
Content string
// Overwrote is true when the write replaced an existing file.
Overwrote bool
}
WriteDetails is attached to a WriteTool result. The TUI uses the path to select syntax highlighting and the content to render the upstream ten-line collapsed preview or complete expanded body.
func (*WriteDetails) ToolResultDetails ¶
func (d *WriteDetails) ToolResultDetails() any
ToolResultDetails reports that write results carry no SDK details, matching upstream (write.ts:223 sets details: undefined). The internal WriteDetails exists only for the TUI renderer.
type WriteTool ¶
type WriteTool struct {
CWD string
Queue *FileMutationQueue // serialises concurrent writes
}
WriteTool creates or overwrites files.
func (*WriteTool) Execute ¶
func (t *WriteTool) Execute(ctx context.Context, _ string, rawParams json.RawMessage, _ agent.ToolUpdateCallback) (agent.AgentToolResult, error)
Execute mirrors upstream write.ts execute: inside the file mutation queue create the parent directories and write the file, checking for an abort after each step.
func (*WriteTool) ExecutionMode ¶
func (t *WriteTool) ExecutionMode() agent.ToolExecutionMode
ExecutionMode is parallel: upstream's write definition sets no executionMode, and the file mutation queue serialises writes to one file.
func (*WriteTool) ReserveMutationOrder ¶
func (t *WriteTool) ReserveMutationOrder(rawParams json.RawMessage) (*agent.MutationTicket, bool)
ReserveMutationOrder implements agent.QueueOrderable: the parallel dispatcher calls this synchronously, in tool-call order, before spawning this call's goroutine, so this write's place in the shared file mutation queue is fixed before goroutine scheduling can reorder it. Returns ok=false whenever Execute would not reach the queue either (invalid params), so no reservation is ever left un-awaited.
func (*WriteTool) Schema ¶
func (t *WriteTool) Schema() ai.ToolSchema
Source Files
¶
- bash.go
- bash_executor.go
- bash_group_unix.go
- bash_operations.go
- bash_session_env.go
- details.go
- diff_string.go
- edit.go
- edit_diff.go
- ext_details.go
- find.go
- fs_access_unix.go
- fs_errors.go
- grep.go
- image_detect.go
- ls.go
- mutation_queue.go
- output_accumulator.go
- path_utils.go
- powershell.go
- read.go
- sanitize.go
- shell_config.go
- shell_tool.go
- shell_updates.go
- tools.go
- tools_manager.go
- truncate.go
- unified_patch.go
- write.go