Documentation
¶
Overview ¶
Package utils corresponds to pi's packages/agent/src/harness/utils.
pi: src/harness/utils/shell-output.ts — shell execution with bounded tail capture and full-output spilling.
Deviations:
- TS serializes the async appendFile calls through a promise chain (writeChain); pig's FileSystem.AppendFile is synchronous, so the chain collapses to sequential inline writes with the same ordering and error-stop semantics (first write failure stops later ones and is surfaced after exec completes).
- TS strings are UTF-16; Go strings are UTF-8. sanitizeBinaryOutput iterates runes (pi iterates code points); trimToLastUtf8Bytes slices at a UTF-8 continuation boundary (pi re-decodes with replacement).
- pi's options.abortSignal and exec's abortSignal are carried by the leading context.Context; callback exceptions (TS try/catch) are recovered as callback_error ExecutionErrors.
pi: src/harness/utils/truncate.ts — shared truncation utilities for tool outputs.
Truncation is based on two independent limits - whichever is hit first wins:
- Line limit (default: 2000 lines)
- Byte limit (default: 50KB)
Never returns partial lines (except bash tail truncation edge case).
Deviations:
- TS strings are UTF-16 code-unit sequences; Go strings are UTF-8 bytes. utf8ByteLength collapses to len(string). Lone surrogates are unrepresentable in Go, so replaceUnpairedSurrogates has no counterpart (decoder-level U+FFFD replaces invalid input before we ever see it).
- truncateLine counts characters as UTF-16 code units in TS (.length); the Go counterpart counts runes, the closest analog for "characters".
- TruncationOptions optional members are pointers (nil = pi's undefined default); truncatedBy is "" when TS yields null.
pi: harness/utils/usage.ts — usage aggregation helpers.
Index ¶
- Constants
- func AddUsage(left, right types.Usage) types.Usage
- func EmptyUsage() types.Usage
- func FormatSize(bytes int64) string
- func SanitizeBinaryOutput(str string) string
- func TruncateLine(line string, maxChars int) (string, bool)
- type ShellCaptureOptions
- type ShellCaptureProgress
- type ShellCaptureResult
- type TruncationOptions
- type TruncationResult
Constants ¶
const ( // DefaultMaxLines is the default line limit (pi: DEFAULT_MAX_LINES). DefaultMaxLines = 2000 // DefaultMaxBytes is the default byte limit: 50KB (pi: DEFAULT_MAX_BYTES). DefaultMaxBytes = 50 * 1024 // GrepMaxLineLength is the max chars per grep match line (pi: // GREP_MAX_LINE_LENGTH). GrepMaxLineLength = 500 )
const ( TruncatedByLines string = "lines" TruncatedByBytes string = "bytes" )
TruncatedBy names the limit that was hit: "", "lines", or "bytes" (pi: truncatedBy: "lines" | "bytes" | null).
Variables ¶
This section is empty.
Functions ¶
func AddUsage ¶
AddUsage sums two usage records (pi: addUsage). Optional members (cacheWrite1h, reasoning) survive only when present on at least one side.
func FormatSize ¶
FormatSize formats bytes as human-readable size (pi: formatSize).
func SanitizeBinaryOutput ¶
SanitizeBinaryOutput strips control characters that would corrupt the captured text, keeping tab/newline/carriage-return (pi: sanitizeBinaryOutput). In TS this also drops UTF-16 line/paragraph separators (0xfff9-0xfffb are interlinear annotation anchors); the same rune range is dropped here.
Types ¶
type ShellCaptureOptions ¶
type ShellCaptureOptions struct {
// Cwd is the working directory for the command (pi: ShellExecOptions.cwd).
Cwd string
// Env holds environment variables for the command (pi: env).
Env map[string]string
// InheritEnv controls whether default environment variables are
// inherited; nil = pi's true default.
InheritEnv *bool
// Timeout is the command timeout in seconds; nil = no timeout (pi:
// timeout).
Timeout *float64
// OnChunk is called with each sanitized output chunk and a lazy progress
// getter (pi: onChunk(chunk, getProgress)).
OnChunk func(chunk string, getProgress func() ShellCaptureProgress)
// ReturnExecutionErrors returns shell execution failures with captured
// output instead of as a failed result (pi: returnExecutionErrors).
ReturnExecutionErrors bool
}
ShellCaptureOptions parameterizes ExecuteShellWithCapture (pi: ShellCaptureOptions; the ShellExecOptions onStdout/onStderr members are replaced by the single OnChunk here, mirroring pi's Omit).
type ShellCaptureProgress ¶
type ShellCaptureProgress struct {
// Output is the tail output, truncated when the whole capture exceeded
// the limits.
Output string
// Truncation describes the truncation state of the capture.
Truncation TruncationResult
// FullOutputPath points at the spilled full-output file, empty when not
// requested.
FullOutputPath string
// LastLineBytes is the byte length of the currently open line.
LastLineBytes int
}
ShellCaptureProgress is the streaming capture snapshot handed to ShellCaptureOptions.OnChunk (pi: ShellCaptureProgress).
type ShellCaptureResult ¶
type ShellCaptureResult struct {
ShellCaptureProgress
// ExitCode is the command's exit code; nil when cancelled or when the
// command failed to run.
ExitCode *int
// Cancelled reports whether the execution was cancelled.
Cancelled bool
// Truncated reports whether the captured output was truncated.
Truncated bool
// ExecutionError carries the failure when ReturnExecutionErrors is set
// and the command failed to run.
ExecutionError *harness.ExecutionError
}
ShellCaptureResult is the final capture outcome (pi: ShellCaptureResult; extends ShellCaptureProgress via embedding).
func ExecuteShellWithCapture ¶
func ExecuteShellWithCapture(ctx context.Context, env harness.ExecutionEnv, command string, options *ShellCaptureOptions) (*ShellCaptureResult, error)
ExecuteShellWithCapture executes a shell command while capturing bounded tail output and spilling the full output to a file when limits are hit (pi: executeShellWithCapture). Execution failures return a *harness.ExecutionError as the concrete error (pi: Result collapse).
type TruncationOptions ¶
type TruncationOptions struct {
// MaxLines is the maximum number of lines (default: 2000). nil = default.
MaxLines *int
// MaxBytes is the maximum number of bytes (default: 50KB). nil = default.
MaxBytes *int
}
TruncationOptions parameterizes truncation (pi: TruncationOptions).
type TruncationResult ¶
type TruncationResult struct {
// Content is the truncated content.
Content string
// Truncated reports whether truncation occurred.
Truncated bool
// TruncatedBy names the limit that was hit: "", "lines", or "bytes"
// (pi: truncatedBy, "" ↔ null).
TruncatedBy string
// TotalLines is the total number of lines in the original content.
TotalLines int
// TotalBytes is the total number of bytes in the original content.
TotalBytes int
// OutputLines is the number of complete lines in the truncated output.
OutputLines int
// OutputBytes is the number of bytes in the truncated output.
OutputBytes int
// LastLinePartial reports whether the last line was partially truncated
// (only for tail truncation edge case).
LastLinePartial bool
// FirstLineExceedsLimit reports whether the first line exceeded the byte
// limit (for head truncation).
FirstLineExceedsLimit bool
// MaxLines is the max lines limit that was applied.
MaxLines int
// MaxBytes is the max bytes limit that was applied.
MaxBytes int
}
TruncationResult reports one truncation outcome (pi: TruncationResult).
func TruncateHead ¶
func TruncateHead(content string, options *TruncationOptions) TruncationResult
TruncateHead truncates content from the head (keep first N lines/bytes) (pi: truncateHead). Suitable for file reads where you want to see the beginning.
Never returns partial lines. If first line exceeds byte limit, returns empty content with FirstLineExceedsLimit=true.
func TruncateTail ¶
func TruncateTail(content string, options *TruncationOptions) TruncationResult
TruncateTail truncates content from the tail (keep last N lines/bytes) (pi: truncateTail). Suitable for bash output where you want to see the end (errors, final results).
May return partial first line if the last line of original content exceeds byte limit.