utils

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 41 Imported by: ? modules, 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/utils/ansi.ts — strip ANSI escape sequences.

Portions of this file are derived from: - ansi-regex (https://github.com/chalk/ansi-regex) - strip-ansi (https://github.com/chalk/strip-ansi) MIT License, Copyright (c) Sindre Sorhus — see the pi source for the full notice; the regex patterns are ported verbatim.

changelog.go (pi: src/utils/changelog.ts) — parse CHANGELOG.md entries and rewrite relative markdown links into tag-pinned GitHub source links.

pi: src/utils/child-process.ts — spawn wrappers and the wait-with-stdio-grace helper.

Segment deviations:

  • cross-spawn's Windows argv repair has no Go counterpart (os/exec handles Windows process creation natively).
  • pig's spawnProcess returns the cmd plus manually created stdout/stderr pipe pairs (os/exec's StdoutPipe must not be read past Wait; the caller-driven data callbacks and the grace-timer finalize need reads that outlive Wait).
  • waitForChildProcess is ported as SpawnAndAwaitChild: pi's caller attaches data listeners before awaiting; pig's onData replaces them and runs under the same grace/idle semantics (data after exit re-arms the 100ms timer).

clipboard.go (pi: src/utils/clipboard.ts) — system clipboard text read/write with OSC 52 fallback for remote sessions (rewritten in pi v0.86.0 around runClipboardCommand).

Segment deviations:

  • pi's native path (getNativeClipboard()) has no Go equivalent: pig's GetNativeClipboard() is nil (S6-2). Every platform goes through the external tools (and OSC 52); reads gain platform-tool fallbacks that pi's native addon covered (pbpaste / powershell Get-Clipboard / xclip / xsel), and writes skip the non-Linux native setText step. Declared; see docs/feat/MAC-CLIPBOARD-IMAGE.md for the image-path equivalent.
  • pi returns `string | null`; pig returns "" for null (existing signature).

clipboard_command.go (pi: src/utils/clipboard-command.ts, new in v0.86.0) — the shared clipboard subprocess runner.

Segment deviations:

  • pi returns Promise<Buffer | undefined>; pig returns ([]byte, bool) with ok=false mapping pi's undefined and ok=true mapping a Buffer (possibly empty).
  • pi's "close" event fires when stdio settles; cmd.Run() waits for the process exit, which is the same observable for clipboard tools (the daemonizing-writer concern is handled by discarding stdout on the write path, matching pi's stdio ["pipe", "ignore", "ignore"]).
  • overflow aborts with SIGKILL in both (exec.CommandContext kills on deadline; the oversized write itself errors out the capture).

clipboard_image.go (pi: src/utils/clipboard-image.ts) — read an image from the system clipboard (Wayland / X11 / WSL PowerShell paths).

pi v0.86.0 reworked the chain around a three-state protocol: a backend that answers but has no image returns null (pi) and stops the chain, while a backend that cannot answer returns undefined (pi) and falls through to the next backend ("An empty Wayland clipboard must not fall through to stale X11 clipboard contents"). pig models the two nils with clipboardImageResult.

Segment deviations:

  • pi converts unsupported formats (e.g. Windows DIB data wrapped as BMP) to PNG via photon (WASM). The photon pipeline lands with Phase 8; convertToPng returns not-ok until then (declared).
  • pi's native path (getNativeClipboard().getImage()) has no Go equivalent: pig's GetNativeClipboard() is nil (S6-2). On darwin pig substitutes external tools (pig-only, docs/feat/MAC-CLIPBOARD-IMAGE.md): osascript ships with every macOS and reads the PNG pasteboard flavor; optional pngpaste (user-installed) covers TIFF-only clipboards. pi's detectSupportedImageMimeType probe is unnecessary on that path — both tools yield image/png verbatim (declared). Windows still reports nothing (declared).

Package utils corresponds to pi's packages/coding-agent/src/utils — coding-agent-level helpers shared by the core tools and higher layers.

Segment deviations:

  • child-process.ts wraps node's spawn/cross-spawn; pig uses os/exec directly (crossSpawn's Windows argv quirks have no Go counterpart — go buildmode handles Windows process creation natively). The waitForChildProcess grace semantics are ported in shell.go/exec land.
  • text.ts/ansi.ts are tiny string helpers ported as-is.

external_editor.go (pi: src/modes/interactive/external-editor.ts) — edit editor text in the user's external editor ($EDITOR-style command).

Segment deviations:

  • pi avoids spawnSync on Windows because libuv's console read races the child; Go's exec has no such shared console reader, so a plain synchronous run is equivalent on every platform.

pi: src/utils/frontmatter.ts — YAML frontmatter extraction and parsing for coding-agent resources.

Segment deviations:

  • npm `yaml` → gopkg.in/yaml.v3 (established precedent from the harness resource-loading batch). Error message wording differs between the libraries (pi's test asserts "at line 1, column 10"; yaml.v3 words the same unterminated-flow error differently) — parse failures are what matter, the exact message is library-specific (declared).
  • pi's generic <T> frontmatter record → map[string]any.

fs_watch.go (pi: src/utils/fs-watch.ts).

Declared deviation: pi wraps node:fs.watch; Go's stdlib has no file watcher. pig provides a mtime/size polling watcher with the same close-on-error contract. The 5s retry delay constant is kept for the footer git watcher (pi: FS_WATCH_RETRY_DELAY_MS).

pi: src/utils/image-process.ts — image normalization/resize pipeline for inline model attachments.

Segment deviations (photon/WASM boundary, see §1):

  • pi runs photon (WASM) for decode/resize/re-encode. pig implements the same pipeline with Go-native codecs instead of porting photon/wazero: stdlib image/jpeg|png|gif plus golang.org/x/image bmp|webp|tiff for decode, golang.org/x/image/draw ApproxBiLinear for resampling (2026-09-22, see docs/fix/2026-09-22-image-tool-413-oversize-and-history-bloat.md; the previous declared deviation — oversized images passed through unresized and convertImageBytesToPng always failing — is retired). ApproxBiLinear over CatmullRom is deliberate: CatmullRom's large-downscale distributor allocates ~srcW*dstH temp buffers (measured 168MB of churn on a 10MP photo vs 1MB for ApproxBiLinear), which defeats the pipeline's memory goal; encoded-size difference at inline-use scales is marginal (302KB vs 247KB on the same photo).
  • Animated sources (multi-frame GIF) are passed through unchanged rather than flattened: providers take the first frame anyway and re-encoding animation is out of scope.
  • Animated PNG / animated WebP decode as their first frame; resizing one flattens the animation (photon behaves the same on the inline path).
  • Decode failures pass the original bytes through unchanged instead of returning null→omitted (pi's resizeImage contract): a file the read tool sniffed as an image is more useful to the model untouched than silently dropped. Only the explicit MaxBytes contract path returns null (→ "[Image omitted: could not be resized ...]"), matching pi.
  • WebP has no Go encoder (x/image/webp is decode-only), so a resized WebP re-encodes as PNG with the mime type updated; pi re-encodes WebP→WebP.
  • The worker-thread indirection of image-resize.ts is node-runtime plumbing with no pig counterpart (in-process execution).

pi: src/utils/json.ts — strip `//` line comments and trailing commas from JSON, leaving string literals untouched.

pi: src/utils/management-http.ts — fetch with bounded immediate retry for idempotent management requests.

Segment deviations:

  • The fetch Response body is returned as a raw reader plus status; pig callers read to completion.
  • Caller cancellation rides the context (pi: parent signal / AbortSignal.any).

pi: src/utils/mime.ts — image signature sniffing (coding-agent copy; the agent package has its own near-identical copy in agent/harness/tools/ image.go, and pig mirrors the duplication).

Minimal minimatch-compatible glob matcher (npm minimatch, as consumed by model-resolver.ts with { nocase: true }).

Segment deviations (declared): pig implements the subset minimatch's consumers here use — `*` (within a path segment), `**` (across segments), `?`, `[...]`/`[!...]` character classes, `{a,b}` brace alternation, and case-insensitive matching. Extglob `+(...)` patterns and Windows path handling are not implemented (no pi test pins them on this surface).

node-style errno code mapping (pi surfaces error.code strings like "ENOENT"/"EACCES" in tool error messages; pig derives them from syscall errno values).

open_browser.go (pi: src/utils/open-browser.ts) — open a URL or file in the platform browser/default handler.

This intentionally never invokes a shell. On Windows, do not use `cmd /c start`: cmd.exe re-parses metacharacters (&, |, ^, ...) before `start` runs, which would make attacker-controlled URLs injectable.

pi: src/utils/paths.ts — path normalization and resolution helpers.

Segment deviations:

  • node path.resolve/join/relative/basename/isAbsolute/sep → path/filepath (POSIX separators; Windows-specific branches keyed on runtime.GOOS are ported but the drive-letter nuances of node's win32 path module are approximated by filepath — declared here).
  • fileURLToPath → net/url (same approximation as the env package).
  • spawnProcessSync for the cloud-sync attribute marking → os/exec.

pi: src/utils/pi-user-agent.ts — the coding-agent user agent sent to management endpoints (the pi.dev model catalog). pig/ai has its own provider-facing user agent (ai/utils/pi_user_agent.go).

Segment deviation (declared): pi renders the JS runtime segment (`bun/x.y.z` or `node/vX`); pig has no JS runtime and reports "pig" in its place, keeping the `pi/<version> (<platform>; <runtime>; <arch>)` shape.

pi: src/utils/shell.ts — shell resolution, environment assembly, and process-tree management for the coding-agent shell tools.

This is pi's own duplicate of the agent package's env/shell helpers (the two TS copies drifted slightly); pig mirrors the duplication and ports this copy verbatim.

Segment deviations:

  • existsSync → os.Stat; spawnSync which/where → exec.Command with timeout.
  • getShellEnv returns the child environment as a []string slice (NodeJS.ProcessEnv → string pairs; the PATH key lookup is case-insensitive over os.Environ as in pi).
  • sanitizeBinaryOutput iterates runes (pi iterates code points via Array.from — equivalent for UTF-8 input).

pi: utils/sleep.ts — sleep helper that respects the abort signal.

pi: src/core/source-info.ts — resource source provenance.

Lives in utils (not core) because the theme package needs the SourceInfo type and cannot import core (core → core/tools and, since T5a-2, core/tools → theme). core aliases these types so its public API is unchanged.

Package utils: syntax_highlight.go (pi: src/utils/syntax-highlight.ts + src/utils/html.ts decodeHtmlEntityAt/decodeHtmlEntity).

Backend deviation (declared): pi uses highlight.js; pig uses github.com/alecthomas/chroma/v2 (the repo's chosen highlighter, also slated for export-html). The two-stage pipeline is preserved verbatim: the lexer produces HTML spans whose class names are chroma token categories mapped onto highlight.js scope names (keyword, string, comment, function, ...), and RenderHighlightedHtml applies the caller's HighlightTheme formatters over that HTML. Language coverage therefore follows chroma's lexer registry (broader than pi's 20 eager languages); language names resolve through chroma's aliases.

HTML entity decoding is ported verbatim from html.ts (used by RenderHighlightedHtml; the rest of html.ts has no consumer yet).

pi: src/utils/text.ts — BOM helpers.

pi: utils/tool-result-images.ts — normalize image blocks returned by tool results.

The `read` tool and `@file` CLI attachments run their images through processImage, but tools that produce images themselves (extensions, MCP bridges, screenshot tools) hand back arbitrary base64 payloads that go straight into session history and every subsequent provider request. Oversized images make the provider reject the whole conversation, not just the offending turn, so normalize them once as they enter history.

pi: src/utils/tools-manager.ts — availability and GitHub-release download of the external search binaries (fd, ripgrep).

Segment deviations:

  • process.platform/arch → runtime.GOOS/runtime.GOARCH; pi's "x64" arch string maps from GOARCH "amd64" (fd's darwin x64 pin included).
  • The tar/zip extraction shells out to tar/unzip/powershell exactly as pi does (spawnSync → exec.Command).
  • fetchWithRetry carries the caller ctx; pi relies on AbortSignal timeouts.

wsl.go (pi: src/utils/wsl.ts) — Windows Subsystem for Linux detection, where Windows executables are reachable through interop. pi moved isWSL here from clipboard-image.ts in v0.86.1; pig keeps the same shape the clipboard-image port had (compiled per call, like the regex literal).

Index

Constants

View Source
const ExitStdioGraceMs = 100 * time.Millisecond

ExitStdioGraceMs is the post-exit idle window before finalizing (pi: EXIT_STDIO_GRACE_MS).

View Source
const FSWatchRetryDelayMs = 5000

FSWatchRetryDelayMs is pi's FS_WATCH_RETRY_DELAY_MS.

View Source
const ImageTypeSniffBytes = 4100

ImageTypeSniffBytes is the number of leading bytes read for sniffing (pi: IMAGE_TYPE_SNIFF_BYTES).

Variables

View Source
var (

	// InlineMarkdownLinkRe matches inline markdown links (pi:
	// INLINE_MARKDOWN_LINK_RE, global).
	InlineMarkdownLinkRe = regexp.MustCompile(changelogInlineMarkdownLinkRe)
)
View Source
var PowerShellArgs = []string{"-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command"}

PowerShellArgs are the fixed arguments for PowerShell invocations (pi: POWERSHELL_ARGS).

View Source
var ResizeImageFn = resizeImage

ResizeImageFn is the resizeImage entry used by ProcessImage; package-level var for tests (pig-only seam; pi mocks the image-resize module via vi.mock).

Functions

func AwaitChild

func AwaitChild(cmd *exec.Cmd, pipes *ChildPipes, ctx context.Context, onData func(chunk []byte)) error

AwaitChild waits for the spawned child per waitForChildProcess semantics, forwarding stdout/stderr chunks (with UTF-8 chunk decoding like node's setEncoding) to onData as they arrive. A read error on either pipe ends that stream; a spawn-side error surfaces through the returned error only when Wait itself reports a start failure handled by the caller.

func AwaitChildWaiter

func AwaitChildWaiter(cmd *exec.Cmd, pipes *ChildPipes, ctx context.Context, waiter *childProcessWaiter, onData func(chunk []byte)) error

AwaitChildWaiter is AwaitChild with a waiter created by StartChild.

func CanonicalizePath

func CanonicalizePath(path string) string

CanonicalizePath resolves a path to its canonical (real) form, following symlinks, falling back to the raw path when resolution fails (pi: canonicalizePath).

func CloseWatcher

func CloseWatcher(watcher *PollWatcher)

CloseWatcher stops a watcher, ignoring nil and close errors (pi: closeWatcher).

func CompareVersions

func CompareVersions(v1, v2 ChangelogEntry) int

CompareVersions returns -1/0/1 (pi: compareVersions).

func CopyToClipboard

func CopyToClipboard(text string) error

CopyToClipboard writes text to the system clipboard, preferring direct clipboard writes and emitting OSC 52 for remote sessions (pi: copyToClipboard; v0.86.0 — "Direct writes precede OSC 52 so the terminal cannot race the native writer"; v0.86.1 — WSL routes + OSC 52 for headless sessions, #9688). See the file header for the native-addon deviation.

func DecodeHtmlEntity

func DecodeHtmlEntity(entity string) (string, bool)

DecodeHtmlEntity mirrors pi's decodeHtmlEntity.

func DetectSupportedImageMimeType

func DetectSupportedImageMimeType(buffer []byte) string

DetectSupportedImageMimeType sniffs the buffer for a supported image format (pi: detectSupportedImageMimeType); "" = null.

func DetectSupportedImageMimeTypeFromFile

func DetectSupportedImageMimeTypeFromFile(filePath string) string

DetectSupportedImageMimeTypeFromFile sniffs the first bytes of a file (pi: detectSupportedImageMimeTypeFromFile).

func EnsureTool

func EnsureTool(ctx context.Context, tool string, onStatus func(status ToolStatus)) string

EnsureTool ensures a tool is available, downloading if necessary (pi: ensureTool). Progress reports go through onStatus; "" = undefined when unavailable.

func ErrnoCode

func ErrnoCode(err error) string

ErrnoCode extracts a node-style errno code ("EIO", "EPIPE", ...) from an error (pig addition for isDeadTerminalError; pi reads error.code on NodeJS.ErrnoException).

func ExtensionForImageMimeType

func ExtensionForImageMimeType(mimeType string) string

ExtensionForImageMimeType maps an image MIME type to a file extension (pi: extensionForImageMimeType); "" = unsupported.

func FSAccessMessage

func FSAccessMessage(err error, path string) error

FSAccessMessage formats an access failure the way node's fs.access throws ("ENOENT: no such file or directory, stat '<path>'"). Non-errno errors pass through unwrapped.

func FormatDimensionNote

func FormatDimensionNote(result *ResizedImage) string

FormatDimensionNote formats the coordinate-mapping note for resized images (pi: formatDimensionNote).

func FormatPathRelativeToCwdOrAbsolute

func FormatPathRelativeToCwdOrAbsolute(filePath string, cwd string) string

FormatPathRelativeToCwdOrAbsolute formats a path relative to cwd when inside it, otherwise absolute, with posix separators (pi: formatPathRelativeToCwdOrAbsolute).

func FormatSpawnFailure

func FormatSpawnFailure(err error, stderr string, stdout string, exitCode int) string

FormatSpawnFailure renders a spawnSync failure (pi: formatSpawnFailure).

func GetCwdRelativePath

func GetCwdRelativePath(filePath string, cwd string) string

GetCwdRelativePath returns the path relative to cwd when inside it (pi: getCwdRelativePath), "" when outside (pi: undefined).

func GetFileRevision

func GetFileRevision(path string) string

GetFileRevision returns a change-detection token for a file (pi: getFileRevision), "" when the path does not exist (pi: undefined). pi includes mtimeNs/ctimeNs; pig uses the modtime nanos only (the ctime is not portable), which preserves the change-detection contract.

func GetLatestVersion

func GetLatestVersion(ctx context.Context, repo string) (string, error)

getLatestVersion resolves the latest release version from the release page redirect (pi: getLatestVersion, v0.85.1). The api.github.com releases endpoint counts against the anonymous API quota (60 requests/hour per IP), which is permanently exhausted behind shared egress IPs such as corporate proxies and CI runners. The web endpoint answers with a redirect to the tagged release at no quota cost and lives on the same origin as the binary download itself.

func GetPiUserAgent

func GetPiUserAgent(version string) string

GetPiUserAgent builds the user agent sent to management endpoints (pi: getPiUserAgent(version)).

func GetShellEnv

func GetShellEnv() []string

GetShellEnv assembles the child environment with the managed bin dir prepended to PATH (pi: getShellEnv).

func GetToolPath

func GetToolPath(tool string) string

GetToolPath gets the path to a tool (system-wide or in our tools dir) (pi: getToolPath); "" = null.

func Highlight

func Highlight(code string, options HighlightOptions) string

Highlight mirrors pi's highlight(): lex code (or auto-detect when no language is given) and render the token stream through the theme formatters. Auto-detection maps to chroma's AnalyseLexer (pi: hljs.highlightAuto with languageSubset; the subset hint is accepted but chroma's analysis does not consume it — declared deviation).

func IsLocalPath

func IsLocalPath(value string) bool

IsLocalPath reports whether the value is NOT a package source (npm:, git:, etc.) or a remote URL protocol (pi: isLocalPath).

func IsWaylandSession

func IsWaylandSession(env func(string) string) bool

IsWaylandSession reports a Wayland session (pi: isWaylandSession, clipboard-image.ts; kept for callers).

func KillProcessTree

func KillProcessTree(pid int)

KillProcessTree kills a process and all its children (pi: killProcessTree).

func KillTrackedDetachedChildren

func KillTrackedDetachedChildren()

KillTrackedDetachedChildren kills all tracked detached children (pi: killTrackedDetachedChildren).

func MarkPathIgnoredByCloudSync

func MarkPathIgnoredByCloudSync(path string)

MarkPathIgnoredByCloudSync marks a path ignored by common cloud-sync providers (pi: markPathIgnoredByCloudSync). Failures are silent.

func Minimatch

func Minimatch(pattern, text string) bool

Minimatch reports whether text matches the glob pattern (pi consumes npm minimatch with { nocase: true }).

func NodeErrCode

func NodeErrCode(err error) string

NodeErrCode maps an os error to node's errno code string; other errors yield "" (pi: error.code is undefined for non-errno errors).

func NodeErrCodeOf

func NodeErrCodeOf(err error) string

NodeErrCodeOf extracts a NodeErr code from an error chain; "" when absent.

func NormalizeChangelogLinks(markdown string, version any) string

NormalizeChangelogLinks rewrites relative links in changelog markdown into tag-pinned GitHub links (pi: normalizeChangelogLinks). version is a string or ChangelogEntry.

func NormalizePath

func NormalizePath(input string, options *PathInputOptions) string

NormalizePath normalizes user path input (pi: normalizePath).

func NormalizeToolResultImages

func NormalizeToolResultImages(content []types.Content, options *NormalizeToolResultImagesOptions) ([]types.Content, error)

NormalizeToolResultImages normalizes image blocks returned by tool results. Returns the original slice when nothing changed so callers can skip rewriting the result (pi: normalizeToolResultImages).

func NormalizeWindowsShellPath

func NormalizeWindowsShellPath(filePath string) string

NormalizeWindowsShellPath converts Git Bash, MSYS, Cygwin, and WSL drive paths to a form native Windows APIs accept (pi: normalizeWindowsShellPath).

func OpenBrowser

func OpenBrowser(target string)

OpenBrowser opens a URL or file with the platform default handler (pi: openBrowser). Launcher failures are swallowed: browser launch is best-effort and callers still present the target to the user.

func ParseFrontmatter

func ParseFrontmatter(content string) (frontmatter map[string]any, body string, err error)

ParseFrontmatter parses YAML frontmatter and returns the remaining body (pi: parseFrontmatter). A missing or unterminated frontmatter block leaves the content as the body with an empty frontmatter map.

func ReadClipboardFilePaths added in v1.0.0

func ReadClipboardFilePaths() ([]string, error)

ReadClipboardFilePaths reads file paths, such as Finder file copies, from the clipboard (pi: readClipboardFilePaths — the native addon's getFilePaths, which reads NSPasteboard file URLs; a rejected promise maps to a non-nil error). pig has no native clipboard (file header): macOS substitutes osascript reading the «class furl» pasteboard flavor, the same external-tool route as image reading; other platforms have no equivalent reader, matching pi's addon coverage. nil = nothing available (pi null).

func ReadClipboardText

func ReadClipboardText() string

ReadClipboardText reads plain text from the system clipboard (pi: readClipboardText; v0.86.0 chains the platform tools via runClipboardCommand). "" = nothing available (pi null).

func RenderHighlightedHtml

func RenderHighlightedHtml(htmlStr string, theme HighlightTheme) string

RenderHighlightedHtml walks highlighter HTML output, replaces span nesting with the mapped theme formatters and decodes HTML entities (pi: renderHighlightedHtml).

func ResolvePath

func ResolvePath(input string, baseDir string, options *PathInputOptions) string

ResolvePath resolves input against baseDir (pi: resolvePath; baseDir "" = process.cwd()).

func SanitizeBinaryOutput

func SanitizeBinaryOutput(str string) string

func Sleep

func Sleep(ctx context.Context, ms int64) error

Sleep waits for ms, returning early when ctx is cancelled (pi: sleep(ms, signal?) — the optional AbortSignal becomes the ctx parameter; pi rejects with Error("Aborted"), pig returns ctx.Err()).

func SplitBom

func SplitBom(content string) (bom string, text string)

SplitBom splits a leading UTF-8 BOM from the content (pi: splitBom).

func SplitIncompleteAnsiSuffix added in v1.1.0

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

SplitIncompleteAnsiSuffix splits streamed text into a part that is safe to pass to StripAnsi now and a trailing unfinished escape sequence that should be prepended to the next chunk (pi: splitIncompleteAnsiSuffix).

Window arithmetic deviates from pi by design: pi slices by UTF-16 code units, Go by bytes — the window is only a bounding heuristic for the look-back, and every possible split point (before an ESC/CSI introducer or the U+009B rune) is at a rune boundary in both.

func StartChild

func StartChild(cmd *exec.Cmd, pipes *ChildPipes) (*childProcessWaiter, error)

StartChild starts the spawned child and releases the parent's write ends. Returns the waiter used by AwaitChild. (pig addition: split from AwaitChild so callers can register timers/watchers against the live pid, matching pi's spawn → track → listen ordering.)

func StripAnsi

func StripAnsi(value string) string

StripAnsi removes ANSI escape sequences (pi: stripAnsi). The TypeError guard has no Go counterpart (static typing).

func StripBom

func StripBom(content string) string

StripBom removes a leading UTF-8 byte order mark from decoded text (pi: stripBom).

func StripFrontmatter

func StripFrontmatter(content string) (string, error)

StripFrontmatter returns the body of a document (pi: stripFrontmatter; pi propagates parse errors, so does pig).

func StripJsonComments

func StripJsonComments(input string) string

StripJsonComments removes // line comments and trailing commas (pi: stripJsonComments).

func SupportsLanguage

func SupportsLanguage(name string) bool

SupportsLanguage mirrors pi's supportsLanguage (hljs.getLanguage !== undefined → chroma lexers.Get !== nil). Names resolve through chroma's alias table (e.g. "js", "golang", "sh").

func TrackDetachedChildPid

func TrackDetachedChildPid(pid int)

TrackDetachedChildPid records a live detached child (pi: trackDetachedChildPid).

func UntrackDetachedChildPid

func UntrackDetachedChildPid(pid int)

UntrackDetachedChildPid drops a settled detached child (pi: untrackDetachedChildPid).

Types

type ChangelogEntry

type ChangelogEntry struct {
	Major   int
	Minor   int
	Patch   int
	Content string
}

ChangelogEntry is one parsed `## [x.y.z]` section (pi: ChangelogEntry).

func GetNewEntries

func GetNewEntries(entries []ChangelogEntry, lastVersion string) []ChangelogEntry

GetNewEntries returns entries newer than lastVersion (pi: getNewEntries).

func ParseChangelog

func ParseChangelog(changelogPath string) []ChangelogEntry

ParseChangelog parses changelog entries from CHANGELOG.md. Scans for ## lines and collects content until the next ## or EOF (pi: parseChangelog).

type ChildPipes

type ChildPipes struct {
	StdoutRead  *os.File
	StdoutWrite *os.File
	StderrRead  *os.File
	StderrWrite *os.File
}

ChildPipes holds the manually created stdio pipe ends for one spawned child. The parent closes the write ends immediately after start and the read ends after the child settles.

func SpawnProcess

func SpawnProcess(command string, args []string, cwd string, env []string) (*exec.Cmd, *ChildPipes, error)

SpawnProcess spawns a command with piped stdout/stderr (pi: spawnProcess with ['ignore', 'pipe', 'pipe'] stdio). stdin wiring is the caller's job (pi: commandFromStdin passes "pipe" for stdin; pig callers set cmd.Stdin).

func (*ChildPipes) CloseReadEnds

func (p *ChildPipes) CloseReadEnds()

CloseReadEnds releases the parent's pipe read ends after settling.

func (*ChildPipes) CloseWriteEnds

func (p *ChildPipes) CloseWriteEnds()

CloseWriteEnds releases the parent's pipe write ends so readers observe EOF once the child (and any surviving descendants) close theirs (node's pipe stdio setup does the same).

type ClipboardImage

type ClipboardImage struct {
	Bytes    []byte
	MimeType string
}

ClipboardImage is an image read from the clipboard (pi: ClipboardImage).

func ReadClipboardImage

func ReadClipboardImage(options *ReadClipboardImageOptions) *ClipboardImage

ReadClipboardImage reads an image from the system clipboard (pi: readClipboardImage; v0.86.0 three-state chain); nil = nothing available.

type DecodedHtmlEntity

type DecodedHtmlEntity struct {
	Text   string
	Length int
}

DecodedHtmlEntity is pi's DecodedHtmlEntity.

func DecodeHtmlEntityAt

func DecodeHtmlEntityAt(htmlStr string, index int) *DecodedHtmlEntity

DecodeHtmlEntityAt mirrors pi's decodeHtmlEntityAt.

type ExternalEditorResult

type ExternalEditorResult struct {
	// Status is "complete" or "failed".
	Status string
	// Content is the edited text when Status == "complete".
	Content string
}

ExternalEditorResult is the editor outcome (pi: ExternalEditorResult).

func EditInExternalEditor

func EditInExternalEditor(ctx context.Context, command string, content string) (ExternalEditorResult, error)

EditInExternalEditor runs the editor command over the content in a temp file (pi: editInExternalEditor). command is split on spaces (pi's split).

type FetchResponse

type FetchResponse struct {
	StatusCode int
	Header     http.Header
	Body       io.ReadCloser
	// contains filtered or unexported fields
}

FetchResponse is the minimal response surface needed by callers. The attempt context's cancel travels with the response (pi: the attempt AbortSignal also governs the body stream); callers must call Close, which closes the body and releases the attempt context.

func FetchWithRetry

func FetchWithRetry(ctx context.Context, method string, url string, headers map[string]string, options *FetchRetryOptions) (*FetchResponse, error)

FetchWithRetry fetches a management HTTP resource with a bounded immediate retry (pi: fetchWithRetry). Caller cancellation and the overall timeout are terminal; the attempt timeout aborts only the current attempt.

func (*FetchResponse) Close

func (r *FetchResponse) Close()

Close releases the response body and the attempt context.

type FetchRetryOptions

type FetchRetryOptions struct {
	// MaxRetries is the number of additional attempts after the initial
	// request. Defaults to two.
	MaxRetries *int
	// RetryTransientStatus also retries transient HTTP responses. Defaults
	// to true; nil = default.
	RetryOnStatus *bool
	// TimeoutMs is the overall time budget shared by all attempts (pi:
	// timeoutMs; millis).
	TimeoutMs *int64
	// AttemptTimeoutMs aborts only the current attempt so a hung connection
	// can be retried (pi: attemptTimeoutMs; millis).
	AttemptTimeoutMs *int64
	// NoRedirect stops at the first redirect response (pi: fetch's
	// redirect:"manual" option, v0.85.1); the 3xx response is returned as-is.
	NoRedirect *bool
}

FetchRetryOptions parameterize FetchWithRetry (pi: FetchRetryOptions).

type HighlightFormatter

type HighlightFormatter = func(text string) string

HighlightFormatter is pi's HighlightFormatter.

type HighlightOptions

type HighlightOptions struct {
	Language       string
	IgnoreIllegals bool
	LanguageSubset []string
	Theme          HighlightTheme
}

HighlightOptions mirrors pi's HighlightOptions.

type HighlightTheme

type HighlightTheme map[string]HighlightFormatter

HighlightTheme is pi's HighlightTheme (Partial<Record<string, HighlightFormatter>> → map; missing keys fall through scope prefixes and finally to the "default" entry).

type ImageResizeOptions

type ImageResizeOptions struct {
	MaxWidth  *int
	MaxHeight *int
	// MaxBytes is the maximum base64-encoded payload size in bytes (pi:
	// maxBytes; 0/unset = the defaultResizeMaxBytes budget).
	MaxBytes *int
	// JpegQuality is the re-encode quality for JPEG output. 0/unset =
	// defaultJpegQuality.
	JpegQuality *int
}

ImageResizeOptions carries the resize overrides (pi: ImageResizeOptions in image-resize-core.ts).

func ResizeOptionsFromModel added in v0.87.0

func ResizeOptionsFromModel(profile *types.ModelImageResizeOptions) *ImageResizeOptions

ResizeOptionsFromModel maps a model's catalog resize profile onto the processing options (pi: ModelImageResizeOptions — pi passes it straight into processImage thanks to TS structural typing; Go needs the explicit mapping). nil profile → nil options (resizeImage defaults apply).

type NodeErr

type NodeErr struct {
	// Code is the node errno code ("ENOENT", "EACCES", ...).
	Code string
	// Message is the formatted node-style message.
	Message string
	// Err is the underlying error.
	Err error
}

NodeErr carries a node errno code with its formatted message (pig addition: the tools branch on error.code; Go errors lose the code unless carried explicitly).

func (*NodeErr) Error

func (e *NodeErr) Error() string

func (*NodeErr) Unwrap

func (e *NodeErr) Unwrap() error

type NormalizeToolResultImagesOptions

type NormalizeToolResultImagesOptions struct {
	// AutoResizeImages resizes oversized images to inline provider limits.
	// Defaults to true; nil = default (pi: autoResizeImages?).
	AutoResizeImages *bool
	// ResizeOptions is the model-specific resize profile (pi:
	// resizeOptions?); the conservative built-in defaults apply when
	// omitted. nil = unset.
	ResizeOptions *types.ModelImageResizeOptions
}

NormalizeToolResultImagesOptions are the options for NormalizeToolResultImages (pi: NormalizeToolResultImagesOptions).

type PathInputOptions

type PathInputOptions struct {
	// Trim strips leading/trailing whitespace before normalization; nil =
	// pi's undefined (false).
	Trim *bool
	// ExpandTilde expands a leading `~` to a home directory. Defaults to
	// true; nil = default.
	ExpandTilde *bool
	// HomeDir is the home directory used for `~` expansion; empty = pi's
	// os.homedir() default.
	HomeDir string
	// StripAtPrefix strips a leading `@`, used for CLI @file paths; nil =
	// pi's undefined (false).
	StripAtPrefix *bool
	// NormalizeUnicodeSpaces normalizes unicode space variants to regular
	// spaces; nil = pi's undefined (false).
	NormalizeUnicodeSpaces *bool
}

PathInputOptions parameterize normalizePath (pi: PathInputOptions).

type PollWatcher

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

PollWatcher is the pig replacement for node's FSWatcher: it polls a path's mtime/size and fires onChange on detected changes.

func WatchWithErrorHandler

func WatchWithErrorHandler(path string, onChange func(), onError func()) *PollWatcher

WatchWithErrorHandler polls path for mtime/size changes and invokes onChange; poll-setup errors invoke onError and return nil, matching pi's watchWithErrorHandler error contract (pi's per-event errors surface via the watcher's 'error' listener → onError; pig has no async poll errors). The default poll interval is 500ms (pi: fs.watch coalescing heuristic); use WatchWithErrorHandlerWithInterval to override it.

func WatchWithErrorHandlerWithInterval

func WatchWithErrorHandlerWithInterval(path string, interval time.Duration, onChange func(), onError func()) *PollWatcher

WatchWithErrorHandlerWithInterval is WatchWithErrorHandler with an explicit poll interval (pig addition; the WSL git-HEAD poller and the reftable tables.list poller in pi watch files at fixed intervals).

func (*PollWatcher) Close

func (w *PollWatcher) Close()

Close stops the polling loop (pi: watcher.close()).

type ProcessImageOptions

type ProcessImageOptions struct {
	// AutoResizeImages resizes images to inline provider limits. Defaults
	// to true; nil = default.
	AutoResizeImages *bool
	// ResizeOptions are optional resize overrides; nil = resizeImage
	// defaults.
	ResizeOptions *ImageResizeOptions
}

ProcessImageOptions parameterize ProcessImage (pi: ProcessImageOptions).

type ProcessImageResult

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

ProcessImageResult is the outcome of ProcessImage (pi: ProcessImageResult union → single struct; OK discriminates the success payload from Message).

func ProcessImage

func ProcessImage(data []byte, mimeType string, options *ProcessImageOptions) ProcessImageResult

ProcessImage normalizes and optionally resizes an image for inline use (pi: processImage).

type ReadClipboardImageOptions

type ReadClipboardImageOptions struct {
	// Env overrides the environment lookup (pig: test seam).
	Env func(string) string
	// Platform overrides the GOOS lookup (pig: test seam).
	Platform string
}

ReadClipboardImageOptions parameterize ReadClipboardImage (pi: the options param; nil = process values).

type ResizedImage added in v0.87.0

type ResizedImage struct {
	Data           string
	MimeType       string
	OriginalWidth  int
	OriginalHeight int
	Width          int
	Height         int
	WasResized     bool
}

ResizedImage is the resize outcome (pi: ResizedImage, exported for the test seam).

type ShellConfig

type ShellConfig struct {
	Shell string
	Args  []string
	// CommandTransport is "" (argv) or "stdin" (pi: "argv" | "stdin" |
	// undefined; undefined collapses to "").
	CommandTransport string
}

ShellConfig selects the shell binary and argument transport (pi: ShellConfig).

func GetPowerShellConfig

func GetPowerShellConfig() (ShellConfig, error)

GetPowerShellConfig resolves PowerShell on Windows, preferring PowerShell 7 when available (pi: getPowerShellConfig).

func GetShellConfig

func GetShellConfig(cwd string, customShellPath string) (ShellConfig, error)

GetShellConfig resolves the shell configuration based on platform and an optional explicit shell path (pi: getShellConfig; pi resolves relative custom paths against the process cwd, pig against the supplied cwd). Resolution errors are returned as plain errors (pi: throws).

type SourceInfo

type SourceInfo struct {
	Path    string       `json:"path"`
	Source  string       `json:"source"`
	Scope   SourceScope  `json:"scope"`
	Origin  SourceOrigin `json:"origin"`
	BaseDir string       `json:"baseDir,omitempty"`
}

SourceInfo records where a loaded resource came from (pi: SourceInfo).

type SourceOrigin

type SourceOrigin = string

SourceOrigin identifies how a resource was referenced (pi: SourceOrigin).

const (
	SourceOriginPackage  SourceOrigin = "package"
	SourceOriginTopLevel SourceOrigin = "top-level"
)

Source origin values (pi: "package" | "top-level").

type SourceScope

type SourceScope = string

SourceScope identifies where a resource came from (pi: SourceScope).

const (
	SourceScopeUser      SourceScope = "user"
	SourceScopeProject   SourceScope = "project"
	SourceScopeTemporary SourceScope = "temporary"
)

Source scope values (pi: "user" | "project" | "temporary").

type ToolStatus

type ToolStatus struct {
	// Type is "info" or "warning".
	Type string
	// Message is the progress message.
	Message string
}

ToolStatus is one progress report (pi: ToolStatus).

Jump to

Keyboard shortcuts

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