tools

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 29 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

pi: src/core/tools/bash.ts — the coding-agent shell tool (shared by bash and powershell via createShellToolDefinition).

Segment deviations:

  • The render functions and BashResultRenderComponent depend on Theme/pi-tui and arrive with the theme batch.
  • signal wiring → context.Context; the abort-listener pattern collapses to ctx cancellation, and the aborted/timeout error protocol keeps the exact TS message strings ("aborted", "timeout:<seconds>") since the execute body branches on them.
  • resolveSpawnContext reads the session identity from the ToolExecuteContext slice (pi: ctx.sessionManager).

diff.go (pi: src/modes/interactive/components/diff.ts) — renderDiff: colored diff text with word-level intra-line change highlighting.

Declared deviation: pi keeps this file in modes/interactive/components, but its only consumer is core/tools' edit tool renderer and core/tools cannot import components (components → core/tools for tool-execution's builtin-definition fallback would cycle). Consumed from core/tools by edit.go; pi's components/index.ts re-export has no Go counterpart.

Package tools corresponds to pi's packages/coding-agent/src/core/tools — the coding-agent built-in tools (read/bash/powershell/edit/write/grep/ find/ls), their shared path/mutation/diff helpers, the external search binary manager, and the tool factory surface.

File mapping: bash.ts → bash.go, edit.ts → edit.go, edit-diff.ts → edit_diff.go (shared algorithm imported from agent/harness/tools), file- mutation-queue.ts → file_mutation_queue.go, find.ts → find.go, grep.ts → grep.go, index.ts → index.go, ls.ts → ls.go, output-accumulator.ts → output_accumulator.go, path-utils.ts → path_utils.go, powershell.ts → powershell.go, read.ts → read.go, render-utils.ts → (pure text helpers in shared.go; TUI-dependent helpers arrive with the theme batch), tool-definition-wrapper.ts → tool_context.go's wrapToolDefinition, truncate.ts → (byte-identical duplicate of the agent package's utils/truncate.ts; pig imports agent/harness/utils).

Batch scope and placeholders are declared in tool_context.go.

pi: src/core/tools/edit.ts — the coding-agent edit tool.

Segment deviations:

  • The render functions live in renderers_edit.go (S5a: pi moved them to core/tools/renderers/edit.ts; pig keeps package tools, see the file header there).
  • signal wiring → context.Context (the throwIfAborted probes observe the same aborts while keeping the mutation queue locked, per the TS comment).
  • editAccessError formats node errno codes; pig surfaces the os error's wrapped errno.

pi: src/core/tools/edit-diff.ts — the diff algorithm functions are byte-identical to the agent package's copy (verified by diff); pig imports agent/harness/tools and adds only the coding-agent preview helpers.

Not yet ported: nothing — computeEditsDiff/computeEditDiff are the TUI-preview helpers and are ported here (they have no theme dependency).

pi: src/core/tools/bash.ts reads `child.signalCode` (Node) to map signal-killed shells to 128 + signal number (pi v0.86.0, #9577). The Go equivalent reads the WaitStatus; the signal half is Unix-only, so the extraction is split by build tag (see exit_code_windows.go).

pi: src/core/tools/file-mutation-queue.ts — coding-agent mutation serialization (global map keyed by absolute path, unlike the agent package's per-env WeakMap; pig mirrors the difference).

Segment deviations:

  • pi chains promises per absolute path; pig uses per-key "token" channels closed to release the next waiter, with the registration serialized under a package mutex (pi: registrationQueue chain).
  • isMissingPathError checks ENOENT/ENOTDIR from node errors; pig checks the os error against syscall.ENOENT/ENOTDIR.

pi: src/core/tools/find.ts — the find tool (streaming fd with glob patterns, gitignore-aware behavior, and result limits).

Segment deviations:

  • The render functions live in renderers_*.go (S5a: pi moved them to core/tools/renderers/; pig keeps package tools, see the file header there).
  • node child_process + readline streaming → the shared codingagent/utils spawn helpers with a bufio scanner.
  • signal wiring → context.Context (abort kills the child and rejects with "Operation aborted").
  • The windows full-path separator rewrite ([/\\]) applies only on runtime.GOOS == "windows" (pi: process.platform).

pi: src/core/tools/grep.ts — the grep tool (streaming ripgrep with JSON events, match limits, context blocks, and byte truncation).

Segment deviations:

  • The render functions live in renderers_*.go (S5a: pi moved them to core/tools/renderers/; pig keeps package tools, see the file header there).
  • node child_process + readline streaming → the shared codingagent/utils spawn helpers; the JSON event lines are read with a bufio scanner on the child's stdout pipe.
  • signal wiring → context.Context (abort kills the child and rejects with "Operation aborted").
  • ensureTool's onStatus progress is silent in execute (pi passes no onStatus here either).

pi: src/core/tools/index.ts — the tool factory surface.

Segment deviations:

  • ToolName/allToolNames stay as the same literal union/Set; pig uses a named string type plus a map-based Set.
  • ToolDefinition (ToolDef) arrives with the extensions batch; the create*ToolDefinition functions are exported (they return the non-UI ToolDefinition struct, see tool_context.go).
  • The throw on unknown tool names → error return.

keybinding_hints.go (pi: components/keybinding-hints.ts) — utilities for formatting keybinding hints in the UI.

Declared deviation: pi keeps this file in modes/interactive/components, but pig's core/tools renderers (write/read) need KeyHint/KeyText and core/tools cannot import components (components → core/tools for tool-execution's builtin-definition fallback would cycle). The components message components consume these helpers via the tools import.

pi: src/core/tools/ls.ts — the ls tool (directory listing with entry limits and byte truncation).

Segment deviations:

  • The render functions live in renderers_*.go (S5a: pi moved them to core/tools/renderers/; pig keeps package tools, see the file header there).
  • signal wiring → context.Context (abort-listener pattern collapses to ctx probes; the entries loop is synchronous so there is nothing to interrupt mid-flight).
  • pi sorts with localeCompare (lowercased); pig sorts with strings.ToLower + < byte comparison (ASCII filenames sort identically, declared per the truncation-module convention).

pi: src/core/tools/output-accumulator.ts — incremental streaming-output tracking with bounded memory.

Segment deviations:

  • TextDecoder streaming decode → a utf8Decoder helper that buffers incomplete trailing sequences across append() calls (node's TextDecoder({stream:true}) semantics).
  • The WriteStream temp file → os.File appends; closeTempFile's promise collapses to Close.

pi: src/core/tools/path-utils.ts — coding-agent path resolution (built on utils/paths.ts; the agent package has its own env-based copy and pig mirrors the duplication).

pi: src/core/tools/powershell.ts — the PowerShell variant of the shell tool.

pi: src/core/tools/read.ts — the coding-agent read tool.

Segment deviations:

  • The render functions live in renderers_read.go (S5a: pi moved them to core/tools/renderers/read.ts; pig keeps package tools, see the file header there).
  • execute's ExtensionContext → ToolExecuteContext (see tool_context.go).
  • processImage → codingagent/utils (photon-backed resize takes pi's photon-unavailable path until Phase 8).
  • signal wiring → context.Context; the pre-abort check collapses to a ctx.Err() probe, and the abort-listener pattern collapses to ctx cancellation.

render_utils.go (pi: src/core/tools/render-utils.ts) — shared helpers for the built-in tools' renderCall/renderResult implementations.

renderers_bash.go (pi: src/core/tools/renderers/bash.ts) — presentation for the shell tools.

S5a note: pi moved the renderers out of bash.ts into core/tools/renderers/ so a process that only displays tool output does not load the execution path. pig keeps them in package tools (files named renderers_*.go) because the renderers depend on package-tools values (render-utils, edit-diff, keybinding hints, detail types) while the tool files spread them back into their definitions — a Go subpackage would be an import cycle. Grep mapping: pi renderers/bash.ts ↔ renderers_bash.go.

Renderers live apart from the implementation; bash.ts spreads these into the shell tool definition, so the tool's public shape is unchanged.

renderers_edit.go (pi: src/core/tools/renderers/edit.ts) — presentation for the edit tool.

S5a note: pi hosts the renderers in core/tools/renderers/; pig keeps them in package tools (files named renderers_*.go) because the renderers depend on package-tools values (render-utils, edit-diff, detail types) while the tool files spread them back into their definitions — a Go subpackage would be an import cycle. Grep mapping: pi renderers/edit.ts ↔ renderers_edit.go.

renderers_find.go (pi: src/core/tools/renderers/find.ts) — presentation for the find tool.

S5a note: pi hosts the renderers in core/tools/renderers/; pig keeps them in package tools (files named renderers_*.go) because the renderers depend on package-tools values (render-utils, detail types) while the tool files spread them back into their definitions — a Go subpackage would be an import cycle. Grep mapping: pi renderers/find.ts ↔ renderers_find.go.

renderers_grep.go (pi: src/core/tools/renderers/grep.ts) — presentation for the grep tool.

S5a note: pi hosts the renderers in core/tools/renderers/; pig keeps them in package tools (files named renderers_*.go) because the renderers depend on package-tools values (render-utils, detail types) while the tool files spread them back into their definitions — a Go subpackage would be an import cycle. Grep mapping: pi renderers/grep.ts ↔ renderers_grep.go.

renderers_index.go (pi: src/core/tools/renderers/index.ts) — built-in tool renderers, without the tools themselves.

S5a note: pi hosts the renderers in core/tools/renderers/ so a process that only displays tool output can import them without the execution graph. pig keeps them in package tools (renderers_*.go files) because the renderers consume package-tools values (render-utils, edit-diff, keybinding hints, detail types) while the tool files spread them back into their definitions — a Go subpackage would be an import cycle.

renderers_ls.go (pi: src/core/tools/renderers/ls.ts) — presentation for the ls tool.

S5a note: pi hosts the renderers in core/tools/renderers/; pig keeps them in package tools (files named renderers_*.go) because the renderers depend on package-tools values (render-utils, detail types) while the tool files spread them back into their definitions — a Go subpackage would be an import cycle. Grep mapping: pi renderers/ls.ts ↔ renderers_ls.go.

renderers_read.go (pi: src/core/tools/renderers/read.ts) — presentation for the read tool.

S5a note: pi hosts the renderers in core/tools/renderers/; pig keeps them in package tools (files named renderers_*.go) because the renderers depend on package-tools values (render-utils, detail types) while the tool files spread them back into their definitions — a Go subpackage would be an import cycle. Grep mapping: pi renderers/read.ts ↔ renderers_read.go.

renderers_write.go (pi: src/core/tools/renderers/write.ts) — presentation for the write tool.

S5a note: pi hosts the renderers in core/tools/renderers/; pig keeps them in package tools (files named renderers_*.go) because the renderers depend on package-tools values (render-utils, theme adapters, detail types) while the tool files spread them back into their definitions — a Go subpackage would be an import cycle. Grep mapping: pi renderers/write.ts ↔ renderers_write.go.

Shared helpers for the coding-agent tools (pi: inline helpers in each tool file; the JSON param decode replaces Static<TParameters>' compile-time typing).

Package tools corresponds to pi's packages/coding-agent/src/core/tools — the coding-agent built-in tools and their ToolDefinition layer.

Batch scope (Phase 4, core/tools):

  • The runtime layer is complete: Operations interfaces, execute logic, and the createXTool AgentTool constructors.
  • truncate.ts: pi ships a duplicate of the agent package's utils/truncate.ts in core/tools (verified byte-identical logic); pig imports agent/harness/utils instead of porting a second copy.
  • edit-diff.ts: identical to the harness copy for the shared algorithm; pig imports agent/harness/tools and adds only the coding-agent preview wrappers (computeEditsDiff/computeEditDiff) here.

Not yet ported (arrive with their consumers, placeholders left at their source positions):

  • createXToolDefinition's render members (renderCall/renderResult/ renderShell) and render-utils' Theme/pi-tui-dependent helpers: the TUI types arrive with Phase 6. The ToolDefinition struct here carries the non-UI surface only; UI members are placed at their pi source positions when the theme batch lands.
  • constrainedSampling: pi wires getExperimentalToolSampling() (core/ experimental.ts + config experimental flags) into every definition; it arrives with the settings/config batch as nil (undefined) until then.
  • getReadmePath-based compact read classification (read.ts) is render- layer only and follows the theme batch.

pi: src/core/tools/tool-definition-wrapper.ts — synthesize a minimal ToolDefinition from an AgentTool.

wrapToolDefinition/wrapToolDefinitions already live in tool_context.go (consolidated with the tools batch); only the AgentTool→ToolDefinition synthesis is ported here.

visual_truncate.go (pi: components/visual-truncate.ts) — shared utility for truncating text to visual lines (accounting for line wrapping). Used by tool-execution and bash-execution for consistent behavior.

Declared deviation: pi keeps this file in modes/interactive/components, but pig's bash tool renderer needs it and core/tools cannot import components (components → core/tools for tool-execution would cycle); moved here, components/bash-execution consumes it via the tools import.

pi: src/core/tools/write.ts — the coding-agent write tool.

Segment deviations:

  • The render functions live in renderers_write.go (S5a: pi moved them to core/tools/renderers/write.ts; pig keeps package tools, see the file header there).
  • signal wiring → context.Context (throwIfAborted probes).
  • content.length (UTF-16 code units) → len(content) bytes.

Index

Constants

This section is empty.

Variables

View Source
var BashToolSystemPromptContribution = struct {
	Snippet    string
	Guidelines []string
}{
	Snippet:    "Execute bash commands (ls, grep, find, etc.)",
	Guidelines: []string{"You can inspect PI_* environment variables for current model and session details."},
}

BashToolSystemPromptContribution is the bash tool's system prompt metadata (pi: bashToolSystemPromptContribution).

View Source
var EditRenderers = ToolRenderers{
	NewRenderState: func() any { return &EditRenderState{} },
	RenderCall:     editRenderCall,
	RenderResult:   editRenderResult,
}

EditRenderers is the edit renderer pair (pi: editRenderers; edit.ts spreads it into its definition).

View Source
var EditToolSystemPromptContribution = struct {
	Snippet    string
	Guidelines []string
}{
	Snippet: "Make precise file edits with exact text replacement, including multiple disjoint edits in one call",
	Guidelines: []string{
		"Use edit for precise changes (edits[].oldText must match exactly)",
		"When changing multiple separate locations in one file, use one edit call with multiple entries in edits[] instead of multiple edit calls",
		"Each edits[].oldText is matched against the original file, not after earlier edits are applied. Do not emit overlapping or nested edits. Merge nearby changes into one edit.",
		"Keep edits[].oldText as small as possible while still being unique in the file. Do not pad with large unchanged regions.",
	},
}

EditToolSystemPromptContribution is the edit tool's system prompt metadata (pi: editToolSystemPromptContribution).

View Source
var FindRenderers = ToolRenderers{
	RenderCall:   findRenderCall,
	RenderResult: findRenderResult,
}

FindRenderers is the find renderer pair (pi: findRenderers; find.ts spreads it into its definition).

View Source
var FindToolSystemPromptContribution = struct {
	Snippet    string
	Guidelines []string
}{
	Snippet:    "Find files by glob pattern (respects .gitignore)",
	Guidelines: nil,
}

FindToolSystemPromptContribution is the find tool's system prompt metadata (pi: findToolSystemPromptContribution).

View Source
var GrepRenderers = ToolRenderers{
	RenderCall:   grepRenderCall,
	RenderResult: grepRenderResult,
}

GrepRenderers is the grep renderer pair (pi: grepRenderers; grep.ts spreads it into its definition).

View Source
var GrepToolSystemPromptContribution = struct {
	Snippet    string
	Guidelines []string
}{
	Snippet:    "Search file contents for patterns (respects .gitignore)",
	Guidelines: nil,
}

GrepToolSystemPromptContribution is the grep tool's system prompt metadata (pi: grepToolSystemPromptContribution).

View Source
var LsRenderers = ToolRenderers{
	RenderCall:   lsRenderCall,
	RenderResult: lsRenderResult,
}

LsRenderers is the ls renderer pair (pi: lsRenderers; ls.ts spreads it into its definition).

View Source
var LsToolSystemPromptContribution = struct {
	Snippet    string
	Guidelines []string
}{
	Snippet:    "List directory contents",
	Guidelines: nil,
}

LsToolSystemPromptContribution is the ls tool's system prompt metadata (pi: lsToolSystemPromptContribution).

View Source
var PowerShellToolSystemPromptContribution = struct {
	Snippet    string
	Guidelines []string
}{
	Snippet:    "Execute PowerShell commands",
	Guidelines: []string{"You can inspect PI_* environment variables for current model and session details."},
}

PowerShellToolSystemPromptContribution is the PowerShell tool's system prompt metadata (pi: powershellToolSystemPromptContribution).

View Source
var ReadRenderers = ToolRenderers{
	RenderCall:   readRenderCall,
	RenderResult: readRenderResult,
}

ReadRenderers is the read renderer pair (pi: readRenderers; read.ts spreads it into its definition).

View Source
var ReadToolSystemPromptContribution = struct {
	Snippet    string
	Guidelines []string
}{
	Snippet:    "Read file contents",
	Guidelines: []string{"Use read to examine files instead of cat or sed."},
}

ReadToolSystemPromptContribution is the read tool's system prompt metadata (pi: readToolSystemPromptContribution).

View Source
var WriteRenderers = ToolRenderers{
	RenderCall:   writeRenderCall,
	RenderResult: writeRenderResult,
}

WriteRenderers is the write renderer pair (pi: writeRenderers; write.ts spreads it into its definition).

View Source
var WriteToolSystemPromptContribution = struct {
	Snippet    string
	Guidelines []string
}{
	Snippet:    "Create or overwrite files",
	Guidelines: []string{"Use write only for new files or complete rewrites."},
}

WriteToolSystemPromptContribution is the write tool's system prompt metadata (pi: writeToolSystemPromptContribution).

Functions

func ApplyEditsToNormalizedContent

func ApplyEditsToNormalizedContent(normalizedContent string, edits []Edit, path string) (harnessTools.AppliedEditsResult, error)

ApplyEditsToNormalizedContent applies exact-text replacements to LF-normalized content (pi: applyEditsToNormalizedContent).

func ComputeEditDiff

func ComputeEditDiff(ctx context.Context, path string, oldText string, newText string, cwd string) (EditDiffResult, EditDiffError)

ComputeEditDiff computes the diff for a single edit operation without applying it (pi: computeEditDiff; convenience wrapper for single-edit callers).

func ComputeEditsDiff

func ComputeEditsDiff(ctx context.Context, path string, edits []Edit, cwd string) (EditDiffResult, EditDiffError)

ComputeEditsDiff computes the diff for one or more edit operations without applying them (pi: computeEditsDiff; used for preview rendering in the TUI before the tool executes). The OK member discriminates the union result.

func CreateAllToolDefinitions

func CreateAllToolDefinitions(cwd string, options *ToolsOptions) map[ToolName]*ToolDefinition

CreateAllToolDefinitions builds every definition keyed by name (pi: createAllToolDefinitions).

func CreateAllTools

func CreateAllTools(cwd string, options *ToolsOptions) map[ToolName]Tool

CreateAllTools builds every tool keyed by name (pi: createAllTools).

func DetectLineEnding

func DetectLineEnding(content string) string

DetectLineEnding reports the content's line ending (pi: detectLineEnding).

func ExpandPath

func ExpandPath(filePath string) string

ExpandPath normalizes a user path input with unicode-space folding and @-prefix stripping (pi: expandPath).

func FormatKeyText

func FormatKeyText(key string, options KeyTextFormatOptions) string

FormatKeyText formats a slash-joined key list with plus-joined modifiers (pi: formatKeyText).

func FormatToolCallWithArgs added in v1.0.0

func FormatToolCallWithArgs(title string, args any, theme UITheme, expanded bool) string

FormatToolCallWithArgs renders the generic tool call header: the title followed by the arguments. Collapsed, they are `key=value` pairs on the title line, cut to collapsedArgsChars. Expanded, each is a `key: value` line below the title, with strings shown raw and continuation lines indented (pi: formatToolCallWithArgs).

func GenerateUnifiedPatch

func GenerateUnifiedPatch(path string, oldContent string, newContent string) string

GenerateUnifiedPatch renders a unified patch (pi: generateUnifiedPatch).

func GetTextOutput

func GetTextOutput(result *ToolRenderResult, showImages bool) string

GetTextOutput joins the text blocks of a result, appending image indicators when images are hidden or unsupported (pi: getTextOutput).

func InvalidArgText

func InvalidArgText(theme UITheme) string

InvalidArgText renders the "[invalid arg]" marker (pi: invalidArgText).

func IsAllToolName

func IsAllToolName(name ToolName) bool

IsAllToolName reports membership in pi's allToolNames set.

func KeyDisplayText

func KeyDisplayText(keybinding tui.Keybinding) string

KeyDisplayText renders capitalized key text (pi: keyDisplayText).

func KeyHint

func KeyHint(keybinding tui.Keybinding, description string) string

KeyHint renders "keys description" with dim keys and muted description (pi: keyHint).

func KeyText

func KeyText(keybinding tui.Keybinding) string

KeyText renders the keys bound to a keybinding (pi: keyText).

func LinkPath

func LinkPath(styledText string, rawPath string, cwd string) string

LinkPath wraps the styled path in an OSC 8 hyperlink to the absolute path when the terminal supports hyperlinks (pi: linkPath).

func NormalizeDisplayText

func NormalizeDisplayText(text string) string

NormalizeDisplayText strips carriage returns (pi: normalizeDisplayText).

func NormalizeToLF

func NormalizeToLF(text string) string

NormalizeToLF converts CRLF/CR to LF (pi: normalizeToLF).

func PathExists

func PathExists(filePath string) bool

PathExists reports whether the path is accessible (pi: pathExists).

func RawKeyHint

func RawKeyHint(key string, description string) string

RawKeyHint renders a hint for a raw key string (pi: rawKeyHint).

func RelativizeFindResultPath

func RelativizeFindResultPath(resultPath string, searchPath string) string

RelativizeFindResultPath relativizes a find result against the search root and normalizes it to posix separators (pi: relativizeFindResultPath).

func RenderDiff

func RenderDiff(theme UITheme, diffText string, options RenderDiffOptions) string

RenderDiff renders a diff string with colored lines and intra-line change highlighting (pi: renderDiff):

  • context lines: toolDiffContext
  • removed lines: toolDiffRemoved, with inverse on changed tokens
  • added lines: toolDiffAdded, with inverse on changed tokens

func RenderToolPath

func RenderToolPath(rawPath *string, theme UITheme, cwd string, emptyFallback string) string

RenderToolPath renders a tool path argument with hyperlink, shortening, and the invalid/empty fallbacks (pi: renderToolPath).

func ReplaceTabs

func ReplaceTabs(text string) string

ReplaceTabs replaces tabs with three spaces for consistent rendering (pi: replaceTabs).

func ResolveReadPath

func ResolveReadPath(filePath string, cwd string) string

ResolveReadPath resolves a read path, probing macOS filename variants synchronously (pi: resolveReadPath).

func ResolveReadPathAsync

func ResolveReadPathAsync(ctx context.Context, filePath string, cwd string) string

ResolveReadPathAsync resolves a read path, probing macOS filename variants (pi: resolveReadPathAsync).

func ResolveToCwd

func ResolveToCwd(filePath string, cwd string) string

ResolveToCwd resolves a path relative to the given cwd, handling ~ expansion and absolute paths (pi: resolveToCwd).

func RestoreLineEndings

func RestoreLineEndings(text string, ending string) string

RestoreLineEndings converts LF back to the original ending (pi: restoreLineEndings).

func ShortenPath

func ShortenPath(path string) string

ShortenPath replaces the home directory prefix with "~" (pi: shortenPath). Non-string input → "" (pi: typeof check; pig's callers pass strings, the empty fallback covers the invalid-arg path).

func Str

func Str(value any) (string, bool)

Str is pi's str(): the string value of an argument, "" for null/undefined, and null (ok=false) for non-string values.

func WithFileMutationQueue

func WithFileMutationQueue[T any](ctx context.Context, absolutePath string, fn func() (T, error)) (T, error)

WithFileMutationQueue serializes file mutations targeting the same absolute path (pi: withFileMutationQueue). If the canonicalization fails with a missing-path error the raw absolute path is used (pi: the ENOENT/ ENOTDIR fallback); other failures propagate.

Types

type BashExecOptions

type BashExecOptions struct {
	// OnData receives raw output chunks from stdout and stderr (pi: onData
	// Buffer).
	OnData func(data []byte)
	// Timeout is the command timeout in seconds; nil = none (pi: timeout).
	Timeout *float64
	// Env is the child environment (pi: env NodeJS.ProcessEnv).
	Env []string
}

BashExecOptions carry the per-execution options of BashOperations.exec (pi: the options argument).

type BashLocalOptions

type BashLocalOptions struct {
	// ShellPath is an optional explicit shell path.
	ShellPath string
}

BashLocalOptions parameterize CreateLocalBashOperations (pi: the options argument).

type BashOperations

type BashOperations struct {
	// Exec executes a command and streams output (pi: exec). exitCode is
	// nil-ptr when the process was killed by a signal (pi: null).
	Exec func(ctx context.Context, command string, cwd string, options *BashExecOptions) (exitCode *int, err error)
}

BashOperations are pluggable operations for the shell tool; override these to delegate command execution to remote systems (pi: BashOperations).

func CreateLocalBashOperations

func CreateLocalBashOperations(cwd string, options *BashLocalOptions) BashOperations

CreateLocalBashOperations builds bash operations using pi's built-in local shell execution backend (pi: createLocalBashOperations).

func CreateLocalShellOperations

func CreateLocalShellOperations(shellName string, cwd string, resolveShellConfig func() (codingagentutils.ShellConfig, error)) BashOperations

CreateLocalShellOperations builds the shared process execution used by the built-in shell tools (pi: createLocalShellOperations; the shell cwd is captured for relative shell-path resolution).

type BashRenderState

type BashRenderState struct {
	StartedAt int64
	EndedAt   int64
	Interval  *time.Ticker
}

BashRenderState is the call-row renderer state (pi: BashRenderState; timestamps are ms, 0 = undefined; interval is the 1s elapsed ticker pi creates with setInterval).

type BashResultRenderComponent

type BashResultRenderComponent struct {
	tui.Container
	// contains filtered or unexported fields
}

BashResultRenderComponent is the result render component (pi: class BashResultRenderComponent extends Container).

type BashResultRenderState

type BashResultRenderState struct {
	CachedWidth int
	CachedLines []string
	// Cached is true once CachedLines holds a render for CachedWidth (pi:
	// undefined checks).
	Cached bool
}

BashResultRenderState is the result-row cache state (pi: BashResultRenderState).

type BashSpawnContext

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

BashSpawnContext is the resolved spawn description (pi: BashSpawnContext).

type BashSpawnHook

type BashSpawnHook func(context BashSpawnContext) BashSpawnContext

BashSpawnHook adjusts command, cwd, or env before execution (pi: BashSpawnHook).

type BashToolDetails

type BashToolDetails struct {
	Truncation     *harnessutils.TruncationResult `json:"truncation,omitempty"`
	FullOutputPath string                         `json:"fullOutputPath,omitempty"`
}

BashToolDetails carries the truncation state and spill path (pi: BashToolDetails).

type BashToolInput

type BashToolInput struct {
	Command string   `json:"command"`
	Timeout *float64 `json:"timeout,omitempty"`
}

BashToolInput is the shell tool's parameter shape (pi: BashToolInput).

type BashToolOptions

type BashToolOptions struct {
	// Operations customizes command execution. Default: local shell.
	Operations *BashOperations
	// CommandPrefix is prepended to every command (for example shell setup
	// commands).
	CommandPrefix string
	// ShellPath is an optional explicit shell path from settings.
	ShellPath string
	// ExposeSessionEnvironment exposes current Pi session metadata as PI_*
	// environment variables. Default: true.
	ExposeSessionEnvironment *bool
	// SpawnHook adjusts command, cwd, or env before execution.
	SpawnHook BashSpawnHook
}

BashToolOptions parameterize the shell tools (pi: BashToolOptions).

type Edit

type Edit = harnessTools.Edit

Edit is one exact-text replacement (pi: Edit; alias to the harness port).

type EditCallRenderComponent

type EditCallRenderComponent struct {
	*tui.Box
	// contains filtered or unexported fields
}

EditCallRenderComponent is the call component (pi: EditCallRenderComponent = Box & { preview?, previewArgsKey?, previewPending?, settledError? }). The preview fields are guarded: renderCall and the async preview goroutine touch them from different goroutines.

type EditDiffError

type EditDiffError struct {
	Error string
}

EditDiffError carries a preview failure (pi: EditDiffError).

type EditDiffResult

type EditDiffResult struct {
	Diff             string
	FirstChangedLine int
	// HasFirstChangedLine is false when pi's firstChangedLine is undefined.
	HasFirstChangedLine bool
}

EditDiffResult carries the display diff (pi: EditDiffResult).

type EditOperations

type EditOperations struct {
	// ReadFile reads file contents (pi: readFile; Buffer → []byte).
	ReadFile func(ctx context.Context, absolutePath string) ([]byte, error)
	// WriteFile writes content to a file.
	WriteFile func(ctx context.Context, absolutePath string, content string) error
	// Access checks the file is readable and writable (pi: access).
	Access func(ctx context.Context, absolutePath string) error
}

EditOperations are pluggable operations for the edit tool; override these to delegate file editing to remote systems (pi: EditOperations).

type EditPreview

type EditPreview struct {
	// Diff-result form (DiffString; ignored in error form).
	Diff             string
	FirstChangedLine *int
	// Error form (pi: "error" in preview).
	IsErrorForm bool
	Error       string
}

EditPreview is the preview union (pi: EditPreview = EditDiffResult | EditDiffError).

type EditRenderState

type EditRenderState struct {
	CallComponent *EditCallRenderComponent
}

EditRenderState is the renderer state (pi: EditRenderState).

type EditToolDetails

type EditToolDetails struct {
	// Diff is the display-oriented diff of the changes made.
	Diff string
	// Patch is the standard unified patch of the changes made.
	Patch string
	// FirstChangedLine is the line number of the first change in the new
	// file (for editor navigation); nil = pi's undefined.
	FirstChangedLine *int
}

EditToolDetails carries the diff artifacts (pi: EditToolDetails).

type EditToolInput

type EditToolInput struct {
	Path  string `json:"path"`
	Edits []Edit `json:"edits"`
}

EditToolInput is the edit tool's parameter shape (pi: EditToolInput).

type EditToolOptions

type EditToolOptions struct {
	// Operations customizes file editing. Default: local filesystem.
	Operations *EditOperations
}

EditToolOptions parameterize the edit tool (pi: EditToolOptions).

type FindGlobOptions

type FindGlobOptions struct {
	Ignore []string
	Limit  int
}

FindGlobOptions carries the glob invocation options (pi: the options argument of FindOperations.glob).

type FindOperations

type FindOperations struct {
	// Exists checks if path exists.
	Exists func(ctx context.Context, absolutePath string) (bool, error)
	// Glob finds files matching the glob pattern. Returns relative or
	// absolute paths.
	Glob func(ctx context.Context, pattern string, cwd string, options FindGlobOptions) ([]string, error)
}

FindOperations are pluggable operations for the find tool; override these to delegate file search to remote systems (pi: FindOperations).

type FindToolDetails

type FindToolDetails struct {
	Truncation         *harnessutils.TruncationResult `json:"truncation,omitempty"`
	ResultLimitReached *int                           `json:"resultLimitReached,omitempty"`
}

FindToolDetails carries the find outcome metadata (pi: FindToolDetails).

type FindToolInput

type FindToolInput struct {
	Pattern string   `json:"pattern"`
	Path    string   `json:"path,omitempty"`
	Limit   *float64 `json:"limit,omitempty"`
}

FindToolInput is the find tool's parameter shape (pi: FindToolInput).

type FindToolOptions

type FindToolOptions struct {
	// Operations customizes find. Default: local filesystem plus fd.
	Operations *FindOperations
}

FindToolOptions parameterize the find tool (pi: FindToolOptions).

type GrepOperations

type GrepOperations struct {
	// IsDirectory checks if path is a directory. Throws if the path does
	// not exist.
	IsDirectory func(ctx context.Context, absolutePath string) (bool, error)
	// ReadFile reads file contents for context lines.
	ReadFile func(ctx context.Context, absolutePath string) (string, error)
}

GrepOperations are pluggable operations for the grep tool; override these to delegate search to remote systems (pi: GrepOperations).

type GrepToolDetails

type GrepToolDetails struct {
	Truncation        *harnessutils.TruncationResult `json:"truncation,omitempty"`
	MatchLimitReached *int                           `json:"matchLimitReached,omitempty"`
	LinesTruncated    *bool                          `json:"linesTruncated,omitempty"`
}

GrepToolDetails carries the grep outcome metadata (pi: GrepToolDetails).

type GrepToolInput

type GrepToolInput struct {
	Pattern    string   `json:"pattern"`
	Path       string   `json:"path,omitempty"`
	Glob       string   `json:"glob,omitempty"`
	IgnoreCase *bool    `json:"ignoreCase,omitempty"`
	Literal    *bool    `json:"literal,omitempty"`
	Context    *float64 `json:"context,omitempty"`
	Limit      *float64 `json:"limit,omitempty"`
}

GrepToolInput is the grep tool's parameter shape (pi: GrepToolInput).

type GrepToolOptions

type GrepToolOptions struct {
	// Operations customizes grep. Default: local filesystem plus ripgrep.
	Operations *GrepOperations
}

GrepToolOptions parameterize the grep tool (pi: GrepToolOptions).

type KeyTextFormatOptions

type KeyTextFormatOptions struct {
	Capitalize bool
}

KeyTextFormatOptions mirrors pi's KeyTextFormatOptions.

type LsOperations

type LsOperations struct {
	// Exists checks if path exists.
	Exists func(ctx context.Context, absolutePath string) (bool, error)
	// Stat gets file or directory stats. Throws if not found.
	Stat func(ctx context.Context, absolutePath string) (os.FileInfo, error)
	// Readdir reads directory entries.
	Readdir func(ctx context.Context, absolutePath string) ([]string, error)
}

LsOperations are pluggable operations for the ls tool; override these to delegate directory listing to remote systems (pi: LsOperations).

type LsToolDetails

type LsToolDetails struct {
	Truncation        *harnessutils.TruncationResult `json:"truncation,omitempty"`
	EntryLimitReached *int                           `json:"entryLimitReached,omitempty"`
}

LsToolDetails carries the ls outcome metadata (pi: LsToolDetails).

type LsToolInput

type LsToolInput struct {
	Path  string   `json:"path,omitempty"`
	Limit *float64 `json:"limit,omitempty"`
}

LsToolInput is the ls tool's parameter shape (pi: LsToolInput).

type LsToolOptions

type LsToolOptions struct {
	// Operations customizes directory listing. Default: local filesystem.
	Operations *LsOperations
}

LsToolOptions parameterize the ls tool (pi: LsToolOptions).

type OutputAccumulator

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

OutputAccumulator incrementally tracks streaming output with bounded memory (pi: OutputAccumulator). pig addition: a mutex guards the accumulators — pi's data callbacks serialize on the event loop, while pig's exec reads both pipes on separate goroutines.

func NewOutputAccumulator

func NewOutputAccumulator(options *OutputAccumulatorOptions) *OutputAccumulator

NewOutputAccumulator builds the accumulator (pi: constructor).

func (*OutputAccumulator) Append

func (a *OutputAccumulator) Append(data []byte) error

Append decodes and ingests one raw output chunk (pi: append).

func (*OutputAccumulator) CloseTempFile

func (a *OutputAccumulator) CloseTempFile() error

CloseTempFile closes the spill file (pi: closeTempFile).

func (*OutputAccumulator) Finish

func (a *OutputAccumulator) Finish()

Finish flushes the streaming decoder and spills to the temp file when needed (pi: finish).

func (*OutputAccumulator) GetLastLineBytes

func (a *OutputAccumulator) GetLastLineBytes() int

GetLastLineBytes returns the byte length of the currently open line (pi: getLastLineBytes).

func (*OutputAccumulator) Snapshot

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

Snapshot builds the current display snapshot (pi: snapshot).

type OutputAccumulatorOptions

type OutputAccumulatorOptions struct {
	// MaxLines overrides the line limit; nil = DEFAULT_MAX_LINES.
	MaxLines *int
	// MaxBytes overrides the byte limit; nil = DEFAULT_MAX_BYTES.
	MaxBytes *int
	// TempFilePrefix names the spill file; "" = pi's "pi-output".
	TempFilePrefix string
}

OutputAccumulatorOptions parameterize the accumulator (pi: OutputAccumulatorOptions).

type OutputSnapshot

type OutputSnapshot struct {
	Content        string
	Truncation     utils.TruncationResult
	FullOutputPath string
}

OutputSnapshot is a display snapshot (pi: OutputSnapshot).

type PowerShellOperations

type PowerShellOperations = BashOperations

PowerShellOperations/SpawnContext/SpawnHook/Details/Input are aliases of the bash tool's types (pi: type aliases).

func CreateLocalPowerShellOperations

func CreateLocalPowerShellOperations() PowerShellOperations

CreateLocalPowerShellOperations builds PowerShell operations with the UTF-8 output prefix (pi: createLocalPowerShellOperations).

type PowerShellSpawnContext

type PowerShellSpawnContext = BashSpawnContext

PowerShellOperations/SpawnContext/SpawnHook/Details/Input are aliases of the bash tool's types (pi: type aliases).

type PowerShellSpawnHook

type PowerShellSpawnHook = BashSpawnHook

PowerShellOperations/SpawnContext/SpawnHook/Details/Input are aliases of the bash tool's types (pi: type aliases).

type PowerShellToolDetails

type PowerShellToolDetails = BashToolDetails

PowerShellOperations/SpawnContext/SpawnHook/Details/Input are aliases of the bash tool's types (pi: type aliases).

type PowerShellToolInput

type PowerShellToolInput = BashToolInput

PowerShellOperations/SpawnContext/SpawnHook/Details/Input are aliases of the bash tool's types (pi: type aliases).

type PowerShellToolOptions

type PowerShellToolOptions struct {
	// Operations customizes command execution. Default: local PowerShell.
	Operations *BashOperations
	// ExposeSessionEnvironment exposes current Pi session metadata as PI_*
	// environment variables. Default: true.
	ExposeSessionEnvironment *bool
	// SpawnHook adjusts command, cwd, or env before execution.
	SpawnHook BashSpawnHook
}

PowerShellToolOptions parameterize the PowerShell tool (pi: PowerShellToolOptions = Pick<BashToolOptions, ...>).

type ReadOperations

type ReadOperations struct {
	// ReadFile reads file contents (pi: readFile; Buffer → []byte).
	ReadFile func(ctx context.Context, absolutePath string) ([]byte, error)
	// Access checks the file is readable (pi: access; throws if not).
	Access func(ctx context.Context, absolutePath string) error
	// DetectImageMimeType detects the image MIME type; "" for non-images
	// (pi: detectImageMimeType; null/undefined → "").
	DetectImageMimeType func(ctx context.Context, absolutePath string) string
}

ReadOperations are pluggable operations for the read tool; override these to delegate file reading to remote systems (pi: ReadOperations).

type ReadToolDetails

type ReadToolDetails struct {
	Truncation *harnessutils.TruncationResult `json:"truncation,omitempty"`
}

ReadToolDetails carries the truncation outcome (pi: ReadToolDetails).

type ReadToolInput

type ReadToolInput struct {
	Path   string   `json:"path"`
	Offset *float64 `json:"offset,omitempty"`
	Limit  *float64 `json:"limit,omitempty"`
}

ReadToolInput is the read tool's parameter shape (pi: ReadToolInput).

type ReadToolOptions

type ReadToolOptions struct {
	// AutoResizeImages auto-resizes images to the inline provider limits.
	// Default: true.
	AutoResizeImages *bool
	// ResizeOptions is the fallback resize profile when the execution
	// context has no model metadata (pi: resizeOptions?). nil = unset.
	ResizeOptions *types.ModelImageResizeOptions
	// Operations customizes file reading. Default: local filesystem.
	Operations *ReadOperations
}

ReadToolOptions parameterize the read tool (pi: ReadToolOptions).

type RenderDiffOptions

type RenderDiffOptions struct {
	FilePath string
}

RenderDiffOptions carries the renderDiff options (pi: RenderDiffOptions; filePath is unused, kept for API compatibility).

type ShellToolConfig

type ShellToolConfig struct {
	Name             string
	Label            string
	ShellName        string
	Prompt           string
	PromptSnippet    string
	PromptGuidelines []string
	TempFilePrefix   string
}

ShellToolConfig names the shell tool variant (pi: ShellToolConfig).

type Tool

type Tool struct {
	agent.AgentTool
	PromptSnippet    string
	PromptGuidelines []string
	// ExecuteWithToolContext invokes the wrapped definition with the
	// ExtensionContext slice (pi: definition.execute's ctx parameter).
	ExecuteWithToolContext func(ctx context.Context, toolCallID string, params any, onUpdate agent.AgentToolUpdateCallback, toolCtx ToolExecuteContext) (agent.AgentToolResult, error)
}

Tool is pi's `type Tool = AgentTool<any>` plus the prompt metadata that createBashTool/createPowerShellTool assign onto the wrapper (pi: Object.assign(tool, { promptSnippet, promptGuidelines })) and the ExtensionContext-bearing execute of the wrapped definition (pi's wrapper resolves `ctx ?? (ctxFactory?.())`; the ctxFactory variant arrives with the extensions batch, so ExecuteWithToolContext lets callers pass the context explicitly and Execute passes nil, pi's undefined).

func CreateBashTool

func CreateBashTool(cwd string, options *BashToolOptions) Tool

CreateBashTool wraps the bash definition into an AgentTool (pi: createBashTool).

func CreateCodingTools

func CreateCodingTools(cwd string, options *ToolsOptions) []Tool

CreateCodingTools builds the edit-capable tools (pi: createCodingTools).

func CreateEditTool

func CreateEditTool(cwd string, options *EditToolOptions) Tool

CreateEditTool wraps the edit definition into an AgentTool (pi: createEditTool).

func CreateFindTool

func CreateFindTool(cwd string, options *FindToolOptions) Tool

CreateFindTool wraps the find definition into an AgentTool (pi: createFindTool).

func CreateGrepTool

func CreateGrepTool(cwd string, options *GrepToolOptions) Tool

CreateGrepTool wraps the grep definition into an AgentTool (pi: createGrepTool).

func CreateLsTool

func CreateLsTool(cwd string, options *LsToolOptions) Tool

CreateLsTool wraps the ls definition into an AgentTool (pi: createLsTool).

func CreatePowerShellTool

func CreatePowerShellTool(cwd string, options *PowerShellToolOptions) Tool

CreatePowerShellTool wraps the PowerShell definition into an AgentTool (pi: createPowerShellTool).

func CreateReadOnlyTools

func CreateReadOnlyTools(cwd string, options *ToolsOptions) []Tool

CreateReadOnlyTools builds the read-only tools (pi: createReadOnlyTools).

func CreateReadTool

func CreateReadTool(cwd string, options *ReadToolOptions) Tool

CreateReadTool wraps the read definition into an AgentTool (pi: createReadTool).

func CreateTool

func CreateTool(toolName ToolName, cwd string, options *ToolsOptions) (Tool, error)

CreateTool creates one tool by name (pi: createTool).

func CreateWriteTool

func CreateWriteTool(cwd string, options *WriteToolOptions) Tool

CreateWriteTool wraps the write definition into an AgentTool (pi: createWriteTool).

func WrapToolDefinition

func WrapToolDefinition(definition *ToolDefinition, ctxFactory func() ToolExecuteContext) Tool

wrapToolDefinition wraps a definition into an AgentTool for the core runtime (pi: tool-definition-wrapper.ts's wrapToolDefinition). The optional ctxFactory resolves pi's ExtensionContext for the plain execute path (pi: `ctx ?? (ctxFactory?.())`); the extensions batch passes a factory, the factory-free callers pass nil.

type ToolDefinition

type ToolDefinition struct {
	Name        string
	Label       string
	Description string
	// PromptSnippet feeds the Available tools system-prompt section (pi:
	// promptSnippet).
	PromptSnippet string
	// PromptGuidelines feed the system-prompt Guidelines section (pi:
	// promptGuidelines).
	PromptGuidelines []string
	// Parameters is the TypeBox schema (pi: parameters).
	Parameters json.RawMessage
	// ConstrainedSampling is pi's constrainedSampling (pi v0.86.0 hardcodes
	// the strict-mode request at bash/read/write/edit); nil = undefined.
	ConstrainedSampling any
	// ExecutionMode is the per-tool execution mode override (pi:
	// executionMode).
	ExecutionMode agent.ToolExecutionMode
	// PrepareArguments is the optional compatibility shim applied to raw
	// tool-call arguments before schema validation (pi: prepareArguments).
	PrepareArguments func(args any) any
	// Execute runs the tool (pi: execute). ctx carries cancellation (pi:
	// signal) and toolCtx is the ExtensionContext slice (pi: ctx).
	Execute func(ctx context.Context, toolCallID string, params any, onUpdate agent.AgentToolUpdateCallback, toolCtx ToolExecuteContext) (agent.AgentToolResult, error)
	// NewRenderState builds the shared per-tool-row renderer state (pig
	// addition, declared deviation: pi's ToolExecutionComponent initializes
	// state to a plain {} object that renderers mutate in place; Go needs a
	// concrete value. Built-in definitions return their state struct,
	// extension tools keep nil → tool-execution falls back to a
	// map[string]any, the closest analog of pi's {}).
	NewRenderState func() any
	// RenderShell controls whether ToolExecutionComponent renders the
	// standard colored shell or the tool renders its own framing (pi:
	// renderShell; "" = default, "self" = tool renders its own framing).
	RenderShell string
	// RenderCall renders the tool-call row (pi: renderCall); nil = fallback
	// rendering by the consumer.
	RenderCall func(args any, theme UITheme, context ToolRenderContext) tui.Component
	// RenderResult renders the tool result row (pi: renderResult); nil =
	// fallback rendering by the consumer.
	RenderResult func(result ToolRenderResult, options ToolRenderResultOptions, theme UITheme, context ToolRenderContext) tui.Component
}

ToolDefinition is pi's ToolDefinition (core/extensions/types.ts). TS renders tools definition-first and wraps via tool-definition-wrapper.ts; pig keeps the same split. Exported because AgentSession's definition-first registry (core package) stores it (pi: the registry lives next to the ToolDefinition type).

func CreateBashToolDefinition

func CreateBashToolDefinition(cwd string, options *BashToolOptions) *ToolDefinition

CreateBashToolDefinition builds the bash definition (pi: createBashToolDefinition).

func CreateCodingToolDefinitions

func CreateCodingToolDefinitions(cwd string, options *ToolsOptions) []*ToolDefinition

CreateCodingToolDefinitions builds the edit-capable definitions (pi: createCodingToolDefinitions).

func CreateEditToolDefinition

func CreateEditToolDefinition(cwd string, options *EditToolOptions) *ToolDefinition

CreateEditToolDefinition builds the edit tool definition (pi: createEditToolDefinition; renderCall/renderResult arrive with the theme batch).

func CreateFindToolDefinition

func CreateFindToolDefinition(cwd string, options *FindToolOptions) *ToolDefinition

CreateFindToolDefinition builds the find tool definition (pi: createFindToolDefinition; renderCall/renderResult arrive with the theme batch).

func CreateGrepToolDefinition

func CreateGrepToolDefinition(cwd string, options *GrepToolOptions) *ToolDefinition

CreateGrepToolDefinition builds the grep tool definition (pi: createGrepToolDefinition; renderCall/renderResult arrive with the theme batch).

func CreateLsToolDefinition

func CreateLsToolDefinition(cwd string, options *LsToolOptions) *ToolDefinition

CreateLsToolDefinition builds the ls tool definition (pi: createLsToolDefinition; renderCall/renderResult arrive with the theme batch).

func CreatePowerShellToolDefinition

func CreatePowerShellToolDefinition(cwd string, options *PowerShellToolOptions) *ToolDefinition

CreatePowerShellToolDefinition builds the PowerShell definition (pi: createPowerShellToolDefinition).

func CreateReadOnlyToolDefinitions

func CreateReadOnlyToolDefinitions(cwd string, options *ToolsOptions) []*ToolDefinition

CreateReadOnlyToolDefinitions builds the read-only definitions (pi: createReadOnlyToolDefinitions).

func CreateReadToolDefinition

func CreateReadToolDefinition(cwd string, options *ReadToolOptions) *ToolDefinition

CreateReadToolDefinition builds the read tool definition (pi: createReadToolDefinition).

func CreateShellToolDefinition

func CreateShellToolDefinition(cwd string, config ShellToolConfig, options *BashToolOptions) *ToolDefinition

CreateShellToolDefinition builds the shared shell tool definition (pi: createShellToolDefinition; the renderers come from renderers_bash.go — pi: `...createShellRenderers(config.prompt)`).

func CreateToolDefinition

func CreateToolDefinition(toolName ToolName, cwd string, options *ToolsOptions) (*ToolDefinition, error)

CreateToolDefinition creates one tool definition by name (pi: createToolDefinition).

func CreateToolDefinitionFromAgentTool

func CreateToolDefinitionFromAgentTool(tool agent.AgentTool) *ToolDefinition

CreateToolDefinitionFromAgentTool synthesizes a minimal ToolDefinition from an AgentTool (pi: createToolDefinitionFromAgentTool). This keeps AgentSession's internal registry definition-first even when a caller provides plain AgentTool overrides that do not include prompt metadata or renderers.

func CreateWriteToolDefinition

func CreateWriteToolDefinition(cwd string, options *WriteToolOptions) *ToolDefinition

CreateWriteToolDefinition builds the write tool definition (pi: createWriteToolDefinition; renderCall/renderResult arrive with the theme batch).

func WithBuiltInRenderers

func WithBuiltInRenderers(toolName string, definition *ToolDefinition) *ToolDefinition

WithBuiltInRenderers merges built-in renderers into a tool definition that does not supply its own (pi: withBuiltInRenderers). ToolExecutionComponent used to do this lookup itself, which forced every presentation to import the tool implementations. Callers do it now, so a process that renders can import renderers alone. A nil definition yields a render-only definition shell. Only renderCall/renderResult are merged (pi does not fill renderShell either).

type ToolExecuteContext

type ToolExecuteContext interface {
	// GetModel is pi's ctx.model.
	GetModel() *types.Model
	// GetSessionID is pi's ctx.sessionManager.getSessionId().
	GetSessionID() string
	// GetSessionFile is pi's ctx.sessionManager.getSessionFile(); nil when
	// the session is not file-backed.
	GetSessionFile() *string
	// GetThinkingLevel is pi's ctx.thinkingLevel; "" when unset.
	GetThinkingLevel() string
	// GetCwd is pi's ctx.cwd (v0.85.1: the tools resolve paths against it
	// when provided, falling back to the definition-captured cwd); "" =
	// undefined.
	GetCwd() string
}

ToolExecuteContext is the slice of pi's ExtensionContext (core/extensions/ types.ts) consumed by the built-in tools' execute() bodies: the current model (read's non-vision note, bash's PI_* env), the session identity, and the thinking level. The full extensions/types.ts surface arrives with the extensions batch; until then callers pass a value implementing this interface or nil (pi passes undefined outside the interactive session).

type ToolName

type ToolName string

ToolName is the closed tool-name vocabulary (pi: ToolName).

const (
	ToolRead       ToolName = "read"
	ToolBash       ToolName = "bash"
	ToolPowerShell ToolName = "powershell"
	ToolEdit       ToolName = "edit"
	ToolWrite      ToolName = "write"
	ToolGrep       ToolName = "grep"
	ToolFind       ToolName = "find"
	ToolLs         ToolName = "ls"
)

type ToolRenderContext

type ToolRenderContext struct {
	// Args are the current tool call arguments (pi: args).
	Args any
	// ToolCallID is the unique id for this tool execution, stable across
	// call/result renders (pi: toolCallId).
	ToolCallID string
	// Invalidate invalidates just this tool execution component for redraw
	// (pi: invalidate).
	Invalidate func()
	// LastComponent is the previously returned component for this render
	// slot, if any (pi: lastComponent).
	LastComponent tui.Component
	// State is shared renderer state for this tool row (pi: state).
	State any
	// Cwd is the working directory for this tool execution (pi: cwd).
	Cwd string
	// ExecutionStarted reports whether the tool execution has started (pi:
	// executionStarted).
	ExecutionStarted bool
	// ArgsComplete reports whether the tool call arguments are complete
	// (pi: argsComplete).
	ArgsComplete bool
	// IsPartial reports whether the tool result is partial/streaming (pi:
	// isPartial).
	IsPartial bool
	// Expanded reports whether the result view is expanded (pi: expanded).
	Expanded bool
	// ShowImages reports whether inline images are currently shown in the
	// TUI (pi: showImages).
	ShowImages bool
	// IsError reports whether the current result is an error (pi: isError).
	IsError bool
}

ToolRenderContext is the context passed to tool renderers (pi: ToolRenderContext<TState, TArgs>; generics collapse to any).

type ToolRenderResult

type ToolRenderResult = agent.AgentToolResult

ToolRenderResult is the result shape handed to renderResult (pi: ToolRenderResult<TDetails> = { content, details? }); pig passes the full AgentToolResult the tool produced (Details carries TDetails).

type ToolRenderResultLike

type ToolRenderResultLike = ToolRenderResult

ToolRenderResultLike is the result shape the render helpers accept (pi: ToolRenderResultLike<TDetails>); pig passes the full AgentToolResult.

type ToolRenderResultOptions

type ToolRenderResultOptions struct {
	// Expanded reports whether the result view is expanded (pi: expanded).
	Expanded bool
	// IsPartial reports whether this is a partial/streaming result (pi:
	// isPartial).
	IsPartial bool
}

ToolRenderResultOptions carries the tool result render options (pi: ToolRenderResultOptions).

type ToolRenderers

type ToolRenderers struct {
	// RenderShell controls whether ToolExecutionComponent renders the
	// standard colored shell or the tool renders its own framing (pi:
	// renderShell; "" = default, "self" = tool renders its own framing).
	RenderShell string
	// NewRenderState builds the shared per-tool-row renderer state (pig
	// addition, following the ToolDefinition field of the same name; pi
	// initializes state to a plain {} object that renderers mutate in
	// place, Go needs a concrete value). Only the renderers with typed
	// state (bash, edit) set it; nil falls back to a map[string]any.
	NewRenderState func() any
	// RenderCall renders the tool-call row (pi: renderCall); nil = fallback
	// rendering by the consumer.
	RenderCall func(args any, theme UITheme, context ToolRenderContext) tui.Component
	// RenderResult renders the tool result row (pi: renderResult); nil =
	// fallback rendering by the consumer.
	RenderResult func(result ToolRenderResult, options ToolRenderResultOptions, theme UITheme, context ToolRenderContext) tui.Component
}

ToolRenderers is what a presentation needs from a tool: how to draw it (pi: renderers/index.ts ToolRenderers = Pick<ToolDefinition, "renderCall" | "renderResult">, plus tool-execution.ts's ToolRenderers interface which adds renderShell; the two fold into one struct here). It neither executes tools nor reads their parameter schemas, so a definition and a bare renderer pair are equally acceptable.

func CreateShellRenderers

func CreateShellRenderers(prompt string) ToolRenderers

CreateShellRenderers builds the shell renderers; they are shared by bash and powershell, which differ only in the prompt they display (pi: createShellRenderers).

type ToolsOptions

type ToolsOptions struct {
	Read       *ReadToolOptions
	Bash       *BashToolOptions
	PowerShell *PowerShellToolOptions
	Write      *WriteToolOptions
	Edit       *EditToolOptions
	Grep       *GrepToolOptions
	Find       *FindToolOptions
	Ls         *LsToolOptions
}

ToolsOptions collects the per-tool options (pi: ToolsOptions).

type UITheme

type UITheme interface {
	// Fg wraps text in the token's foreground color (pi: theme.fg).
	Fg(color string, text string) string
	// Bg wraps text in the token's background color (pi: theme.bg).
	Bg(color string, text string) string
	// Bold mirrors chalk.bold.
	Bold(text string) string
	// Italic mirrors chalk.italic.
	Italic(text string) string
	// Underline mirrors chalk.underline.
	Underline(text string) string
	// Inverse mirrors chalk.inverse.
	Inverse(text string) string
	// Strikethrough mirrors chalk.strikethrough.
	Strikethrough(text string) string
	// GetFgAnsi returns the raw ANSI foreground prefix (pi: getFgAnsi).
	GetFgAnsi(color string) string
	// GetBgAnsi returns the raw ANSI background prefix (pi: getBgAnsi).
	GetBgAnsi(color string) string
}

UITheme is the theme surface available to UI renderers (pi passes the concrete Theme from modes/interactive/theme; *theme.Theme satisfies this structurally — its color token types are string aliases for exactly this reason). Declared deviation: defined here rather than in package core because core aliases it (core → core/tools is an existing edge, the reverse would cycle); package core re-exports it as core.UITheme.

type VisualTruncateKeep added in v1.0.0

type VisualTruncateKeep string

VisualTruncateKeep selects which visual lines survive truncation.

const (
	// VisualTruncateKeepEnd keeps the last visual lines (bash-style: the
	// newest output matters).
	VisualTruncateKeepEnd VisualTruncateKeep = "end"
	// VisualTruncateKeepStart keeps the first visual lines (MCP-style result
	// previews; pi VisualLinePreview keep:"start").
	VisualTruncateKeepStart VisualTruncateKeep = "start"
)

type VisualTruncateResult

type VisualTruncateResult struct {
	// VisualLines are the visual lines to display.
	VisualLines []string
	// SkippedCount is the number of visual lines that were skipped
	// (hidden).
	SkippedCount int
}

VisualTruncateResult is pi's VisualTruncateResult.

func TruncateToVisualLines

func TruncateToVisualLines(text string, maxVisualLines int, width int, paddingX int, keep VisualTruncateKeep) VisualTruncateResult

TruncateToVisualLines truncates text to a maximum number of visual lines, accounting for line wrapping at the given width (pi: truncateToVisualLines). keep selects whether the first or last lines survive. paddingX: use 0 when the result is placed in a Box (Box adds its own padding), 1 for a plain Container.

type WriteCallRenderComponent

type WriteCallRenderComponent struct {
	*tui.Text
	Cache *WriteHighlightCache
	// contains filtered or unexported fields
}

WriteCallRenderComponent is the call component (pi: class WriteCallRenderComponent extends Text).

type WriteHighlightCache

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

WriteHighlightCache carries the incremental syntax-highlight state (pi: WriteHighlightCache). rawPath nil = pi's null.

type WriteOperations

type WriteOperations struct {
	// WriteFile writes content to a file.
	WriteFile func(ctx context.Context, absolutePath string, content string) error
	// Mkdir creates a directory recursively.
	Mkdir func(ctx context.Context, dir string) error
}

WriteOperations are pluggable operations for the write tool; override these to delegate file writing to remote systems (pi: WriteOperations).

type WriteToolInput

type WriteToolInput struct {
	Path    string `json:"path"`
	Content string `json:"content"`
}

WriteToolInput is the write tool's parameter shape (pi: WriteToolInput).

type WriteToolOptions

type WriteToolOptions struct {
	// Operations customizes file writing. Default: local filesystem.
	Operations *WriteOperations
}

WriteToolOptions parameterize the write tool (pi: WriteToolOptions).

Jump to

Keyboard shortcuts

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