tools

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2026 License: MIT Imports: 46 Imported by: 0

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:

  1. EnsureTool first checks <agentDir>/bin/<binary> (local install),
  2. then PATH (system install),
  3. 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 docs/parity/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

View Source
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

View Source
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.

View Source
const GrepMaxLineLength = GrepMaxLineLengthUpstream

GrepMaxLineLength matches upstream truncate.ts GREP_MAX_LINE_LENGTH.

View Source
const PowerShellPromptSnippet = "Execute PowerShell commands"

PowerShellPromptSnippet mirrors upstream powershellToolSystemPromptContribution.snippet.

Variables

View Source
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 ApplyShellOutputUpdate

func ApplyShellOutputUpdate(current *harness.ShellOutputView, update harness.ShellOutputUpdate) harness.ShellOutputView

Ports packages/agent/src/harness/utils/output-capture.ts. ApplyShellOutputUpdate folds one bounded update into its preceding view.

func BuiltinToolActive

func BuiltinToolActive(name string, active, allowed map[string]struct{}) bool

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

func BuiltinToolDescription(name string) string

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 BuiltinToolSchemas

func BuiltinToolSchemas() []ai.ToolSchema

BuiltinToolSchemas returns the schema of every built-in tool, in registry order (upstream createAllToolDefinitions), without creating runnable tools. The schemas are the definitions upstream getAllTools reports.

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 CreateBashTool

func CreateBashTool(options *BashToolOptions) *harness.AgentHarnessTool

Ports packages/agent/src/harness/tools/bash.ts. CreateBashTool delegates execution and bounded output capture to the turn's environment. Distinct progress snapshots request checkpoints at most once every two seconds; callbacks after execution settles are ignored.

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 CreateEditTool

func CreateEditTool() *harness.AgentHarnessTool

Ports packages/agent/src/harness/tools/edit.ts. CreateEditTool applies disjoint replacements against one original file view.

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 CreateReadTool

func CreateReadTool(options *ReadToolOptions) *harness.AgentHarnessTool

Ports packages/agent/src/harness/tools/read.ts. CreateReadTool reads through the turn's execution environment. An image processor is optional; without one, supported image bytes pass through and BMP is omitted with the upstream configuration notice.

func CreateWriteTool

func CreateWriteTool() *harness.AgentHarnessTool

Ports packages/agent/src/harness/tools/write.ts. CreateWriteTool serializes writes by environment and canonical path.

func DefaultToolGuidelines

func DefaultToolGuidelines() map[string][]string

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

func FormatJSNumber(v float64) string

FormatJSNumber mirrors JavaScript String(number) for a finite number.

func FormatSize

func FormatSize(bytes int) string

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

func GenerateDiffString(oldContent, newContent string) (diff string, firstChangedLine int)

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

func GenerateUnifiedPatch(path, oldStr, newStr string) string

GenerateUnifiedPatch returns a unified diff for path byte-identical to upstream's generateUnifiedPatch with the default 4 lines of context.

func GetShellEnv

func GetShellEnv(binDir string) []string

GetShellEnv mirrors upstream getShellEnv: {...process.env} (nodespawn.ProcessEnv) 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

func LookupToolPath(tool, agentBinDir string) string

LookupToolPath resolves a tool to a usable binary path. Search order:

  1. agentBinDir (if non-empty): the auto-install location used by ToolsManager.downloadTool.
  2. systemBinaryNames (fd has "fdfind" fallback for Debian/Ubuntu) that upstream's commandExists can spawn: nodespawn.LookPath, which on Windows finds only a .com or .exe file, from the working directory first unless NoDefaultCurrentDirectoryInExePath is set.

Returns "" if nothing is found. On Windows, returns the bare command name, as upstream's getToolPath does.

func NodeErrorCode

func NodeErrorCode(err error) string

NodeErrorCode returns the Node error code (error.code) for a file system or spawn error, or "" when it has none.

func NodeFSError

func NodeFSError(err error, syscallName, path string) string

NodeFSError formats err as Node's fs promises reject it: "<CODE>: <message>, <syscall> '<path>'" (read errors carry no path). Errors without a known errno keep their Go text.

func NormalizeWindowsShellPath

func NormalizeWindowsShellPath(filePath string) string

NormalizeWindowsShellPath converts a Git Bash, MSYS, Cygwin or WSL drive path to the form native Windows APIs accept.

upstream: utils/paths.ts normalizeWindowsShellPath

func ResolveToCwd

func ResolveToCwd(filePath, cwd string) (string, error)

ResolveToCwd is upstream path-utils.ts resolveToCwd for other packages.

func SanitizeBinaryOutput

func SanitizeBinaryOutput(s string) string

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

func StripANSI(b []byte) []byte

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

func SupportedImageMime(data []byte) string

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

func TruncateLine(line string, maxChars int) (string, bool)

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 `json:"truncation,omitempty"`
	FullOutputPath string            `json:"fullOutputPath,omitempty"`
}

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 BashExecution

type BashExecution struct {
	Command    string
	Cwd        string
	Env        map[string]string
	InheritEnv bool
}

BashExecution is the mutable shell request passed to Prepare.

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
	// Operations delegates command execution; nil selects local bash.
	Operations BashOperations
	// 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 with local or caller-supplied operations. Ports packages/coding-agent/src/core/tools/bash.ts.

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) ArgumentSchema

func (t *BashTool) ArgumentSchema() json.RawMessage

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) Label

func (t *BashTool) Label() string

func (*BashTool) Name

func (t *BashTool) Name() string

func (*BashTool) Schema

func (t *BashTool) Schema() ai.ToolSchema

type BashToolOptions

type BashToolOptions struct {
	CommandPrefix string
	Prepare       func(context.Context, *BashExecution, any) error
}

BashToolOptions configures a harness bash tool.

type EditOperations

type EditOperations struct {
	ReadFile  func(string) ([]byte, error)
	WriteFile func(string, string) error
	Access    func(string) error
}

EditOperations delegates file editing. Each callback completes before the mutation queue advances. Ports packages/coding-agent/src/core/tools/edit.ts.

type EditReplacement

type EditReplacement struct {
	OldText string
	NewText string
}

EditReplacement is one exact-text replacement of an edit call.

type EditTool

type EditTool struct {
	CWD        string
	Queue      *FileMutationQueue // serialises concurrent edits
	Operations *EditOperations
}

EditTool performs exact-text-replacement edits on files. Mirrors upstream packages/coding-agent/src/core/tools/edit.ts.

func (*EditTool) ArgumentSchema

func (t *EditTool) ArgumentSchema() json.RawMessage

func (*EditTool) Execute

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) Label

func (t *EditTool) Label() string

func (*EditTool) Name

func (t *EditTool) Name() string

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 EditsDiffPreview

type EditsDiffPreview struct {
	Diff             string
	FirstChangedLine int
	Error            string
}

EditsDiffPreview is upstream EditDiffResult or EditDiffError: the diff the edits would make, with its first changed line, or why they cannot apply.

func ComputeEditsDiff

func ComputeEditsDiff(path string, edits []EditReplacement, cwd string) EditsDiffPreview

ComputeEditsDiff computes the diff the edits would make to path without writing it, as the upstream edit renderer previews an edit call.

type ExecutionToolContext

type ExecutionToolContext struct{ Env harness.ExecutionEnv }

Ports packages/agent/src/harness/tools/tool-context.ts. ExecutionToolContext is the filesystem and shell context for execution tools. Applications embed it in their own turn context to retain additional fields.

func (ExecutionToolContext) Environment

func (c ExecutionToolContext) Environment() harness.ExecutionEnv

Environment returns this turn's execution environment.

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 `json:"truncation,omitempty"`
	// Nil means no limit notice; a reached zero remains present on the wire.
	ResultLimitReached *float64 `json:"resultLimitReached,omitempty"`
}

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 FindGlobOptions

type FindGlobOptions struct {
	Ignore []string
	Limit  float64
}

FindGlobOptions is the glob operation's ignore list and requested result limit.

type FindOperations

type FindOperations struct {
	Exists func(string) (bool, error)
	Glob   func(string, string, FindGlobOptions) ([]string, error)
}

FindOperations delegates existence and glob lookup. Execute waits for each callback and discards its result after cancellation. Ports packages/coding-agent/src/core/tools/find.ts.

type FindTool

type FindTool struct {
	CWD        string
	FdPath     string
	Tools      *ToolsManager
	Operations *FindOperations
}

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) ArgumentSchema

func (t *FindTool) ArgumentSchema() json.RawMessage

func (*FindTool) Execute

Execute mirrors upstream find.ts execute over fd.

func (*FindTool) ExecutionMode

func (t *FindTool) ExecutionMode() agent.ToolExecutionMode

func (*FindTool) Label

func (t *FindTool) Label() string

func (*FindTool) Name

func (t *FindTool) Name() string

func (*FindTool) Schema

func (t *FindTool) Schema() ai.ToolSchema

type GrepDetails

type GrepDetails struct {
	Truncation        *TruncationResult `json:"truncation,omitempty"`
	MatchLimitReached float64           `json:"matchLimitReached,omitempty"`
	LinesTruncated    bool              `json:"linesTruncated,omitempty"`
}

GrepDetails carries sparse truncation metadata and the requested match limit, including fractional values.

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) ArgumentSchema

func (t *GrepTool) ArgumentSchema() json.RawMessage

func (*GrepTool) Execute

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) Label

func (t *GrepTool) Label() string

func (*GrepTool) Name

func (t *GrepTool) Name() string

func (*GrepTool) Schema

func (t *GrepTool) Schema() ai.ToolSchema

type HarnessBashToolDetails

type HarnessBashToolDetails struct {
	Truncation     *harness.ShellOutputTruncation `json:"truncation,omitempty"`
	FullOutputPath string                         `json:"fullOutputPath,omitempty"`
}

HarnessBashToolDetails describes truncated shell output.

type HarnessEditToolDetails

type HarnessEditToolDetails struct {
	Diff             string `json:"diff"`
	Patch            string `json:"patch"`
	FirstChangedLine *int   `json:"firstChangedLine,omitempty"`
}

HarnessEditToolDetails carries display and unified diffs.

type HarnessReadToolDetails

type HarnessReadToolDetails struct {
	Truncation *HarnessTruncationResult `json:"truncation,omitempty"`
}

HarnessReadToolDetails describes truncated reads.

type HarnessTruncationResult

type HarnessTruncationResult struct {
	Content string `json:"content"`
	harness.ShellOutputTruncation
}

HarnessTruncationResult includes retained text beside source-side truncation metadata.

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

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 `json:"truncation,omitempty"`
	EntryLimitReached float64           `json:"entryLimitReached,omitempty"`
}

LsDetails carries the sparse upstream ls result metadata. Limits retain the requested number rather than an integer-rounded rendering count.

func (*LsDetails) ToolResultDetails

func (d *LsDetails) ToolResultDetails() any

ToolResultDetails maps ls result details to extension.LsToolDetails.

type LsTool

type LsTool struct {
	CWD string
}

LsTool lists directory contents.

func (*LsTool) ArgumentSchema

func (t *LsTool) ArgumentSchema() json.RawMessage

func (*LsTool) Execute

Execute mirrors upstream ls.ts execute.

func (*LsTool) ExecutionMode

func (t *LsTool) ExecutionMode() agent.ToolExecutionMode

func (*LsTool) Label

func (t *LsTool) Label() string

func (*LsTool) Name

func (t *LsTool) Name() string

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) ArgumentSchema

func (t *PowerShellTool) ArgumentSchema() json.RawMessage

func (*PowerShellTool) Execute

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 `json:"-"`
	StartLine  int    `json:"-"`
	TotalLines int    `json:"-"`
	Truncated  bool   `json:"-"`
	// Truncation is the upstream-shaped truncation object for the extension SDK
	// contract and the TUI warning. It is nil unless truncation occurred.
	Truncation *TruncationResult `json:"truncation,omitempty"`
}

ReadDetails carries the optional upstream truncation object. The renderer derives display-only fields from the retained read call.

func (*ReadDetails) ToolResultDetails

func (d *ReadDetails) ToolResultDetails() any

ToolResultDetails maps read result details to extension.ReadToolDetails.

type ReadImageProcessorResult

type ReadImageProcessorResult struct {
	OK       bool
	Data     string
	MimeType string
	Hints    []string
	Message  string
}

ReadImageProcessorResult is either a converted image or an omission message.

type ReadTool

type ReadTool struct {
	CWD              string
	AutoResizeImages *bool
	ResizeOptions    *ai.ModelImageResizeOptions
}

ReadTool reads file contents.

func (*ReadTool) ArgumentSchema

func (t *ReadTool) ArgumentSchema() json.RawMessage

ArgumentSchema retains the TypeBox metadata and property order used by Pi's built-in argument validator. Schema remains plain JSON for provider requests.

func (*ReadTool) Execute

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) Label

func (t *ReadTool) Label() string

func (*ReadTool) Name

func (t *ReadTool) Name() string

func (*ReadTool) Schema

func (t *ReadTool) Schema() ai.ToolSchema

type ReadToolOptions

type ReadToolOptions struct {
	AutoResizeImages *bool
	ImageProcessor   func(context.Context, []byte, string, bool) (ReadImageProcessorResult, error)
}

ReadToolOptions controls an optional image processor.

type SettingsView

type SettingsView interface {
	GetShellPath() (string, error)
}

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

type ToolStatus struct {
	Type    string
	Message string
}

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:

  1. <agentDir>/bin/<binary>[.exe] (local install)
  2. systemBinaryNames in PATH

type TruncationResult

type TruncationResult struct {
	Content     string `json:"content"`
	Truncated   bool   `json:"truncated"`
	TruncatedBy string `json:"truncatedBy"` // "lines" | "bytes" | ""
	TotalLines  int    `json:"totalLines"`
	TotalBytes  int    `json:"totalBytes"`
	OutputLines int    `json:"outputLines"`
	OutputBytes int    `json:"outputBytes"`
	// 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 `json:"lastLinePartial"`
	// FirstLineExceedsLimit: head-truncation case where the first line
	// alone exceeds maxBytes. We return empty content and let the
	// caller decide.
	FirstLineExceedsLimit bool `json:"firstLineExceedsLimit"`
	MaxLines              int  `json:"maxLines"`
	MaxBytes              int  `json:"maxBytes"`
}

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 display-only metadata derived from the retained write call. Tool results do not carry it.

func (*WriteDetails) ToolResultDetails

func (d *WriteDetails) ToolResultDetails() any

ToolResultDetails reports that write results carry no SDK details, matching upstream (write.ts:87 sets details: undefined). The internal WriteDetails exists only for the TUI renderer.

type WriteOperations

type WriteOperations struct {
	WriteFile func(string, string) error
	Mkdir     func(string) error
}

WriteOperations delegates file creation. Each callback completes before the mutation queue advances. Ports packages/coding-agent/src/core/tools/write.ts.

type WriteTool

type WriteTool struct {
	CWD        string
	Queue      *FileMutationQueue // serialises concurrent writes
	Operations *WriteOperations
}

WriteTool creates or overwrites files.

func (*WriteTool) ArgumentSchema

func (t *WriteTool) ArgumentSchema() json.RawMessage

func (*WriteTool) Execute

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) Label

func (t *WriteTool) Label() string

func (*WriteTool) Name

func (t *WriteTool) Name() string

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

Jump to

Keyboard shortcuts

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