tools

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 59 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. internal/childwait applies utils/child-process.ts waitForChildProcess for the post-exit stdio grace.

Package tools: edit-diff helpers.

Ports 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.

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 = truncate.DefaultMaxBytes
	DefaultMaxLines = truncate.DefaultMaxLines
)

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 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 BuiltinToolDefinition

func BuiltinToolDefinition(tool agent.AgentTool) (extension.ToolDefinition, error)

BuiltinToolDefinition is the ToolDefinition of a built-in tool as upstream's create<Tool>ToolDefinition builds it: the tool's definition with the prompt snippet the system prompt lists it under, no execution mode (the agent supplies the parallel default) and, for edit, the renderShell the tool draws itself (edit.ts:157).

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, options *ToolsOptions) []agent.AgentTool

CreateAllTools returns every registered built-in tool, mirroring upstream createAllTools (tools/index.ts:213): CreateCodingTools plus the opt-in powershell tool, in upstream registry order. Callers select the active subset with SelectBuiltinTools.

func CreateBashToolDefinition

func CreateBashToolDefinition(cwd string, options *BashToolOptions) (extension.ToolDefinition, error)

CreateBashToolDefinition is upstream's createBashToolDefinition (bash.ts:427): the bash tool as a ToolDefinition, with the prompt snippet the system prompt lists it under.

func CreateCodingTools

func CreateCodingTools(cwd string, options *ToolsOptions) []agent.AgentTool

CreateCodingTools returns the default set of LLM-callable coding tools, mirroring upstream createCodingTools (tools/index.ts:195). Edit and write serialise concurrent write/edit calls to the same file from parallel tool batches through the process-wide mutation queue.

func CreateReadOnlyTools

func CreateReadOnlyTools(cwd string, options *ToolsOptions) []agent.AgentTool

CreateReadOnlyTools returns read-only tools (read, grep, find, ls), mirroring upstream createReadOnlyTools (tools/index.ts:204).

func CreateTool

func CreateTool(name, cwd string, options *ToolsOptions) (agent.AgentTool, error)

CreateTool is upstream's createTool: the built-in tool with the given name.

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 GenerateUnifiedPatch

func GenerateUnifiedPatch(path, oldStr, newStr string, contextLines ...int) string

GenerateUnifiedPatch returns a unified diff for path byte-identical to upstream's generateUnifiedPatch; contextLines is its optional fourth parameter (default 4).

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. Ports packages/coding-agent/src/utils/shell.ts

func GetTextOutput

func GetTextOutput(content []ai.ToolResultMessageContent, showImages bool) string

GetTextOutput is a tool result's text for a renderer: its text blocks with ANSI sequences and binary control characters removed, followed, when images are not shown, by one fallback line for each image block. upstream: packages/coding-agent/src/core/tools/render-utils.ts:41-64

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 KillTrackedDetachedChildren

func KillTrackedDetachedChildren()

KillTrackedDetachedChildren kills the process tree of every tracked child and forgets them all. It also sends SIGTERM to the process group of every running MCP stdio server: Pi's stdio transport kills those groups from a process.once("exit") hook, which runs on every exit including the dead-terminal and crash exits, while Go's os.Exit runs no hooks. Every caller is an exit that skips the orderly session shutdown.

Ports packages/coding-agent/src/utils/shell.ts (killTrackedDetachedChildren) and packages/mcp/src/transports/stdio.ts (installExitHook).

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 RebuildStructuredContent

func RebuildStructuredContent(toolName string, content []ai.ToolResultMessageContent) (json.RawMessage, bool)

RebuildStructuredContent returns the structured content the built-in tool named toolName derives from a result's content alone, and false for a tool whose structured content holds more than its content (bash's exit code and wall time) or that has none: read's is toReadOutput(content) (read.ts).

func RegisterExitCleanup

func RegisterExitCleanup(cleanup func())

RegisterExitCleanup adds cleanup to what KillTrackedDetachedChildren runs after it kills the tracked children. A package that owns processes of its own registers its kill here so this package does not link it (a pig_strip_mcp build links no mcp).

func ResolveReadPath

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

ResolveReadPath is upstream path-utils.ts resolveReadPath for other packages.

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 (see text.SanitizeBinaryOutput).

func SelectBuiltinTools

func SelectBuiltinTools(all []agent.AgentTool, active, allowed map[string]struct{}) []agent.AgentTool

SelectBuiltinTools keeps the tools BuiltinToolActive reports active.

func SplitIncompleteAnsiSuffix

func SplitIncompleteAnsiSuffix(value string) (complete, pending string)

SplitIncompleteAnsiSuffix mirrors utils/ansi.ts splitIncompleteAnsiSuffix: it splits streamed text into a part that is safe to strip now and a trailing unfinished escape sequence that belongs in front of the next chunk. Only the last maxPendingAnsiLength UTF-16 code units are searched.

func StripANSI

func StripANSI(b []byte) []byte

StripANSI mirrors upstream stripAnsi (see text.StripANSI). Anything its pattern does not cover (a lone ESC, ESC + letter outside the final-byte set) is left for SanitizeBinaryOutput. Ports packages/coding-agent/src/utils/shell.ts

func ToolDefinitionFromAgentTool

func ToolDefinitionFromAgentTool(tool agent.AgentTool) (extension.ToolDefinition, error)

ToolDefinitionFromAgentTool is upstream's createToolDefinitionFromAgentTool: the ToolDefinition that runs tool. It carries the tool's name, label, description, parameters, structured-output schema, constrained sampling, argument preparation and execution mode, and runs the tool's own Execute. A tool without a label is labelled with its name, as the tool registry lists it.

func TrackDetachedChild

func TrackDetachedChild(process *os.Process)

TrackDetachedChild records a detached child process so KillTrackedDetachedChildren can kill it.

Ports packages/coding-agent/src/utils/shell.ts (trackDetachedChildPid).

func UntrackDetachedChild

func UntrackDetachedChild(process *os.Process)

UntrackDetachedChild forgets a detached child process that has ended.

Ports packages/coding-agent/src/utils/shell.ts (untrackDetachedChildPid).

func WithFileMutationQueue

func WithFileMutationQueue[T any](filePath string, fn func() (T, error)) (T, error)

WithFileMutationQueue is upstream's withFileMutationQueue (file-mutation-queue.ts:32): it runs fn once every mutation registered earlier for the same file has completed (the same canonical path, or the same existing file under another path, D190), through the process-wide queue that every edit and write tool made by the Create functions shares, and returns fn's result. Mutations of different files run in parallel. An error from resolving the path's canonical form is returned without running fn, as upstream's rejection is.

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

A clean chunk costs one string, the decoded text it keeps: the strip and sanitize steps return text they do not change as it is, and the temp file is written through a buffer rather than a write per chunk.

type BashSettingsView

type BashSettingsView interface {
	SettingsView
	GetCommandPrefix() string
}

SettingsView (in shell_config.go) is the inner shell-only subset.

type BashSpawnContext

type BashSpawnContext struct {
	Command string
	CWD     string
	Env     []string
}

BashSpawnContext is upstream's BashSpawnContext: what a shell tool runs. Env holds KEY=VALUE entries, as os/exec takes them, where upstream has a process environment object.

type BashSpawnHook

type BashSpawnHook func(context BashSpawnContext) BashSpawnContext

BashSpawnHook is upstream's BashSpawnHook: it receives the context a shell tool is about to run and returns the context to run.

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
	// SpawnHook adjusts the command, working directory or environment before execution (upstream spawnHook). nil runs the command as built.
	SpawnHook BashSpawnHook
}

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 CreateBashTool

func CreateBashTool(cwd string, options *BashToolOptions) *BashTool

CreateBashTool is upstream's createBashTool (bash.ts:434).

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

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

OutputSchema mirrors upstream bashOutputSchema: the structuredContent of a completed command.

func (*BashTool) Schema

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

type BashToolOptions

type BashToolOptions struct {
	// Operations delegates command execution; nil is the local shell.
	Operations BashOperations
	// BinDir is the managed tools directory (Pi's getBinDir()); ToolsOptions.BinDir sets it for the built-in sets.
	BinDir string
	// CommandPrefix is prepended to every command.
	CommandPrefix string
	// ShellPath is an explicit shell path.
	ShellPath string
	// Settings resolves the shell path live when ShellPath is empty. It stands in for Pi's getShellConfig(settingsManager.getShellPath()) read at call time.
	Settings SettingsView
	// ExposeSessionEnvironment exposes the PI_* session variables; nil is true.
	ExposeSessionEnvironment *bool
	// SpawnHook adjusts the command, working directory or environment before execution.
	SpawnHook BashSpawnHook
}

BashToolOptions is upstream's BashToolOptions (bash.ts:214-226).

type DiffStringResult

type DiffStringResult struct {
	Diff             string
	FirstChangedLine *int
}

DiffStringResult is upstream's `{ diff: string; firstChangedLine: number | undefined }`. FirstChangedLine is nil when there was no change (upstream `undefined`).

func GenerateDiffString

func GenerateDiffString(oldContent, newContent string, contextLines ...int) DiffStringResult

GenerateDiffString returns the line-numbered display diff and the first changed line number in the new file, byte-identical to upstream generateDiffString. contextLines is upstream's optional third parameter (default 4).

type EditDiffError

type EditDiffError struct {
	Error string
}

EditDiffError is upstream's EditDiffError: why the edits cannot apply.

type EditDiffOutcome

type EditDiffOutcome interface {
	// contains filtered or unexported methods
}

EditDiffOutcome is upstream's EditDiffResult | EditDiffError union; EditDiffResult and EditDiffError are its only members.

func ComputeEditsDiff

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

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

type EditDiffResult

type EditDiffResult struct {
	Diff             string
	FirstChangedLine int
}

EditDiffResult is upstream's EditDiffResult: the diff the edits would make and the first changed line, 0 when there is none (upstream undefined, as EditToolDetails).

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 CreateEditTool

func CreateEditTool(cwd string, options *EditToolOptions) *EditTool

CreateEditTool is upstream's createEditTool (edit.ts:218); its mutations serialise with every other edit and write tool's through the process queue.

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

func (t *EditTool) RegistersInFileMutationQueue() bool

RegistersInFileMutationQueue implements agent.RegistersInFileMutationQueue: the parallel dispatcher registers this call in the queue after the extension tools before it in the batch started, as Pi runs their synchronous prefixes first.

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 EditToolOptions

type EditToolOptions struct{ Operations *EditOperations }

EditToolOptions is upstream's EditToolOptions.

type FileMutationQueue

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

FileMutationQueue serialises concurrent mutations of one file, in the order callers entered With: mutations whose canonical paths are equal, and mutations of an existing file reached by different canonical paths (hard links, and case aliases that Go's symlink resolution leaves apart). That second rule goes beyond Pi (D190). Operations on different files proceed in parallel. It coordinates only mutations registered in this process.

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, or for the same existing file under another 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 CreateFindTool

func CreateFindTool(cwd string, options *FindToolOptions) *FindTool

CreateFindTool is upstream's createFindTool (find.ts:316).

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 FindToolOptions

type FindToolOptions struct {
	Operations *FindOperations
	// BinDir is the managed tools directory (Pi's getBinDir()).
	BinDir string
}

FindToolOptions is upstream's FindToolOptions.

type FullOutput

type FullOutput struct {
	Content string
	// Truncated reports whether Content omits part of the output.
	Truncated bool
}

FullOutput mirrors upstream FullOutput (output-accumulator.ts): the complete output for callers that can take more than the display snapshot.

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 GrepOperations

type GrepOperations struct {
	// IsDirectory reports whether the path is a directory and fails when it does not exist.
	IsDirectory func(absolutePath string) (bool, error)
	// ReadFile reads a file for its context lines; nil streams the local file.
	ReadFile func(absolutePath string) (string, error)
}

GrepOperations is upstream's GrepOperations: pluggable path and file reads for the search path and the context lines. Ports packages/coding-agent/src/core/tools/grep.ts.

type GrepTool

type GrepTool struct {
	CWD    string
	RgPath string
	Tools  *ToolsManager
	// Operations delegates the filesystem reads; nil selects the local filesystem (upstream options.operations).
	Operations *GrepOperations
}

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 CreateGrepTool

func CreateGrepTool(cwd string, options *GrepToolOptions) *GrepTool

CreateGrepTool is upstream's createGrepTool (grep.ts:321).

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 GrepToolOptions

type GrepToolOptions struct {
	Operations *GrepOperations
	// BinDir is the managed tools directory (Pi's getBinDir()).
	BinDir string
}

GrepToolOptions is upstream's GrepToolOptions.

type LocalBashOptions

type LocalBashOptions struct {
	// ShellPath selects the shell; empty resolves the platform default (shell.ts getShellConfig). A path that does not exist fails the command.
	ShellPath string
	BinDir    string
}

LocalBashOptions is createLocalBashOperations' `{ shellPath?: string }` (bash.ts:174). BinDir is the directory getShellEnv prepends to PATH (config.ts getBinDir); Pi reads it from its process-wide agent directory, so Go carries it with the options.

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 CreateLocalBashOperations

func CreateLocalBashOperations(options *LocalBashOptions) *LocalShellOperations

CreateLocalBashOperations is upstream createLocalBashOperations(options?): local execution through getShellConfig(options.shellPath), resolved when a command runs. nil options select the default shell.

func NewLocalPowerShellOperations

func NewLocalPowerShellOperations() *LocalShellOperations

NewLocalPowerShellOperations is upstream createLocalPowerShellOperations: local execution through PowerShell, each command prefixed with the UTF-8 output switch.

func (*LocalShellOperations) Exec

Exec runs command through the resolved shell, streaming output to opts.OnData, and waits for the shell (not its background descendants). The chunk OnData receives is lent for the call: the pipe reader reads into one buffer, so a consumer copies what it keeps, as the bash tool's accumulator and the user-bash executor do.

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 LsOperations

type LsOperations struct {
	// Exists reports whether the path exists.
	Exists func(absolutePath string) (bool, error)
	// Stat describes a file or directory and fails when it is not found.
	Stat func(absolutePath string) (LsStat, error)
	// Readdir lists the entry names of a directory.
	Readdir func(absolutePath string) ([]string, error)
}

LsOperations is upstream's LsOperations: pluggable directory reads, for example over SSH. Each callback completes before Execute continues. Ports packages/coding-agent/src/core/tools/ls.ts.

type LsStat

type LsStat interface {
	IsDirectory() bool
}

LsStat is the `{ isDirectory: () => boolean }` that LsOperations.stat resolves (ls.ts:34).

type LsTool

type LsTool struct {
	CWD string
	// Operations delegates the filesystem reads; nil selects the local filesystem (upstream options.operations).
	Operations *LsOperations
}

LsTool lists directory contents.

func CreateLsTool

func CreateLsTool(cwd string, options *LsToolOptions) *LsTool

CreateLsTool is upstream's createLsTool (ls.ts:173).

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 LsToolOptions

type LsToolOptions struct{ Operations *LsOperations }

LsToolOptions is upstream's LsToolOptions.

type MiddleTruncationResult

type MiddleTruncationResult struct {
	// Content is the start and end of the input with a `…N chars truncated…`
	// marker between them.
	Content      string
	Truncated    bool
	RemovedChars int
	TotalBytes   int
	TotalLines   int
}

MiddleTruncationResult mirrors upstream MiddleTruncationResult.

func TruncateMiddle

func TruncateMiddle(content string, maxBytes int) MiddleTruncationResult

TruncateMiddle mirrors upstream truncateMiddle: keep the start and the end of content, half of maxBytes each (the tail takes the odd byte), and replace the middle with a `…N chars truncated…` marker, like Codex does for tool output. It cuts only at character boundaries.

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 ReserveFileMutation

func ReserveFileMutation(filePath string) (*MutationTicket, error)

ReserveFileMutation registers filePath's next position in the process-wide queue that WithFileMutationQueue and every edit and write tool share, synchronously, and returns the ticket: Wait (or WaitContext) for the turn, then Release exactly once after the mutation completes. The extension host reserves through it for the mutations an extension process runs under its own withFileMutationQueue, so they queue with the built-in tools and with each other (plumbing for Pi's single process, D19: each SDK runs in a process of its own).

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 earlier mutations of this ticket's path or file identity complete.

func (*MutationTicket) WaitContext

func (t *MutationTicket) WaitContext(ctx context.Context) error

WaitContext is Wait that gives up when ctx ends: it returns ctx's error and the ticket is the queue's from then on, so the caller must not Release it. A ticket that gave up keeps its place until every earlier mutation of the path has completed and only then passes it on; a successor never runs ahead of a predecessor that is still inside the queue. A ticket with no earlier mutation is admitted whatever ctx says.

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

Append adds a raw output chunk; once Finish has run it fails like upstream's append(), which throws. Append keeps no reference to data: the reader lends its read buffer for the call.

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 fail.

func (*OutputAccumulator) LastLineBytes

func (a *OutputAccumulator) LastLineBytes() int

LastLineBytes mirrors upstream getLastLineBytes.

pig divergence (D153): the size is that of the last line the output counts: the open line, or, when the output ends with a newline, the line that newline ended. Upstream returns the bytes after the final newline, so the notice for a long last line that ends in a newline reads "line is 0B" (Pi #10015).

func (*OutputAccumulator) ReadFullOutput

func (a *OutputAccumulator) ReadFullOutput(maxBytes int) (FullOutput, error)

ReadFullOutput mirrors upstream readFullOutput: the complete output, for callers that can take more than the display snapshot. Call it after Finish and CloseTempFile. Output longer than maxBytes raw bytes keeps its first and last maxBytes/2 bytes around an omission marker. Both halves are cut at character boundaries: the head drops an incomplete trailing sequence and the tail skips leading continuation bytes. A full-output file that cannot be opened or read returns that error, as upstream's promise rejects.

func (*OutputAccumulator) Snapshot

func (a *OutputAccumulator) Snapshot(persistIfTruncated bool) OutputSnapshot

Snapshot mirrors upstream snapshot({ persistIfTruncated }). It copies only the kept text, and a snapshot of output that has not changed since the last one returns that one.

type OutputSnapshot

type OutputSnapshot struct {
	Content        string
	Truncation     TruncationResult
	FullOutputPath string
}

OutputSnapshot mirrors upstream OutputSnapshot.

type PowerShellOperations

type PowerShellOperations = BashOperations

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). PowerShellOperations is upstream PowerShellOperations: the same extension point as BashOperations.

type PowerShellSpawnContext

type PowerShellSpawnContext = BashSpawnContext

PowerShellSpawnContext is upstream's PowerShellSpawnContext, an alias of BashSpawnContext (powershell.ts:24).

type PowerShellSpawnHook

type PowerShellSpawnHook = BashSpawnHook

PowerShellSpawnHook is upstream's PowerShellSpawnHook, an alias of BashSpawnHook (powershell.ts:25).

type PowerShellTool

type PowerShellTool struct {
	CWD string
	// Operations delegates command execution; nil selects [NewLocalPowerShellOperations]. Upstream
	// PowerShellToolOptions.operations.
	Operations PowerShellOperations
	// BinDir (<agentDir>/bin) is prepended to the command's PATH.
	BinDir string
	// HideSessionEnvironment turns off upstream's exposeSessionEnvironment.
	HideSessionEnvironment bool
	// SpawnHook adjusts the command, working directory or environment before execution (upstream spawnHook).
	SpawnHook PowerShellSpawnHook
}

func CreatePowerShellTool

func CreatePowerShellTool(cwd string, options *PowerShellToolOptions) *PowerShellTool

CreatePowerShellTool is upstream's createPowerShellTool (powershell.ts:59).

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

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

OutputSchema mirrors upstream bashOutputSchema: the structuredContent of a completed command.

func (*PowerShellTool) Schema

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

type PowerShellToolOptions

type PowerShellToolOptions struct {
	Operations BashOperations
	// BinDir is the managed tools directory (Pi's getBinDir()).
	BinDir                   string
	ExposeSessionEnvironment *bool
	SpawnHook                PowerShellSpawnHook
}

PowerShellToolOptions is upstream's PowerShellToolOptions: the operations, session-environment and spawn-hook options of BashToolOptions.

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 ReadOperations

type ReadOperations struct {
	// ReadFile reads the file contents.
	ReadFile func(absolutePath string) ([]byte, error)
	// Access fails when the file is not readable.
	Access func(absolutePath string) error
	// DetectImageMimeType returns the image MIME type, or "" for a non-image. A nil function treats every file as text.
	DetectImageMimeType func(absolutePath string) (string, error)
}

ReadOperations is upstream's ReadOperations: pluggable file reads, for example over SSH. Ports packages/coding-agent/src/core/tools/read.ts.

type ReadTool

type ReadTool struct {
	CWD              string
	AutoResizeImages *bool
	ResizeOptions    *ai.ModelImageResizeOptions
	// Operations delegates the file reads; nil selects the local filesystem (upstream options.operations).
	Operations *ReadOperations
}

ReadTool reads file contents.

func CreateReadTool

func CreateReadTool(cwd string, options *ReadToolOptions) *ReadTool

CreateReadTool is upstream's createReadTool (read.ts:222).

func (*ReadTool) ArgumentSchema

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

ArgumentSchema is the tool's parameters schema as the JSON text the argument validator reads (ai.ValidateToolArgumentsJSON), in the authored member order, which orders the validation errors as Pi's validator lists them. Schema remains the declaration for provider requests. Each tool's parameters are source constants (the bash and PowerShell variants differ only in guidelines), so the bytes are encoded once per tool.

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

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

OutputSchema is the schema of the result's structured content.

func (*ReadTool) Schema

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

type ReadToolOptions

type ReadToolOptions struct {
	// AutoResizeImages resizes images before they reach the model; nil is true.
	AutoResizeImages *bool
	// ResizeOptions is the fallback resize profile when the execution context has no model metadata.
	ResizeOptions *ai.ModelImageResizeOptions
	// Operations delegates file reads; nil is the local filesystem.
	Operations *ReadOperations
}

ReadToolOptions is upstream's ReadToolOptions (read.ts:63-70).

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: each executable is looked up on PATH, then PowerShell 7 in its ProgramFiles installation directory and Windows PowerShell in its SystemRoot one; on any other platform it reports that the tool is Windows-only.

func GetShellConfig

func GetShellConfig(customShellPath string) (ShellConfig, error)

GetShellConfig mirrors upstream getShellConfig(customShellPath) (utils/shell.ts): the shell binary and its leading arguments for a custom shell path, or the platform default when the path is empty. A custom path that does not exist is an error.

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

func (m *ToolsManager) BeginEnsureTool(tool string, onStatus func(ToolStatus)) (path string, download func(ctx context.Context, onStatus func(ToolStatus)) string)

BeginEnsureTool runs upstream ensureTool up to its first await on the caller: it resolves a present tool, reports why a missing one is not downloaded, or reports that its download starts. download is nil when ensureTool settles without awaiting; otherwise the caller must call it, and it finishes the download (or waits for this manager's download of the same tool) and reports the result through its onStatus.

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 ToolsOptions

type ToolsOptions struct {
	Read       *ReadToolOptions
	Bash       *BashToolOptions
	Powershell *PowerShellToolOptions
	Write      *WriteToolOptions
	Edit       *EditToolOptions
	Grep       *GrepToolOptions
	Find       *FindToolOptions
	Ls         *LsToolOptions
	// BinDir is <agentDir>/bin: grep and find resolve rg and fd there first, then on PATH, and download them when missing (upstream ensureTool); bash and powershell put it on PATH. Empty means PATH-only lookup and no downloads. It stands in for Pi's process-wide getBinDir().
	BinDir string
}

ToolsOptions is upstream's ToolsOptions (tools/index.ts:107-116).

func ToolsOptionsFromSettings

func ToolsOptionsFromSettings(settings BashSettingsView, agentBinDir string) *ToolsOptions

ToolsOptionsFromSettings builds the options a session passes for its settings: the command prefix, the live shell path and the image auto-resize flag. agentBinDir is ToolsOptions.BinDir.

type TruncateLineResult

type TruncateLineResult struct {
	Text         string
	WasTruncated bool
}

TruncateLineResult is upstream's `{ text: string; wasTruncated: boolean }`.

func TruncateLine

func TruncateLine(line string, maxChars int) TruncateLineResult

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.

type TruncationOptions

type TruncationOptions struct {
	// MaxLines defaults to DefaultMaxLines.
	MaxLines *int
	// MaxBytes defaults to DefaultMaxBytes.
	MaxBytes *int
}

TruncationOptions is upstream TruncationOptions (truncate.ts:40): the limits truncateHead and truncateTail apply. A nil limit takes its default, like an omitted upstream option; a limit of 0 is used as given.

type TruncationResult

type TruncationResult = tui.TruncationResult

TruncationResult is upstream TruncationResult (truncate.ts). Its definition lives in the tui package, which BashExecutionComponent.SetComplete takes, and this package imports tui.

func TruncateHead

func TruncateHead(content string, options TruncationOptions) 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, options TruncationOptions) TruncationResult

TruncateTail keeps the last lines/bytes of content. Used for bash output (errors and final results live at the end).

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 CreateWriteTool

func CreateWriteTool(cwd string, options *WriteToolOptions) *WriteTool

CreateWriteTool is upstream's createWriteTool (write.ts:95); its mutations serialise with every other edit and write tool's through the process queue.

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

func (t *WriteTool) RegistersInFileMutationQueue() bool

RegistersInFileMutationQueue implements agent.RegistersInFileMutationQueue: the parallel dispatcher registers this call in the queue after the extension tools before it in the batch started, as Pi runs their synchronous prefixes first.

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

type WriteToolOptions

type WriteToolOptions struct{ Operations *WriteOperations }

WriteToolOptions is upstream's WriteToolOptions.

Jump to

Keyboard shortcuts

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