Documentation
¶
Overview ¶
pi: src/core/agent-session.ts — AgentSession, the core abstraction for agent lifecycle and session management shared between all run modes (interactive, print, rpc). It encapsulates agent state access, event subscription with automatic session persistence, model and thinking level management, compaction (manual and auto), bash execution, and session switching/branching.
Segment deviations (declared):
- AgentSessionEvent is a discriminated union in pi; pig follows the agent.AgentEvent precedent (single struct, fields named by Type are meaningful). The compaction-end result field is named CompactionResult to avoid colliding with the embedded AgentEvent.Result (pi reuses `result` across union members).
- pi mutates the message object in place on extension message_end replacement (object identity shared with agent state). pig's agent messages are values, so the replacement is located in agent state by role+timestamp and rewritten there; the local event copy is swapped too. Only reachable with extension handlers (Phase 7).
- Private-method spies used by pi tests (_runAutoCompaction) map to the runAutoCompactionFn field (same-package tests overwrite it); see the test files.
- exportToHtml (export-html + theme, Phase 8) is deferred.
- pi's fire-and-forget `void runner.emit(...)` calls run synchronously on a background context (no goroutine: pi's promise is unobserved).
pi: core/agent-session-runtime.ts — owns the current AgentSession plus its cwd-bound services. Session replacement methods tear down the current runtime first, then create and apply the next runtime. If creation fails, the error is propagated to the caller; the caller is responsible for user-facing error handling.
pi: core/agent-session-services.ts — cwd-bound runtime services for one effective session cwd. The extension half of applyExtensionFlagValues (registered flag validation against loaded extensions) is inert until the extension loader (Phase 7) populates extensionsResult.extensions; the unknown-flag diagnostics path is kept because it does not need handlers.
pi: src/core/auth-guidance.ts — auth/setup guidance messages.
pi: src/core/auth-storage.ts — CredentialStore implementation backed by auth.json. Provider auth orchestration belongs to ModelRuntime and pig/ai Models.
Segment deviations (declared):
- pi's AuthStorageBackend has a sync withLock<T> and an async withLockAsync<T>; Go interface methods cannot be generic, so the backend interface carries a non-generic LockFunction and package-level generic helpers (WithLock/WithLockAsync) recover the typed result (same precedent as harness events.go OnTyped). Cancellation rides the Go context (pi: AuthOperationOptions.signal); the sync path passes context.Background().
- proper-lockfile → an O_EXCL lockfile at "<path>.lock"; release = removal. The lock content is the creation mtime; an async acquisition steals locks older than the stale window (proper-lockfile semantics). The acquire primitives are package vars so tests can substitute pi's vi.spyOn(lockfile, "lock") seam. pi's synchronous retry loop busy-waits to stay synchronous; pig sleeps.
- auth.json key order: JSON.stringify preserves object insertion order; pig tracks the parsed key order explicitly and marshals in that order (JS spread semantics: an updated provider keeps its position, a new one is appended) so files stay line-compatible.
- resolveConfigValue returns string | undefined in pi; an undefined resolved key collapses to "" here (pi's {...credential, key: undefined} reads as an absent key downstream; omitempty gives the same JSON).
- pi propagates reload failures only when the caller passed a signal and otherwise falls back to the cached snapshot; pig always carries a context, so cancellation propagates while storage/parse failures fall back to the cache (declared collapse of the two pi branches).
pi: src/core/bash-executor.ts — bash command execution with streaming support and cancellation. A unified bash execution implementation used by AgentSession.executeBash() (interactive and RPC modes) and by modes that need bash execution directly.
Segment deviations (declared):
- pi's options.signal → the Go context; the cancelled flag derives from ctx.Err() (pi: signal.aborted).
- The temp file write stream becomes a plain file handle.
- pi's TextDecoder(stream:true) → a local UTF-8 chunk decoder with the same streaming semantics (incomplete sequences buffered, invalid bytes become U+FFFD).
pi: core/compaction/branch-summarization.ts — branch summarization for tree navigation. When navigating to a different point in the session tree, this generates a summary of the branch being left so context isn't lost.
This is the coding-agent-side implementation over ReadonlySessionManager / SessionEntry (pi keeps a separate, different implementation over the agent harness's session in agent/src/harness/compaction/branch-summarization.ts; pig ports both, this one included per the two-implementations precedent). It lives flat in package core for the dependency-direction reason declared in compaction.go's header.
pi: src/core/bug-report.ts — /bug report collection, redaction, bundling and model-written summaries (pi v0.86.0). Deviations:
- collectEnvironment reports Go runtime facts (go/<version>, GOOS/GOARCH, syscall.Uname) instead of bun/node; the PI_ env scan also collects PIG_* names (pig's own prefix).
- SimpleStreamOptions carries ctx as the Go context argument (AbortSignal → context rule); options.signal members are dropped.
pi: src/core/bug-report-upload.ts — upload a report as multipart form data, anonymously or attributed to a Radius account (pi v0.86.0). pi's options.signal is dropped — cancellation travels as the Go ctx (AbortSignal → context rule).
cache_stats.go (pi: src/core/cache-stats.ts).
pi: src/core/cache-warmer.ts (new in v0.86.0) — keeps one prompt cache entry alive by re-sending its request with a one-token output cap before the entry expires.
Segment deviations:
- AbortController → context.WithCancel; timers → time.AfterFunc. pi's run.timer.unref?.() has no Go equivalent: AfterFunc timers do not keep a Go process alive at exit.
- pi's async decide callback → sync callback with ctx; a returned error falls back to pi's own decision (pi: try/catch around await).
- status/decision getters are Get* methods (Go has no property getters).
- pig's usage entries carry Timestamp as an ISO string on EntryBase; pi's UsageEntry.timestamp is likewise a string.
pi: core/compaction/compaction.ts — context compaction for long sessions.
Pure functions for compaction logic. The session manager handles I/O, and after compaction the session is reloaded.
Placement deviation (reducer/agentharness precedent, inverse direction): pi keeps core/compaction/ in the same TS package as session-manager.ts, and AgentSession (also that package) consumes it. Moving these functions into a Go subpackage would make it import codingagent/core while package core imports it back — an import cycle. They therefore live flat in package core; the pi source path stays in this header.
Segment deviations (declared):
- The token-estimation half (calculateContextTokens / estimateContextTokens / estimateTokens / combineUsage) is byte-level identical in pi between the agent harness's compaction.ts and this file (only safeJsonStringify vs JSON.stringify for tool-call args, behaviorally equivalent for JSON-decoded arguments). Per the edit-diff/truncate reuse precedent pig keeps the single harness implementation and delegates to it (agent/harness/compaction/compaction.go).
- pi's options.signal members are dropped; cancellation travels as the Go context (AbortSignal → context rule).
- The completeSimple fallback of completeSummarization goes through the api-provider registry (ai.GetApiProvider) directly. pi's compat.ts standalone stream family (getBuiltinProviderForModel with the cloudflare-legacy branch) is not ported yet: pig's builtin adapters self-register in the same registry. The withEnvApiKey env-key fill landed in ai.StreamSimple on 2026-09-13 (docs/fix/2026-09-13-env-api-keys-fill.md). AgentSession always supplies the agent's streamFn, so the fallback is only reachable for direct library callers.
- pi v0.87.0 (466db0fec) added a system-message branch to THIS file's estimateTokens only (replayed prompt content, sections, toolsAdded JSON); the agent-harness twin stayed untouched, so the two TS copies are no longer byte-identical. pig keeps the shared twin and adds the branch in the core EstimateTokens wrapper below: the projection cut-point walk and the EstimateProjectedContextTokens fallback see system-message tokens, while the harness-delegated EstimateContextTokens keeps counting trailing system messages as 0 (its callers are usage-anchored; agent-session swaps to the projected estimator with the S8-4 batch).
pi: core/compaction/utils.ts — shared utilities for compaction and branch summarization on the coding-agent side.
This file is a near-byte-identical duplicate of the agent harness's compaction utils (agent/src/harness/compaction/utils.ts; pig: agent/harness/compaction/utils.go). The only behavioral difference is serializeConversation's tool-call argument formatting: the harness uses safeJsonStringify while core uses JSON.stringify — identical output for every JSON-decodable argument object, and tool-call arguments always come from JSON parsing, so per the edit-diff/truncate reuse precedent pig keeps the single harness implementation and re-exports it here under the core names. Go's map iteration order makes the serialized argument order key-sorted where TS preserves object insertion order (declared at the harness port and unchanged here).
pi: src/core/crash-log.ts — best-effort crash persistence so the next start can point the user at `/bug` (pi v0.86.0). Deviation: pi reads `error.stack` off Error objects; Go errors carry no stack, so the caller passes one when available (Input.Stack) and nil otherwise.
pi: src/core/defaults.ts — default thinking level constants.
pi: src/core/diagnostics.ts — resource diagnostic shapes shared by the resource loaders.
Package core corresponds to pi's packages/coding-agent/src/core — the coding-agent headless runtime: session management (session-manager.ts), settings, system prompt assembly, resource loading, project trust, and the print/RPC mode services.
File mapping: session-manager.ts → session_manager.go. Subdirectories hold the pi core sub-packages (tools/ ← core/tools, ...).
pi: core/event-bus.ts — generic channel pub/sub used by the extension loader and resource loader. pi wraps handlers in an async function and swallows errors via console.error; pig keeps the same observable contract with a synchronous dispatch and recover (declared deviation: no event-loop deferral — the emit caller's goroutine runs handlers directly).
pi: src/core/experimental.ts — experimental feature gates.
pi v0.86.0 removed getExperimentalToolSampling/PREFER_STRICT_TOOL_SAMPLING: the strict-mode tool sampling request is now hardcoded at each tool definition site (bash/read/write/edit), no longer gated on PI_EXPERIMENTAL. pig keeps only the feature gate.
export_html.go (pi: core/export-html/index.ts — session-facing half, v0.86.0)
Go's import-cycle rules forced pi's export-html/index.ts to be split in two: the template half (ExportOptions consumers, ToolHtmlRenderer interface, SessionData, generateHtml) lives in codingagent/core/exporthtml, and this file carries the session-facing half — exportSessionToHtml, exportFromFile and preRenderCustomTools — which needs codingagent/core's SessionManager/SessionEntry types.
pi: core/extensions/runner.ts — the ExtensionRunner, restricted to the no-extension path AgentSession consumes. The extension loader (Phase 7) will feed real Extension values into the same surface; until then the extensions slice is always empty, so every handler loop short-circuits: hasHandlers is false, emit is a no-op, and the emitXxx helpers return their no-handler defaults (pi's semantics with zero extensions).
pi: core/extensions/types.ts — the extension system types, restricted to the surface AgentSession (core/agent-session.ts) consumes. The remaining surface arrives with its consumers: renderer/shortcut/widget component types with the TUI batch (Phase 6), and the loader/extension-runtime plumbing with the extensions batch (Phase 7).
Placement deviation (same dependency direction as compaction.go): pi's core/extensions/ is one TS package with session-manager.ts and imports its types; a Go subpackage would import codingagent/core while package core imports it back (AgentSession → ExtensionRunner). Files therefore live flat in package core.
Structural deviations (declared):
- ExtensionContext/ExtensionCommandContext are TS objects whose properties are lazy getters over runner state; Go represents them as structs whose action members are function fields populated by the runner. Stale-instance guards run at runner entry points (assertActive) rather than at property access.
- Event union members are separate structs implementing ExtensionEvent (discriminated union → interface + concrete types rule). pi's `signal: AbortSignal` members on session_before_compact / session_before_tree are dropped; cancellation travels as the Emit call's context.
- ExtensionUIContext's component-factory overloads arrived with T5b-3 (Phase 6 interactive batch); the factories take no theme parameter — pig components read the global current theme via theme.Current() (repo-wide precedent; pi passes the theme as a factory argument).
pi: core/extensions/wrapper.ts — tool wrappers for extension-registered tools. These wrappers only adapt tool execution so extension tools receive the runner context; tool call and tool result interception is handled by AgentSession via agent hooks.
footer_data_provider.go (pi: src/core/footer-data-provider.ts).
Provides git branch and extension statuses — data not otherwise accessible to extensions. Context usage on session.GetContextUsage(), token stats on sessionManager.GetEntries(), model info on session.Model().
Declared deviations:
- pi watches directories via node's fs.watch; pig uses mtime/size polling watchers (codingagent/utils PollWatcher). pi's filename filter (only react to HEAD) has no polling equivalent — a directory change schedules a debounced refresh instead, which re-resolves the branch from HEAD's content.
- pi's WSL watchFile(HEAD, { interval: 1000 }) half is folded into the same poll-watcher mechanism (a second 1s poller on HEAD, kept in the wslHeadWatcher field).
- child_process spawnSync/execFile sit behind unexported function vars (footerResolveBranchSync/footerResolveBranchAsync) so tests can stub git (pi: vi.mock("child_process")).
- pi is single-threaded; pig guards the provider with a mutex and only invokes branch-change callbacks with the lock released.
pi: src/core/http-dispatcher.ts — HTTP transport tuning (portable half).
Segment deviations:
- The undici dispatcher half (configureHttpDispatcher, the undici Client/Pool wiring, the global-fetch installation and the undici error listener) is Node-undici-specific with no Go counterpart — Go's net/http needs no dispatcher swap; deferred until a consumer actually needs Go transport tuning (position kept below).
- applyHttpProxySettings: process.env.HTTP_PROXY ??= proxy → only set when currently unset (Go os.Environ scan for the case-insensitive key is unnecessary here; Go's http transport reads the upper-case vars, matching Node's upper-case convention).
- v0.85.1 adds undici's proxyTunnel:true (keep HTTP origins on CONNECT tunnels as before Undici 8.7): Node-undici-specific, no Go equivalent — Go's http.Transport always proxies https over CONNECT.
keybindings.go (pi: src/core/keybindings.ts).
coding-agent keybindings: the merged definition table (pi-tui defaults + coding-agent's tui.* overrides and app.* bindings), legacy-name migration, and the user keybindings.json loader. The manager itself extends the tui package's KeybindingsManager (pi: KeybindingsManager extends TuiKeybindingsManager) via embedding.
migrations.go (pi: src/migrations.ts, v0.86.0)
One-time migrations that run on startup.
Location deviation: pi keeps this file at the coding-agent src root, but it needs core's keybindings migration and pig's codingagent root package cannot import core (core imports the root for GetAgentDir) — so the file lives in package core, as scoped in the P8-EH1 handoff.
Console-color deviation: pi colors these messages with chalk (green / yellow / dim); pig drops the coloring, consistent with the CLI batch (main.go prints plain diagnostics).
pi: src/core/model-config.ts — an immutable, credential-blind models.json snapshot.
Segment deviations (declared):
- pi validates with a compiled TypeBox schema and renders localized validation errors; pig hand-checks the same schema over the decoded JSON. Error message wording approximates TypeBox's (no pi test pins schema-error text; the surrounding "Failed to load/parse models.json" and "File: <path>" wrappers are verbatim and pinned by tests).
- pi deep-freezes a structuredClone of each provider entry; pig decodes into fresh structs per load (equivalent immutability by construction).
- load() is async in pi (node fs promises); pig reads synchronously.
pi: src/core/model-registry.ts — synchronous compatibility facade exposed to extensions. Coding-agent internals use ModelRuntime directly.
pi: src/core/model-resolver.ts — model resolution, scoping, and initial selection.
Segment deviations (declared):
- pi types the runtime parameter as the concrete ModelRuntime class; pig narrows it to the ModelResolverRuntime interface (the members the resolver actually consumes). ModelRuntime satisfies it once ported, and tests stub it directly.
- pi's async functions only await ModelRuntime calls; they are synchronous here apart from GetAvailable, which carries the Go context.
- localeCompare → byte-order sort (model ids are ASCII; pi's sorts are over these ids only).
- chalk coloring (red/yellow/dim console output) is dropped; messages are verbatim. The warn/fatal sinks are package vars for tests.
- findInitialModel exits the process on a CLI resolution error (pi: process.exit(1)); pig routes the exit through the modelResolverFatal var so tests can intercept.
- defaultModelPerProvider's Object.keys iteration order is insertion order in JS; pig keeps a parallel ordered key slice.
pi: src/core/model-runtime.ts — the configured pi-ai Models collection used by coding-agent and SDK consumers.
Segment deviations (declared):
- pi's getAvailable/getAuth overloads (optional providerId, string|Model) become distinct Go methods; the all-providers GetAvailable(ctx) keeps the resolver-facing signature.
- Cancellation rides the Go context (pi: options.signal on create, refresh, auth operations). ModelRuntimeAuthOverrides therefore has no signal member.
- pi's per-provider credential promise chains serialize operations and race callers against their signal; pig serializes on a per-provider mutex and runs the task on a goroutine so a cancelled caller returns immediately while the operation still holds the chain (same pattern as InMemoryAuthStorageBackend).
- configureRadiusProviders: pig has no radius provider factory yet (the radius OAuth provider is deferred with the OAuth batch, Phase 2 decision); the method rebuilds the builtin map and the radius branch is left at its position.
- prepareRequest is generic over TOptions in pi; pig normalizes to a preparedRequest and each caller assembles its own options shape.
- The snapshot and composition state are mutex-guarded (pi relies on the event loop).
pi: src/core/models-store.ts — locked JSON-backed storage for dynamically refreshed provider catalogs.
Segment deviations (declared):
- InMemoryCodingAgentModelsStore is behaviorally identical to pig/ai's InMemoryModelsStore (as pi's copy is to pi-ai's), so pig aliases the ai implementation instead of duplicating it.
- models-store.json key order: pig marshals maps with sorted keys where JSON.stringify preserves insertion order (content equivalent; no consumer observes the order through the API).
- The file lock reuses FileAuthStorageBackend (pi does the same).
pi: core/output-guard.ts — stdout takeover for JSON/RPC output modes.
Go adaptation (declared): Node swaps process.stdout.write so all writes route to stderr; pig reassigns the os.Stdout package variable (Go's fmt / os helpers resolve os.Stdout at call time) to the raw stderr file. Node's async write callbacks with ENOBUFS/EAGAIN retry have no Go equivalent — file writes are blocking — so the retry loop collapses to a direct write. The serialized write tail is kept: pig enqueues writes on a single goroutine and exposes the same backpressure/flush waits.
pi: core/package-manager.ts — the settings-driven resource-path resolution half only (resolve() minus package sources): local settings entries, pattern enable/disable, and auto-discovered resource directories. The npm/git package installation machinery (install/update/remove, semver, git clone, pi-manifest extension entry discovery) arrives with the package-manager/extension batch (Phase 7) and is declared at resolvePackageSources (absent here) / resolveExtensionEntries below — pig cannot run TS extensions before the sidecar host lands, so extension auto-discovery contributes nothing yet. The ignore machinery (pi: addIgnoreRules/prefixIgnorePattern/IGNORE_FILE_NAMES) is reused from skills.go, which ports the same pi source functions.
pi: src/core/project-trust.ts — app mode type and project trust resolution.
Segment deviations:
- The extension project_trust event branch (pi: emitProjectTrustEvent from extensions/runner.ts with LoadExtensionsResult and ProjectTrustContext) is deferred to the extensions batch — the extensions runtime does not exist yet. The options field ExtensionsResult is declared but always nil until then.
- ProjectTrustContext (pi: extensions/types.ts, carrying ui.select and hasUI) is deferred with the extensions batch; pig takes the hasUI bit as ProjectTrustHasUI. The interactive select branch runs only when that bit is set (and errors until the UI surface exists) — for the headless/print path pi also returns false here.
pi: src/core/prompt-templates.ts — coding-agent prompt template loading and argument expansion.
This is coding-agent's own prompt-template loader (pi's core/ prompt-templates.ts); the agent package has a separate harness copy, and pig mirrors that duplication.
Segment deviations:
- pi's substituteArgs uses one JS regex with a replace callback; Go's RE2 has no replace-with-groups, so the same pattern is matched with FindAllStringSubmatchIndex and spliced manually (same alternation order and semantics).
- `char === '"'` / `/\s/` char tests iterate runes with a JS-\s whitespace set (Go's unicode.IsSpace misses U+00A0/U+FEFF class members that JS \s includes).
- description first-line truncation uses rune counts (TS UTF-16 code units; established precedent).
- non-string truthy frontmatter values (pi's type lies, e.g. a number description) fall back to the derived description instead of being propagated (declared).
pi: core/provider-attribution.ts — provider attribution headers merged into every model request (openrouter/nvidia/cloudflare/opencode specifics).
pi: src/core/provider-composer.ts — compose built-in, models.json, and extension provider layers without reading credentials.
Segment deviations (declared):
- pi's ExtensionOAuthConfig.login receives OAuthLoginCallbacks with a signal member; pig's AuthInteraction carries cancellation at the interaction level, so the callbacks struct has no signal (declared).
- OAuthSelectPrompt's Promise<string | undefined> collapses to (string, error) — an empty string is "undefined" (declared).
- pi's async auth callbacks are synchronous here; cancellation rides the context where applicable.
- pi's Provider literal with optional refreshModels/fetchDeferred members becomes a struct implementing ai.Provider plus the optional ai dynamic/deferred capability interfaces.
pi: src/core/radius.ts — the Radius provider id and gateway origin helper (pi v0.86.0; consumed by the /bug report upload path). The RadiusOAuth- Credential half of pi's radius-config (gateway config sanitize/models) has no consumer in pig yet — the radius provider itself (pi-messages adapter) is deferred (see AGENTS.md Phase 2 scope); only the id + gateway URL are ported here. Declared deviation, not an omission.
pi: src/core/remote-catalog-provider.ts — a persisted pi.dev catalog overlay on top of a static built-in provider.
Segment deviations (declared):
- pi wraps providers via object spread ({...provider, getModels, refreshModels}); pig embeds the base Provider interface in a struct.
- The object-form catalog ({providerA: [...], ...}) is iterated in JSON document order via a token decoder (pi: Object.values insertion order), matching pi's merge order.
- encodeURIComponent → url.PathEscape (provider ids are simple slugs; edge-case escapes differ, no behavior pins them).
pi: src/core/resolve-config-value.ts — resolve configuration values that may be shell commands, environment variables, or literals. Used by auth-storage.ts and model-registry.ts.
Segment deviations:
- pi's getShellConfig() reads the process cwd implicitly; pig's utils.GetShellConfig takes an explicit cwd — "" is passed (no custom shell path here, so cwd is never used).
- executeWithDefaultShell: node's execSync uses /bin/sh -c on POSIX and cmd.exe on Windows; pig mirrors both branches.
- process.platform probes go through configValuePlatform (a var so tests can pin the platform like pi's Object.defineProperty mock); the getShellConfig call goes through getShellConfigForConfigValue for the same reason (pi mocks shellModule.getShellConfig).
- The command result cache is guarded by a mutex (pi relies on the JS event loop).
pi: core/resource-loader.ts — the ResourceLoader interface, restricted to the consumer surface AgentSession uses (pi: the ResourceLoader interface at the top of resource-loader.ts; the full loader implementation arrives with the resource-loader/extensions batch, see the batch plan). The getThemes/getSystemPromptSource/getAppendSystemPromptSources members are declared here so the interface shape stays visible, but return placeholder values until the theme and source-info batches land.
pi: core/resource-loader.ts — DefaultResourceLoader, the no-extension / no-package subset. The extension loading halves (loadExtensionsCached, loadExtensionFactories, clearExtensionCache, addExtensionConflictDiagnostics) arrive with the extension/sidecar batch (Phase 7) — until then extensionsResult is always the empty result and extension conflict diagnostics cannot occur (declared at loadFinalExtensionSet). Theme loading is deferred with the theme batch (Phase 6/8) — declared at updateThemesFromPaths/loadThemes. Package sources resolve only through the settings half in package_manager_paths.go (pi: resolve()'s npm/git half deferred). The override hooks and no* flags keep pi's full shape so the later batches fill in without re-shaping this struct.
pi: src/core/runtime-credentials.ts — async credential store overlay for non-persistent runtime API keys.
pi: core/sdk.ts — the programmatic entry point: createAgentSession wires model runtime, settings, resources, and the agent into one AgentSession.
pi: src/core/session-cwd.ts — stored session cwd validation.
SessionCwdSource collapses pi's inline interface; MissingSessionCwdError → error struct with the same message and an exposed Issue (pi subclasses Error).
pi: src/core/session-export.ts — write the current session branch and optional trailing export-only entries as JSONL.
pi: src/core/session-manager.ts — append-only JSONL session trees with compaction-aware context building, branching, labels, migrations, and session discovery/listing.
Deviations:
- Entry/FileEntry discriminated unions → interface + pointer concrete types + DecodeFileEntry dispatch (per §3.4). rawFileEntry preserves entries whose shape pig's typed decode rejects (pi's JSON.parse keeps arbitrary objects verbatim); they round-trip byte-for-byte but are skipped by migration and the id index (pi assigns ids to every parsed object; raw shapes cannot occur in files pi itself writes).
- AgentMessage is the open agent.AgentMessage interface. Message payloads with an unrecognized role decode into untypedMessage (raw-preserving); pi's v2→v3 hookMessage→custom role flip happens on that wrapper.
- Unknown/extra fields on typed entries are dropped on re-serialization (TS parsed objects keep them); only compaction's legacy firstKeptEntryIndex is retained, as FirstKeptEntryIndex, for the v1→v2 migration to consume and zero.
- pi throws synchronously (invalid session ids, missing entries, mkdir / write failures, non-session files) → error returns on the same methods.
- leafId: string | null on the manager maps to *string (nil = null). The package-level BuildContextEntries/BuildSessionProjection/ BuildSessionContext take *string with nil = TS undefined (fall back to the last entry); the null semantics (empty path) is internalized by the manager methods.
- SessionManager.list/listAll/buildSessionInfo are async in pi purely for fs concurrency; pig runs them synchronously with the same bounded concurrency (10) and progress callbacks. No ctx: pi has no AbortSignal.
- buildSessionInfosWithConcurrency invokes onProgress from worker goroutines; pig serializes the calls behind a mutex (pi's microtask queue serialized them implicitly). onProgress must not re-enter the SessionManager.
- Date handling: entry timestamps are ISO strings (wire format); message timestamps stay int64 milliseconds. Invalid date strings → zero time.Time (pi: Invalid Date / NaN).
- getChildren order: pi iterates Map insertion order (= file order); pig iterates fileEntries directly (same order).
- createBranchedSession's labelsToWrite order: pi iterates the insertion-ordered labelsById Map; pig derives target order from first-appearance in fileEntries (same content, stable order).
- messages.ts: the four custom message types and convertToLlm already live in agent/harness (pi re-declares them in core/messages.ts via declaration merging; pig imports the single implementation).
pi: src/core/settings-diagnostics.ts — settings load-error diagnostics.
AgentSessionRuntimeDiagnostic's canonical home is pi's agent-session-services.ts; pig declares it here ahead of that batch (the agent-session batch moves nothing — the type is consumed across settings-diagnostics and agent-session-services alike). The union "info" | "warning" | "error" collapses to a string Type field.
pi: src/core/settings-manager.ts — layered settings (global ~/.pi/agent/ settings.json + project .pi/settings.json), modified-field tracking on save, migrations, and the typed accessor surface.
Representation deviation (declared): pi's Settings is a TS interface whose runtime values are plain JSON objects; pi's own implementation manipulates them dynamically (field-name-keyed modified tracking, migrateSettings key deletes, deep merge over arbitrary JSON, unknown-field preservation on rewrite). pig therefore models Settings as a JSON object map and provides the typed surface exclusively through the SettingsManager accessors below, mirroring pi's class API 1:1. pi's Settings interface is documented field by field on Settings. Consequences:
- JSON null (a nil interface value) merges as an override; a missing key does not. pi additionally skips undefined-valued keys, which Go map literals cannot express (declared; only reachable from in-memory overrides).
- Wrong-typed values (e.g. a string where a number is expected) fall back to the default instead of propagating pi's runtime type lie.
- JSON.stringify preserves object insertion order; Go marshals maps with sorted keys — settings.json key order differs from pi (content equivalent).
- pi's writeQueue promise chain serializes async writes; pig writes synchronously under the manager mutex (same visible ordering for callers; Flush then only waits for in-flight access). Errors the promise chain would swallow are recorded via recordError the same way.
- proper-lockfile → an O_EXCL lockfile at "<path>.lock" with the same 10×20ms retry loop (pi's lockSync ELOCKED retry); release = removal. pi's `withLock(scope, fn): void` throws on failure; Go returns error.
- Setters that pi can throw from (the setProject* family and SetHttpIdleTimeoutMs) return error; the rest keep void signatures.
- PackageSource's TS string|object union → PackageSource struct with an ObjectForm marker; settings maps store the JSON-native form so deep merge / clone / rewrite stay shape-faithful.
pi: src/core/skills.ts — coding-agent skill loading (discovery rules, Agent Skills spec validation, collision handling) and prompt formatting.
This is coding-agent's own skills loader (pi's core/skills.ts); the agent package has a separate harness copy, and pig mirrors that duplication.
Segment deviations:
- npm `ignore` → github.com/sabhiram/go-gitignore (harness precedent; edge-case pattern differences beyond pi's locked tests are accepted).
- readdirSync/readdir entries → os.ReadDir + os.Stat for symlink resolution; read errors inside the scan are swallowed like pi's try/catch.
- description truncation for prompts uses rune counts (TS UTF-16 code units; established precedent).
pi: src/core/slash-commands.ts — slash command metadata.
pi: src/core/source-info.ts — resource source provenance.
The SourceInfo/SourceScope/SourceOrigin types live in codingagent/utils (the theme package needs the type and cannot import core); they are aliased here so core's public API is unchanged.
createSourceInfo now builds from PathMetadata in package_manager_paths.go (the npm/git half of package-manager.ts remains deferred).
pi: src/core/system-prompt.ts — system prompt construction and project context loading (rewritten in pi v0.86.0 to build ordered, independently replaceable prompt sections that ride the transcript's system messages).
Segment deviations:
- sections maps: pi uses plain Records (insertion order); pig uses the order-preserving ai/types.SystemSections ({Keys, Values}) so request rendering and JSONL replay stay reproducible.
- selectedTools: pi's `selectedTools ?? [...]` vs `|| [...]` — after normalization the collection-complete shape always materializes the default tool list for a nil slice; an explicit empty slice stays empty ("(none)").
- normalizeBuildSystemPromptOptions deep-copies slices/maps; pig's copies are shallow where pi's spread is shallow ({...input.x}), except toolGuidelines whose inner arrays are copied like pi's.
pi: core/telemetry.ts — install telemetry toggle (13 lines).
pi: core/timings.ts — central timing instrumentation for startup profiling. Enabled with PI_TIMING=1.
pi: src/core/trust-manager.ts — project trust decisions (store, nearest- parent lookup, trust-requiring resource detection).
Segment deviations:
- proper-lockfile → O_EXCL "<trust.json>.lock" lockfile with the same 10×20ms retry loop (settings-manager batch precedent). pi locks the trust dir with an explicit lockfilePath of `${path}.lock`; pig locks the same path directly.
- TrustFile: Record<string, boolean|null> → map[string]*bool (nil = null).
pi: src/core/usage-totals.ts — usage accumulation and cost breakdown.
Index ¶
- Constants
- Variables
- func AddUsageToTotals(totals *UsageTotals, usage types.Usage)
- func ApplyHTTPProxySettings(httpProxy string)
- func AreExperimentalFeaturesEnabled() bool
- func AssertSessionCwdExists(sessionManager SessionCwdSource, fallbackCwd string) error
- func AssertValidSessionID(id string) error
- func BugReportArchiveFileName(id string) string
- func BuildSystemPrompt(input BuildSystemPromptOptions) string
- func BuildSystemPromptSections(input BuildSystemPromptOptions) *types.SystemSections
- func BuildSystemPromptState(input BuildSystemPromptOptions) buildSystemPromptStateOutput
- func CalculateContextTokens(usage *types.Usage) int64
- func ClearConfigValueCache()
- func ClearCrashLog(path string)
- func CollectBugReportDiagnostics(sessionManager *SessionManager, crashes []CrashRecord) bugReportDiagnostics
- func CollectBugReportMetadata(options CollectBugReportMetadataOptions) bugReportMetadata
- func CompleteSummarization(ctx context.Context, model *ai.Model, llmContext *ai.Context, ...) (*types.AssistantMessage, error)
- func ComposeModelProvider(providerID string, base ai.Provider, modelConfig *ModelConfig, ...) (ai.Provider, error)
- func ComputeFileLists(fileOps *FileOperations) (readFiles []string, modifiedFiles []string)
- func DiffSystemPromptSections(previous *types.SystemSections, current *types.SystemSections) *types.SystemSections
- func EmitSessionShutdownEvent(ctx context.Context, extensionRunner *ExtensionRunner, ...) (bool, error)
- func EnabledPaths(resources []ResolvedResource) []string
- func EstimateTokens(message agent.AgentMessage) int64
- func ExpandPromptTemplate(text string, templates []PromptTemplate) string
- func ExportFromFile(inputPath string, options exporthtml.ExportOptions) (string, error)
- func ExportSessionToHtml(sm *SessionManager, state *agent.AgentState, options exporthtml.ExportOptions) (string, error)
- func ExportSessionToJsonl(sessionManager *SessionManager, outputPath string, ...) (string, error)
- func ExtractFileOpsFromMessage(message agent.AgentMessage, fileOps *FileOperations)
- func FindExactModelReferenceMatch(modelReference string, availableModels []ai.Model) (ai.Model, bool)
- func FindExtensionStackMatches(stack string, extensions []*extensionStackMetadata) []string
- func FindMostRecentSession(sessionDir string, cwd string) *string
- func FindSessionById(cwd string, id string, sessionDir string) string
- func FindTurnStartIndex(entries []SessionEntry, entryIndex int, startIndex int) int
- func FlushRawStdout()
- func FormatCacheWarmingDollars(value float64) string
- func FormatCacheWarmingStatus(status CacheWarmingStatus, now int64) string
- func FormatCacheWarmingUsage(entry *UsageEntry) string
- func FormatFileOperations(readFiles []string, modifiedFiles []string) string
- func FormatHTTPIdleTimeoutMs(timeoutMs int64) string
- func FormatMissingSessionCwdError(issue SessionCwdIssue) string
- func FormatMissingSessionCwdPrompt(issue SessionCwdIssue) string
- func FormatNoApiKeyFoundMessage(provider string) string
- func FormatNoModelSelectedMessage() string
- func FormatNoModelsAvailableMessage() string
- func FormatSkillsForPrompt(skills []Skill, fileReadTool ...string) string
- func GenerateBugReportSummary(ctx context.Context, options GenerateBugReportSummaryOptions) (string, error)
- func GenerateSummary(ctx context.Context, currentMessages []agent.AgentMessage, model *ai.Model, ...) (string, error)
- func GetCacheWarmingDelayMs(ttlMs int64) (int64, bool)
- func GetConfigValueEnvVarName(config string) (string, bool)
- func GetConfigValueEnvVarNames(config string) []string
- func GetDefaultSessionDir(cwd string, agentDir string) (string, error)
- func GetLastAssistantUsage(entries []SessionEntry) *types.Usage
- func GetMissingConfigValueEnvVarNames(config string, env map[string]string) []string
- func GetProjectTrustParentPath(cwd string) string
- func GetPromptCacheTtlMs(model *ai.Model, options *types.SimpleStreamOptions) (int64, bool)
- func GetProviderLoginHelp() string
- func GetRadiusGatewayUrl() string
- func GetSummarizationFailure(response *types.AssistantMessage, label string) string
- func HasTrustRequiringProjectResources(cwd string) bool
- func IsCommandConfigValue(config string) bool
- func IsConfigValueConfigured(config string, env map[string]string) bool
- func IsInstallTelemetryEnabled(settingsManager *SettingsManager, telemetryEnv *string) bool
- func IsReplayable(model *ai.Model, options *types.SimpleStreamOptions) bool
- func IsStdoutTakenOver() bool
- func IsValidCacheWarmingMode(mode string) bool
- func IsoToMillis(s string) int64
- func MergeProviderAttributionHeaders(model *types.Model, settingsManager *SettingsManager, sessionID string, ...) types.ProviderHeaders
- func MigrateAuthToAuthJson() []string
- func MigrateKeybindingsConfig(rawConfig map[string]any) (config map[string]any, migrated bool)
- func MigrateSessionEntries(entries []FileEntry)
- func MigrateSessionsFromAgentRoot()
- func ParseCommandArgs(argsString string) []string
- func ParseHTTPIdleTimeoutMs(value any) (int64, bool)
- func PrintTimings()
- func ReadStoredCredential(providerID string, authPath string) auth.Credential
- func RedactJsonValue(value any) any
- func RedactUrl(value string) string
- func ResetTimings(namespace TimingLabel)
- func ResolveConfigValue(config string, env map[string]string) (string, bool)
- func ResolveConfigValueOrThrow(config string, description string, env map[string]string) (string, error)
- func ResolveConfigValueUncached(config string, env map[string]string) (string, bool)
- func ResolveConfiguredModelHeaders(model ai.Model, config *ModelsJsonProvider, extension *ProviderConfigInput, ...) (map[string]string, error)
- func ResolveHeaders(headers map[string]string, env map[string]string) (map[string]string, bool)
- func ResolveHeadersOrThrow(headers map[string]string, description string, env map[string]string) (map[string]string, error)
- func ResolveProjectTrusted(options ResolveProjectTrustedOptions) (bool, error)
- func RestoreModelFromSession(savedProvider, savedModelID string, currentModel *ai.Model, ...) (*ai.Model, string)
- func RestoreStdout()
- func SerializeConversation(messages []types.Message) string
- func SerializeSessionBranch(sessionManager *SessionManager, createTrailingEntries TrailingEntries) (string, error)
- func SessionEntryToContextMessages(entry SessionEntry) []agent.AgentMessage
- func ShouldCompact(contextTokens int64, contextWindow int64, settings CompactionSettingsValues) bool
- func ShowDeprecationWarnings(warnings []string)
- func SubstituteArgs(content string, args []string) string
- func TakeOverStdout()
- func Time(label string, namespace TimingLabel)
- func UploadBugReport(ctx context.Context, bundle *BugReportBundle, options UploadBugReportOptions) (string, error)
- func UseWindowsKeybindings(platform string, env func(key string) (string, bool)) bool
- func ValidateExtensionProvider(providerID string, base ai.Provider, modelsConfig *ModelsJsonProvider, ...) error
- func WaitForRawStdoutBackpressure()
- func WithLock[T any](ctx context.Context, backend AuthStorageBackend, ...) (T, error)
- func WithLockAsync[T any](ctx context.Context, backend AuthStorageBackend, ...) (T, error)
- func WithRemoteCatalog(provider ai.Provider, catalogBaseURL string, localGeneratedAt *int64) ai.Provider
- func WrapRegisteredTool(registeredTool RegisteredTool, runner *ExtensionRunner) agent.AgentTool
- func WrapRegisteredTools(registeredTools []RegisteredTool, runner *ExtensionRunner) []agent.AgentTool
- func WriteBugReportArchive(bundle *BugReportBundle, filePath string) error
- func WriteRawStdout(text string)
- type AfterProviderResponseEvent
- type AgentActivityOutcome
- type AgentBeforeSettleEvent
- type AgentBeforeSettleEventResult
- type AgentEndEvent
- type AgentSession
- func (s *AgentSession) Abort(ctx context.Context) error
- func (s *AgentSession) AbortBash()
- func (s *AgentSession) AbortBranchSummary()
- func (s *AgentSession) AbortCompaction()
- func (s *AgentSession) AbortRetry()
- func (s *AgentSession) AutoCompactionEnabled() bool
- func (s *AgentSession) AutoRetryEnabled() bool
- func (s *AgentSession) BindExtensions(ctx context.Context, bindings *ExtensionBindings) error
- func (s *AgentSession) CacheWarmingStatus() (CacheWarmingStatus, bool)
- func (s *AgentSession) ClearQueue() (steering []string, followUp []string)
- func (s *AgentSession) Compact(ctx context.Context, customInstructions string) (*CompactionResult, error)
- func (s *AgentSession) CreateReplacedSessionContext() *ReplacedSessionContext
- func (s *AgentSession) CycleModel(ctx context.Context, direction string, options *ModelMutationOptions) (*ModelCycleResult, error)
- func (s *AgentSession) CycleThinkingLevel(options *ModelMutationOptions) agent.ThinkingLevel
- func (s *AgentSession) Dispose()
- func (s *AgentSession) ExecuteBash(ctx context.Context, command string, onChunk func(chunk string), ...) (BashResult, error)
- func (s *AgentSession) ExportToHtml(outputPath string, themeName string) (string, error)
- func (s *AgentSession) ExportToJsonl(outputPath string) (string, error)
- func (s *AgentSession) FollowUp(ctx context.Context, text string, images []types.ImageContent, ...) error
- func (s *AgentSession) FollowUpMode() agent.QueueMode
- func (s *AgentSession) GetActiveToolNames() []string
- func (s *AgentSession) GetAllTools() []ToolInfo
- func (s *AgentSession) GetAvailableThinkingLevels() []agent.ThinkingLevel
- func (s *AgentSession) GetContextUsage() *ContextUsage
- func (s *AgentSession) GetExtensionRunner() *ExtensionRunner
- func (s *AgentSession) GetFollowUpMessages() []string
- func (s *AgentSession) GetLastAssistantText() string
- func (s *AgentSession) GetModelRuntime() *ModelRuntime
- func (s *AgentSession) GetResourceLoader() ResourceLoader
- func (s *AgentSession) GetSessionStats() SessionStats
- func (s *AgentSession) GetSteeringMessages() []string
- func (s *AgentSession) GetToolDefinition(name string) *tools.ToolDefinition
- func (s *AgentSession) GetUserMessagesForForking() []ForkUserMessage
- func (s *AgentSession) HasExtensionHandlers(eventType string) bool
- func (s *AgentSession) HasPendingBashMessages() bool
- func (s *AgentSession) IsBashRunning() bool
- func (s *AgentSession) IsCompacting() bool
- func (s *AgentSession) IsIdle() bool
- func (s *AgentSession) IsRetrying() bool
- func (s *AgentSession) IsStreaming() bool
- func (s *AgentSession) Messages() []agent.AgentMessage
- func (s *AgentSession) Model() *types.Model
- func (s *AgentSession) NavigateTree(ctx context.Context, targetID string, options *NavigateTreeOptions) (*NavigateTreeResult, error)
- func (s *AgentSession) PendingMessageCount() int
- func (s *AgentSession) Prompt(ctx context.Context, text string, options *PromptOptions) error
- func (s *AgentSession) PromptTemplates() []PromptTemplate
- func (s *AgentSession) RecordBashResult(command string, result BashResult, excludeFromContext bool)
- func (s *AgentSession) RefreshContext()
- func (s *AgentSession) Reload(ctx context.Context, options *ReloadOptions) error
- func (s *AgentSession) RetryAttempt() int
- func (s *AgentSession) ScopedModels() []ScopedModel
- func (s *AgentSession) SendCustomMessage(ctx context.Context, message *CustomMessagePayload, ...) error
- func (s *AgentSession) SendUserMessage(ctx context.Context, content any, options *SendUserMessageOptions) error
- func (s *AgentSession) SessionFile() string
- func (s *AgentSession) SessionID() string
- func (s *AgentSession) SessionName() (string, bool)
- func (s *AgentSession) SetActiveToolsByName(toolNames []string)
- func (s *AgentSession) SetAutoCompactionEnabled(enabled bool)
- func (s *AgentSession) SetAutoRetryEnabled(enabled bool)
- func (s *AgentSession) SetCacheWarmingMode(mode CacheWarmingMode)
- func (s *AgentSession) SetFollowUpMode(mode string)
- func (s *AgentSession) SetListenerPanicObserver(observer func(event *AgentSessionEvent, logPath string))
- func (s *AgentSession) SetModel(ctx context.Context, model *types.Model, options *ModelMutationOptions) error
- func (s *AgentSession) SetScopedModels(scopedModels []ScopedModel)
- func (s *AgentSession) SetSessionName(name string)
- func (s *AgentSession) SetSteeringMode(mode string)
- func (s *AgentSession) SetThinkingLevel(level agent.ThinkingLevel, options *ModelMutationOptions)
- func (s *AgentSession) State() *agent.AgentState
- func (s *AgentSession) Steer(ctx context.Context, text string, images []types.ImageContent, ...) error
- func (s *AgentSession) SteeringMode() agent.QueueMode
- func (s *AgentSession) Subscribe(listener AgentSessionEventListener) func()
- func (s *AgentSession) SummarizeForBugReport(ctx context.Context, options *BugReportSummaryOptions) (string, error)
- func (s *AgentSession) SupportsThinking() bool
- func (s *AgentSession) SystemPrompt() string
- func (s *AgentSession) ThinkingLevel() agent.ThinkingLevel
- func (s *AgentSession) WaitForIdle(ctx context.Context) error
- type AgentSessionConfig
- type AgentSessionEvent
- type AgentSessionEventListener
- type AgentSessionRuntime
- func (r *AgentSessionRuntime) Cwd() string
- func (r *AgentSessionRuntime) Diagnostics() []AgentSessionRuntimeDiagnostic
- func (r *AgentSessionRuntime) Dispose() error
- func (r *AgentSessionRuntime) Fork(ctx context.Context, entryID string, options *ForkOptions) (*ForkResult, error)
- func (r *AgentSessionRuntime) ImportFromJsonl(ctx context.Context, inputPath string, cwdOverride *string) (bool, error)
- func (r *AgentSessionRuntime) ModelFallbackMessage() string
- func (r *AgentSessionRuntime) NewSession(ctx context.Context, options *RuntimeNewSessionOptions) (bool, error)
- func (r *AgentSessionRuntime) Services() *AgentSessionServices
- func (r *AgentSessionRuntime) Session() *AgentSession
- func (r *AgentSessionRuntime) SetBeforeSessionInvalidate(beforeSessionInvalidate func())
- func (r *AgentSessionRuntime) SetRebindSession(rebindSession func(session *AgentSession) error)
- func (r *AgentSessionRuntime) SwitchSession(ctx context.Context, sessionPath string, options *SwitchSessionOptions) (bool, error)
- type AgentSessionRuntimeDiagnostic
- type AgentSessionServices
- type AgentSettledEvent
- type AgentStartEvent
- type AgentsFile
- type AppKeybinding
- type AppMode
- type AuthStatus
- type AuthStorage
- func AuthStorageFromStorage(storage AuthStorageBackend) *AuthStorage
- func CreateAuthStorage(authPath string) *AuthStorage
- func NewAuthStorage(storage AuthStorageBackend, authPath string) *AuthStorage
- func NewInMemoryAuthStorage(data authStorageData) *AuthStorage
- func NewInMemoryAuthStorageWithCredentials(credentials map[string]string) *AuthStorage
- func (s *AuthStorage) Delete(ctx context.Context, providerID string) error
- func (s *AuthStorage) List(ctx context.Context) ([]auth.CredentialInfo, error)
- func (s *AuthStorage) Modify(ctx context.Context, providerID string, ...) (auth.Credential, error)
- func (s *AuthStorage) Read(ctx context.Context, providerID string) (auth.Credential, error)
- func (s *AuthStorage) Reload()
- type AuthStorageBackend
- type AutocompleteProviderFactory
- type BashExecuteOptions
- type BashExecutorOptions
- type BashResult
- type BeforeAgentStartCombinedResult
- type BeforeAgentStartEvent
- type BeforeAgentStartEventResult
- type BeforeProviderHeadersEvent
- type BeforeProviderRequestEvent
- type BoundaryContextBuilder
- type BoundaryContextPreview
- type BoundaryDispatchResult
- type BoundaryResult
- type BoundaryState
- type BranchPreparation
- type BranchSummaryDetails
- type BranchSummaryEntry
- type BranchSummaryResult
- type BranchSummarySettings
- type BranchSummarySettingsValues
- type BugReportBundle
- type BugReportSessionEntryData
- type BugReportSummaryOptions
- type BuildSystemPromptOptions
- type BuiltinSlashCommand
- type CacheMiss
- type CacheWarmRequest
- type CacheWarmer
- type CacheWarmerSurface
- type CacheWarmingAction
- type CacheWarmingDecision
- type CacheWarmingDecisionEvent
- type CacheWarmingDecisionEventResult
- type CacheWarmingMode
- type CacheWarmingStatus
- type CacheWasteTotals
- type CollectBugReportMetadataOptions
- type CollectEntriesResult
- type CompactOptions
- type CompactionDetails
- type CompactionEntry
- type CompactionEntryDraft
- type CompactionModelOverride
- type CompactionPreparation
- type CompactionResult
- type CompactionSettings
- type CompactionSettingsValues
- type CompatibilityRequestConfig
- type ContextEditEntry
- type ContextEditEntryDraft
- type ContextEditReplacement
- type ContextEditableContent
- type ContextEvent
- type ContextEventResult
- type ContextFile
- type ContextUsage
- type ContextUsageEstimate
- type ContextWithSystemEvent
- type CrashRecord
- type CrashRecordInput
- type CrashRecordKind
- type CreateAgentSessionFromServicesOptions
- type CreateAgentSessionOptions
- type CreateAgentSessionResult
- type CreateAgentSessionRuntimeFactory
- type CreateAgentSessionRuntimeFactoryOptions
- type CreateAgentSessionRuntimeResult
- type CreateAgentSessionServicesOptions
- type CreateModelRuntimeOptions
- type CredentialSynchronizationError
- type CredentialSynchronizationOperation
- type CustomEntry
- type CustomEntryDraft
- type CustomMessageEntry
- type CustomMessageEntryDraft
- type CustomMessagePayload
- type CutPointResult
- type DefaultProjectTrust
- type DefaultResourceLoader
- func (l *DefaultResourceLoader) ExtendResources(paths ResourceExtensionPaths)
- func (l *DefaultResourceLoader) GetAgentsFiles() []AgentsFile
- func (l *DefaultResourceLoader) GetAppendSystemPrompt() []string
- func (l *DefaultResourceLoader) GetAppendSystemPromptSources() []string
- func (l *DefaultResourceLoader) GetExtensions() *LoadExtensionsResult
- func (l *DefaultResourceLoader) GetPrompts() ([]PromptTemplate, []ResourceDiagnostic)
- func (l *DefaultResourceLoader) GetSkills() ([]Skill, []ResourceDiagnostic)
- func (l *DefaultResourceLoader) GetSystemPrompt() (string, bool)
- func (l *DefaultResourceLoader) GetSystemPromptSource() (string, bool)
- func (l *DefaultResourceLoader) GetThemes() ([]any, []ResourceDiagnostic)
- func (l *DefaultResourceLoader) Reload(options *ResourceLoaderReloadOptions) error
- type DefaultResourceLoaderOptions
- type EditorFactory
- type EntryBase
- type EntryRenderOptions
- type EntryRenderer
- type EventBus
- type EventBusController
- type Extension
- type ExtensionActions
- type ExtensionBindings
- type ExtensionCommandContext
- type ExtensionCommandContextActions
- type ExtensionContext
- type ExtensionContextActions
- type ExtensionCustomFactory
- type ExtensionCustomOptions
- type ExtensionError
- type ExtensionErrorListener
- type ExtensionEvent
- type ExtensionFlag
- type ExtensionFooterFactory
- type ExtensionHandler
- type ExtensionHeaderFactory
- type ExtensionMode
- type ExtensionOAuthConfig
- type ExtensionProviderActions
- type ExtensionRunner
- func (r *ExtensionRunner) BindCommandContext(actions *ExtensionCommandContextActions)
- func (r *ExtensionRunner) BindCore(actions *ExtensionActions, contextActions *ExtensionContextActions, ...)
- func (r *ExtensionRunner) CreateCommandContext() *ExtensionCommandContext
- func (r *ExtensionRunner) CreateContext() ExtensionContext
- func (r *ExtensionRunner) Emit(ctx context.Context, event ExtensionEvent) (any, error)
- func (r *ExtensionRunner) EmitBeforeAgentStart(ctx context.Context, prompt string, images []types.ImageContent, ...) (*BeforeAgentStartCombinedResult, error)
- func (r *ExtensionRunner) EmitBeforeProviderHeaders(ctx context.Context, headers types.ProviderHeaders) types.ProviderHeaders
- func (r *ExtensionRunner) EmitBeforeProviderRequest(ctx context.Context, payload any) any
- func (r *ExtensionRunner) EmitBoundary(ctx context.Context, baseEvent ExtensionEvent, ...) (BoundaryDispatchResult, error)
- func (r *ExtensionRunner) EmitCacheWarmingDecision(ctx context.Context, event *CacheWarmingDecisionEvent) CacheWarmingAction
- func (r *ExtensionRunner) EmitContext(ctx context.Context, messages []agent.AgentMessage) []agent.AgentMessage
- func (r *ExtensionRunner) EmitError(err ExtensionError)
- func (r *ExtensionRunner) EmitInput(ctx context.Context, text string, images []types.ImageContent, ...) (*InputEventResult, error)
- func (r *ExtensionRunner) EmitMessageEnd(ctx context.Context, event *MessageEndEvent) (agent.AgentMessage, error)
- func (r *ExtensionRunner) EmitResourcesDiscover(ctx context.Context, cwd string, reason string) (*ResourcesDiscoverResult, error)
- func (r *ExtensionRunner) EmitToolCall(ctx context.Context, event *ToolCallEvent) (*ToolCallEventResult, error)
- func (r *ExtensionRunner) EmitToolResult(ctx context.Context, event *ToolResultEvent) (*ToolResultEventResult, error)
- func (r *ExtensionRunner) EmitUserBash(ctx context.Context, event *UserBashEvent) (*UserBashEventResult, error)
- func (r *ExtensionRunner) GetActiveTools() []string
- func (r *ExtensionRunner) GetAllRegisteredTools() []RegisteredTool
- func (r *ExtensionRunner) GetCommand(name string) *ResolvedCommand
- func (r *ExtensionRunner) GetCommandDiagnostics() []ResourceDiagnostic
- func (r *ExtensionRunner) GetEntryRenderer(customType string) EntryRenderer
- func (r *ExtensionRunner) GetExtensionPaths() []string
- func (r *ExtensionRunner) GetFlagValues() map[string]any
- func (r *ExtensionRunner) GetMessageRenderer(customType string) MessageRenderer
- func (r *ExtensionRunner) GetModelRegistry() *ModelRegistry
- func (r *ExtensionRunner) GetRegisteredCommands() []ResolvedCommand
- func (r *ExtensionRunner) GetShortcutDiagnostics() []ResourceDiagnostic
- func (r *ExtensionRunner) GetShortcuts(resolvedKeybindings tui.KeybindingsConfig) map[tui.KeyId]*ExtensionShortcut
- func (r *ExtensionRunner) HasHandlers(eventType string) bool
- func (r *ExtensionRunner) HasUI() bool
- func (r *ExtensionRunner) Invalidate(message string)
- func (r *ExtensionRunner) OnError(listener ExtensionErrorListener) func()
- func (r *ExtensionRunner) SetFlagValue(name string, value any)
- func (r *ExtensionRunner) SetUIContext(uiContext ExtensionUIContext, mode ExtensionMode)
- func (r *ExtensionRunner) Shutdown()
- type ExtensionRunnerRef
- type ExtensionRuntime
- type ExtensionShortcut
- type ExtensionThemeInfo
- type ExtensionUIContext
- type ExtensionUIDialogOptions
- type ExtensionWidgetFactory
- type ExtensionWidgetOptions
- type FileAuthStorageBackend
- type FileEntry
- type FileModelsStore
- type FileOperations
- type FileSettingsStorage
- type FindInitialModelOptions
- type FooterDataProvider
- func (p *FooterDataProvider) ClearExtensionStatuses()
- func (p *FooterDataProvider) Dispose()
- func (p *FooterDataProvider) GetAvailableProviderCount() int
- func (p *FooterDataProvider) GetExtensionStatuses() map[string]string
- func (p *FooterDataProvider) GetGitBranch() *string
- func (p *FooterDataProvider) OnBranchChange(callback func()) func()
- func (p *FooterDataProvider) SetAvailableProviderCount(count int)
- func (p *FooterDataProvider) SetCwd(cwd string)
- func (p *FooterDataProvider) SetExtensionStatus(key string, text *string)
- type ForkCommandOptions
- type ForkOptions
- type ForkResult
- type ForkUserMessage
- type FullscreenExitOutput
- type GenerateBranchSummaryOptions
- type GenerateBugReportSummaryOptions
- type GitPaths
- type HTTPIdleTimeoutChoice
- type ImageSettings
- type InMemoryAuthStorageBackend
- type InMemoryCodingAgentModelsStore
- type InMemorySettingsStorage
- type InitialModelResult
- type InputEvent
- type InputEventResult
- type InputSource
- type KeybindingsManager
- type LabelEntry
- type LoadExtensionError
- type LoadExtensionsResult
- type LoadPromptTemplatesOptions
- type LoadPromptTemplatesResult
- type LoadSkillsFromDirOptions
- type LoadSkillsOptions
- type LoadSkillsResult
- type LockFunction
- type MarkdownSettings
- type MarkdownTransformContext
- type MarkdownTransformer
- type MermaidRenderingMode
- type MessageEndEvent
- type MessageEndEventResult
- type MessageRenderOptions
- type MessageRenderer
- type MessageStartEvent
- type MessageUpdateEvent
- type MissingSessionCwdError
- type ModelChangeEntry
- type ModelConfig
- type ModelCycleResult
- type ModelMutationOptions
- type ModelPriceSource
- type ModelPriceSourceFunc
- type ModelRegistry
- func (r *ModelRegistry) Complete(ctx context.Context, model *ai.Model, llmContext *ai.Context, ...) (*ai.AssistantMessage, error)
- func (r *ModelRegistry) Find(provider, modelID string) *ai.Model
- func (r *ModelRegistry) GetAll() []ai.Model
- func (r *ModelRegistry) GetApiKeyAndHeaders(ctx context.Context, model ai.Model) ResolvedRequestAuth
- func (r *ModelRegistry) GetApiKeyForProvider(ctx context.Context, provider string) string
- func (r *ModelRegistry) GetAvailable() []ai.Model
- func (r *ModelRegistry) GetError() string
- func (r *ModelRegistry) GetProvider(provider string) ai.Provider
- func (r *ModelRegistry) GetProviderAuth(ctx context.Context, provider string) (*auth.AuthResult, error)
- func (r *ModelRegistry) GetProviderAuthStatus(provider string) AuthStatus
- func (r *ModelRegistry) GetProviderDisplayName(provider string) string
- func (r *ModelRegistry) GetRegisteredNativeProvider(providerName string) ai.Provider
- func (r *ModelRegistry) GetRegisteredProviderConfig(providerName string) *ProviderConfigInput
- func (r *ModelRegistry) GetRegisteredProviderIds() []string
- func (r *ModelRegistry) HasConfiguredAuth(model ai.Model) bool
- func (r *ModelRegistry) IsUsingOAuth(model ai.Model) bool
- func (r *ModelRegistry) Refresh(ctx context.Context, options *ai.ModelsRefreshOptions) ai.ModelsRefreshResult
- func (r *ModelRegistry) RegisterNativeProvider(provider ai.Provider) error
- func (r *ModelRegistry) RegisterProvider(providerName string, config *ProviderConfigInput) error
- func (r *ModelRegistry) Stream(ctx context.Context, model *ai.Model, llmContext *ai.Context, ...) *ai.AssistantMessageEventStream
- func (r *ModelRegistry) StreamSimple(ctx context.Context, model *ai.Model, llmContext *ai.Context, ...) *ai.AssistantMessageEventStream
- func (r *ModelRegistry) UnregisterProvider(providerName string)
- type ModelResolverRuntime
- type ModelRuntime
- func (r *ModelRuntime) CancelDeferred(ctx context.Context, model *ai.Model, handle *ai.DeferredHandle, ...) error
- func (r *ModelRuntime) CheckAuth(ctx context.Context, providerID string) (*auth.AuthCheck, error)
- func (r *ModelRuntime) Complete(ctx context.Context, model *ai.Model, llmContext *ai.Context, ...) (*ai.AssistantMessage, error)
- func (r *ModelRuntime) CompleteSimple(ctx context.Context, model *ai.Model, llmContext *ai.Context, ...) (*ai.AssistantMessage, error)
- func (r *ModelRuntime) FetchDeferred(ctx context.Context, model *ai.Model, handle *ai.DeferredHandle, ...) (*ai.AssistantMessage, error)
- func (r *ModelRuntime) GetAuth(ctx context.Context, providerID string, overrides *ModelRuntimeAuthOverrides) (*auth.AuthResult, error)
- func (r *ModelRuntime) GetAuthForModel(ctx context.Context, model *ai.Model, overrides *ModelRuntimeAuthOverrides) (*auth.AuthResult, error)
- func (r *ModelRuntime) GetAvailable(ctx context.Context) ([]ai.Model, error)
- func (r *ModelRuntime) GetAvailableForProvider(ctx context.Context, providerID string) ([]ai.Model, error)
- func (r *ModelRuntime) GetAvailableSnapshot() []ai.Model
- func (r *ModelRuntime) GetCompatibilityRequestConfig(model ai.Model) CompatibilityRequestConfig
- func (r *ModelRuntime) GetError() string
- func (r *ModelRuntime) GetModel(providerID, modelID string) (ai.Model, bool)
- func (r *ModelRuntime) GetModels(providerID string) []ai.Model
- func (r *ModelRuntime) GetProvider(providerID string) ai.Provider
- func (r *ModelRuntime) GetProviderAuthStatus(providerID string) AuthStatus
- func (r *ModelRuntime) GetProviders() []ai.Provider
- func (r *ModelRuntime) GetRegisteredNativeProvider(providerID string) ai.Provider
- func (r *ModelRuntime) GetRegisteredProviderConfig(providerID string) *ProviderConfigInput
- func (r *ModelRuntime) GetRegisteredProviderIds() []string
- func (r *ModelRuntime) HasConfiguredAuth(providerID string) bool
- func (r *ModelRuntime) IsUsingOAuth(providerID string) bool
- func (r *ModelRuntime) IsUsingSubscription(providerID string) bool
- func (r *ModelRuntime) ListCredentials(ctx context.Context) ([]auth.CredentialInfo, error)
- func (r *ModelRuntime) Login(ctx context.Context, providerID string, authType auth.AuthType, ...) (auth.Credential, error)
- func (r *ModelRuntime) Logout(ctx context.Context, providerID string) error
- func (r *ModelRuntime) Refresh(ctx context.Context, options *ai.ModelsRefreshOptions) ai.ModelsRefreshResult
- func (r *ModelRuntime) RegisterNativeProvider(provider ai.Provider) error
- func (r *ModelRuntime) RegisterProvider(providerID string, config *ProviderConfigInput) error
- func (r *ModelRuntime) RemoveRuntimeApiKey(ctx context.Context, providerID string) error
- func (r *ModelRuntime) SetRuntimeApiKey(ctx context.Context, providerID string, apiKey string) error
- func (r *ModelRuntime) Stream(ctx context.Context, model *ai.Model, llmContext *ai.Context, ...) *ai.AssistantMessageEventStream
- func (r *ModelRuntime) StreamDeferred(ctx context.Context, model *ai.Model, handle *ai.DeferredHandle, ...) *ai.AssistantMessageEventStream
- func (r *ModelRuntime) StreamSimple(ctx context.Context, model *ai.Model, llmContext *ai.Context, ...) *ai.AssistantMessageEventStream
- func (r *ModelRuntime) UnregisterProvider(providerID string)
- type ModelRuntimeAuthOverrides
- type ModelRuntimeRequestOptions
- type ModelScopeDiagnostic
- type ModelSelectEvent
- type ModelSelectSource
- type ModelsJsonChatTemplateKwarg
- type ModelsJsonChatTemplateKwargVariable
- type ModelsJsonCost
- type ModelsJsonCostTier
- type ModelsJsonImageLimits
- type ModelsJsonImageResize
- type ModelsJsonInputLimits
- type ModelsJsonModel
- type ModelsJsonModelOverride
- type ModelsJsonOpenRouterRouting
- type ModelsJsonOverrideCost
- type ModelsJsonPercentileCutoffs
- type ModelsJsonPromptCache
- type ModelsJsonProvider
- type ModelsJsonThinkingLevelMap
- type ModelsJsonVercelGatewayRouting
- type NavigateTreeCommandOptions
- type NavigateTreeOptions
- type NavigateTreeResult
- type NewSessionCommandOptions
- type NewSessionOptions
- type NormalizedBuildSystemPromptOptions
- type PackageSource
- type ParseModelPatternOptions
- type ParsedModelResult
- type ParsedSkillBlock
- type PathMetadata
- type ProjectTrustContext
- type ProjectTrustDecision
- type ProjectTrustOption
- type ProjectTrustSetting
- type ProjectTrustStore
- func (s *ProjectTrustStore) Get(cwd string) (ProjectTrustDecision, error)
- func (s *ProjectTrustStore) GetEntry(cwd string) (*ProjectTrustStoreEntry, error)
- func (s *ProjectTrustStore) Set(cwd string, decision ProjectTrustDecision) error
- func (s *ProjectTrustStore) SetMany(decisions []ProjectTrustUpdate) error
- type ProjectTrustStoreEntry
- type ProjectTrustUI
- type ProjectTrustUpdate
- type ProjectedSessionEntry
- type PromptLoaderResult
- type PromptOptions
- type PromptTemplate
- type ProviderConfig
- type ProviderConfigInput
- type ProviderConfigInputModel
- type ProviderModelConfig
- type ProviderRetrySettings
- type ProviderRetrySettingsValues
- type QueueUserInputOptions
- type ReadOnlyAuthStorage
- func (s *ReadOnlyAuthStorage) Delete(ctx context.Context, providerID string) error
- func (s *ReadOnlyAuthStorage) List(ctx context.Context) ([]auth.CredentialInfo, error)
- func (s *ReadOnlyAuthStorage) Modify(ctx context.Context, providerID string, ...) (auth.Credential, error)
- func (s *ReadOnlyAuthStorage) Read(ctx context.Context, providerID string) (auth.Credential, error)
- type ReadonlyFooterDataProvider
- type ReadonlySessionManager
- type RegisteredCommand
- type RegisteredTool
- type ReloadOptions
- type ReplacedSessionContext
- type ResolveCliModelOptions
- type ResolveCliModelResult
- type ResolveModelScopeResult
- type ResolveProjectTrustedOptions
- type ResolvedCommand
- type ResolvedPaths
- type ResolvedRequestAuth
- type ResolvedResource
- type ResourceCollision
- type ResourceDiagnostic
- type ResourceExtensionPath
- type ResourceExtensionPathMetadata
- type ResourceExtensionPaths
- type ResourceLoader
- type ResourceLoaderReloadOptions
- type ResourceType
- type ResourcesDiscoverEvent
- type ResourcesDiscoverResult
- type RetrySettings
- type RetrySettingsValues
- type RunMigrationsResult
- type RuntimeCredentials
- func (c *RuntimeCredentials) Delete(ctx context.Context, providerID string) error
- func (c *RuntimeCredentials) HasRuntimeApiKey(providerID string) bool
- func (c *RuntimeCredentials) List(ctx context.Context) ([]auth.CredentialInfo, error)
- func (c *RuntimeCredentials) Modify(ctx context.Context, providerID string, ...) (auth.Credential, error)
- func (c *RuntimeCredentials) Read(ctx context.Context, providerID string) (auth.Credential, error)
- func (c *RuntimeCredentials) RemoveRuntimeApiKey(providerID string)
- func (c *RuntimeCredentials) SetRuntimeApiKey(providerID string, apiKey string)
- type RuntimeNewSessionOptions
- type ScopedModel
- type ScrollViewScrollbar
- type SendMessageOptions
- type SendUserMessageOptions
- type SessionBeforeCompactEvent
- type SessionBeforeCompactResult
- type SessionBeforeForkEvent
- type SessionBeforeForkResult
- type SessionBeforeSwitchEvent
- type SessionBeforeSwitchResult
- type SessionBeforeTreeEvent
- type SessionBeforeTreeResult
- type SessionBeforeTreeSummary
- type SessionBoundaryDraft
- type SessionCompactEvent
- type SessionCompactFailedEvent
- type SessionContext
- type SessionCwdIssue
- type SessionCwdSource
- type SessionEntry
- type SessionHeader
- type SessionHeaderScanLimitError
- type SessionImportFileNotFoundError
- type SessionInfo
- type SessionInfoChangedEvent
- type SessionInfoEntry
- type SessionListProgress
- type SessionManager
- func ContinueRecentSession(cwd string, sessionDir string) (*SessionManager, error)
- func CreateSessionManager(cwd string, sessionDir string, options *NewSessionOptions) (*SessionManager, error)
- func ForkSession(sourcePath string, targetCwd string, sessionDir string, ...) (*SessionManager, error)
- func InMemorySession(cwd string, options *NewSessionOptions, entries ...[]FileEntry) (*SessionManager, error)
- func OpenSession(path string, sessionDir string, cwdOverride *string) (*SessionManager, error)
- func (m *SessionManager) AppendCompaction(summary string, firstKeptEntryID *string, tokensBefore int64, details any, ...) (string, error)
- func (m *SessionManager) AppendContextEdit(targetID string, replacement *ContextEditReplacement) (string, error)
- func (m *SessionManager) AppendCustomEntry(customType string, data any) (string, error)
- func (m *SessionManager) AppendCustomMessageEntry(customType string, content any, display bool, details any) (string, error)
- func (m *SessionManager) AppendLabelChange(targetID string, label *string) (string, error)
- func (m *SessionManager) AppendMessage(message agent.AgentMessage) (string, error)
- func (m *SessionManager) AppendModelChange(provider string, modelID string) (string, error)
- func (m *SessionManager) AppendSessionInfo(name string) (string, error)
- func (m *SessionManager) AppendThinkingLevelChange(thinkingLevel string) (string, error)
- func (m *SessionManager) AppendUsage(kind string, provider string, model string, usage *types.Usage, note string) (*UsageEntry, error)
- func (m *SessionManager) Branch(branchFromID string) error
- func (m *SessionManager) BranchWithSummary(branchFromID string, summary string, details any, fromHook *bool, ...) (string, error)
- func (m *SessionManager) BuildContextEntries() []SessionEntry
- func (m *SessionManager) BuildSessionContext() SessionContext
- func (m *SessionManager) BuildSessionProjection() SessionProjection
- func (m *SessionManager) CreateBranchedSession(leafID string) (string, error)
- func (m *SessionManager) GetBranch(fromID string) []SessionEntry
- func (m *SessionManager) GetChildren(parentID string) []SessionEntry
- func (m *SessionManager) GetCwd() string
- func (m *SessionManager) GetEntries() []SessionEntry
- func (m *SessionManager) GetEntry(id string) SessionEntry
- func (m *SessionManager) GetHeader() *SessionHeader
- func (m *SessionManager) GetLabel(id string) (string, bool)
- func (m *SessionManager) GetLeafEntry() SessionEntry
- func (m *SessionManager) GetLeafID() *string
- func (m *SessionManager) GetSessionDir() string
- func (m *SessionManager) GetSessionFile() string
- func (m *SessionManager) GetSessionID() string
- func (m *SessionManager) GetSessionName() (string, bool)
- func (m *SessionManager) GetTree() []*SessionTreeNode
- func (m *SessionManager) IsPersisted() bool
- func (m *SessionManager) NewSession(options *NewSessionOptions) (string, error)
- func (m *SessionManager) ResetLeaf()
- func (m *SessionManager) SetSessionFile(sessionFile string) error
- func (m *SessionManager) UsesDefaultSessionDir() bool
- type SessionMessageEntry
- type SessionModelRef
- type SessionProjection
- type SessionShutdownEvent
- type SessionStartEvent
- type SessionStats
- type SessionTreeEvent
- type SessionTreeNode
- type Settings
- type SettingsError
- type SettingsManager
- func CreateSettingsManager(cwd string, agentDir string, options *SettingsManagerCreateOptions) *SettingsManager
- func InMemorySettingsManager(settings Settings, options *SettingsManagerCreateOptions) *SettingsManager
- func SettingsManagerFromStorage(storage SettingsStorage, options *SettingsManagerCreateOptions) *SettingsManager
- func (m *SettingsManager) ApplyOverrides(overrides Settings)
- func (m *SettingsManager) DrainErrors() []SettingsError
- func (m *SettingsManager) Flush()
- func (m *SettingsManager) GetAllModelThinkingLevels() map[string]agent.ThinkingLevel
- func (m *SettingsManager) GetAutocompleteMaxVisible() int64
- func (m *SettingsManager) GetBlockImages() bool
- func (m *SettingsManager) GetBranchSummarySettings() BranchSummarySettingsValues
- func (m *SettingsManager) GetBranchSummarySkipPrompt() bool
- func (m *SettingsManager) GetCJKSegmenter() string
- func (m *SettingsManager) GetCacheWarmingMode() CacheWarmingMode
- func (m *SettingsManager) GetClearOnShrink() bool
- func (m *SettingsManager) GetCodeBlockIndent() string
- func (m *SettingsManager) GetCollapseChangelog() bool
- func (m *SettingsManager) GetCompactionEnabled() bool
- func (m *SettingsManager) GetCompactionKeepRecentTokens(model *types.Model) (int64, error)
- func (m *SettingsManager) GetCompactionReserveTokens(model *types.Model) (int64, error)
- func (m *SettingsManager) GetCompactionSettings(model *types.Model) (CompactionSettingsValues, error)
- func (m *SettingsManager) GetDefaultModel() (string, bool)
- func (m *SettingsManager) GetDefaultProjectTrust() DefaultProjectTrust
- func (m *SettingsManager) GetDefaultProvider() (string, bool)
- func (m *SettingsManager) GetDefaultThinkingLevel() (agent.ThinkingLevel, bool)
- func (m *SettingsManager) GetDefaultTools() ([]string, bool)
- func (m *SettingsManager) GetDoubleEscapeAction() string
- func (m *SettingsManager) GetEditorPaddingX() int64
- func (m *SettingsManager) GetEnableAnalytics() bool
- func (m *SettingsManager) GetEnableInstallTelemetry() bool
- func (m *SettingsManager) GetEnableSkillCommands() bool
- func (m *SettingsManager) GetEnabledModels() ([]string, bool)
- func (m *SettingsManager) GetExtensionPaths() []string
- func (m *SettingsManager) GetExternalEditorCommand() string
- func (m *SettingsManager) GetFollowUpMode() string
- func (m *SettingsManager) GetFullscreenCopyOnSelect() bool
- func (m *SettingsManager) GetFullscreenExitOutput() FullscreenExitOutput
- func (m *SettingsManager) GetFullscreenScrollbar() ScrollViewScrollbar
- func (m *SettingsManager) GetGlobalSettings() Settings
- func (m *SettingsManager) GetHTTPIdleTimeoutMs() (int64, error)
- func (m *SettingsManager) GetHideThinkingBlock() bool
- func (m *SettingsManager) GetImageAutoResize() bool
- func (m *SettingsManager) GetImageWidthCells() int64
- func (m *SettingsManager) GetLastChangelogVersion() (string, bool)
- func (m *SettingsManager) GetMermaidRenderingMode() MermaidRenderingMode
- func (m *SettingsManager) GetModelThinkingLevel(provider string, modelID string) (agent.ThinkingLevel, bool)
- func (m *SettingsManager) GetNpmCommand() ([]string, bool)
- func (m *SettingsManager) GetOutputPad() int
- func (m *SettingsManager) GetPackages() []PackageSource
- func (m *SettingsManager) GetProjectSettings() Settings
- func (m *SettingsManager) GetPromptTemplatePaths() []string
- func (m *SettingsManager) GetProviderRetrySettings() ProviderRetrySettingsValues
- func (m *SettingsManager) GetQuietStartup() bool
- func (m *SettingsManager) GetRetryEnabled() bool
- func (m *SettingsManager) GetRetrySettings() RetrySettingsValues
- func (m *SettingsManager) GetSessionDir() (string, bool)
- func (m *SettingsManager) GetShellCommandPrefix() (string, bool)
- func (m *SettingsManager) GetShellPath() (string, bool)
- func (m *SettingsManager) GetShowCacheMissNotices() bool
- func (m *SettingsManager) GetShowHardwareCursor() bool
- func (m *SettingsManager) GetShowImages() bool
- func (m *SettingsManager) GetShowResourceStats() bool
- func (m *SettingsManager) GetShowTerminalProgress() bool
- func (m *SettingsManager) GetSkillPaths() []string
- func (m *SettingsManager) GetSteeringMode() string
- func (m *SettingsManager) GetTerminalCapabilityOverrides() TerminalCapabilityOverrides
- func (m *SettingsManager) GetTheme() (string, bool)
- func (m *SettingsManager) GetThemePaths() []string
- func (m *SettingsManager) GetThemeSetting() (string, bool)
- func (m *SettingsManager) GetThinkingBudgets() (*ThinkingBudgetsSettings, bool)
- func (m *SettingsManager) GetTrackingId() (string, bool)
- func (m *SettingsManager) GetTransport() TransportSetting
- func (m *SettingsManager) GetTreeFilterMode() string
- func (m *SettingsManager) GetTuiMode() TuiMode
- func (m *SettingsManager) GetWarnings() WarningSettings
- func (m *SettingsManager) GetWebSocketConnectTimeoutMs() (*int64, error)
- func (m *SettingsManager) IsProjectTrusted() bool
- func (m *SettingsManager) Reload()
- func (m *SettingsManager) RemoveModelThinkingLevel(provider string, modelID string)
- func (m *SettingsManager) SetAutocompleteMaxVisible(maxVisible int64)
- func (m *SettingsManager) SetBlockImages(blocked bool)
- func (m *SettingsManager) SetCJKSegmenter(mode string)
- func (m *SettingsManager) SetCacheWarmingMode(mode CacheWarmingMode)
- func (m *SettingsManager) SetClearOnShrink(enabled bool)
- func (m *SettingsManager) SetCollapseChangelog(collapse bool)
- func (m *SettingsManager) SetCompactionEnabled(enabled bool)
- func (m *SettingsManager) SetDefaultModel(modelID string)
- func (m *SettingsManager) SetDefaultModelAndProvider(provider string, modelID string)
- func (m *SettingsManager) SetDefaultProjectTrust(defaultProjectTrust DefaultProjectTrust)
- func (m *SettingsManager) SetDefaultProvider(provider string)
- func (m *SettingsManager) SetDefaultThinkingLevel(level agent.ThinkingLevel)
- func (m *SettingsManager) SetDoubleEscapeAction(action string)
- func (m *SettingsManager) SetEditorPaddingX(padding int64)
- func (m *SettingsManager) SetEnableAnalytics(enabled bool)
- func (m *SettingsManager) SetEnableInstallTelemetry(enabled bool)
- func (m *SettingsManager) SetEnableSkillCommands(enabled bool)
- func (m *SettingsManager) SetEnabledModels(patterns []string)
- func (m *SettingsManager) SetExtensionPaths(paths []string)
- func (m *SettingsManager) SetFollowUpMode(mode string)
- func (m *SettingsManager) SetFullscreenCopyOnSelect(enabled bool)
- func (m *SettingsManager) SetFullscreenExitOutput(output FullscreenExitOutput)
- func (m *SettingsManager) SetFullscreenScrollbar(mode ScrollViewScrollbar)
- func (m *SettingsManager) SetHTTPIdleTimeoutMs(timeoutMs float64) error
- func (m *SettingsManager) SetHideThinkingBlock(hide bool)
- func (m *SettingsManager) SetImageAutoResize(enabled bool)
- func (m *SettingsManager) SetImageWidthCells(width int64)
- func (m *SettingsManager) SetLastChangelogVersion(version string)
- func (m *SettingsManager) SetMermaidRenderingMode(mode MermaidRenderingMode)
- func (m *SettingsManager) SetModelThinkingLevel(provider string, modelID string, level agent.ThinkingLevel)
- func (m *SettingsManager) SetNpmCommand(command []string)
- func (m *SettingsManager) SetOutputPad(padding int)
- func (m *SettingsManager) SetPackages(packages []PackageSource)
- func (m *SettingsManager) SetProjectExtensionPaths(paths []string) error
- func (m *SettingsManager) SetProjectPackages(packages []PackageSource) error
- func (m *SettingsManager) SetProjectPromptTemplatePaths(paths []string) error
- func (m *SettingsManager) SetProjectSkillPaths(paths []string) error
- func (m *SettingsManager) SetProjectThemePaths(paths []string) error
- func (m *SettingsManager) SetProjectTrusted(trusted bool)
- func (m *SettingsManager) SetPromptTemplatePaths(paths []string)
- func (m *SettingsManager) SetQuietStartup(quiet bool)
- func (m *SettingsManager) SetRetryEnabled(enabled bool)
- func (m *SettingsManager) SetShellCommandPrefix(prefix string)
- func (m *SettingsManager) SetShellPath(path string)
- func (m *SettingsManager) SetShowCacheMissNotices(show bool)
- func (m *SettingsManager) SetShowHardwareCursor(enabled bool)
- func (m *SettingsManager) SetShowImages(show bool)
- func (m *SettingsManager) SetShowResourceStats(show bool)
- func (m *SettingsManager) SetShowTerminalProgress(enabled bool)
- func (m *SettingsManager) SetSkillPaths(paths []string)
- func (m *SettingsManager) SetSteeringMode(mode string)
- func (m *SettingsManager) SetTheme(theme string)
- func (m *SettingsManager) SetThemePaths(paths []string)
- func (m *SettingsManager) SetTransport(transport TransportSetting)
- func (m *SettingsManager) SetTreeFilterMode(mode string)
- func (m *SettingsManager) SetTuiMode(mode TuiMode)
- func (m *SettingsManager) SetWarnings(warnings WarningSettings)
- type SettingsManagerCreateOptions
- type SettingsScope
- type SettingsStorage
- type ShutdownHandler
- type Skill
- type SkillDiscoveryMode
- type SkillFrontmatter
- type SlashCommandInfo
- type SlashCommandSource
- type SourceInfo
- type SourceOrigin
- type SourceScope
- type SummaryWithUsage
- type SwitchSessionCommandOptions
- type SwitchSessionOptions
- type SyntheticSourceInfoOptions
- type TerminalCapabilityOverrides
- type TerminalInputHandler
- type TerminalInputResult
- type TerminalSettings
- type ThemeLoaderResult
- type ThemeSetResult
- type ThinkingBudgetsSettings
- type ThinkingLevelChangeEntry
- type ThinkingLevelSelectEvent
- type TimingLabel
- type ToolCallEvent
- type ToolCallEventResult
- type ToolExecutionEndEvent
- type ToolExecutionStartEvent
- type ToolExecutionUpdateEvent
- type ToolInfo
- type ToolRenderContext
- type ToolRenderResultOptions
- type ToolResultEvent
- type ToolResultEventResult
- type TrailingEntries
- type TransportSetting
- type TreePreparation
- type TuiMode
- type TurnEndEvent
- type TurnEndEventResult
- type TurnStartEvent
- type UIPromptEndEvent
- type UIPromptKind
- type UIPromptStartEvent
- type UITheme
- type UploadBugReportOptions
- type UsageCostBreakdownEntry
- type UsageEntry
- type UsageTotals
- type UserBashEvent
- type UserBashEventResult
- type WarningSettings
- type WorkingIndicatorOptions
Constants ¶
const ( AgentSessionEventAgentSettled agent.AgentEventType = "agent_settled" AgentSessionEventQueueUpdate agent.AgentEventType = "queue_update" AgentSessionEventCompactionStart agent.AgentEventType = "compaction_start" AgentSessionEventEntryAppended agent.AgentEventType = "entry_appended" AgentSessionEventSessionInfoChanged agent.AgentEventType = "session_info_changed" AgentSessionEventThinkingLevelChanged agent.AgentEventType = "thinking_level_changed" AgentSessionEventCompactionEnd agent.AgentEventType = "compaction_end" AgentSessionEventAutoRetryStart agent.AgentEventType = "auto_retry_start" AgentSessionEventAutoRetryEnd agent.AgentEventType = "auto_retry_end" AgentSessionEventSummarizationRetryScheduled agent.AgentEventType = "summarization_retry_scheduled" AgentSessionEventSummarizationRetryAttemptStart agent.AgentEventType = "summarization_retry_attempt_start" AgentSessionEventSummarizationRetryFinished agent.AgentEventType = "summarization_retry_finished" AgentSessionEventBashExecutionUpdate agent.AgentEventType = "bash_execution_update" )
AgentSessionEventType extends the agent event vocabulary with the session-specific event types (pi: the AgentSessionEvent union members).
const ( AgentSessionRuntimeDiagnosticInfo = "info" AgentSessionRuntimeDiagnosticWarning = "warning" AgentSessionRuntimeDiagnosticError = "error" )
AgentSessionRuntimeDiagnostic is one user-facing runtime diagnostic (pi: AgentSessionRuntimeDiagnostic — canonical struct lives in settings_diagnostics.go per the settings batch's forward declaration). The Type constants are declared here, where pi defines the union.
const ( AppKeybindingInterrupt = "app.interrupt" AppKeybindingClear = "app.clear" AppKeybindingExit = "app.exit" AppKeybindingSuspend = "app.suspend" AppKeybindingThinkingCycle = "app.thinking.cycle" AppKeybindingThinkingSave = "app.thinking.save" AppKeybindingModelCycleForward = "app.model.cycleForward" AppKeybindingModelCycleBackward = "app.model.cycleBackward" AppKeybindingModelSelect = "app.model.select" AppKeybindingToolsExpand = "app.tools.expand" AppKeybindingThinkingToggle = "app.thinking.toggle" AppKeybindingSessionToggleNamedFilter = "app.session.toggleNamedFilter" AppKeybindingEditorExternal = "app.editor.external" AppKeybindingMessageCopy = "app.message.copy" AppKeybindingMessageFollowUp = "app.message.followUp" AppKeybindingMessageDequeue = "app.message.dequeue" AppKeybindingClipboardPasteImage = "app.clipboard.pasteImage" AppKeybindingSessionNew = "app.session.new" AppKeybindingSessionTree = "app.session.tree" AppKeybindingSessionFork = "app.session.fork" AppKeybindingSessionResume = "app.session.resume" AppKeybindingTreeFoldOrUp = "app.tree.foldOrUp" AppKeybindingTreeUnfoldOrDown = "app.tree.unfoldOrDown" AppKeybindingTreeEditLabel = "app.tree.editLabel" AppKeybindingTreeToggleLabelTimestamp = "app.tree.toggleLabelTimestamp" AppKeybindingSessionTogglePath = "app.session.togglePath" AppKeybindingSessionToggleSort = "app.session.toggleSort" AppKeybindingSessionRename = "app.session.rename" AppKeybindingSessionDelete = "app.session.delete" AppKeybindingSessionDeleteNoninvasive = "app.session.deleteNoninvasive" AppKeybindingModelsSave = "app.models.save" AppKeybindingModelsEnableAll = "app.models.enableAll" AppKeybindingModelsClearAll = "app.models.clearAll" AppKeybindingModelsToggleProvider = "app.models.toggleProvider" AppKeybindingModelsReorderUp = "app.models.reorderUp" AppKeybindingModelsReorderDown = "app.models.reorderDown" AppKeybindingTreeFilterDefault = "app.tree.filter.default" AppKeybindingTreeFilterNoTools = "app.tree.filter.noTools" AppKeybindingTreeFilterUserOnly = "app.tree.filter.userOnly" AppKeybindingTreeFilterLabeledOnly = "app.tree.filter.labeledOnly" AppKeybindingTreeFilterAll = "app.tree.filter.all" AppKeybindingTreeFilterCycleForward = "app.tree.filter.cycleForward" AppKeybindingTreeFilterCycleBackward = "app.tree.filter.cycleBackward" )
App keybinding ids (pi: AppKeybindings interface keys, declaration order preserved).
const ( SESSION_READ_BUFFER_SIZE = 1024 * 1024 SESSION_HEADER_READ_BUFFER_SIZE = 4096 // MAX_SESSION_HEADER_SCAN_BYTES bounds synchronous header discovery // while allowing large cwd and custom metadata fields. MAX_SESSION_HEADER_SCAN_BYTES = 1024 * 1024 )
const ( MAX_CONCURRENT_SESSION_INFO_LOADS = 10 MAX_CONCURRENT_SESSION_DISCOVERY_LOADS = 64 CURRENT_SESSION_LIST_PUBLISH_INTERVAL = 10 ALL_SESSION_LIST_PUBLISH_INTERVAL = 100 )
const ( SourceScopeUser = utils.SourceScopeUser SourceScopeProject = utils.SourceScopeProject SourceScopeTemporary = utils.SourceScopeTemporary )
Source scope values (pi: "user" | "project" | "temporary").
const ( SourceOriginPackage = utils.SourceOriginPackage SourceOriginTopLevel = utils.SourceOriginTopLevel )
Source origin values (pi: "package" | "top-level").
const BugReportCustomEntryType = "pi.bug-report"
BugReportCustomEntryType is the custom entry type recording bug report deliveries (pi: BUG_REPORT_CUSTOM_ENTRY_TYPE).
const CURRENT_SESSION_VERSION = 3
CURRENT_SESSION_VERSION is the session file format version pig writes (pi: CURRENT_SESSION_VERSION).
const CacheTtlMs = 5 * 60 * 1000
CacheTtlMs is the prompt-cache TTL: idle gaps longer than this are worth mentioning as the likely cause of a miss. Anthropic's default cache TTL is 5 minutes.
const DefaultHTTPIdleTimeoutMs = 300_000
DefaultHTTPIdleTimeoutMs is the default HTTP header/body idle timeout (pi: DEFAULT_HTTP_IDLE_TIMEOUT_MS).
const DefaultThinkingLevel = agent.ThinkingLevel("medium")
DefaultThinkingLevel is the default thinking level (pi: DEFAULT_THINKING_LEVEL).
const ENV_RADIUS_GATEWAY = "PI_RADIUS_GATEWAY"
ENV_RADIUS_GATEWAY overrides the Radius gateway origin (pi: ENV_RADIUS_GATEWAY).
const MaxDescriptionLength = 1024
MaxDescriptionLength is the max description length per spec (pi: MAX_DESCRIPTION_LENGTH).
const MaxNameLength = 64
MaxNameLength is the max name length per spec (pi: MAX_NAME_LENGTH).
const RADIUS_PROVIDER_ID = "radius"
RADIUS_PROVIDER_ID matches LLAMA-style inline provider ids (pi: RADIUS_PROVIDER_ID).
const RemoteCatalogRefreshIntervalMs = 4 * 60 * 60 * 1000
RemoteCatalogRefreshIntervalMs is how long a stored catalog stays fresh before a refresh revalidates it (pi: REMOTE_CATALOG_REFRESH_INTERVAL_MS).
const SummarizationSystemPrompt = compaction.SummarizationSystemPrompt
SummarizationSystemPrompt is the system prompt for every summarization request (pi: SUMMARIZATION_SYSTEM_PROMPT in core/compaction/utils.ts; the harness twin lives in its compaction.ts).
Variables ¶
var BuiltinSlashCommands = []BuiltinSlashCommand{ {Name: "settings", Description: "Open settings menu"}, {Name: "model", Description: "Select model (opens selector UI)", ArgumentHint: "<provider/model>"}, {Name: "tree", Description: "Navigate session tree (switch branches)"}, {Name: "thinking", Description: "Set thinking level", ArgumentHint: "<level>"}, {Name: "scoped-models", Description: "Enable/disable models for Ctrl+P cycling"}, {Name: "export", Description: "Export session (HTML default, or specify path: .html/.jsonl)"}, {Name: "import", Description: "Import and resume a session from a JSONL file"}, {Name: "share", Description: "Share session as a secret GitHub gist"}, {Name: "bug", Description: "Report a bug to the Pi developers", ArgumentHint: "<description>"}, {Name: "copy", Description: "Copy last agent message to clipboard"}, {Name: "name", Description: "Set session display name"}, {Name: "session", Description: "Show session info and stats"}, {Name: "changelog", Description: "Show changelog entries"}, {Name: "hotkeys", Description: "Show all keyboard shortcuts"}, {Name: "fork", Description: "Create a new fork from a previous user message"}, {Name: "clone", Description: "Duplicate the current session at the current position"}, {Name: "trust", Description: "Save project trust decision for future sessions"}, {Name: "login", Description: "Configure provider authentication", ArgumentHint: "<provider>"}, {Name: "logout", Description: "Remove provider authentication"}, {Name: "new", Description: "Start a new session"}, {Name: "compact", Description: "Manually compact the session context"}, {Name: "resume", Description: "Resume a different session"}, {Name: "reload", Description: "Reload keybindings, extensions, skills, prompts, themes, and context files"}, {Name: "quit", Description: "Quit " + codingagent.AppName}, }
BuiltinSlashCommands lists the built-in slash commands in declaration order (pi: BUILTIN_SLASH_COMMANDS).
var CacheWarmingModes = []CacheWarmingMode{"off", "streaming", "idle"}
CacheWarmingModes lists the valid profiles in declaration order (pi: CACHE_WARMING_MODES).
var ClearApiKeyCache = ClearConfigValueCache
ClearApiKeyCache clears the config-value resolution cache (pi: clearApiKeyCache = clearConfigValueCache).
var ClearRegistryApiKeyCache = ClearApiKeyCache
ClearRegistryApiKeyCache re-exported (pi: clearApiKeyCache re-export).
var DefaultCompactionSettings = CompactionSettingsValues{ Enabled: true, ReserveTokens: 16384, KeepRecentTokens: 20000, }
DefaultCompactionSettings are the default compaction settings (pi: DEFAULT_COMPACTION_SETTINGS).
var DefaultCompactionTokenSettings = struct { ReserveTokens int64 KeepRecentTokens int64 }{ReserveTokens: 16384, KeepRecentTokens: 20000}
DefaultCompactionTokenSettings mirrors pi's DEFAULT_COMPACTION_TOKEN_SETTINGS (v0.86.0).
var DefaultModelPerProvider = map[string]string{
"amazon-bedrock": "us.anthropic.claude-opus-4-6-v1",
"ant-ling": "Ring-2.6-1T",
"anthropic": "claude-opus-4-8",
"openai": "gpt-5.5",
"azure-openai-responses": "gpt-5.4",
"openai-codex": "gpt-5.5",
"radius": "balanced",
"nvidia": "nvidia/nemotron-3-super-120b-a12b",
"deepseek": "deepseek-v4-pro",
"google": "gemini-3.1-pro-preview",
"google-vertex": "gemini-3.1-pro-preview",
"github-copilot": "gpt-5.4",
"openrouter": "moonshotai/kimi-k2.6",
"vercel-ai-gateway": "zai/glm-5.1",
"xai": "grok-4.7",
"groq": "openai/gpt-oss-120b",
"cerebras": "gpt-oss-120b",
"zai": "glm-5.3",
"zai-coding-cn": "glm-5.3",
"mistral": "devstral-medium-latest",
"minimax": "MiniMax-M2.7",
"minimax-cn": "MiniMax-M2.7",
"moonshotai": "kimi-k2.6",
"moonshotai-cn": "kimi-k2.6",
"huggingface": "moonshotai/Kimi-K2.6",
"fireworks": "accounts/fireworks/models/kimi-k2p6",
"together": "moonshotai/Kimi-K2.6",
"baseten": "zai-org/GLM-5.2",
"opencode": "kimi-k2.6",
"opencode-go": "kimi-k2.6",
"kimi-coding": "kimi-for-coding",
"meta": "muse-spark-1.3",
"cloudflare-workers-ai": "@cf/moonshotai/kimi-k2.6",
"cloudflare-ai-gateway": "workers-ai/@cf/moonshotai/kimi-k2.6",
"qwen-token-plan": "qwen3.7-max",
"qwen-token-plan-cn": "qwen3.7-max",
"qwen-token-plan-individual": "qwen3.8-max",
"xiaomi": "mimo-v2.5-pro",
"xiaomi-token-plan-cn": "mimo-v2.5-pro",
"xiaomi-token-plan-ams": "mimo-v2.5-pro",
"xiaomi-token-plan-sgp": "mimo-v2.5-pro",
}
DefaultModelPerProvider holds the default model id for each known provider (pi: defaultModelPerProvider). DefaultModelProviderKeys preserves pi's Object.keys insertion order for the first-match loops.
var DefaultModelProviderKeys = []string{
"amazon-bedrock", "ant-ling", "anthropic", "openai", "azure-openai-responses",
"openai-codex", "radius", "nvidia", "deepseek", "google", "google-vertex",
"github-copilot", "openrouter", "vercel-ai-gateway", "xai", "groq",
"cerebras", "zai", "zai-coding-cn", "mistral", "minimax", "minimax-cn",
"moonshotai", "moonshotai-cn", "huggingface", "fireworks", "together",
"baseten", "opencode", "opencode-go", "kimi-coding", "cloudflare-workers-ai",
"cloudflare-ai-gateway", "qwen-token-plan", "qwen-token-plan-cn",
"qwen-token-plan-individual", "xiaomi", "xiaomi-token-plan-cn",
"xiaomi-token-plan-ams", "xiaomi-token-plan-sgp",
}
DefaultModelProviderKeys preserves pi's Object.keys(defaultModelPerProvider) insertion order.
var HTTPIdleTimeoutChoices = []HTTPIdleTimeoutChoice{
{Label: "30 sec", TimeoutMs: 30_000},
{Label: "1 min", TimeoutMs: 60_000},
{Label: "2 min", TimeoutMs: 120_000},
{Label: "5 min", TimeoutMs: 300_000},
{Label: "disabled", TimeoutMs: 0},
}
HTTPIdleTimeoutChoices lists the idle-timeout picker options (pi: HTTP_IDLE_TIMEOUT_CHOICES, declaration order kept).
var Keybindings = func() tui.KeybindingDefinitions { windows := useWindowsKeybindings() defs := tui.KeybindingDefinitions{} for id, def := range tui.TUIKeyBindings { defs[id] = def } defs["tui.editor.undo"] = tui.KeybindingDefinition{ DefaultKeys: func() []tui.KeyId { if runtime.GOOS == "windows" { return keys("ctrl+z") } if windows { return keys("alt+z") } return keys("ctrl+-") }(), Description: "Undo", } defs["tui.altScreen.previousPrompt"] = tui.KeybindingDefinition{ DefaultKeys: func() []tui.KeyId { if windows { return keys("ctrl+up") } return keys("ctrl+shift+up", "ctrl+up") }(), Description: "Jump to previous semantic prompt", } defs["tui.altScreen.nextPrompt"] = tui.KeybindingDefinition{ DefaultKeys: func() []tui.KeyId { if windows { return keys("ctrl+down") } return keys("ctrl+shift+down", "ctrl+down") }(), Description: "Jump to next semantic prompt", } defs["tui.altScreen.search"] = tui.KeybindingDefinition{ DefaultKeys: func() []tui.KeyId { if windows { return keys("ctrl+f") } return keys("ctrl+shift+f") }(), Description: "Search the primary scroll view", } defs["app.interrupt"] = tui.KeybindingDefinition{DefaultKeys: keys("escape"), Description: "Cancel or abort"} defs["app.clear"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+c"), Description: "Clear editor"} defs["app.exit"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+d"), Description: "Exit when editor is empty"} defs["app.suspend"] = tui.KeybindingDefinition{ DefaultKeys: func() []tui.KeyId { if runtime.GOOS == "windows" { return []tui.KeyId{} } return keys("ctrl+z") }(), Description: "Suspend to background", } defs["app.thinking.cycle"] = tui.KeybindingDefinition{DefaultKeys: keys("shift+tab"), Description: "Cycle thinking level"} defs["app.thinking.save"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+s"), Description: "Save thinking level"} defs["app.model.cycleForward"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+p"), Description: "Cycle to next model"} defs["app.model.cycleBackward"] = tui.KeybindingDefinition{ DefaultKeys: func() []tui.KeyId { if windows { return keys("alt+p") } return keys("shift+ctrl+p") }(), Description: "Cycle to previous model", } defs["app.model.select"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+l"), Description: "Open model selector"} defs["app.tools.expand"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+o"), Description: "Toggle tool output"} defs["app.thinking.toggle"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+t"), Description: "Toggle thinking blocks"} defs["app.session.toggleNamedFilter"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+n"), Description: "Toggle named session filter"} defs["app.editor.external"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+g"), Description: "Open external editor"} defs["app.message.copy"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+x"), Description: "Copy selection or last assistant message"} defs["app.message.followUp"] = tui.KeybindingDefinition{ DefaultKeys: func() []tui.KeyId { if windows { return keys("ctrl+q") } return keys("alt+enter") }(), Description: "Queue follow-up message", } defs["app.message.dequeue"] = tui.KeybindingDefinition{ DefaultKeys: func() []tui.KeyId { if windows { return keys("alt+q") } return keys("alt+up") }(), Description: "Restore queued messages", } defs["app.clipboard.pasteImage"] = tui.KeybindingDefinition{ DefaultKeys: func() []tui.KeyId { if windows { return keys("alt+v") } return keys("ctrl+v") }(), Description: "Paste image from clipboard (text fallback)", } defs["app.session.new"] = tui.KeybindingDefinition{DefaultKeys: []tui.KeyId{}, Description: "Start a new session"} defs["app.session.tree"] = tui.KeybindingDefinition{DefaultKeys: []tui.KeyId{}, Description: "Open session tree"} defs["app.session.fork"] = tui.KeybindingDefinition{DefaultKeys: []tui.KeyId{}, Description: "Fork current session"} defs["app.session.resume"] = tui.KeybindingDefinition{DefaultKeys: []tui.KeyId{}, Description: "Resume a session"} defs["app.tree.foldOrUp"] = tui.KeybindingDefinition{ DefaultKeys: func() []tui.KeyId { if runtime.GOOS == "darwin" { return keys("alt+left", "ctrl+left") } return keys("ctrl+left", "alt+left") }(), Description: "Fold tree branch or move up", } defs["app.tree.unfoldOrDown"] = tui.KeybindingDefinition{ DefaultKeys: func() []tui.KeyId { if runtime.GOOS == "darwin" { return keys("alt+right", "ctrl+right") } return keys("ctrl+right", "alt+right") }(), Description: "Unfold tree branch or move down", } defs["app.tree.editLabel"] = tui.KeybindingDefinition{DefaultKeys: keys("shift+l"), Description: "Edit tree label"} defs["app.tree.toggleLabelTimestamp"] = tui.KeybindingDefinition{DefaultKeys: keys("shift+t"), Description: "Toggle tree label timestamps"} defs["app.session.togglePath"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+p"), Description: "Toggle session path display"} defs["app.session.toggleSort"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+s"), Description: "Toggle session sort mode"} defs["app.session.rename"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+r"), Description: "Rename session"} defs["app.session.delete"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+d"), Description: "Delete session"} defs["app.session.deleteNoninvasive"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+backspace"), Description: "Delete session when query is empty"} defs["app.models.save"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+s"), Description: "Save model selection"} defs["app.models.enableAll"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+a"), Description: "Enable all models"} defs["app.models.clearAll"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+x"), Description: "Clear all models"} defs["app.models.toggleProvider"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+p"), Description: "Toggle all models for provider"} defs["app.models.reorderUp"] = tui.KeybindingDefinition{DefaultKeys: keys("alt+up"), Description: "Move model up in order"} defs["app.models.reorderDown"] = tui.KeybindingDefinition{DefaultKeys: keys("alt+down"), Description: "Move model down in order"} defs["app.tree.filter.default"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+d"), Description: "Tree filter: default view"} defs["app.tree.filter.noTools"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+t"), Description: "Tree filter: hide tool results"} defs["app.tree.filter.userOnly"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+u"), Description: "Tree filter: user messages only"} defs["app.tree.filter.labeledOnly"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+l"), Description: "Tree filter: labeled entries only"} defs["app.tree.filter.all"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+a"), Description: "Tree filter: show all entries"} defs["app.tree.filter.cycleForward"] = tui.KeybindingDefinition{DefaultKeys: keys("ctrl+o"), Description: "Tree filter: cycle forward"} defs["app.tree.filter.cycleBackward"] = tui.KeybindingDefinition{DefaultKeys: keys("shift+ctrl+o"), Description: "Tree filter: cycle backward"} return defs }()
Keybindings holds the merged default keybinding definitions (pi: KEYBINDINGS = { ...TUI_KEYBINDINGS, ...overrides, ...app } — declaration order follows pi: tui.* overrides first, then app.* in interface order).
var ThinkingLevelOptions = []agent.ThinkingLevel{
"off",
"minimal",
"low",
"medium",
"high",
"xhigh",
"max",
}
ThinkingLevelOptions lists all selectable thinking levels (pi: THINKING_LEVEL_OPTIONS, declaration order kept).
Functions ¶
func AddUsageToTotals ¶
func AddUsageToTotals(totals *UsageTotals, usage types.Usage)
AddUsageToTotals adds one usage to the totals (pi: addUsageToTotals).
func ApplyHTTPProxySettings ¶
func ApplyHTTPProxySettings(httpProxy string)
ApplyHTTPProxySettings applies the httpProxy setting as HTTP_PROXY / HTTPS_PROXY for Pi-managed HTTP clients (pi: applyHttpProxySettings). Only sets variables that are currently unset (pi's ??=).
func AreExperimentalFeaturesEnabled ¶
func AreExperimentalFeaturesEnabled() bool
AreExperimentalFeaturesEnabled reports whether experimental features are on (pi: areExperimentalFeaturesEnabled — PI_EXPERIMENTAL=1).
func AssertSessionCwdExists ¶
func AssertSessionCwdExists(sessionManager SessionCwdSource, fallbackCwd string) error
AssertSessionCwdExists errors when the stored session cwd is missing (pi: assertSessionCwdExists throws).
func AssertValidSessionID ¶
AssertValidSessionID validates a caller-provided session id (pi: assertValidSessionId; pi throws → error return).
func BugReportArchiveFileName ¶ added in v0.86.0
BugReportArchiveFileName is the export file name (pi: bugReportArchiveFileName).
func BuildSystemPrompt ¶
func BuildSystemPrompt(input BuildSystemPromptOptions) string
BuildSystemPrompt builds the system prompt text, rendered exactly as the transcript's system message replays it (pi: buildSystemPrompt).
func BuildSystemPromptSections ¶ added in v0.86.0
func BuildSystemPromptSections(input BuildSystemPromptOptions) *types.SystemSections
BuildSystemPromptSections builds the ordered, independently replaceable sections of the structured system prompt (pi: buildSystemPromptSections). `preamble` carries untagged text; every other section value is wrapped in a tag of the same name so the model can match later updates to it. The returned SystemSections is normalized: preamble value untagged, others tagged, nil absent.
func BuildSystemPromptState ¶ added in v0.86.0
func BuildSystemPromptState(input BuildSystemPromptOptions) buildSystemPromptStateOutput
BuildSystemPromptState returns the complete prompt state for `input` (pi: buildSystemPromptState). A forced prompt is opaque and lives in `content` with no sections; otherwise `content` is empty and the structured sections carry the prompt.
func CalculateContextTokens ¶
CalculateContextTokens calculates total context tokens from usage; uses the native totalTokens field when available, falls back to computing from components (pi: calculateContextTokens; identical twin delegated to the harness implementation, see header).
func ClearConfigValueCache ¶
func ClearConfigValueCache()
ClearConfigValueCache clears the command cache (pi: clearConfigValueCache — exported for testing).
func ClearCrashLog ¶ added in v0.86.0
func ClearCrashLog(path string)
ClearCrashLog removes the crash log; the records can be attached again if cleanup fails (pi: clearCrashLog).
func CollectBugReportDiagnostics ¶ added in v0.86.0
func CollectBugReportDiagnostics(sessionManager *SessionManager, crashes []CrashRecord) bugReportDiagnostics
CollectBugReportDiagnostics collects failed assistant turns without collecting conversation content (pi: collectBugReportDiagnostics).
func CollectBugReportMetadata ¶ added in v0.86.0
func CollectBugReportMetadata(options CollectBugReportMetadataOptions) bugReportMetadata
CollectBugReportMetadata assembles the redacted report metadata (pi: collectBugReportMetadata).
func CompleteSummarization ¶
func CompleteSummarization( ctx context.Context, model *ai.Model, llmContext *ai.Context, options *ai.SimpleStreamOptions, streamFn agent.StreamFn, retry *ai.RetryPolicy, callbacks *ai.RetryCallbacks, ) (*types.AssistantMessage, error)
CompleteSummarization is the shared choke point for every compaction/branch-summary summarization call. It wraps the single LLM call in RetryAssistantCall so transient stream drops (e.g. `terminated`, socket close) honor the configured retry policy instead of failing the whole compaction on the first attempt. Deterministic errors and aborts return immediately (pi: completeSummarization).
func ComposeModelProvider ¶
func ComposeModelProvider(providerID string, base ai.Provider, modelConfig *ModelConfig, extension *ProviderConfigInput) (ai.Provider, error)
ComposeModelProvider composes built-in, models.json, and extension layers without reading credentials (pi: composeModelProvider).
func ComputeFileLists ¶
func ComputeFileLists(fileOps *FileOperations) (readFiles []string, modifiedFiles []string)
ComputeFileLists computes the sorted read-only and modified file lists from accumulated operations (pi: computeFileLists).
func DiffSystemPromptSections ¶ added in v0.86.0
func DiffSystemPromptSections(previous *types.SystemSections, current *types.SystemSections) *types.SystemSections
DiffSystemPromptSections diffs the sections the model currently has (replayed from the transcript, so never nil values) against the desired ones. Returns a SystemSections patch — non-nil values replace, nil values remove — or nil when nothing changed (pi: diffSystemPromptSections).
func EmitSessionShutdownEvent ¶
func EmitSessionShutdownEvent(ctx context.Context, extensionRunner *ExtensionRunner, event *SessionShutdownEvent) (bool, error)
EmitSessionShutdownEvent emits session_shutdown to extensions (pi: emitSessionShutdownEvent). Returns whether the event was emitted.
func EnabledPaths ¶
func EnabledPaths(resources []ResolvedResource) []string
EnabledPaths extracts the enabled paths of one resource list (pi's getEnabledPaths helper in resource-loader.ts).
func EstimateTokens ¶
func EstimateTokens(message agent.AgentMessage) int64
EstimateTokens estimates the token count for a message using the chars/4 heuristic; conservative (overestimates tokens) (pi: estimateTokens).
The v0.87.0 system-message branch lives in this core wrapper — see the package header for why the harness twin stays untouched.
func ExpandPromptTemplate ¶
func ExpandPromptTemplate(text string, templates []PromptTemplate) string
ExpandPromptTemplate expands a prompt template if it matches a template name (pi: expandPromptTemplate). Returns the expanded content or the original text if not a template.
func ExportFromFile ¶ added in v0.86.0
func ExportFromFile(inputPath string, options exporthtml.ExportOptions) (string, error)
ExportFromFile exports a session file to HTML (standalone, without AgentState) (pi: exportFromFile). Used by CLI for exporting arbitrary session files.
func ExportSessionToHtml ¶ added in v0.86.0
func ExportSessionToHtml(sm *SessionManager, state *agent.AgentState, options exporthtml.ExportOptions) (string, error)
ExportSessionToHtml exports a session to HTML using SessionManager and AgentState (pi: exportSessionToHtml). Used by TUI's /export command.
func ExportSessionToJsonl ¶
func ExportSessionToJsonl(sessionManager *SessionManager, outputPath string, createTrailingEntries TrailingEntries) (string, error)
ExportSessionToJsonl writes the current session branch and optional trailing export-only entries as JSONL, returning the file path (pi: exportSessionToJsonl). The trailing callback receives the last branch entry's parent id (nil when the branch is empty) and the export timestamp. An empty outputPath defaults to "session-<timestamp>.jsonl" in the process cwd.
func ExtractFileOpsFromMessage ¶
func ExtractFileOpsFromMessage(message agent.AgentMessage, fileOps *FileOperations)
ExtractFileOpsFromMessage adds the file operations of one assistant message's tool calls to the accumulator (pi: extractFileOpsFromMessage).
func FindExactModelReferenceMatch ¶
func FindExactModelReferenceMatch(modelReference string, availableModels []ai.Model) (ai.Model, bool)
FindExactModelReferenceMatch finds an exact model reference match: a bare model id or a canonical provider/modelId reference. Bare-id matches that are ambiguous across providers are rejected (pi: findExactModelReferenceMatch).
func FindExtensionStackMatches ¶ added in v0.87.0
FindExtensionStackMatches returns the labels of loaded extensions whose source files appear in a stack trace (pi: findExtensionStackMatches; v0.87.0). stack "" = no matches (pi: undefined → []). Paths are matched with backslash/trailing-slash normalization, decodeURI'd frames, and case-insensitive matching for Windows drive-letter roots; the error line itself is dropped so paths quoted in the message never attribute.
func FindMostRecentSession ¶
FindMostRecentSession returns the most recently modified session file in sessionDir, optionally filtered by cwd (pi: findMostRecentSession; cwd "" = no filter). Returns nil when unavailable. pi v0.86.0 sorts by mtime first and then finds the first header match, so a corrupt header no longer hides a newer matching session behind it.
func FindSessionById ¶ added in v0.86.0
FindSessionById finds an exact session ID without loading transcript bodies. sessionDir "" = the default per-cwd directory (pi: SessionManager.findById; v0.86.0). Returns "" when not found.
func FindTurnStartIndex ¶
func FindTurnStartIndex(entries []SessionEntry, entryIndex int, startIndex int) int
FindTurnStartIndex finds the context-visible user-role message that starts the turn containing the given entry index; returns -1 if no turn start found before the index (pi: findTurnStartIndex).
func FlushRawStdout ¶
func FlushRawStdout()
FlushRawStdout waits for the tail and performs an empty write (pi: flushRawStdout).
func FormatCacheWarmingDollars ¶ added in v0.86.0
FormatCacheWarmingDollars renders a dollar amount (pi: formatDollars).
func FormatCacheWarmingStatus ¶ added in v0.86.0
func FormatCacheWarmingStatus(status CacheWarmingStatus, now int64) string
FormatCacheWarmingStatus renders the one-line status for /session (pi: formatCacheWarmingStatus).
func FormatCacheWarmingUsage ¶ added in v0.86.0
func FormatCacheWarmingUsage(entry *UsageEntry) string
FormatCacheWarmingUsage renders the one-line transcript text for persisted cache-warming usage (pi: formatCacheWarmingUsage).
func FormatFileOperations ¶
FormatFileOperations formats the file lists as summary metadata tags (pi: formatFileOperations).
func FormatHTTPIdleTimeoutMs ¶
FormatHTTPIdleTimeoutMs renders a timeout for display (pi: formatHttpIdleTimeoutMs). Non-choice values render as "<n> sec" (pi's number division → shortest float formatting).
func FormatMissingSessionCwdError ¶
func FormatMissingSessionCwdError(issue SessionCwdIssue) string
FormatMissingSessionCwdError renders the issue as an error message (pi: formatMissingSessionCwdError).
func FormatMissingSessionCwdPrompt ¶
func FormatMissingSessionCwdPrompt(issue SessionCwdIssue) string
FormatMissingSessionCwdPrompt renders the issue as a user prompt (pi: formatMissingSessionCwdPrompt).
func FormatNoApiKeyFoundMessage ¶
FormatNoApiKeyFoundMessage formats the missing-API-key guidance (pi: formatNoApiKeyFoundMessage).
func FormatNoModelSelectedMessage ¶
func FormatNoModelSelectedMessage() string
FormatNoModelSelectedMessage formats the no-model-selected guidance (pi: formatNoModelSelectedMessage).
func FormatNoModelsAvailableMessage ¶
func FormatNoModelsAvailableMessage() string
FormatNoModelsAvailableMessage formats the no-models guidance (pi: formatNoModelsAvailableMessage).
func FormatSkillsForPrompt ¶
FormatSkillsForPrompt formats skills for inclusion in a system prompt (pi: formatSkillsForPrompt).
Uses XML format per Agent Skills standard. See: https://agentskills.io/integrate-skills
Skills with disableModelInvocation=true are excluded from the prompt (they can only be invoked explicitly via /skill:name commands). FormatSkillsForPrompt renders the available-skills prompt section (pi: formatSkillsForPrompt; v0.85.1 adds fileReadTool — "bash" when the read tool is unavailable).
func GenerateBugReportSummary ¶ added in v0.86.0
func GenerateBugReportSummary(ctx context.Context, options GenerateBugReportSummaryOptions) (string, error)
GenerateBugReportSummary asks the session model for a report when the user does not share the transcript (pi: generateBugReportSummary).
func GenerateSummary ¶
func GenerateSummary( ctx context.Context, currentMessages []agent.AgentMessage, model *ai.Model, reserveTokens int64, apiKey string, headers map[string]string, customInstructions string, previousSummary string, thinkingLevel types.ThinkingLevel, streamFn agent.StreamFn, env ai.ProviderEnv, retry *ai.RetryPolicy, callbacks *ai.RetryCallbacks, sessionID string, ) (string, error)
GenerateSummary generates a summary of the conversation using the LLM; if previousSummary is provided, uses the update prompt to merge (pi: generateSummary). Empty strings mean pi's undefined optional arguments.
func GetCacheWarmingDelayMs ¶ added in v0.86.0
GetCacheWarmingDelayMs refreshes at 90% of the TTL while preserving at least ten seconds of margin (pi: getCacheWarmingDelayMs). ok=false when the TTL is too short.
func GetConfigValueEnvVarName ¶
GetConfigValueEnvVarName returns the env var name when the config value is exactly one env reference (pi: getConfigValueEnvVarName).
func GetConfigValueEnvVarNames ¶
GetConfigValueEnvVarNames returns all referenced env var names (pi: getConfigValueEnvVarNames).
func GetDefaultSessionDir ¶
GetDefaultSessionDir returns (creating if needed) the default session directory for a cwd (pi: getDefaultSessionDir; pi's mkdirSync throws → error return). agentDir "" = the default agent dir.
func GetLastAssistantUsage ¶
func GetLastAssistantUsage(entries []SessionEntry) *types.Usage
GetLastAssistantUsage finds the last valid assistant message usage from session entries (pi: getLastAssistantUsage).
func GetMissingConfigValueEnvVarNames ¶
GetMissingConfigValueEnvVarNames returns referenced env var names that are not set (pi: getMissingConfigValueEnvVarNames).
func GetProjectTrustParentPath ¶
GetProjectTrustParentPath returns the parent of the normalized cwd (pi: getProjectTrustParentPath; "" = undefined at the filesystem root).
func GetPromptCacheTtlMs ¶ added in v0.86.0
GetPromptCacheTtlMs returns the lifetime of the prompt cache entry a request writes, from the model's promptCache tier for the retention the request used (pi: getPromptCacheTtlMs). ok=false when the model has no lifetime for that tier or caching is off.
func GetProviderLoginHelp ¶
func GetProviderLoginHelp() string
GetProviderLoginHelp returns the provider login guidance (pi: getProviderLoginHelp).
func GetRadiusGatewayUrl ¶ added in v0.86.0
func GetRadiusGatewayUrl() string
GetRadiusGatewayUrl returns the Radius gateway origin, honoring the PI_RADIUS_GATEWAY override (pi: getRadiusGatewayUrl).
func GetSummarizationFailure ¶
func GetSummarizationFailure(response *types.AssistantMessage, label string) string
GetSummarizationFailure returns an error message when a summarization response cannot safely be persisted (pi: getSummarizationFailure, v0.85.1). A length stop contains partial text and must not become a session checkpoint; "" = no failure.
func HasTrustRequiringProjectResources ¶
HasTrustRequiringProjectResources returns true when cwd has project-local resources that must be gated by project trust: trust-requiring entries under cwd/.pi, or .agents/skills in cwd or one of its ancestors. Returns false when no such project resources exist. The user/global ~/.agents/skills directory is always treated as a trusted user resource and is ignored here, even when cwd is $HOME. (pi: hasTrustRequiringProjectResources.)
func IsCommandConfigValue ¶
IsCommandConfigValue reports whether the value is a shell command (pi: isCommandConfigValue).
func IsConfigValueConfigured ¶
IsConfigValueConfigured reports whether all referenced env vars are set (pi: isConfigValueConfigured).
func IsInstallTelemetryEnabled ¶
func IsInstallTelemetryEnabled(settingsManager *SettingsManager, telemetryEnv *string) bool
IsInstallTelemetryEnabled reports whether install telemetry is enabled (pi: isInstallTelemetryEnabled). telemetryEnv nil = PI_TELEMETRY unset (pi: undefined, the process.env default); a non-nil empty string is a set-empty env value (falsy).
func IsReplayable ¶ added in v0.86.0
func IsReplayable(model *ai.Model, options *types.SimpleStreamOptions) bool
IsReplayable reports whether replaying the request with a one-token output cap leaves its cache entry untouched (pi: isReplayable). Anthropic's budget-based thinking (Claude models without adaptive thinking) derives budget_tokens from max_tokens; the replay would get a different budget, which Anthropic keys the message cache on, and the model could still think for thousands of tokens.
func IsStdoutTakenOver ¶
func IsStdoutTakenOver() bool
IsStdoutTakenOver reports whether stdout is currently taken over (pi: isStdoutTakenOver).
func IsValidCacheWarmingMode ¶ added in v0.86.0
IsValidCacheWarmingMode reports whether the value is a known profile.
func IsoToMillis ¶ added in v0.87.0
IsoToMillis is the exported form of isoToMillis for consumers outside core (pig-only export; pi inlines new Date(str).getTime() at call sites).
func MergeProviderAttributionHeaders ¶
func MergeProviderAttributionHeaders( model *types.Model, settingsManager *SettingsManager, sessionID string, headerSources ...types.ProviderHeaders, ) types.ProviderHeaders
mergeProviderAttributionHeaders merges session + attribution headers over the request header sources (pi: mergeProviderAttributionHeaders). pi's variadic headerSources become a slice; nil entries are skipped. A value later in the chain wins (Object.assign semantics).
func MigrateAuthToAuthJson ¶ added in v0.86.0
func MigrateAuthToAuthJson() []string
MigrateAuthToAuthJson migrates legacy oauth.json and settings.json apiKeys to auth.json (pi: migrateAuthToAuthJson).
Returns the provider names that were migrated.
Serialization deviation: the rewritten auth.json key order is Go's map (sorted) rather than JS's insertion order; the providers list order follows the source document via jsonObjectEntries.
func MigrateKeybindingsConfig ¶
MigrateKeybindingsConfig rewrites legacy key names to namespaced ids (pi: migrateKeybindingsConfig). The returned config preserves KEYBINDINGS declaration order first, then extras alphabetically (orderKeybindingsConfig).
func MigrateSessionEntries ¶
func MigrateSessionEntries(entries []FileEntry)
MigrateSessionEntries brings entries to the current version, in place (pi: migrateSessionEntries; exported for testing).
func MigrateSessionsFromAgentRoot ¶ added in v0.86.0
func MigrateSessionsFromAgentRoot()
MigrateSessionsFromAgentRoot migrates sessions from ~/.pig/agent/*.jsonl to proper session directories (pi: migrateSessionsFromAgentRoot).
Bug in v0.30.0: Sessions were saved to ~/.pi/agent/ instead of ~/.pi/agent/sessions/<encoded-cwd>/. This migration moves them to the correct location based on the cwd in their session header.
func ParseCommandArgs ¶
ParseCommandArgs parses command arguments respecting quoted strings (bash-style); returns the argument array (pi: parseCommandArgs).
Byte-level iteration mirrors TS's UTF-16 code-unit iteration for all multibyte content (bytes reassemble); the only divergence is non-ASCII JS-\s whitespace (e.g. U+00A0) acting as a separator, which pi's tests never exercise (declared).
func ParseHTTPIdleTimeoutMs ¶
ParseHTTPIdleTimeoutMs parses the httpIdleTimeoutMs setting value (pi: parseHttpIdleTimeoutMs). Returns (n, true) for a valid timeout, (_, false) for undefined (value unset or unparseable).
func PrintTimings ¶
func PrintTimings()
PrintTimings renders all collected timings (pi: printTimings).
func ReadStoredCredential ¶
func ReadStoredCredential(providerID string, authPath string) auth.Credential
ReadStoredCredential performs a one-off synchronous read of a stored credential from an auth.json file, without instantiating a store or resolving configured key values (pi: readStoredCredential); an empty path defaults to <agentDir>/auth.json. Any failure yields nil.
func RedactJsonValue ¶ added in v0.86.0
RedactJsonValue copies a JSON value while removing values that may contain credentials (pi: redactJsonValue). Structs are converted through their JSON representation; the result is the generic decoded value.
func RedactUrl ¶ added in v0.86.0
RedactUrl strips credentials and secret-looking query parameters from a URL (pi: redactUrl).
func ResetTimings ¶
func ResetTimings(namespace TimingLabel)
ResetTimings clears one timing namespace (pi: resetTimings).
func ResolveConfigValue ¶
ResolveConfigValue resolves a config value (API key, header value, etc.) to an actual value (pi: resolveConfigValue):
- "!..." executes the rest as a shell command and uses stdout (cached)
- "$ENV_VAR" / "${ENV_VAR}" interpolates the named environment variable
- in non-command values, "$$" escapes a literal "$" and "$!" escapes a literal "!"
- otherwise the value is a literal
func ResolveConfigValueOrThrow ¶
func ResolveConfigValueOrThrow(config string, description string, env map[string]string) (string, error)
ResolveConfigValueOrThrow resolves or errors with pi's exact messages (pi: resolveConfigValueOrThrow).
func ResolveConfigValueUncached ¶
ResolveConfigValueUncached resolves without consulting or filling the command cache (pi: resolveConfigValueUncached — used for header values).
func ResolveConfiguredModelHeaders ¶
func ResolveConfiguredModelHeaders(model ai.Model, config *ModelsJsonProvider, extension *ProviderConfigInput, env map[string]string) (map[string]string, error)
ResolveConfiguredModelHeaders resolves the per-model configured headers (pi: resolveConfiguredModelHeaders).
func ResolveHeaders ¶
ResolveHeaders resolves all header values using the same resolution logic as API keys (pi: resolveHeaders).
func ResolveHeadersOrThrow ¶
func ResolveHeadersOrThrow(headers map[string]string, description string, env map[string]string) (map[string]string, error)
ResolveHeadersOrThrow resolves all header values, erroring on failure (pi: resolveHeadersOrThrow).
func ResolveProjectTrusted ¶
func ResolveProjectTrusted(options ResolveProjectTrustedOptions) (bool, error)
ResolveProjectTrusted resolves whether the project at cwd is trusted (pi: resolveProjectTrusted; async throws → bool + error).
func RestoreModelFromSession ¶
func RestoreModelFromSession(savedProvider, savedModelID string, currentModel *ai.Model, shouldPrintMessages bool, modelRuntime ModelResolverRuntime) (*ai.Model, string)
RestoreModelFromSession restores the model from a session, with fallback to available models (pi: restoreModelFromSession). Empty strings in place of pi's undefined booleans: shouldPrintMessages is passed explicitly.
func RestoreStdout ¶
func RestoreStdout()
RestoreStdout restores the original stdout (pi: restoreStdout).
func SerializeConversation ¶
SerializeConversation serializes LLM messages to text for summarization; call ConvertToLlm first to handle custom message types (pi: serializeConversation).
func SerializeSessionBranch ¶ added in v0.86.0
func SerializeSessionBranch(sessionManager *SessionManager, createTrailingEntries TrailingEntries) (string, error)
SerializeSessionBranch serializes the current branch and optional export-only entries as JSONL (pi: serializeSessionBranch).
func SessionEntryToContextMessages ¶
func SessionEntryToContextMessages(entry SessionEntry) []agent.AgentMessage
SessionEntryToContextMessages projects one selected session entry into LLM/runtime messages. Plain custom entries are display/state entries and do not participate in context (pi: sessionEntryToContextMessages).
func ShouldCompact ¶
func ShouldCompact(contextTokens int64, contextWindow int64, settings CompactionSettingsValues) bool
ShouldCompact checks if compaction should trigger based on context usage (pi: shouldCompact; identical twin reimplemented over the resolved settings shape).
func ShowDeprecationWarnings ¶ added in v0.86.0
func ShowDeprecationWarnings(warnings []string)
ShowDeprecationWarnings prints deprecation warnings and waits for a keypress (pi: showDeprecationWarnings).
pig addition: pi's stdin flow-mode wait never resolves on a piped stdin's EOF; the caller only invokes this for interactive mode (TTY), so the raw-mode keypress is skipped when stdin is not a character device.
func SubstituteArgs ¶
SubstituteArgs substitutes argument placeholders in template content (pi: substituteArgs). Supports:
- $1, $2, ... for positional args
- $@ and $ARGUMENTS for all args
- ${N:-default} for positional arg N with default when missing/empty
- ${@:-default} and ${ARGUMENTS:-default} for all args with a default when empty
- ${@:N} for args from Nth onwards (bash-style slicing)
- ${@:N:L} for L args starting from Nth
Note: Replacement happens on the template string only. Argument and default values containing patterns like $1, $@, or $ARGUMENTS are NOT recursively substituted.
func TakeOverStdout ¶
func TakeOverStdout()
TakeOverStdout redirects process stdout to stderr (pi: takeOverStdout). Idempotent.
func Time ¶
func Time(label string, namespace TimingLabel)
Time records one timing entry (pi: time).
func UploadBugReport ¶ added in v0.86.0
func UploadBugReport(ctx context.Context, bundle *BugReportBundle, options UploadBugReportOptions) (string, error)
UploadBugReport uploads the bundle to the Radius gateway (pi: uploadBugReport). Returns the report id.
func UseWindowsKeybindings ¶
UseWindowsKeybindings reports whether Windows-flavoured defaults apply (pi: useWindowsKeybindings — native Windows or WSL).
func ValidateExtensionProvider ¶
func ValidateExtensionProvider(providerID string, base ai.Provider, modelsConfig *ModelsJsonProvider, extension *ProviderConfigInput) error
ValidateExtensionProvider validates an extension registration on its own (pi: validateExtensionProvider).
func WaitForRawStdoutBackpressure ¶
func WaitForRawStdoutBackpressure()
WaitForRawStdoutBackpressure waits for all queued writes to complete (pi: waitForRawStdoutBackpressure). pi rechecks for writes enqueued while waiting; pig samples the tail before and after the wait the same way.
func WithLock ¶
func WithLock[T any](ctx context.Context, backend AuthStorageBackend, fn func(current *string) (T, *string, error)) (T, error)
WithLock runs fn under the backend lock and returns its typed result (pi: LockResult unwrapping). Generic helper because Go interfaces cannot have generic methods.
func WithLockAsync ¶
func WithLockAsync[T any](ctx context.Context, backend AuthStorageBackend, fn func(current *string) (T, *string, error)) (T, error)
WithLockAsync is WithLock with the async retry policy (pi: withLockAsync). The result is captured only when fn itself succeeds; pi discards it on any later throw the same way (callers must check err first).
func WithRemoteCatalog ¶
func WithRemoteCatalog(provider ai.Provider, catalogBaseURL string, localGeneratedAt *int64) ai.Provider
WithRemoteCatalog adds a persisted pi.dev catalog overlay to a static built-in provider (pi: withRemoteCatalog); an empty catalogBaseURL defaults to https://pi.dev, and a nil localGeneratedAt means "no generated catalog timestamp".
func WrapRegisteredTool ¶
func WrapRegisteredTool(registeredTool RegisteredTool, runner *ExtensionRunner) agent.AgentTool
WrapRegisteredTool wraps a RegisteredTool into an AgentTool (pi: wrapRegisteredTool). v0.86.0 removed the addedToolNames reporting wrapper: tool introductions move to transcript system messages.
func WrapRegisteredTools ¶
func WrapRegisteredTools(registeredTools []RegisteredTool, runner *ExtensionRunner) []agent.AgentTool
WrapRegisteredTools wraps all registered tools into AgentTools (pi: wrapRegisteredTools).
func WriteBugReportArchive ¶ added in v0.86.0
func WriteBugReportArchive(bundle *BugReportBundle, filePath string) error
WriteBugReportArchive writes the zip archive (pi: writeBugReportArchive).
func WriteRawStdout ¶
func WriteRawStdout(text string)
WriteRawStdout writes directly to the raw stdout (pi: writeRawStdout). pi exits the process when a write fails permanently; pig records the failure the same way (os.Exit(1)) inside the write goroutine.
Types ¶
type AfterProviderResponseEvent ¶
type AfterProviderResponseEvent struct {
Type string `json:"type"`
Status int `json:"status"`
Headers map[string]string `json:"headers"`
}
AfterProviderResponseEvent fires after a provider response is received and before the response stream is consumed (pi: AfterProviderResponseEvent).
func (*AfterProviderResponseEvent) EventType ¶
func (e *AfterProviderResponseEvent) EventType() string
type AgentActivityOutcome ¶ added in v0.87.0
type AgentActivityOutcome string
AgentActivityOutcome classifies the outcome of an agent run (pi: AgentActivityOutcome, v0.87.0).
const ( AgentActivityCompleted AgentActivityOutcome = "completed" AgentActivityAborted AgentActivityOutcome = "aborted" AgentActivityError AgentActivityOutcome = "error" )
type AgentBeforeSettleEvent ¶ added in v0.87.0
type AgentBeforeSettleEvent struct {
Type string `json:"type"`
// Outcome classifies the activity being settled.
Outcome AgentActivityOutcome `json:"outcome"`
BoundaryState
}
AgentBeforeSettleEvent fires before final settlement; handlers may append entries and request one continuation (pi: AgentBeforeSettleEvent, v0.87.0).
func (*AgentBeforeSettleEvent) EventType ¶ added in v0.87.0
func (e *AgentBeforeSettleEvent) EventType() string
type AgentBeforeSettleEventResult ¶ added in v0.87.0
type AgentBeforeSettleEventResult = BoundaryResult
TurnEndEventResult and AgentBeforeSettleEventResult are the boundary handler results (pi: TurnEndEventResult / AgentBeforeSettleEventResult, v0.87.0).
type AgentEndEvent ¶
type AgentEndEvent struct {
Type string `json:"type"`
Messages []agent.AgentMessage `json:"messages"`
}
AgentEndEvent fires when an agent loop ends (pi: AgentEndEvent).
func (*AgentEndEvent) EventType ¶
func (e *AgentEndEvent) EventType() string
type AgentSession ¶
type AgentSession struct {
Agent *agent.Agent
SessionManager *SessionManager
SettingsManager *SettingsManager
// contains filtered or unexported fields
}
AgentSession is the core abstraction for agent lifecycle and session management (pi: AgentSession).
func NewAgentSession ¶
func NewAgentSession(config AgentSessionConfig) *AgentSession
NewAgentSession creates the session (pi: constructor).
func (*AgentSession) Abort ¶
func (s *AgentSession) Abort(ctx context.Context) error
Abort aborts the current operation and waits for the agent to become idle (pi: abort).
func (*AgentSession) AbortBash ¶
func (s *AgentSession) AbortBash()
AbortBash cancels running bash commands (pi: abortBash).
func (*AgentSession) AbortBranchSummary ¶
func (s *AgentSession) AbortBranchSummary()
AbortBranchSummary cancels in-progress branch summarization (pi: abortBranchSummary).
func (*AgentSession) AbortCompaction ¶
func (s *AgentSession) AbortCompaction()
AbortCompaction cancels in-progress compaction (manual or auto) (pi: abortCompaction).
func (*AgentSession) AbortRetry ¶
func (s *AgentSession) AbortRetry()
AbortRetry cancels the in-progress retry (pi: abortRetry).
func (*AgentSession) AutoCompactionEnabled ¶
func (s *AgentSession) AutoCompactionEnabled() bool
AutoCompactionEnabled reports whether auto-compaction is enabled (pi: get autoCompactionEnabled).
func (*AgentSession) AutoRetryEnabled ¶
func (s *AgentSession) AutoRetryEnabled() bool
AutoRetryEnabled reports whether auto-retry is enabled (pi: get autoRetryEnabled).
func (*AgentSession) BindExtensions ¶
func (s *AgentSession) BindExtensions(ctx context.Context, bindings *ExtensionBindings) error
BindExtensions binds the extension host bindings and emits session_start (pi: bindExtensions).
func (*AgentSession) CacheWarmingStatus ¶ added in v0.86.0
func (s *AgentSession) CacheWarmingStatus() (CacheWarmingStatus, bool)
CacheWarmingStatus returns the current cache-warming state and the policy inputs that produced it (pi: get cacheWarmingStatus; v0.86.0).
func (*AgentSession) ClearQueue ¶
func (s *AgentSession) ClearQueue() (steering []string, followUp []string)
ClearQueue clears all queued messages and returns them. Useful for restoring to editor when user aborts (pi: clearQueue).
func (*AgentSession) Compact ¶
func (s *AgentSession) Compact(ctx context.Context, customInstructions string) (*CompactionResult, error)
Compact manually compacts the session context (pi: compact). This is the manual entry point used by /compact, RPC, and extensions. It is separate from automatic threshold/overflow compaction, which enters through checkCompaction and runAutoCompaction. After preparation and the session_before_compact hook, both paths call the lower-level Compact function, unless the hook cancels or supplies a custom result.
Aborts the current agent operation first. Manual compaction never retries or continues the interrupted agent turn.
func (*AgentSession) CreateReplacedSessionContext ¶
func (s *AgentSession) CreateReplacedSessionContext() *ReplacedSessionContext
CreateReplacedSessionContext builds the replacement session context for newSession/fork/switchSession flows (pi: createReplacedSessionContext).
func (*AgentSession) CycleModel ¶
func (s *AgentSession) CycleModel(ctx context.Context, direction string, options *ModelMutationOptions) (*ModelCycleResult, error)
CycleModel cycles to the next/previous model. Uses scoped models (from --models flag) if available, otherwise all available models. Returns nil when only one model is available (pi: cycleModel).
func (*AgentSession) CycleThinkingLevel ¶
func (s *AgentSession) CycleThinkingLevel(options *ModelMutationOptions) agent.ThinkingLevel
CycleThinkingLevel cycles to the next thinking level. Returns "" when the model doesn't support thinking (pi: cycleThinkingLevel).
func (*AgentSession) Dispose ¶
func (s *AgentSession) Dispose()
Dispose removes all listeners and disconnects from the agent. Call this when completely done with the session (pi: dispose).
func (*AgentSession) ExecuteBash ¶
func (s *AgentSession) ExecuteBash(ctx context.Context, command string, onChunk func(chunk string), options *BashExecuteOptions) (BashResult, error)
ExecuteBash executes a bash command and adds the result to agent context and session (pi: executeBash).
func (*AgentSession) ExportToHtml ¶ added in v0.86.0
func (s *AgentSession) ExportToHtml(outputPath string, themeName string) (string, error)
ExportToHtml exports the session to HTML (pi: agent-session.ts exportToHtml). outputPath "" = a default next to the session file (pi: outputPath?).
func (*AgentSession) ExportToJsonl ¶ added in v0.86.0
func (s *AgentSession) ExportToJsonl(outputPath string) (string, error)
ExportToJsonl exports the current branch to a JSONL file and returns the written path (pi: exportToJsonl).
func (*AgentSession) FollowUp ¶
func (s *AgentSession) FollowUp(ctx context.Context, text string, images []types.ImageContent, options *QueueUserInputOptions) error
FollowUp queues a follow-up message to be processed after the agent finishes. Delivered only when agent has no more tool calls or steering messages. Expands skill commands and prompt templates. Errors on extension commands (pi: followUp).
func (*AgentSession) FollowUpMode ¶
func (s *AgentSession) FollowUpMode() agent.QueueMode
FollowUpMode returns the current follow-up mode (pi: get followUpMode).
func (*AgentSession) GetActiveToolNames ¶
func (s *AgentSession) GetActiveToolNames() []string
GetActiveToolNames returns the names of currently active tools (pi: getActiveToolNames).
func (*AgentSession) GetAllTools ¶
func (s *AgentSession) GetAllTools() []ToolInfo
GetAllTools returns all configured tools with name, description, parameter schema, prompt guidelines, and source metadata (pi: getAllTools).
func (*AgentSession) GetAvailableThinkingLevels ¶
func (s *AgentSession) GetAvailableThinkingLevels() []agent.ThinkingLevel
GetAvailableThinkingLevels returns the available thinking levels for the current model. The provider will clamp to what the specific model supports internally (pi: getAvailableThinkingLevels).
func (*AgentSession) GetContextUsage ¶
func (s *AgentSession) GetContextUsage() *ContextUsage
GetContextUsage returns the current context usage; nil when no model is selected or the context window is unknown (pi: getContextUsage).
func (*AgentSession) GetExtensionRunner ¶
func (s *AgentSession) GetExtensionRunner() *ExtensionRunner
GetExtensionRunner returns the extension runner (for setting UI context and error handlers) (pi: get extensionRunner).
func (*AgentSession) GetFollowUpMessages ¶
func (s *AgentSession) GetFollowUpMessages() []string
GetFollowUpMessages returns the pending follow-up messages (read-only) (pi: getFollowUpMessages).
func (*AgentSession) GetLastAssistantText ¶
func (s *AgentSession) GetLastAssistantText() string
GetLastAssistantText returns the text content of the last assistant message, for the /copy command (pi: getLastAssistantText). Returns "" when no assistant message exists (pi: undefined).
func (*AgentSession) GetModelRuntime ¶
func (s *AgentSession) GetModelRuntime() *ModelRuntime
GetModelRuntime returns the canonical model/auth runtime (pi: get modelRuntime).
func (*AgentSession) GetResourceLoader ¶
func (s *AgentSession) GetResourceLoader() ResourceLoader
GetResourceLoader returns the resource loader (pi: get resourceLoader).
func (*AgentSession) GetSessionStats ¶
func (s *AgentSession) GetSessionStats() SessionStats
GetSessionStats aggregates session statistics over ALL session entries (including history that was compacted away), so token/cost totals reflect what was actually billed across the session (pi: getSessionStats).
func (*AgentSession) GetSteeringMessages ¶
func (s *AgentSession) GetSteeringMessages() []string
GetSteeringMessages returns the pending steering messages (read-only) (pi: getSteeringMessages).
func (*AgentSession) GetToolDefinition ¶
func (s *AgentSession) GetToolDefinition(name string) *tools.ToolDefinition
GetToolDefinition returns the named tool definition, or nil (pi: getToolDefinition).
func (*AgentSession) GetUserMessagesForForking ¶
func (s *AgentSession) GetUserMessagesForForking() []ForkUserMessage
GetUserMessagesForForking returns all user messages from the session for the fork selector (pi: getUserMessagesForForking).
func (*AgentSession) HasExtensionHandlers ¶
func (s *AgentSession) HasExtensionHandlers(eventType string) bool
HasExtensionHandlers reports whether extensions have handlers for the event type (pi: hasExtensionHandlers).
func (*AgentSession) HasPendingBashMessages ¶
func (s *AgentSession) HasPendingBashMessages() bool
HasPendingBashMessages reports whether there are pending bash messages waiting to be flushed (pi: get hasPendingBashMessages).
func (*AgentSession) IsBashRunning ¶
func (s *AgentSession) IsBashRunning() bool
IsBashRunning reports whether a bash command is currently running (pi: get isBashRunning).
func (*AgentSession) IsCompacting ¶
func (s *AgentSession) IsCompacting() bool
IsCompacting reports whether compaction or branch summarization is currently running (pi: get isCompacting).
func (*AgentSession) IsIdle ¶
func (s *AgentSession) IsIdle() bool
IsIdle reports whether the session has no active agent run, compaction, branch summary, retry, or queued continuation (pi: get isIdle; v0.85.1 adds the compaction gate).
func (*AgentSession) IsRetrying ¶
func (s *AgentSession) IsRetrying() bool
IsRetrying reports whether auto-retry is currently in progress (pi: get isRetrying).
func (*AgentSession) IsStreaming ¶
func (s *AgentSession) IsStreaming() bool
IsStreaming reports whether the session is currently processing an agent run or post-run continuation (pi: get isStreaming).
func (*AgentSession) Messages ¶
func (s *AgentSession) Messages() []agent.AgentMessage
Messages returns all messages including custom types like BashExecutionMessage (pi: get messages).
func (*AgentSession) Model ¶
func (s *AgentSession) Model() *types.Model
Model returns the current model; nil = not yet selected (pi: get model).
func (*AgentSession) NavigateTree ¶
func (s *AgentSession) NavigateTree(ctx context.Context, targetID string, options *NavigateTreeOptions) (*NavigateTreeResult, error)
NavigateTree navigates to a different node in the session tree. Unlike forking, which creates a new session file, this stays in the same file (pi: navigateTree).
func (*AgentSession) PendingMessageCount ¶
func (s *AgentSession) PendingMessageCount() int
PendingMessageCount returns the number of pending messages (includes both steering and follow-up) (pi: get pendingMessageCount).
func (*AgentSession) Prompt ¶
func (s *AgentSession) Prompt(ctx context.Context, text string, options *PromptOptions) error
Prompt sends a prompt to the agent (pi: prompt). It handles extension commands (registered via pi.registerCommand) immediately, even during streaming, expands file-based prompt templates by default, queues via Steer/FollowUp during streaming based on the StreamingBehavior option, and validates model and API key before sending (when not streaming).
func (*AgentSession) PromptTemplates ¶
func (s *AgentSession) PromptTemplates() []PromptTemplate
PromptTemplates returns the file-based prompt templates (pi: get promptTemplates).
func (*AgentSession) RecordBashResult ¶
func (s *AgentSession) RecordBashResult(command string, result BashResult, excludeFromContext bool)
RecordBashResult records a bash execution result in session history. Used by ExecuteBash and by extensions that handle bash execution themselves (pi: recordBashResult).
func (*AgentSession) RefreshContext ¶ added in v0.87.0
func (s *AgentSession) RefreshContext()
RefreshContext rebuilds the public finalized transcript from the canonical session projection (pi: refreshContext, v0.87.0).
func (*AgentSession) Reload ¶
func (s *AgentSession) Reload(ctx context.Context, options *ReloadOptions) error
Reload rebuilds the extension runtime and resources (pi: reload).
func (*AgentSession) RetryAttempt ¶
func (s *AgentSession) RetryAttempt() int
RetryAttempt returns the current retry attempt (0 if not retrying) (pi: get retryAttempt).
func (*AgentSession) ScopedModels ¶
func (s *AgentSession) ScopedModels() []ScopedModel
ScopedModels returns the scoped models for cycling (from --models flag) (pi: get scopedModels).
func (*AgentSession) SendCustomMessage ¶
func (s *AgentSession) SendCustomMessage(ctx context.Context, message *CustomMessagePayload, options *SendMessageOptions) error
SendCustomMessage sends a custom message to the session and creates a CustomMessageEntry (pi: sendCustomMessage).
Handles three cases:
- Streaming: queues message, processed when loop pulls from queue
- Not streaming + triggerTurn: appends to state/session, starts new turn
- Not streaming + no trigger: appends to state/session, no turn
func (*AgentSession) SendUserMessage ¶
func (s *AgentSession) SendUserMessage(ctx context.Context, content any, options *SendUserMessageOptions) error
SendUserMessage sends a user message to the agent. Always triggers a turn. When the agent is streaming, use DeliverAs to specify how to queue the message (pi: sendUserMessage).
func (*AgentSession) SessionFile ¶
func (s *AgentSession) SessionFile() string
SessionFile returns the current session file path, or "" if sessions are disabled (pi: get sessionFile).
func (*AgentSession) SessionID ¶
func (s *AgentSession) SessionID() string
SessionID returns the current session ID (pi: get sessionId).
func (*AgentSession) SessionName ¶
func (s *AgentSession) SessionName() (string, bool)
SessionName returns the current session display name, if set (pi: get sessionName). The second return is false when unset.
func (*AgentSession) SetActiveToolsByName ¶
func (s *AgentSession) SetActiveToolsByName(toolNames []string)
SetActiveToolsByName sets active tools by name. Only tools in the registry can be enabled. Unknown tool names are ignored. Also rebuilds the system prompt to reflect the new tool set. Changes take effect on the next agent turn (pi: setActiveToolsByName).
func (*AgentSession) SetAutoCompactionEnabled ¶
func (s *AgentSession) SetAutoCompactionEnabled(enabled bool)
SetAutoCompactionEnabled toggles the auto-compaction setting (pi: setAutoCompactionEnabled).
func (*AgentSession) SetAutoRetryEnabled ¶
func (s *AgentSession) SetAutoRetryEnabled(enabled bool)
SetAutoRetryEnabled toggles the auto-retry setting (pi: setAutoRetryEnabled).
func (*AgentSession) SetCacheWarmingMode ¶ added in v0.86.0
func (s *AgentSession) SetCacheWarmingMode(mode CacheWarmingMode)
SetCacheWarmingMode persists the cache-warming mode and immediately reconciles active warming (pi: setCacheWarmingMode; v0.86.0).
func (*AgentSession) SetFollowUpMode ¶
func (s *AgentSession) SetFollowUpMode(mode string)
SetFollowUpMode sets the follow-up message mode. Saves to settings (pi: setFollowUpMode).
func (*AgentSession) SetListenerPanicObserver ¶
func (s *AgentSession) SetListenerPanicObserver(observer func(event *AgentSessionEvent, logPath string))
SetListenerPanicObserver registers a callback invoked (guarded) when a session listener panics during emit() (pig addition; pi crashes instead). Interactive mode uses it to surface the recovered panic in the chat UI.
func (*AgentSession) SetModel ¶
func (s *AgentSession) SetModel(ctx context.Context, model *types.Model, options *ModelMutationOptions) error
SetModel sets the model directly. Validates that auth is configured and saves to the session transcript. Persists to global defaults only when options.Persist is true (pi: setModel).
func (*AgentSession) SetScopedModels ¶
func (s *AgentSession) SetScopedModels(scopedModels []ScopedModel)
SetScopedModels updates the scoped models for cycling (pi: setScopedModels).
func (*AgentSession) SetSessionName ¶
func (s *AgentSession) SetSessionName(name string)
SetSessionName sets a display name for the current session (pi: setSessionName).
func (*AgentSession) SetSteeringMode ¶
func (s *AgentSession) SetSteeringMode(mode string)
SetSteeringMode sets the steering message mode. Saves to settings (pi: setSteeringMode).
func (*AgentSession) SetThinkingLevel ¶
func (s *AgentSession) SetThinkingLevel(level agent.ThinkingLevel, options *ModelMutationOptions)
SetThinkingLevel sets the thinking level. Clamps to model capabilities based on available thinking levels. Saves the clamped level to the session transcript only if the level actually changes. Persists the requested level to global defaults only when options.Persist is true (pi: setThinkingLevel).
func (*AgentSession) State ¶
func (s *AgentSession) State() *agent.AgentState
State returns the full agent state (pi: get state).
func (*AgentSession) Steer ¶
func (s *AgentSession) Steer(ctx context.Context, text string, images []types.ImageContent, options *QueueUserInputOptions) error
Steer queues a steering message while the agent is running. Delivered after the current assistant turn finishes executing its tool calls, before the next LLM call. Expands skill commands and prompt templates. Errors on extension commands (pi: steer).
func (*AgentSession) SteeringMode ¶
func (s *AgentSession) SteeringMode() agent.QueueMode
SteeringMode returns the current steering mode (pi: get steeringMode).
func (*AgentSession) Subscribe ¶
func (s *AgentSession) Subscribe(listener AgentSessionEventListener) func()
Subscribe adds a listener; session persistence is handled internally (saves messages on message_end). Returns the unsubscribe function for this listener (pi: subscribe).
func (*AgentSession) SummarizeForBugReport ¶ added in v0.86.0
func (s *AgentSession) SummarizeForBugReport(ctx context.Context, options *BugReportSummaryOptions) (string, error)
SummarizeForBugReport asks the session model for a bug report summary when the user does not share the transcript (pi: summarizeForBugReport, pi v0.86.0). ctx carries the loader's cancellation (pi: options.signal).
func (*AgentSession) SupportsThinking ¶
func (s *AgentSession) SupportsThinking() bool
SupportsThinking reports whether the current model supports thinking/reasoning (pi: supportsThinking).
func (*AgentSession) SystemPrompt ¶
func (s *AgentSession) SystemPrompt() string
SystemPrompt returns the current effective system prompt (includes any per-turn extension modifications) (pi: get systemPrompt). SystemPrompt returns the current effective system prompt, including changes not yet sent to the model (pi: get systemPrompt; v0.86.0 renders from the run/base prompt options).
func (*AgentSession) ThinkingLevel ¶
func (s *AgentSession) ThinkingLevel() agent.ThinkingLevel
ThinkingLevel returns the current thinking level (pi: get thinkingLevel).
func (*AgentSession) WaitForIdle ¶
func (s *AgentSession) WaitForIdle(ctx context.Context) error
WaitForIdle blocks until the session is idle (pi: waitForIdle). ctx cancellation aborts the wait (pi has no timeout).
type AgentSessionConfig ¶
type AgentSessionConfig struct {
Agent *agent.Agent
SessionManager *SessionManager
SettingsManager *SettingsManager
Cwd string
// ScopedModels are the models to cycle through with Ctrl+P (from
// --models flag).
ScopedModels []ScopedModel
// ResourceLoader supplies extensions, skills, prompts, themes, context
// files, and the system prompt.
ResourceLoader ResourceLoader
// CustomTools are SDK custom tools registered outside extensions.
CustomTools []*tools.ToolDefinition
// ModelRuntime is the canonical model/auth runtime used by
// coding-agent internals.
ModelRuntime *ModelRuntime
// CacheWarmer keeps the prompt cache entry of the last session request
// warm (pi: cacheWarmer; v0.86.0). pig takes the surface the session
// consumes (pi: Pick<CacheWarmer, ...>).
CacheWarmer CacheWarmerSurface
// InitialActiveToolNames are the initial active built-in tool names.
// Default: [read, bash, edit, write].
InitialActiveToolNames []string
// AllowedToolNames is an optional allowlist of tool names. When
// provided, only these tool names are exposed.
AllowedToolNames []string
// ExcludedToolNames is an optional denylist of tool names. When
// provided, these tool names are not exposed.
ExcludedToolNames []string
// BaseToolsOverride overrides base tools (useful for custom runtimes).
// These are synthesized into minimal ToolDefinitions internally so
// AgentSession can keep a definition-first registry even when callers
// provide plain AgentTool instances.
BaseToolsOverride map[string]agent.AgentTool
// ExtensionRunnerRef is the mutable ref used by Agent to access the
// current ExtensionRunner.
ExtensionRunnerRef *ExtensionRunnerRef
// SessionStartEvent is the session start event metadata emitted when
// extensions bind to this runtime.
SessionStartEvent *SessionStartEvent
}
AgentSessionConfig configures a new AgentSession (pi: AgentSessionConfig).
type AgentSessionEvent ¶
type AgentSessionEvent struct {
agent.AgentEvent
// WillRetry (agent_end) reports whether auto-retry will continue the run.
WillRetry bool
// Steering/FollowUp (queue_update) are the pending queue snapshots.
Steering []string
FollowUp []string
// Reason (compaction_start/compaction_end): "manual" | "threshold" |
// "overflow".
Reason string
// CompactionResult (compaction_end) is the compaction result; nil =
// undefined (pi: result; renamed from Result to avoid the embedded
// AgentEvent.Result collision, see header).
CompactionResult *CompactionResult
// Aborted (compaction_end) reports cancellation.
Aborted bool
// ErrorMessage (compaction_end) is the failure message; "" = undefined.
ErrorMessage string
// Entry (entry_appended) is the appended custom entry.
Entry SessionEntry
// Name (session_info_changed) is the session display name; nil =
// cleared (pi: name: string | undefined).
Name *string
// ThinkingLevel (thinking_level_changed) is the new level.
ThinkingLevel agent.ThinkingLevel
// Attempt/MaxAttempts/DelayMs (auto_retry_start,
// summarization_retry_scheduled) describe the retry schedule.
Attempt int
MaxAttempts int
DelayMs int64
// FinalError (auto_retry_end) is the terminal error; "" = undefined.
FinalError string
// Success (auto_retry_end) reports retry success.
Success bool
// SummaryRetrySource (summarization_retry_attempt_start):
// "branchSummary" | "compaction".
SummaryRetrySource string
// ID (bash_execution_update) is the optional execution id; nil =
// absent (pi: id?).
ID *string
// Delta (bash_execution_update) is the streamed output chunk.
Delta string
}
AgentSessionEvent is a session-specific event that extends the core AgentEvent (pi: AgentSessionEvent discriminated union; pig follows the agent.AgentEvent single-struct precedent — exactly the fields named by Type are meaningful). Agent event payloads (message_start/message_end/turn_*/ tool_execution_*/agent_start/agent_end) ride the embedded AgentEvent.
func (AgentSessionEvent) MarshalJSON ¶
func (e AgentSessionEvent) MarshalJSON() ([]byte, error)
MarshalJSON renders the event as pi's AgentSessionEvent union wire shape (pi serializes the union object with JSON.stringify: only the members of the active variant, camelCase keys). The Go struct carries every variant's members; this encoder picks the ones the event type owns, keeping --mode json / RPC output wire-compatible with pi.
type AgentSessionEventListener ¶
type AgentSessionEventListener func(event *AgentSessionEvent)
AgentSessionEventListener listens to agent session events (pi: AgentSessionEventListener). pig wraps listeners in listenerEntry so unsubscribe can identify the exact registration (Go funcs are not comparable; pi uses Set identity).
type AgentSessionRuntime ¶
type AgentSessionRuntime struct {
// contains filtered or unexported fields
}
AgentSessionRuntime owns the current AgentSession plus its cwd-bound services (pi: AgentSessionRuntime).
func CreateAgentSessionRuntime ¶
func CreateAgentSessionRuntime( createRuntime CreateAgentSessionRuntimeFactory, options CreateAgentSessionRuntimeFactoryOptions, ) (*AgentSessionRuntime, error)
CreateAgentSessionRuntime creates the initial runtime from a runtime factory and initial session target (pi: createAgentSessionRuntime). The same factory is stored on the returned AgentSessionRuntime and reused for later /new, /resume, /fork, and import flows.
func NewAgentSessionRuntime ¶
func NewAgentSessionRuntime( session *AgentSession, services *AgentSessionServices, createRuntime CreateAgentSessionRuntimeFactory, diagnostics []AgentSessionRuntimeDiagnostic, modelFallbackMessage string, ) *AgentSessionRuntime
NewAgentSessionRuntime builds the runtime host (pi: constructor).
func (*AgentSessionRuntime) Cwd ¶
func (r *AgentSessionRuntime) Cwd() string
Cwd returns the effective cwd (pi: cwd getter).
func (*AgentSessionRuntime) Diagnostics ¶
func (r *AgentSessionRuntime) Diagnostics() []AgentSessionRuntimeDiagnostic
Diagnostics returns the collected diagnostics (pi: diagnostics getter).
func (*AgentSessionRuntime) Dispose ¶
func (r *AgentSessionRuntime) Dispose() error
Dispose emits session_shutdown(quit) and tears down the session (pi: dispose).
func (*AgentSessionRuntime) Fork ¶
func (r *AgentSessionRuntime) Fork(ctx context.Context, entryID string, options *ForkOptions) (*ForkResult, error)
Fork forks the session at (or before) an entry and replaces the runtime (pi: fork).
func (*AgentSessionRuntime) ImportFromJsonl ¶
func (r *AgentSessionRuntime) ImportFromJsonl(ctx context.Context, inputPath string, cwdOverride *string) (bool, error)
ImportFromJsonl imports a session JSONL file and switches runtime state to the imported session (pi: importFromJsonl). Returns cancelled=true when cancelled by session_before_switch. Errors:
- SessionImportFileNotFoundError when the input path does not exist.
- MissingSessionCwdError when the imported session cwd cannot be resolved and no override is provided.
func (*AgentSessionRuntime) ModelFallbackMessage ¶
func (r *AgentSessionRuntime) ModelFallbackMessage() string
ModelFallbackMessage returns the model fallback warning, "" = none (pi: modelFallbackMessage getter).
func (*AgentSessionRuntime) NewSession ¶
func (r *AgentSessionRuntime) NewSession(ctx context.Context, options *RuntimeNewSessionOptions) (bool, error)
NewSession replaces the runtime with a fresh session (pi: newSession).
func (*AgentSessionRuntime) Services ¶
func (r *AgentSessionRuntime) Services() *AgentSessionServices
Services returns the cwd-bound services (pi: services getter).
func (*AgentSessionRuntime) Session ¶
func (r *AgentSessionRuntime) Session() *AgentSession
Session returns the current session (pi: session getter).
func (*AgentSessionRuntime) SetBeforeSessionInvalidate ¶
func (r *AgentSessionRuntime) SetBeforeSessionInvalidate(beforeSessionInvalidate func())
SetBeforeSessionInvalidate sets a synchronous callback that runs after session_shutdown handlers finish but before the current session is invalidated (pi: setBeforeSessionInvalidate).
This is for host-owned UI teardown that must not yield to the event loop, such as detaching extension-provided TUI components before the old extension context becomes stale.
func (*AgentSessionRuntime) SetRebindSession ¶
func (r *AgentSessionRuntime) SetRebindSession(rebindSession func(session *AgentSession) error)
SetRebindSession sets the session rebind callback (pi: setRebindSession). nil = unset.
func (*AgentSessionRuntime) SwitchSession ¶
func (r *AgentSessionRuntime) SwitchSession(ctx context.Context, sessionPath string, options *SwitchSessionOptions) (bool, error)
SwitchSession opens another session file and replaces the runtime (pi: switchSession).
type AgentSessionRuntimeDiagnostic ¶
type AgentSessionRuntimeDiagnostic struct {
Type string // "info" | "warning" | "error"
Message string
}
AgentSessionRuntimeDiagnostic is one user-facing runtime diagnostic (pi: AgentSessionRuntimeDiagnostic; canonical source agent-session-services.ts).
func CollectSettingsDiagnostics ¶
func CollectSettingsDiagnostics(settingsManager *SettingsManager) []AgentSessionRuntimeDiagnostic
CollectSettingsDiagnostics drains settings errors into warnings (pi: collectSettingsDiagnostics).
func DeduplicateDiagnostics ¶
func DeduplicateDiagnostics(diagnostics []AgentSessionRuntimeDiagnostic) []AgentSessionRuntimeDiagnostic
DeduplicateDiagnostics removes duplicate type/message diagnostics while preserving their first occurrence (pi: deduplicateDiagnostics). Startup and runtime settings managers can report the same file error.
type AgentSessionServices ¶
type AgentSessionServices struct {
Cwd string
AgentDir string
ModelRuntime *ModelRuntime
SettingsManager *SettingsManager
ResourceLoader ResourceLoader
Diagnostics []AgentSessionRuntimeDiagnostic
}
AgentSessionServices is the coherent cwd-bound runtime services for one effective session cwd (pi: AgentSessionServices). This is infrastructure only: the AgentSession itself is created separately so session options can be resolved against these services first.
func CreateAgentSessionServices ¶
func CreateAgentSessionServices(ctx context.Context, options CreateAgentSessionServicesOptions) (*AgentSessionServices, error)
CreateAgentSessionServices creates cwd-bound runtime services (pi: createAgentSessionServices). Returns services plus diagnostics; it does not create an AgentSession.
type AgentSettledEvent ¶
type AgentSettledEvent struct {
Type string `json:"type"`
}
AgentSettledEvent fires after an agent run has fully settled (pi: AgentSettledEvent).
func (*AgentSettledEvent) EventType ¶
func (e *AgentSettledEvent) EventType() string
type AgentStartEvent ¶
type AgentStartEvent struct {
Type string `json:"type"`
}
AgentStartEvent fires when an agent loop starts (pi: AgentStartEvent).
func (*AgentStartEvent) EventType ¶
func (e *AgentStartEvent) EventType() string
type AgentsFile ¶
AgentsFile is one loaded AGENTS.md-style context file (pi: getAgentsFiles' { path, content } members).
func LoadProjectContextFiles ¶
func LoadProjectContextFiles(cwd string, agentDir string) []AgentsFile
LoadProjectContextFiles loads the AGENTS.md-style context files from the agent dir and every ancestor of cwd (pi: loadProjectContextFiles).
type AppKeybinding ¶
type AppKeybinding = string
AppKeybinding is the app-level keybinding id union (pi: AppKeybinding = keyof AppKeybindings — an open string union in pig, matching the repo's `X | string` open-union rule).
type AppMode ¶
type AppMode = string
AppMode selects the coding-agent mode (pi: AppMode = "interactive" | "print" | "json" | "rpc").
type AuthStatus ¶
type AuthStatus struct {
Configured bool
// Source is "stored" | "runtime" | "environment" | "fallback" |
// "models_json_key" | "models_json_command".
Source string
Label string
}
AuthStatus reports provider auth configuration (pi: AuthStatus).
func ConfiguredRequestAuthStatus ¶
func ConfiguredRequestAuthStatus(config *ModelsJsonProvider, extension *ProviderConfigInput) *AuthStatus
ConfiguredRequestAuthStatus reports the configured-key auth status without touching credentials (pi: configuredRequestAuthStatus).
type AuthStorage ¶
type AuthStorage struct {
// contains filtered or unexported fields
}
AuthStorage is the credential storage backed by a JSON file (pi: AuthStorage).
func AuthStorageFromStorage ¶
func AuthStorageFromStorage(storage AuthStorageBackend) *AuthStorage
AuthStorageFromStorage builds an AuthStorage over an explicit backend (pi: AuthStorage.fromStorage).
func CreateAuthStorage ¶
func CreateAuthStorage(authPath string) *AuthStorage
CreateAuthStorage opens the file-backed credential store (pi: AuthStorage.create); an empty path defaults to <agentDir>/auth.json.
func NewAuthStorage ¶
func NewAuthStorage(storage AuthStorageBackend, authPath string) *AuthStorage
NewAuthStorage builds an AuthStorage over a backend; authPath enables the shared file read cache and revision checks (pi: private constructor).
func NewInMemoryAuthStorage ¶
func NewInMemoryAuthStorage(data authStorageData) *AuthStorage
NewInMemoryAuthStorage builds an in-memory credential store seeded with data; a nil data seeds an empty store (pi: AuthStorage.inMemory).
func NewInMemoryAuthStorageWithCredentials ¶
func NewInMemoryAuthStorageWithCredentials(credentials map[string]string) *AuthStorage
NewInMemoryAuthStorageWithCredentials builds an in-memory AuthStorage seeded with one api key per provider id (pi: AuthStorage.inMemory({ provider: { type: "api_key", key } })). Exported for out-of-package test scaffolding; authStorageData stays unexported.
func (*AuthStorage) Delete ¶
func (s *AuthStorage) Delete(ctx context.Context, providerID string) error
func (*AuthStorage) List ¶
func (s *AuthStorage) List(ctx context.Context) ([]auth.CredentialInfo, error)
List returns credential metadata without resolving configured key values (pi: list).
func (*AuthStorage) Modify ¶
func (s *AuthStorage) Modify(ctx context.Context, providerID string, fn func(current auth.Credential) (auth.Credential, error)) (auth.Credential, error)
func (*AuthStorage) Read ¶
func (s *AuthStorage) Read(ctx context.Context, providerID string) (auth.Credential, error)
func (*AuthStorage) Reload ¶
func (s *AuthStorage) Reload()
Reload rereads credentials from storage, keeping the last valid snapshot on failure (pi: reload).
type AuthStorageBackend ¶
type AuthStorageBackend interface {
// WithLock runs fn under the storage lock with the synchronous retry
// policy (pi: withLock; no cancellation).
WithLock(ctx context.Context, fn LockFunction) error
// WithLockAsync runs fn under the storage lock with the async retry
// policy: stale-aware acquisition, exponential backoff with jitter, and
// cancellation (pi: withLockAsync).
WithLockAsync(ctx context.Context, fn LockFunction) error
}
AuthStorageBackend is the storage abstraction behind AuthStorage (pi: AuthStorageBackend). pi's withLock/withLockAsync differ only in lock-acquisition retry policy; both are context-aware here.
type AutocompleteProviderFactory ¶
type AutocompleteProviderFactory func(provider tui.AutocompleteProvider) tui.AutocompleteProvider
AutocompleteProviderFactory wraps/replaces the editor autocomplete provider (pi: extensions/types.ts AutocompleteProviderFactory).
type BashExecuteOptions ¶
type BashExecuteOptions struct {
// ExcludeFromContext excludes the command output from the LLM context
// (!! prefix).
ExcludeFromContext bool
// ID is an optional identifier included in bash execution update events.
ID string
// Operations customizes command execution for remote execution.
Operations tools.BashOperations
// HasOperations distinguishes a nil Operations from an unset one.
HasOperations bool
}
BashExecuteOptions are the executeBash options (pi: the third parameter).
type BashExecutorOptions ¶
type BashExecutorOptions struct {
// OnChunk receives streaming output chunks (already sanitized).
OnChunk func(chunk string)
// Context carries cancellation (pi: signal).
Context context.Context
}
BashExecutorOptions parameterize ExecuteBashWithOperations (pi: BashExecutorOptions).
type BashResult ¶
type BashResult struct {
// Output is the combined stdout+stderr output (sanitized, possibly
// truncated).
Output string
// ExitCode is the process exit code; nil when killed/cancelled (pi:
// undefined).
ExitCode *int
// Cancelled reports whether the command was cancelled via the context.
Cancelled bool
// Truncated reports whether the output was truncated.
Truncated bool
// FullOutputPath is the temp file containing the full output when the
// output exceeded the truncation threshold.
FullOutputPath string
}
BashResult is the outcome of one bash execution (pi: BashResult).
func ExecuteBashWithOperations ¶
func ExecuteBashWithOperations(ctx context.Context, command string, cwd string, operations tools.BashOperations, options *BashExecutorOptions) (BashResult, error)
ExecuteBashWithOperations executes a bash command using custom BashOperations, used for remote execution (SSH, containers, etc.) (pi: executeBashWithOperations).
type BeforeAgentStartCombinedResult ¶
type BeforeAgentStartCombinedResult struct {
// Messages are the custom messages to inject (pi: messages).
Messages []CustomMessagePayload `json:"messages,omitempty"`
// SystemPromptOptions is the normalized, handler-mutated prompt options
// (pi: systemPromptOptions; the ForceSystemPrompt field carries a
// handler's systemPrompt override).
SystemPromptOptions NormalizedBuildSystemPromptOptions `json:"systemPromptOptions"`
}
BeforeAgentStartCombinedResult merges all handler results (pi: emitBeforeAgentStart's inline return shape; v0.86.0 always returns the normalized options).
type BeforeAgentStartEvent ¶
type BeforeAgentStartEvent struct {
Type string `json:"type"`
Prompt string `json:"prompt"`
Images []types.ImageContent `json:"images,omitempty"`
// SystemPrompt is the current system prompt, rendered from
// systemPromptOptions and earlier handler changes (pi v0.86.0: a
// getter; pig renders it once per handler dispatch).
SystemPrompt string `json:"systemPrompt"`
// SystemPromptOptions is mutable; later handlers observe mutations made
// by earlier handlers (pi v0.86.0). Pointer so handler field assignments
// (e.g. replacing Sections) are visible to the runner's result — pi
// passes the same options object by reference.
SystemPromptOptions *NormalizedBuildSystemPromptOptions `json:"systemPromptOptions"`
}
BeforeAgentStartEvent fires before the agent run starts (pi: BeforeAgentStartEvent).
func (*BeforeAgentStartEvent) EventType ¶
func (e *BeforeAgentStartEvent) EventType() string
type BeforeAgentStartEventResult ¶
type BeforeAgentStartEventResult struct {
// Message is a custom message to inject alongside the prompt (pi:
// message?).
Message *CustomMessagePayload `json:"message,omitempty"`
// SystemPrompt replaces the system prompt for this turn; nil = unchanged
// (pi: systemPrompt?).
SystemPrompt *string `json:"systemPrompt,omitempty"`
}
BeforeAgentStartEventResult is one handler's result (pi: BeforeAgentStartEventResult).
type BeforeProviderHeadersEvent ¶
type BeforeProviderHeadersEvent struct {
Type string `json:"type"`
Headers types.ProviderHeaders `json:"headers"`
}
BeforeProviderHeadersEvent fires after request headers are assembled, before the provider HTTP call. Handlers mutate headers in place (e.g. to inject tracing/session headers); the return value is ignored. A nil value deletes that header (pi: BeforeProviderHeadersEvent).
func (*BeforeProviderHeadersEvent) EventType ¶
func (e *BeforeProviderHeadersEvent) EventType() string
type BeforeProviderRequestEvent ¶
BeforeProviderRequestEvent fires before a provider request is sent; can replace the payload (pi: BeforeProviderRequestEvent).
func (*BeforeProviderRequestEvent) EventType ¶
func (e *BeforeProviderRequestEvent) EventType() string
type BoundaryContextBuilder ¶ added in v0.87.0
type BoundaryContextBuilder func(entries []SessionBoundaryDraft) (BoundaryContextPreview, error)
BoundaryContextBuilder builds the would-be model context for the proposed drafts (pi: emitBoundary's buildContext callback). An error marks the preview invalid.
type BoundaryContextPreview ¶ added in v0.87.0
type BoundaryContextPreview struct {
ContextEntries []ProjectedSessionEntry `json:"contextEntries"`
ContextMessages []agent.AgentMessage `json:"contextMessages"`
LLMMessages []types.Message `json:"llmMessages"`
PendingMessages []agent.AgentMessage `json:"pendingMessages"`
CanContinue bool `json:"canContinue"`
}
BoundaryContextPreview is the would-be model context for the proposed drafts (pi: BoundaryContextPreview, v0.87.0).
type BoundaryDispatchResult ¶ added in v0.87.0
type BoundaryDispatchResult struct {
Entries []SessionBoundaryDraft
Continue bool
Context BoundaryContextPreview
// Valid reports whether the last preview build succeeded; an invalid
// dispatch drops the drafts and the continuation (pi: valid).
Valid bool
}
BoundaryDispatchResult is the outcome of EmitBoundary (pi: BoundaryDispatchResult, v0.87.0).
type BoundaryResult ¶ added in v0.87.0
type BoundaryResult struct {
Entries []SessionBoundaryDraft `json:"entries,omitempty"`
Continue *bool `json:"continue,omitempty"`
}
BoundaryResult is the handler result for boundary events (pi: BoundaryResult, v0.87.0). nil Entries keeps the proposed draft list; nil Continue leaves the continuation unspecified.
type BoundaryState ¶ added in v0.87.0
type BoundaryState struct {
Entries []SessionBoundaryDraft `json:"entries"`
Continue bool `json:"continue"`
Context BoundaryContextPreview `json:"context"`
}
BoundaryState is the shared state carried by turn_end and agent_before_settle (pi: BoundaryState, v0.87.0).
type BranchPreparation ¶
type BranchPreparation struct {
// Messages are the extracted messages for summarization, in
// chronological order.
Messages []agent.AgentMessage
// FileOps are the file operations extracted from tool calls.
FileOps *FileOperations
// TotalTokens is the total estimated tokens in messages.
TotalTokens int64
}
BranchPreparation is the prepared summarization input with token budget (pi: BranchPreparation).
func PrepareBranchEntries ¶
func PrepareBranchEntries(entries []SessionEntry, tokenBudget int64) *BranchPreparation
PrepareBranchEntries prepares entries for summarization with a token budget.
Walks entries from NEWEST to OLDEST, adding messages until we hit the token budget. This ensures we keep the most recent context when the branch is too long.
Also collects file operations from:
- Tool calls in assistant messages
- Existing branch_summary entries' details (for cumulative tracking)
tokenBudget is the maximum tokens to include (0 = no limit) (pi: prepareBranchEntries, default tokenBudget 0).
type BranchSummaryDetails ¶
type BranchSummaryDetails struct {
ReadFiles []string `json:"readFiles"`
ModifiedFiles []string `json:"modifiedFiles"`
}
BranchSummaryDetails holds the details stored in BranchSummaryEntry.Details for file tracking (pi: BranchSummaryDetails).
type BranchSummaryEntry ¶
type BranchSummaryEntry struct {
EntryBase
FromID string `json:"fromId"`
Summary string `json:"summary"`
// Details is extension-specific data (not sent to LLM).
Details any `json:"details,omitempty"`
// Usage comes from the LLM call that generated this summary, if
// available.
Usage *types.Usage `json:"usage,omitempty"`
// FromHook is true when generated by an extension, false when
// pi-generated.
FromHook *bool `json:"fromHook,omitempty"`
}
BranchSummaryEntry records a branch summarization (pi: BranchSummaryEntry).
type BranchSummaryResult ¶
type BranchSummaryResult struct {
// Summary is the generated summary text; "" = not generated.
Summary string
// Usage is the usage of the summarization call, if available.
Usage *types.Usage
// ReadFiles are files only read, not modified; nil = not reported (pi:
// readFiles?).
ReadFiles []string
// ModifiedFiles are modified files; nil = not reported (pi:
// modifiedFiles?).
ModifiedFiles []string
// Aborted is true when the summarization call was aborted (pi: aborted?).
Aborted bool
// Error is the error message when summarization failed; "" = success (pi:
// error?).
Error string
}
BranchSummaryResult is the outcome of GenerateBranchSummary; empty strings and false mean pi's undefined members (pi: BranchSummaryResult).
func GenerateBranchSummary ¶
func GenerateBranchSummary( ctx context.Context, entries []SessionEntry, options *GenerateBranchSummaryOptions, ) (*BranchSummaryResult, error)
GenerateBranchSummary generates a summary of abandoned branch entries (pi: generateBranchSummary).
type BranchSummarySettings ¶
type BranchSummarySettings struct {
ReserveTokens *int64 // default: 16384 (tokens reserved for prompt + LLM response)
SkipPrompt *bool // default: false - when true, skips "Summarize branch?" prompt and defaults to no summary
}
BranchSummarySettings holds the branch summary settings shape (pi: BranchSummarySettings).
type BranchSummarySettingsValues ¶
BranchSummarySettingsValues is the resolved branch summary shape (pi: getBranchSummarySettings's inline object literal).
type BugReportBundle ¶ added in v0.86.0
type BugReportBundle struct {
Metadata bugReportMetadata
Diagnostics bugReportDiagnostics
SessionJsonl string // "" = undefined
Summary string // "" = undefined
}
BugReportBundle is everything a delivery needs (pi: BugReportBundle).
type BugReportSessionEntryData ¶ added in v0.86.0
type BugReportSessionEntryData struct {
ID string `json:"id"`
CreatedAt string `json:"createdAt"`
Hint *string `json:"hint"`
SessionIncluded bool `json:"sessionIncluded"`
SummaryIncluded bool `json:"summaryIncluded"`
Delivery string `json:"delivery"` // "zip" | "upload"
Path string `json:"path,omitempty"`
}
BugReportSessionEntryData is the custom entry recording a delivery (pi: BugReportSessionEntryData).
type BugReportSummaryOptions ¶ added in v0.86.0
type BugReportSummaryOptions struct {
// Hint is the user-provided description; "" = undefined.
Hint string
}
BugReportSummaryOptions are the summarizeForBugReport options (pi: the `{ hint?, signal }` object; signal → ctx).
type BuildSystemPromptOptions ¶
type BuildSystemPromptOptions struct {
// CustomPrompt replaces the default prefix ("" = absent).
CustomPrompt string
// ForceSystemPrompt is the exact full prompt replacement set by a
// before_agent_start handler (pi: forceSystemPrompt; v0.86.0). nil =
// unset.
ForceSystemPrompt *string
// SelectedTools lists the tools to include in the prompt; nil = absent
// (default: [read, bash, edit, write]).
SelectedTools []string
// ToolSnippets are optional one-line tool snippets keyed by tool name.
ToolSnippets map[string]string
// ToolGuidelines are guideline bullets contributed by each tool, keyed
// by tool name (pi: toolGuidelines; v0.86.0).
ToolGuidelines map[string][]string
// PromptGuidelines are additional guideline bullets appended to the
// default system prompt rules.
PromptGuidelines []string
// AppendSystemPrompt is text appended from user configuration before
// project context, skills, and cwd ("" = absent).
AppendSystemPrompt string
// Sections are additional XML-wrapped prompt sections keyed by tag name
// (pi: sections; v0.86.0). pig keeps declaration order.
Sections *types.SystemSections
// Cwd is the working directory.
Cwd string
// ContextFiles are pre-loaded context files.
ContextFiles []ContextFile
// Skills are pre-loaded skills.
Skills []Skill
}
BuildSystemPromptOptions carries the buildSystemPrompt options (pi: BuildSystemPromptOptions).
type BuiltinSlashCommand ¶
BuiltinSlashCommand is one built-in slash command (pi: BuiltinSlashCommand).
type CacheMiss ¶
type CacheMiss struct {
// MissedTokens: prompt tokens that were in the previous turn's prompt
// but not read from cache.
MissedTokens int64
// MissedCost: extra dollars paid vs. a full cache hit; 0 when pricing
// is unknown.
MissedCost float64
// IdleMs: milliseconds since the previous request (which last refreshed
// the cache).
IdleMs int64
// ModelChanged is true when the model changed relative to the previous
// request.
ModelChanged bool
}
CacheMiss is a counted cache miss on a single assistant message.
func CollectCacheMisses ¶
func CollectCacheMisses(entries []SessionEntry, models ModelPriceSource) (map[*ai.AssistantMessage]*CacheMiss, []*CacheMiss)
CollectCacheMisses returns all counted cache misses across a session, keyed by the assistant message (by pointer) that paid for them. Used to re-derive transcript notices when rebuilding the chat from entries (resume, post-compaction rebuild). Iteration order is entry order (pig: the misses map plus missSeq preserve it).
func DetectCacheMiss ¶
func DetectCacheMiss(entries []SessionEntry, message *ai.AssistantMessage, models ModelPriceSource) *CacheMiss
DetectCacheMiss detects a cache miss on a just-completed assistant message. `entries` must not yet contain `message` (message_end fires before persistence).
type CacheWarmRequest ¶ added in v0.86.0
type CacheWarmRequest struct {
Model *ai.Model
Context *types.TranscriptContext
Options *ai.ModelsSimpleStreamOptions
}
CacheWarmRequest is the request whose prompt cache entry should be kept warm, exactly as it was sent (pi: CacheWarmRequest).
type CacheWarmer ¶ added in v0.86.0
type CacheWarmer struct {
// contains filtered or unexported fields
}
CacheWarmer keeps one prompt cache entry warm (pi: CacheWarmer).
func NewCacheWarmer ¶ added in v0.86.0
func NewCacheWarmer( models streamSimpleOnly, session usageAppendingSessionManager, getMode func() CacheWarmingMode, decide func(ctx context.Context, event *CacheWarmingDecisionEvent) (CacheWarmingAction, error), ) *CacheWarmer
NewCacheWarmer constructs the warmer (pi: constructor).
func (*CacheWarmer) Cancel ¶ added in v0.86.0
func (w *CacheWarmer) Cancel()
Cancel stops warming (pi: cancel).
func (*CacheWarmer) GetStatus ¶ added in v0.86.0
func (w *CacheWarmer) GetStatus() CacheWarmingStatus
GetStatus returns the current cache-warming state (pi: get status).
func (*CacheWarmer) OnAgentSettled ¶ added in v0.86.0
func (w *CacheWarmer) OnAgentSettled()
OnAgentSettled reconciles the run after an agent run settles (pi: onAgentSettled).
func (*CacheWarmer) OnModeChanged ¶ added in v0.86.0
func (w *CacheWarmer) OnModeChanged()
OnModeChanged reconciles an active run after the persisted warming mode changes (pi: onModeChanged).
func (*CacheWarmer) SetOnWarmed ¶ added in v0.86.0
func (w *CacheWarmer) SetOnWarmed(fn func(entry *UsageEntry))
SetOnWarmed installs the warmed-usage callback (pi: onWarmed property).
func (*CacheWarmer) Start ¶ added in v0.86.0
func (w *CacheWarmer) Start(request CacheWarmRequest, isCurrent func() bool)
Start replaces any previous run and keeps the prompt cache entry written by `request` warm while `isCurrent` holds (pi: start). Warm requests never extend the fixed safety windows.
type CacheWarmerSurface ¶ added in v0.86.0
type CacheWarmerSurface interface {
Cancel()
GetStatus() CacheWarmingStatus
OnAgentSettled()
OnModeChanged()
SetOnWarmed(func(entry *UsageEntry))
}
CacheWarmerSurface is the cache-warmer surface AgentSession consumes (pi: Pick<CacheWarmer, "cancel" | "status" | "onAgentSettled" | "onModeChanged" | "onWarmed">).
type CacheWarmingAction ¶ added in v0.86.0
type CacheWarmingAction string
CacheWarmingAction is pi's warm-or-stop decision outcome (pi: CacheWarmingAction).
const ( CacheWarmingActionWarm CacheWarmingAction = "warm" CacheWarmingActionStop CacheWarmingAction = "stop" )
type CacheWarmingDecision ¶ added in v0.86.0
type CacheWarmingDecision struct {
// Phase is "streaming" while the agent run that sent the request is
// still active.
Phase string
// WarmCost is the price of this refresh: a cache read of the prompt plus
// one output token.
WarmCost float64
// MissCost is the extra price of the next real request if the cache
// entry is lost.
MissCost float64
// ContinuationProbability is the estimated chance that a real request
// arrives before the entry expires.
ContinuationProbability float64
// ExpectedSavings is `continuationProbability * missCost - warmCost`.
ExpectedSavings float64
// EconomicsAvailable is false when the prompt size or the model's
// prices are unknown.
EconomicsAvailable bool
// Action is pi's decision: "warm" when expectedSavings is at least
// $0.05.
Action CacheWarmingAction
}
CacheWarmingDecision holds the inputs and outcome of one warm-or-stop decision, as shown by /session (pi: CacheWarmingDecision).
type CacheWarmingDecisionEvent ¶ added in v0.86.0
type CacheWarmingDecisionEvent struct {
Type string `json:"type"`
WarmCost float64
MissCost float64
ContinuationProbability float64
Action CacheWarmingAction
}
CacheWarmingDecisionEvent is fired before each refresh with pi's decision filled in. Everything else an extension might want (model, idle state, context size) is on the context (pi: CacheWarmingDecisionEvent).
func (*CacheWarmingDecisionEvent) EventType ¶ added in v0.86.0
func (e *CacheWarmingDecisionEvent) EventType() string
type CacheWarmingDecisionEventResult ¶ added in v0.86.0
type CacheWarmingDecisionEventResult struct {
// Action overrides whether this refresh is sent; "stop" ends warming
// until the next real request.
Action CacheWarmingAction `json:"action,omitempty"`
}
CacheWarmingDecisionEventResult is one handler's result (pi: CacheWarmingDecisionEventResult).
type CacheWarmingMode ¶ added in v0.86.0
type CacheWarmingMode string
CacheWarmingMode is a cache-warming profile (pi: CacheWarmingMode; v0.86.0). "idle" also warms between agent runs.
type CacheWarmingStatus ¶ added in v0.86.0
type CacheWarmingStatus struct {
// State: "scheduled" = a refresh timer is armed; "refreshing" = a warm
// request is in flight; "inactive" = nothing scheduled.
State string
// Reason explains why nothing is scheduled.
Reason string
// NextWarmAt is the next refresh time (Unix ms); 0 = unset.
NextWarmAt int64
// Decision is the pending decision, or the decision that stopped
// warming.
Decision *CacheWarmingDecision
// ExtensionOverride is true when an extension changed decision.action.
ExtensionOverride bool
}
CacheWarmingStatus is the current warming state (pi: CacheWarmingStatus).
type CacheWasteTotals ¶
type CacheWasteTotals struct {
MissedTokens int64
MissedCost float64
// MissCount: number of counted misses (turns above the noise floor).
MissCount int
}
CacheWasteTotals is the cumulative cache waste across a session.
func ComputeCacheWaste ¶
func ComputeCacheWaste(entries []SessionEntry, models ModelPriceSource) CacheWasteTotals
ComputeCacheWaste returns cumulative cache waste across a session: prompt tokens that should have been cache reads (they were in the previous turn's prompt) but were re-billed.
type CollectBugReportMetadataOptions ¶ added in v0.86.0
type CollectBugReportMetadataOptions struct {
ID string // "" = a fresh uuidv7
Hint string // "" = null
SessionID string
Cwd string
IncludeSession bool
IncludeSummary bool
MessageCount int
Model *types.Model
ModelRuntime *ModelRuntime
ThinkingLevel agent.ThinkingLevel
Extensions []*Extension
ExtensionErrors []LoadExtensionError
GlobalSettings Settings
ProjectSettings Settings
}
CollectBugReportMetadataOptions are the collectBugReportMetadata parameters (pi: CollectBugReportMetadataOptions).
type CollectEntriesResult ¶
type CollectEntriesResult struct {
// Entries are the entries to summarize, in chronological order.
Entries []SessionEntry
// CommonAncestorID is the deepest node shared by both paths; nil = none
// (pi: string | null).
CommonAncestorID *string
}
CollectEntriesResult holds the entries to summarize plus the common ancestor between old and new position, if any (pi: CollectEntriesResult; commonAncestorId string|null → *string).
func CollectEntriesForBranchSummary ¶
func CollectEntriesForBranchSummary( session ReadonlySessionManager, oldLeafID *string, targetID string, ) *CollectEntriesResult
CollectEntriesForBranchSummary collects the entries that should be summarized when navigating from one position to another.
Walks from oldLeafId back to the common ancestor with targetId, collecting entries along the way. Does NOT stop at compaction boundaries — those are included and their summaries become context.
oldLeafID nil means no old position: nothing to summarize (pi: collectEntriesForBranchSummary).
type CompactOptions ¶
type CompactOptions struct {
// CustomInstructions are the optional custom focus for the summary;
// "" = none (pi: customInstructions?).
CustomInstructions string
// OnComplete fires with the compaction result (pi: onComplete).
OnComplete func(result *CompactionResult)
// OnError fires when compaction failed (pi: onError).
OnError func(err error)
}
CompactOptions are the options for triggering compaction from extensions (pi: CompactOptions).
type CompactionDetails ¶
type CompactionDetails struct {
ReadFiles []string `json:"readFiles"`
ModifiedFiles []string `json:"modifiedFiles"`
}
CompactionDetails holds the details stored in CompactionEntry.Details for file tracking (pi: CompactionDetails).
type CompactionEntry ¶
type CompactionEntry struct {
EntryBase
Summary string `json:"summary"`
FirstKeptEntryID string `json:"firstKeptEntryId"`
TokensBefore int64 `json:"tokensBefore"`
// Details is extension-specific data (e.g. ArtifactIndex, version
// markers for structured compaction).
Details any `json:"details,omitempty"`
// Usage comes from the LLM call(s) that generated this summary, if
// available.
Usage *types.Usage `json:"usage,omitempty"`
// FromHook is true when generated by an extension, nil/false when
// pi-generated (backward compatible).
FromHook *bool `json:"fromHook,omitempty"`
// SystemMessage is the complete prompt state at this compaction
// boundary (pi: systemMessage; v0.86.0). Replayed ahead of the summary
// so mid-conversation system messages survive compaction.
SystemMessage *types.SystemMessage `json:"systemMessage,omitempty"`
// FirstKeptEntryIndex is the v1 legacy field (pi: firstKeptEntryIndex,
// deleted during v1→v2 migration; pig keeps it as a pointer the
// migration zeroes so it never re-serializes).
FirstKeptEntryIndex *int64 `json:"firstKeptEntryIndex,omitempty"`
}
CompactionEntry records a compaction summary (pi: CompactionEntry).
func GetLatestCompactionEntry ¶
func GetLatestCompactionEntry(entries []SessionEntry) *CompactionEntry
GetLatestCompactionEntry returns the most recent compaction entry, or nil (pi: getLatestCompactionEntry).
type CompactionEntryDraft ¶ added in v0.87.0
type CompactionEntryDraft struct {
Type string `json:"type"`
Summary string `json:"summary"`
// FirstKeptEntryID nil creates a self-retaining compaction that keeps no
// preceding entries (pi: firstKeptEntryId: string | null).
FirstKeptEntryID *string `json:"firstKeptEntryId"`
Details any `json:"details,omitempty"`
Usage *types.Usage `json:"usage,omitempty"`
}
CompactionEntryDraft proposes a compaction (pi: CompactionEntryDraft, v0.87.0).
type CompactionModelOverride ¶ added in v0.86.0
CompactionModelOverride overrides one model's compaction token settings (pi: CompactionModelOverride; v0.86.0).
type CompactionPreparation ¶
type CompactionPreparation struct {
// FirstKeptEntryID is the UUID of first entry to keep.
FirstKeptEntryID string
// MessagesToSummarize are the messages that will be summarized and
// discarded.
MessagesToSummarize []agent.AgentMessage
// TurnPrefixMessages are the messages that will be turned into turn
// prefix summary (if splitting).
TurnPrefixMessages []agent.AgentMessage
// IsSplitTurn reports whether this is a split turn (cut point in middle
// of turn).
IsSplitTurn bool
TokensBefore int64
// PreviousSummary is the summary from previous compaction, for iterative
// update; "" = none (pi: previousSummary?).
PreviousSummary string
// FileOps are the file operations extracted from messagesToSummarize.
FileOps *FileOperations
// Settings are the compaction settings from settings.json (pi: settings;
// comment's "settings.jsonl" typo follows pi).
Settings CompactionSettingsValues
}
CompactionPreparation is the pre-calculated compaction input consumed by Compact and exposed to the session_before_compact extension event (pi: CompactionPreparation).
func PrepareCompaction ¶
func PrepareCompaction(pathEntries []SessionEntry, settings CompactionSettingsValues) *CompactionPreparation
PrepareCompaction computes the compaction preparation for a session branch; nil means nothing to compact (pi: prepareCompaction; v0.87.0 projection rewrite).
type CompactionResult ¶
type CompactionResult struct {
Summary string `json:"summary"`
FirstKeptEntryID string `json:"firstKeptEntryId"`
TokensBefore int64 `json:"tokensBefore"`
// EstimatedTokensAfter is filled by AgentSession after rebuilding the
// context (pi: estimatedTokensAfter?).
EstimatedTokensAfter *int64 `json:"estimatedTokensAfter,omitempty"`
// Usage is the usage from the LLM call(s) that generated this summary,
// if available.
Usage *types.Usage `json:"usage,omitempty"`
// Details is extension-specific data (e.g. ArtifactIndex, version
// markers for structured compaction).
Details any `json:"details,omitempty"`
}
CompactionResult is the result from Compact — SessionManager adds uuid/parentUuid when saving (pi: CompactionResult<T>; the details generic collapses to any, filled with CompactionDetails by Compact).
func Compact ¶
func Compact( ctx context.Context, preparation *CompactionPreparation, model *ai.Model, apiKey string, headers map[string]string, customInstructions string, thinkingLevel types.ThinkingLevel, streamFn agent.StreamFn, env ai.ProviderEnv, retry *ai.RetryPolicy, callbacks *ai.RetryCallbacks, sessionID string, ) (*CompactionResult, error)
Compact generates summaries for compaction using prepared data; the returned CompactionResult is persisted by SessionManager, which adds uuid/parentUuid when saving (pi: compact; pi's signal member is dropped — cancellation travels as ctx).
sessionId is the optional routing session ID forwarded without enabling prompt caching.
type CompactionSettings ¶
type CompactionSettings struct {
Enabled *bool // default: true
ReserveTokens *int64 // default: 16384
KeepRecentTokens *int64 // default: 20000
// ModelOverrides overrides token settings per exact "provider/modelId"
// key (pi: modelOverrides; v0.86.0).
ModelOverrides map[string]CompactionModelOverride
}
CompactionSettings holds the user-facing compaction settings shape (pi: CompactionSettings in settings-manager.ts — the optional shape; distinct from the resolved shape of the same name in harness).
type CompactionSettingsValues ¶
CompactionSettingsValues is the resolved compaction settings shape (pi: getCompactionSettings's inline object literal).
type CompatibilityRequestConfig ¶
type CompatibilityRequestConfig struct {
Headers types.ProviderHeaders
AuthHeader bool
}
CompatibilityRequestConfig is the request config used when provider auth is unconfigured (pi: CompatibilityRequestConfig).
func ResolveCompatibilityRequestConfig ¶
func ResolveCompatibilityRequestConfig(model ai.Model, config *ModelsJsonProvider, extension *ProviderConfigInput) (CompatibilityRequestConfig, error)
ResolveCompatibilityRequestConfig resolves the compatibility request config (pi: resolveCompatibilityRequestConfig).
type ContextEditEntry ¶ added in v0.87.0
type ContextEditEntry struct {
EntryBase
TargetID string `json:"targetId"`
// Replacement nil (pi: null) omits the target from model context; a
// value replaces only its content.
Replacement *ContextEditReplacement `json:"replacement"`
}
ContextEditEntry is an append-only edit of one earlier context-producing entry (pi: ContextEditEntry; v0.87.0). It changes only future model context; the target entry and its metadata remain unchanged in raw history, UI, exports, and session accounting.
type ContextEditEntryDraft ¶ added in v0.87.0
type ContextEditEntryDraft struct {
Type string `json:"type"`
TargetID string `json:"targetId"`
// Replacement nil (pi: null) omits the target from model context; a value
// replaces only its content.
Replacement *ContextEditReplacement `json:"replacement"`
}
ContextEditEntryDraft proposes a context edit (pi: ContextEditEntryDraft, v0.87.0).
type ContextEditReplacement ¶ added in v0.87.0
type ContextEditReplacement struct {
Content ContextEditableContent `json:"content"`
}
ContextEditReplacement is the non-null replacement payload of a ContextEditEntry (pi: `{ content: ContextEditableContent }`).
func (*ContextEditReplacement) UnmarshalJSON ¶ added in v0.87.0
func (r *ContextEditReplacement) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes replacement content as string or []types.Content (pi: ContextEditableContent; pig decodes content-block arrays into typed Content at the boundary so projections see one shape). JSON null content normalizes to an empty array (pi's own writer never produces it; appendContextEdit rejects it).
type ContextEditableContent ¶ added in v0.87.0
type ContextEditableContent = any
ContextEditableContent is the content shape an append-only context edit may replace without changing message metadata (pi: ContextEditableContent = UserMessage.content | AssistantMessage.content | ToolResultMessage.content | CustomMessage.content). Decoded values are string or []types.Content (see ContextEditReplacement.UnmarshalJSON).
type ContextEvent ¶
type ContextEvent struct {
Type string `json:"type"`
Messages []agent.AgentMessage `json:"messages"`
}
ContextEvent fires with the message context before each agent loop (pi: ContextEvent).
func (*ContextEvent) EventType ¶
func (e *ContextEvent) EventType() string
type ContextEventResult ¶
type ContextEventResult struct {
Messages []agent.AgentMessage `json:"messages"`
}
ContextEventResult is the handler result of context and context_with_system (pi: ContextEventResult).
type ContextFile ¶
ContextFile is one pre-loaded context file (pi: inline { path, content } member of BuildSystemPromptOptions).
type ContextUsage ¶
type ContextUsage struct {
// Tokens is the estimated context token count; nil = unknown.
Tokens *int64
// ContextWindow is the model's context window.
ContextWindow int64
// Percent is the usage as percentage of the context window; nil = unknown.
Percent *float64
}
ContextUsage describes the current context window usage (pi: ContextUsage). nil Tokens/Percent = pi's null (unknown, e.g. right after compaction before the next LLM response).
type ContextUsageEstimate ¶
type ContextUsageEstimate = compaction.ContextUsageEstimate
ContextUsageEstimate is the result of EstimateContextTokens (pi: ContextUsageEstimate; identical shape delegated to the harness type, see header).
func EstimateContextTokens ¶
func EstimateContextTokens(messages []agent.AgentMessage) ContextUsageEstimate
EstimateContextTokens estimates context tokens from messages, using the last assistant usage when available; messages after the last usage are estimated with EstimateTokens (pi: estimateContextTokens; identical twin delegated to the harness implementation, see header).
func EstimateProjectedContextTokens ¶ added in v0.87.0
func EstimateProjectedContextTokens(projection SessionProjection, branchEntries []SessionEntry) ContextUsageEstimate
EstimateProjectedContextTokens estimates the projected context without trusting usage captured before a later edit or compaction (pi: estimateProjectedContextTokens; v0.87.0). When the message carrying the last assistant usage is followed — along the raw branch — by a context_edit or compaction entry, the usage no longer describes the projected context and every message falls back to the chars/4 estimate, with the replayed system message replacing the stored system entries.
type ContextWithSystemEvent ¶ added in v0.87.0
type ContextWithSystemEvent struct {
Type string `json:"type"`
Messages []agent.AgentMessage `json:"messages"`
}
ContextWithSystemEvent fires before each LLM call after every context handler has run and Pi has restored the prompt and tool state; the result is sent as returned (pi: ContextWithSystemEvent, v0.87.0).
func (*ContextWithSystemEvent) EventType ¶ added in v0.87.0
func (e *ContextWithSystemEvent) EventType() string
type CrashRecord ¶ added in v0.86.0
type CrashRecord struct {
Timestamp string `json:"timestamp"`
Version string `json:"version"`
Kind CrashRecordKind `json:"kind"`
Message string `json:"message"`
Stack *string `json:"stack"`
SessionFile *string `json:"sessionFile"`
Cwd string `json:"cwd"`
Notified *bool `json:"notified,omitempty"`
}
CrashRecord is one persisted crash entry (pi: CrashRecord).
func ReadCrashLog ¶ added in v0.86.0
func ReadCrashLog(path string) []CrashRecord
ReadCrashLog returns the persisted crash records, skipping malformed ones (pi: readCrashLog). Records must carry string timestamp + message.
func RecordCrash ¶ added in v0.86.0
func RecordCrash(crash CrashRecordInput, path string) *CrashRecord
RecordCrash persists one crash entry, keeping the newest maxCrashRecords (pi: recordCrash — "best-effort persistence for callers that are already crashing"). Returns the record, or nil when nothing was written.
func TakeUnnotifiedCrash ¶ added in v0.86.0
func TakeUnnotifiedCrash(path string, now time.Time) *CrashRecord
TakeUnnotifiedCrash returns the newest recent unannounced crash, marking pending records as announced (pi: takeUnnotifiedCrash).
type CrashRecordInput ¶ added in v0.86.0
type CrashRecordInput struct {
Kind CrashRecordKind
Error error
SessionFile string // "" = null (pi: sessionFile?)
Cwd string
// Stack attaches a stack trace when the caller has one (pig deviation:
// Go errors carry no stack; pi reads error.stack). "" = null.
Stack string
}
CrashRecordInput is the recordCrash parameter (pi: the options object).
type CrashRecordKind ¶ added in v0.86.0
type CrashRecordKind string
CrashRecordKind discriminates the crash origin (pi: CrashRecord["kind"]).
const ( // CrashKindUncaughtException is an uncaught panic (pi: // "uncaught_exception"). CrashKindUncaughtException CrashRecordKind = "uncaught_exception" // CrashKindFatalError is a fatal runtime error path (pi: "fatal_error"). CrashKindFatalError CrashRecordKind = "fatal_error" )
type CreateAgentSessionFromServicesOptions ¶
type CreateAgentSessionFromServicesOptions struct {
Services *AgentSessionServices
SessionManager *SessionManager
SessionStartEvent *SessionStartEvent
Model *types.Model
ThinkingLevel agent.ThinkingLevel
ScopedModels []ScopedModel
Tools []string
ExcludeTools []string
NoTools string
CustomTools []*tools.ToolDefinition
}
CreateAgentSessionFromServicesOptions are the inputs for creating an AgentSession from already-created services (pi: CreateAgentSessionFromServicesOptions).
type CreateAgentSessionOptions ¶
type CreateAgentSessionOptions struct {
// Cwd is the working directory for project-local discovery. Default:
// process.cwd().
Cwd string
// AgentDir is the global config directory. Default: ~/.pi/agent.
AgentDir string
// ModelRuntime is the canonical model/auth runtime. Defaults to a
// runtime using agentDir/auth.json and models.json.
ModelRuntime *ModelRuntime
// Model is the model to use. Default: from settings, else first
// available.
Model *types.Model
// ThinkingLevel is the thinking level. Default: from settings, else
// "medium" (clamped to model capabilities). "" = undefined.
ThinkingLevel agent.ThinkingLevel
// ScopedModels are the models available for cycling (Ctrl+P in
// interactive mode).
ScopedModels []ScopedModel
// NoTools is the default tool suppression mode when no explicit
// allowlist is provided (pi: noTools?: "all" | "builtin"). "" =
// undefined.
//
// - "all": start with no tools enabled
// - "builtin": disable the default built-in tools (read, bash, edit,
// write) but keep extension/custom tools enabled
NoTools string
// Tools is the optional allowlist of tool names. When omitted, pig uses
// the defaultTools setting for the initial built-in selection when
// configured; otherwise it enables the default built-in tools (read,
// bash, edit, write). Extension/custom tools remain enabled unless
// NoTools changes that default. When provided, only the listed tool
// names are enabled.
Tools []string
// ExcludeTools is the optional denylist of tool names to disable.
// Applies after Tools when both are provided.
ExcludeTools []string
// CustomTools are custom tools to register (in addition to built-in
// tools).
CustomTools []*tools.ToolDefinition
// ResourceLoader supplies resources. When nil, DefaultResourceLoader is
// used.
ResourceLoader ResourceLoader
// SessionManager is the session manager. Default:
// SessionManager.create(cwd).
SessionManager *SessionManager
// SettingsManager is the settings manager. Default:
// SettingsManager.create(cwd, agentDir).
SettingsManager *SettingsManager
// SessionStartEvent is the session start event metadata for extension
// runtime startup.
SessionStartEvent *SessionStartEvent
}
CreateAgentSessionOptions are the createAgentSession inputs (pi: CreateAgentSessionOptions). pi's optional fields collapse per §3.4: nil pointers / empty values = undefined.
type CreateAgentSessionResult ¶
type CreateAgentSessionResult struct {
// Session is the created session.
Session *AgentSession
// ExtensionsResult carries the extensions result (for UI context setup
// in interactive mode).
ExtensionsResult *LoadExtensionsResult
// ModelFallbackMessage is set when the session was restored with a
// different model than saved. "" = none (pi: string | undefined).
ModelFallbackMessage string
}
CreateAgentSessionResult is the createAgentSession result (pi: CreateAgentSessionResult).
func CreateAgentSession ¶
func CreateAgentSession(ctx context.Context, options *CreateAgentSessionOptions) (*CreateAgentSessionResult, error)
CreateAgentSession creates an AgentSession with the specified options (pi: createAgentSession).
func CreateAgentSessionFromServices ¶
func CreateAgentSessionFromServices(ctx context.Context, options CreateAgentSessionFromServicesOptions) (*CreateAgentSessionResult, error)
CreateAgentSessionFromServices creates an AgentSession from previously created services (pi: createAgentSessionFromServices). This keeps session creation separate from service creation so callers can resolve model, thinking, tools, and other session inputs against the target cwd before constructing the session.
type CreateAgentSessionRuntimeFactory ¶
type CreateAgentSessionRuntimeFactory = func(options CreateAgentSessionRuntimeFactoryOptions) (*CreateAgentSessionRuntimeResult, error)
CreateAgentSessionRuntimeFactory creates a full runtime for a target cwd and session manager (pi: CreateAgentSessionRuntimeFactory).
type CreateAgentSessionRuntimeFactoryOptions ¶
type CreateAgentSessionRuntimeFactoryOptions struct {
Cwd string
AgentDir string
SessionManager *SessionManager
SessionStartEvent *SessionStartEvent
// ProjectTrustContext is deferred with the extensions batch (pi:
// projectTrustContext: ProjectTrustContext); the factory below feeds it
// once the type lands.
ProjectTrustContext any
}
CreateAgentSessionRuntimeFactoryOptions are the factory inputs (pi's inline options object).
type CreateAgentSessionRuntimeResult ¶
type CreateAgentSessionRuntimeResult struct {
CreateAgentSessionResult
Services *AgentSessionServices
Diagnostics []AgentSessionRuntimeDiagnostic
ModelFallbackMessage string
}
CreateAgentSessionRuntimeResult is the result returned by runtime creation (pi: CreateAgentSessionRuntimeResult extends CreateAgentSessionResult).
type CreateAgentSessionServicesOptions ¶
type CreateAgentSessionServicesOptions struct {
Cwd string
AgentDir string
// SettingsManager is an explicit override; nil = create (pi:
// settingsManager?).
SettingsManager *SettingsManager
// ModelRuntime is an explicit override; nil = create (pi:
// modelRuntime?).
ModelRuntime *ModelRuntime
// ExtensionFlagValues maps "--name" → value for extension flags (pi:
// extensionFlagValues). nil = none.
ExtensionFlagValues map[string]any
// ResourceLoaderOptions are the loader options minus cwd/agentDir/
// settingsManager, which this function fixes (pi: resourceLoaderOptions:
// Omit<DefaultResourceLoaderOptions, ...>).
ResourceLoaderOptions *DefaultResourceLoaderOptions
// ResourceLoaderReloadOptions are forwarded to loader.Reload (pi:
// resourceLoaderReloadOptions).
ResourceLoaderReloadOptions *ResourceLoaderReloadOptions
}
CreateAgentSessionServicesOptions are the inputs for creating cwd-bound runtime services (pi: CreateAgentSessionServicesOptions). pi's modelRuntimeSignal is dropped per the AbortSignal → ctx rule: the ctx passed to CreateAgentSessionServices carries cancellation.
type CreateModelRuntimeOptions ¶
type CreateModelRuntimeOptions struct {
// Credentials is the credential storage; defaults to the file at
// AuthPath (pi: credentials / authPath).
Credentials auth.CredentialStore
AuthPath string
// ModelsPath selects models.json: nil = the default agent-dir path, a
// pointer to "" = no file (pi: modelsPath?: string | null).
ModelsPath *string
ModelsStore ai.ModelsStore
// ModelsStorePath overrides the catalog store location (pi:
// modelsStorePath).
ModelsStorePath string
// AllowModelNetwork lets create() refresh model catalogs over the
// network; defaults to false.
AllowModelNetwork bool
// ModelRefreshTimeoutMs bounds the create-time network model refresh.
ModelRefreshTimeoutMs int64
CatalogBaseURL string
// RefreshOnCreate skips the initial catalog and availability refresh
// when false; static models remain available.
RefreshOnCreate *bool
}
CreateModelRuntimeOptions parameterize CreateModelRuntime (pi: CreateModelRuntimeOptions). Cancellation rides the context instead of the signal member.
type CredentialSynchronizationError ¶
type CredentialSynchronizationError struct {
ProviderID string
Operation CredentialSynchronizationOperation
Credential auth.Credential
Cause error
}
CredentialSynchronizationError reports that credentials changed successfully but the local model/auth snapshot could not be synchronized (pi: CredentialSynchronizationError).
func (*CredentialSynchronizationError) Error ¶
func (e *CredentialSynchronizationError) Error() string
func (*CredentialSynchronizationError) Unwrap ¶
func (e *CredentialSynchronizationError) Unwrap() error
type CredentialSynchronizationOperation ¶
type CredentialSynchronizationOperation string
CredentialSynchronizationOperation names one credential mutation (pi: CredentialSynchronizationOperation).
const ( CredentialSyncLogin CredentialSynchronizationOperation = "login" CredentialSyncLogout CredentialSynchronizationOperation = "logout" CredentialSyncSetRuntimeApiKey CredentialSynchronizationOperation = "setRuntimeApiKey" CredentialSyncRemoveRuntimeApiKey CredentialSynchronizationOperation = "removeRuntimeApiKey" )
type CustomEntry ¶
type CustomEntry struct {
EntryBase
CustomType string `json:"customType"`
// Data is extension-specific payload (pi: data?: T).
Data any `json:"data,omitempty"`
}
CustomEntry stores extension-specific data in the session (pi: CustomEntry). It does NOT participate in LLM context (ignored by buildSessionContext); for injecting content into context see CustomMessageEntry.
type CustomEntryDraft ¶ added in v0.87.0
type CustomEntryDraft struct {
Type string `json:"type"`
CustomType string `json:"customType"`
// Data is the entry payload; nil = pi's omitted optional key.
Data any `json:"data,omitempty"`
}
CustomEntryDraft proposes a custom entry (pi: CustomEntryDraft, v0.87.0).
type CustomMessageEntry ¶
type CustomMessageEntry struct {
EntryBase
CustomType string `json:"customType"`
// Content is a string or a []types.Content of text/image parts (pi:
// `string | (TextContent | ImageContent)[]`); values decoded from
// generic JSON arrive as map/slice values.
Content any `json:"content"`
Details any `json:"details,omitempty"`
Display bool `json:"display"`
}
CustomMessageEntry lets extensions inject messages into LLM context (pi: CustomMessageEntry). Unlike CustomEntry this DOES participate in LLM context: the content is converted to a user message in buildSessionContext. Details is extension-specific metadata (not sent to LLM). Display controls TUI rendering: false = hidden entirely, true = rendered with distinct styling.
type CustomMessageEntryDraft ¶ added in v0.87.0
type CustomMessageEntryDraft struct {
Type string `json:"type"`
CustomType string `json:"customType"`
// Content is a string or a (TextContent | ImageContent)[] (pi union).
Content any `json:"content"`
Display bool `json:"display"`
// Details is the entry payload; nil = pi's omitted optional key.
Details any `json:"details,omitempty"`
}
CustomMessageEntryDraft proposes a custom message entry (pi: CustomMessageEntryDraft, v0.87.0).
type CustomMessagePayload ¶
type CustomMessagePayload struct {
CustomType string
// Content is a string or a []types.Content of text/image parts (pi:
// `string | (TextContent | ImageContent)[]`).
Content any
Display bool
Details any
}
CustomMessagePayload is the message payload of sendCustomMessage/sendMessage (pi: Pick<CustomMessage, "customType" | "content" | "display" | "details">).
type CutPointResult ¶
type CutPointResult struct {
// FirstKeptEntryIndex is the index of first entry to keep.
FirstKeptEntryIndex int
// TurnStartIndex is the index of the user message that starts the turn
// being split, or -1 if not splitting.
TurnStartIndex int
// IsSplitTurn reports whether this cut splits a turn (cut point is not a
// user message).
IsSplitTurn bool
}
CutPointResult is the outcome of FindCutPoint (pi: CutPointResult).
func FindCutPoint ¶
func FindCutPoint(entries []SessionEntry, startIndex int, endIndex int, keepRecentTokens int64) CutPointResult
FindCutPoint finds the cut point in session entries that keeps approximately keepRecentTokens.
Algorithm: walk backwards from newest, accumulating estimated message sizes. Stop when we've accumulated >= keepRecentTokens. Cut at that point.
Can cut at user OR assistant messages (never tool results). When cutting at an assistant message with tool calls, its tool results come after and will be kept.
Only considers entries between startIndex and endIndex (exclusive) (pi: findCutPoint).
type DefaultProjectTrust ¶
type DefaultProjectTrust = string
DefaultProjectTrust selects the default project trust decision.
const ( DefaultProjectTrustAsk DefaultProjectTrust = "ask" DefaultProjectTrustAlways DefaultProjectTrust = "always" DefaultProjectTrustNever DefaultProjectTrust = "never" )
type DefaultResourceLoader ¶
type DefaultResourceLoader struct {
// contains filtered or unexported fields
}
DefaultResourceLoader is the main resource loader (pi: DefaultResourceLoader).
func NewDefaultResourceLoader ¶
func NewDefaultResourceLoader(options DefaultResourceLoaderOptions) *DefaultResourceLoader
NewDefaultResourceLoader builds the loader (pi: constructor).
func (*DefaultResourceLoader) ExtendResources ¶
func (l *DefaultResourceLoader) ExtendResources(paths ResourceExtensionPaths)
ExtendResources merges extension-contributed resource paths (pi: extendResources). pi's PathMetadata entries carry baseDir; pig reuses PathMetadata with the extension metadata literal mapped by the caller.
func (*DefaultResourceLoader) GetAgentsFiles ¶
func (l *DefaultResourceLoader) GetAgentsFiles() []AgentsFile
GetAgentsFiles returns the context files (pi: getAgentsFiles).
func (*DefaultResourceLoader) GetAppendSystemPrompt ¶
func (l *DefaultResourceLoader) GetAppendSystemPrompt() []string
GetAppendSystemPrompt returns the append segments (pi: getAppendSystemPrompt).
func (*DefaultResourceLoader) GetAppendSystemPromptSources ¶
func (l *DefaultResourceLoader) GetAppendSystemPromptSources() []string
GetAppendSystemPromptSources returns append source paths (pi: getAppendSystemPromptSources).
func (*DefaultResourceLoader) GetExtensions ¶
func (l *DefaultResourceLoader) GetExtensions() *LoadExtensionsResult
GetExtensions returns the loaded extensions result (pi: getExtensions).
func (*DefaultResourceLoader) GetPrompts ¶
func (l *DefaultResourceLoader) GetPrompts() ([]PromptTemplate, []ResourceDiagnostic)
GetPrompts returns prompts and diagnostics (pi: getPrompts).
func (*DefaultResourceLoader) GetSkills ¶
func (l *DefaultResourceLoader) GetSkills() ([]Skill, []ResourceDiagnostic)
GetSkills returns skills and diagnostics (pi: getSkills).
func (*DefaultResourceLoader) GetSystemPrompt ¶
func (l *DefaultResourceLoader) GetSystemPrompt() (string, bool)
GetSystemPrompt returns the custom system prompt override (pi: getSystemPrompt). ok=false = undefined.
func (*DefaultResourceLoader) GetSystemPromptSource ¶
func (l *DefaultResourceLoader) GetSystemPromptSource() (string, bool)
GetSystemPromptSource returns the system prompt source path (pi: getSystemPromptSource).
func (*DefaultResourceLoader) GetThemes ¶
func (l *DefaultResourceLoader) GetThemes() ([]any, []ResourceDiagnostic)
GetThemes returns themes and diagnostics (pi: getThemes). Theme loading is deferred with the theme batch; only diagnostics are populated today.
func (*DefaultResourceLoader) Reload ¶
func (l *DefaultResourceLoader) Reload(options *ResourceLoaderReloadOptions) error
Reload reloads all resources (pi: reload).
type DefaultResourceLoaderOptions ¶
type DefaultResourceLoaderOptions struct {
Cwd string
AgentDir string
SettingsManager *SettingsManager
EventBus EventBus
// PackageManager is deferred with the package-manager batch (pi:
// packageManager / DefaultPackageManager).
AdditionalExtensionPaths []string
AdditionalSkillPaths []string
AdditionalPromptTemplatePaths []string
AdditionalThemePaths []string
// ExtensionFactories is deferred with the extension batch (pi:
// extensionFactories: InlineExtension[]).
NoExtensions bool
NoSkills bool
NoPromptTemplates bool
NoThemes bool
NoContextFiles bool
SystemPrompt string
AppendSystemPrompt []string
// ExtensionsOverride is deferred with the extension batch (pi:
// extensionsOverride).
SkillsOverride func(base LoadSkillsResult) LoadSkillsResult
PromptsOverride func(base PromptLoaderResult) PromptLoaderResult
ThemesOverride func(base ThemeLoaderResult) ThemeLoaderResult
AgentsFilesOverride func(base []AgentsFile) []AgentsFile
SystemPromptOverride func(base string, ok bool) (string, bool)
AppendSystemPromptOverride func(base []string) []string
}
DefaultResourceLoaderOptions configures the loader (pi: DefaultResourceLoaderOptions).
type EditorFactory ¶
type EditorFactory func(tui tui.TUI, editorTheme tui.EditorTheme, keybindings *KeybindingsManager) tui.EditorComponent
EditorFactory builds a custom editor component (pi: EditorFactory `(tui, theme, keybindings) => EditorComponent`).
type EntryBase ¶
type EntryBase struct {
Type string `json:"type"`
ID string `json:"id"`
ParentID *string `json:"parentId"`
Timestamp string `json:"timestamp"`
}
EntryBase carries the fields shared by every session-tree entry (pi: SessionEntryBase). Timestamp is an ISO date string (wire format).
type EntryRenderOptions ¶
type EntryRenderOptions struct {
Expanded bool
}
EntryRenderOptions carries the entry renderer options (pi: EntryRenderOptions).
type EntryRenderer ¶
type EntryRenderer func(entry *CustomEntry, options EntryRenderOptions, theme UITheme) tui.Component
EntryRenderer renders a CustomEntry to a component; nil = no content (pi: EntryRenderer<T>).
type EventBus ¶
type EventBus interface {
Emit(channel string, data any)
On(channel string, handler func(data any)) (unsubscribe func())
}
EventBus is the channel pub/sub interface (pi: EventBus).
type EventBusController ¶
type EventBusController interface {
EventBus
Clear()
}
EventBusController adds clearing all listeners (pi: EventBusController).
func CreateEventBus ¶
func CreateEventBus() EventBusController
CreateEventBus creates the shared event bus (pi: createEventBus).
type Extension ¶
type Extension struct {
Path string
ResolvedPath string
Hidden bool
SourceInfo SourceInfo
Handlers map[string][]ExtensionHandler
Tools map[string]RegisteredTool
// MessageRenderers map CustomMessage custom types to components (pi:
// messageRenderers: Map<string, MessageRenderer>).
MessageRenderers map[string]MessageRenderer
EntryRenderers map[string]EntryRenderer
// MarkdownTransformer transforms user/assistant Markdown before the
// transcript renders it (pi: markdownTransformer?; single slot — the
// last registration wins).
MarkdownTransformer MarkdownTransformer
Commands map[string]RegisteredCommand
Flags map[string]ExtensionFlag
// Shortcuts maps the shortcut key id to the handler (pi: shortcuts:
// Map<KeyId, ExtensionShortcut>).
Shortcuts map[tui.KeyId]*ExtensionShortcut
}
Extension is one loaded extension with all registered items (pi: Extension; the loader arrives in Phase 7 — the runner only ever sees an empty slice until then).
type ExtensionActions ¶
type ExtensionActions struct {
SendMessage func(ctx context.Context, message *CustomMessagePayload, options *SendMessageOptions)
SendUserMessage func(ctx context.Context, content string, options *SendUserMessageOptions)
AppendEntry func(customType string, data any) string
SetSessionName func(name string)
GetSessionName func() (string, bool)
SetLabel func(entryID string, label string)
GetActiveTools func() []string
GetAllTools func() []ToolInfo
SetActiveTools func(toolNames []string)
RefreshTools func()
GetCommands func() []SlashCommandInfo
SetModel func(ctx context.Context, model *types.Model) bool
GetThinkingLevel func() agent.ThinkingLevel
SetThinkingLevel func(level agent.ThinkingLevel)
}
ExtensionActions are the action implementations for the pi.* API methods, provided to the runner via bindCore (pi: ExtensionActions).
type ExtensionBindings ¶
type ExtensionBindings struct {
UIContext ExtensionUIContext
Mode ExtensionMode
CommandContextActions *ExtensionCommandContextActions
AbortHandler func()
ShutdownHandler ShutdownHandler
OnError ExtensionErrorListener
}
ExtensionBindings are the extension host bindings (pi: ExtensionBindings).
type ExtensionCommandContext ¶
type ExtensionCommandContext struct {
ExtensionContext
// GetSystemPromptOptions returns the base system-prompt construction
// options (pi: getSystemPromptOptions).
GetSystemPromptOptions func() BuildSystemPromptOptions
// WaitForIdle waits for the agent to finish streaming (pi: waitForIdle).
WaitForIdle func(ctx context.Context) error
// NewSession starts a new session, optionally with initialization (pi:
// newSession).
NewSession func(ctx context.Context, options *NewSessionCommandOptions) (cancelled bool, err error)
// Fork forks from a specific entry, creating a new session file (pi:
// fork).
Fork func(ctx context.Context, entryID string, options *ForkCommandOptions) (cancelled bool, err error)
// navigateTree).
NavigateTree func(ctx context.Context, targetID string, options *NavigateTreeCommandOptions) (cancelled bool, err error)
// SwitchSession switches to a different session file (pi:
// switchSession).
SwitchSession func(ctx context.Context, sessionPath string, options *SwitchSessionCommandOptions) (cancelled bool, err error)
// Reload reloads extensions, skills, prompts, themes, and context files
// (pi: reload).
Reload func(ctx context.Context) error
}
ExtensionCommandContext is the extended context for command handlers (pi: ExtensionCommandContext).
type ExtensionCommandContextActions ¶
type ExtensionCommandContextActions struct {
WaitForIdle func(ctx context.Context) error
NewSession func(ctx context.Context, options *NewSessionCommandOptions) (cancelled bool, err error)
Fork func(ctx context.Context, entryID string, options *ForkCommandOptions) (cancelled bool, err error)
SwitchSession func(ctx context.Context, sessionPath string, options *SwitchSessionCommandOptions) (cancelled bool, err error)
Reload func(ctx context.Context) error
}
ExtensionCommandContextActions are the actions for ExtensionCommandContext; only needed for interactive mode where extension commands are invokable (pi: ExtensionCommandContextActions).
type ExtensionContext ¶
type ExtensionContext struct {
// UI is the UI surface for user interaction (pi: ui).
UI ExtensionUIContext
// Mode is the current run mode; use ExtensionModeTUI to guard
// terminal-only UI (pi: mode).
Mode ExtensionMode
// HasUI reports whether dialog-capable UI is available (true in TUI and
// RPC modes) (pi: hasUI).
HasUI bool
// Cwd is the current working directory (pi: cwd).
Cwd string
// SessionManager is the session manager (read-only) (pi:
// sessionManager).
SessionManager ReadonlySessionManager
// ModelRegistry resolves API keys (pi: modelRegistry).
ModelRegistry *ModelRegistry
// Model is the current model; nil = none (pi: model).
Model *types.Model
// ScopedModels are the models scoped to this session (pi:
// scopedModels).
ScopedModels []ScopedModel
// ThinkingLevel is the current thinking level; "" = unset (pi:
// thinkingLevel?).
ThinkingLevel agent.ThinkingLevel
// IsIdle reports whether the agent is idle (not streaming) (pi: isIdle).
IsIdle func() bool
// IsProjectTrusted reports whether project-local trust is active (pi:
// isProjectTrusted).
IsProjectTrusted func() bool
// Signal returns the current run context, or nil when the agent is not
// streaming (pi: signal: AbortSignal | undefined).
Signal func() context.Context
// Abort aborts the current agent operation (pi: abort).
Abort func()
// HasPendingMessages reports whether queued messages are waiting (pi:
// hasPendingMessages).
HasPendingMessages func() bool
// Shutdown gracefully shuts pi down (pi: shutdown).
Shutdown func()
// GetContextUsage returns the context usage for the active model (pi:
// getContextUsage).
GetContextUsage func() *ContextUsage
// Compact triggers compaction without awaiting completion (pi: compact).
Compact func(options *CompactOptions)
// GetSystemPrompt returns the current effective system prompt (pi:
// getSystemPrompt).
GetSystemPrompt func() string
// SendMessage sends a custom message to the session (pi: sendMessage;
// bound by bindCore, panics when the runtime is not initialized — pi's
// throwing stub).
SendMessage func(ctx context.Context, message *CustomMessagePayload, options *SendMessageOptions)
// SendUserMessage sends a user message to the agent (pi:
// sendUserMessage; bound by bindCore, panics when the runtime is not
// initialized — pi's throwing stub).
SendUserMessage func(ctx context.Context, content string, options *SendUserMessageOptions)
}
ExtensionContext is the context passed to extension event handlers (pi: ExtensionContext; see header for the lazy-getter → struct deviation).
func (*ExtensionContext) GetCwd ¶
func (c *ExtensionContext) GetCwd() string
GetCwd is pi's ctx.cwd (v0.85.1): the built-in tools resolve paths against it when provided.
func (*ExtensionContext) GetModel ¶
func (c *ExtensionContext) GetModel() *types.Model
ExtensionContext satisfies the built-in tools' execute-context slice (pi: the tools read the same ExtensionContext object; pig bridges the struct fields to the tools.ToolExecuteContext methods).
func (*ExtensionContext) GetSessionFile ¶
func (c *ExtensionContext) GetSessionFile() *string
GetSessionFile is nil when the session is not file-backed.
func (*ExtensionContext) GetSessionID ¶
func (c *ExtensionContext) GetSessionID() string
func (*ExtensionContext) GetThinkingLevel ¶
func (c *ExtensionContext) GetThinkingLevel() string
type ExtensionContextActions ¶
type ExtensionContextActions struct {
GetModel func() *types.Model
GetScopedModels func() []ScopedModel
IsIdle func() bool
IsProjectTrusted func() bool
GetSignal func() context.Context
Abort func()
HasPendingMessages func() bool
Shutdown func()
GetContextUsage func() *ContextUsage
Compact func(options *CompactOptions)
GetSystemPrompt func() string
// GetSystemPromptOptions is optional in pi; nil = unset (pi:
// getSystemPromptOptions?).
GetSystemPromptOptions func() BuildSystemPromptOptions
}
ExtensionContextActions are the context action implementations for ExtensionContext (pi: ExtensionContextActions). Required by all modes.
type ExtensionCustomFactory ¶
type ExtensionCustomFactory func(tui tui.TUI, keybindings *KeybindingsManager, done func(result any)) (tui.Component, func())
ExtensionCustomFactory builds a custom component shown with keyboard focus (pi: custom's factory `(tui, theme, keybindings, done) => Component & {dispose?} | Promise<...>`; pig factories are synchronous and report the optional dispose via the second return).
type ExtensionCustomOptions ¶
type ExtensionCustomOptions struct {
// Overlay renders the component on top of existing content instead of
// replacing the editor (pi: overlay?).
Overlay bool
// OverlayOptions resolves overlay positioning/sizing when Overlay is
// set; called each time the overlay is (re)positioned. nil falls back to
// the component's width when it exposes one (pi: overlayOptions:
// OverlayOptions | (() => OverlayOptions) — the static form is the
// constant closure).
OverlayOptions func() *tui.OverlayOptions
// OnHandle receives the overlay handle after the overlay is shown, for
// visibility control (pi: onHandle?).
OnHandle func(handle tui.OverlayHandle)
}
ExtensionCustomOptions configure the custom component surface (pi: custom's options parameter).
type ExtensionError ¶
type ExtensionError struct {
ExtensionPath string
Event string
Error string
// Stack is the JS stack when the panic carried one; "" = none (pi:
// stack?). Go recover() has no portable stack string, so it stays empty.
Stack string
}
ExtensionError reports an extension handler failure (pi: ExtensionError).
type ExtensionErrorListener ¶
type ExtensionErrorListener func(error ExtensionError)
ExtensionErrorListener consumes extension errors (pi: ExtensionErrorListener).
type ExtensionEvent ¶
type ExtensionEvent interface {
// EventType returns the JSON "type" discriminant.
EventType() string
}
ExtensionEvent is the event union passed to runner.Emit (pi: ExtensionEvent; discriminated union → interface + concrete types).
type ExtensionFlag ¶
type ExtensionFlag struct {
Name string
Description string
Type string // "boolean" | "string"
Def any // pi: default?: boolean | string
ExtensionPath string
}
ExtensionFlag is one extension-declared flag (pi: ExtensionFlag).
type ExtensionFooterFactory ¶
type ExtensionFooterFactory func(tui tui.TUI, footerData ReadonlyFooterDataProvider) (tui.Component, func())
ExtensionFooterFactory builds a custom footer component (pi: setFooter's factory `(tui, theme, footerData) => Component & {dispose?}`).
type ExtensionHandler ¶
type ExtensionHandler func(ctx context.Context, extCtx *ExtensionContext, event ExtensionEvent) (any, error)
ExtensionHandler is the handler function type for events (pi: HandlerFn, whose (event, ctx) order becomes (ctx, extCtx, event) per the Go context convention).
type ExtensionHeaderFactory ¶
ExtensionHeaderFactory builds a custom header component (pi: setHeader's factory `(tui, theme) => Component & {dispose?}`).
type ExtensionMode ¶
type ExtensionMode string
ExtensionMode is the run mode reported to extensions (pi: ExtensionMode).
const ( ExtensionModeTUI ExtensionMode = "tui" ExtensionModeRPC ExtensionMode = "rpc" ExtensionModeJSON ExtensionMode = "json" ExtensionModePrint ExtensionMode = "print" )
type ExtensionOAuthConfig ¶
type ExtensionOAuthConfig struct {
Name string
// IsSubscription reports whether access through this auth method is
// backed by a provider subscription.
IsSubscription bool
// UsesCallbackServer is retained for extension source compatibility;
// ignored by canonical auth flows (pi: @deprecated).
UsesCallbackServer bool
Login func(callbacks ai.OAuthLoginCallbacks) (auth.OAuthCredentials, error)
// RefreshToken refreshes the stored token; pi's signal rides the context.
RefreshToken func(ctx context.Context, credentials auth.OAuthCredentials) (auth.OAuthCredentials, error)
GetAPIKey func(credentials auth.OAuthCredentials) string
ModifyModels func(models []ai.Model, credentials auth.OAuthCredentials) []ai.Model
}
ExtensionOAuthConfig is the OAuth config of the extension registerProvider API (pi: ExtensionOAuthConfig).
type ExtensionProviderActions ¶
type ExtensionProviderActions struct {
RegisterProvider func(name string, config ProviderConfig)
RegisterNativeProvider func(provider any)
UnregisterProvider func(name string)
}
ExtensionProviderActions register or unregister providers (pi: bindCore's optional providerActions parameter).
type ExtensionRunner ¶
type ExtensionRunner struct {
// contains filtered or unexported fields
}
ExtensionRunner drives extension event dispatch for one session (pi: ExtensionRunner).
func NewExtensionRunner ¶
func NewExtensionRunner( extensions []*Extension, runtime *ExtensionRuntime, cwd string, sessionManager *SessionManager, modelRegistry *ModelRegistry, ) *ExtensionRunner
NewExtensionRunner constructs the runner (pi: constructor).
func (*ExtensionRunner) BindCommandContext ¶
func (r *ExtensionRunner) BindCommandContext(actions *ExtensionCommandContextActions)
BindCommandContext binds the command context actions (pi: bindCommandContext). nil keeps the previous binding (pi: `if (!actions) return`).
func (*ExtensionRunner) BindCore ¶
func (r *ExtensionRunner) BindCore( actions *ExtensionActions, contextActions *ExtensionContextActions, providerActions *ExtensionProviderActions, )
BindCore copies actions into the shared runtime and binds the context actions (pi: bindCore). nil actions fields keep the previous binding, and a nil providerActions skips provider rebinding (pi: optional parameter).
func (*ExtensionRunner) CreateCommandContext ¶
func (r *ExtensionRunner) CreateCommandContext() *ExtensionCommandContext
CreateCommandContext builds the command-handler context (pi: createCommandContext).
func (*ExtensionRunner) CreateContext ¶
func (r *ExtensionRunner) CreateContext() ExtensionContext
CreateContext builds the context for event handlers and tool execution (pi: createContext; the lazy TS getters become eager struct fields, see the types header).
func (*ExtensionRunner) Emit ¶
func (r *ExtensionRunner) Emit(ctx context.Context, event ExtensionEvent) (any, error)
Emit dispatches one event to all matching handlers in registration order, returning the last non-nil handler result; a cancel result from session_before_* events short-circuits (pi: emit — the result variable is overwritten by each handler, and cancel results abort the dispatch).
func (*ExtensionRunner) EmitBeforeAgentStart ¶
func (r *ExtensionRunner) EmitBeforeAgentStart( ctx context.Context, prompt string, images []types.ImageContent, systemPromptOptions BuildSystemPromptOptions, ) (*BeforeAgentStartCombinedResult, error)
EmitBeforeAgentStart runs before_agent_start handlers and merges their results (pi: emitBeforeAgentStart; v0.86.0 always returns the normalized options — a handler's systemPrompt override is recorded as forceSystemPrompt, and later handlers observe earlier mutations).
func (*ExtensionRunner) EmitBeforeProviderHeaders ¶
func (r *ExtensionRunner) EmitBeforeProviderHeaders(ctx context.Context, headers types.ProviderHeaders) types.ProviderHeaders
EmitBeforeProviderHeaders applies extension header mutations (pi: emitBeforeProviderHeaders). Handlers mutate headers in place; the return value is ignored. A nil entry deletes that header.
func (*ExtensionRunner) EmitBeforeProviderRequest ¶
func (r *ExtensionRunner) EmitBeforeProviderRequest(ctx context.Context, payload any) any
EmitBeforeProviderRequest applies extension payload transforms (pi: emitBeforeProviderRequest). A non-nil handler result replaces the payload.
func (*ExtensionRunner) EmitBoundary ¶ added in v0.87.0
func (r *ExtensionRunner) EmitBoundary(ctx context.Context, baseEvent ExtensionEvent, buildContext BoundaryContextBuilder) (BoundaryDispatchResult, error)
EmitBoundary dispatches one boundary event (turn_end / agent_before_settle) to all handlers in registration order, threading the shared draft list and continuation flag through every handler (pi: emitBoundary, v0.87.0).
Handlers see a fresh event per dispatch carrying the current shared state; mutating event.Entries appends to the shared list (pi: the event holds the same array), and a BoundaryResult return overrides entries/continue. After every handler the preview is rebuilt; a build failure reports "Invalid boundary entries" and marks the dispatch invalid — an invalid final dispatch drops the drafts and the continuation. An error from the INITIAL preview build is returned (pi: it rejects the emitBoundary promise and fails the run).
func (*ExtensionRunner) EmitCacheWarmingDecision ¶ added in v0.86.0
func (r *ExtensionRunner) EmitCacheWarmingDecision(ctx context.Context, event *CacheWarmingDecisionEvent) CacheWarmingAction
EmitContext applies extension context transforms (pi: emitContext). pi structuredClones the messages first so handlers cannot mutate the caller's slice; pig clones via JSON round-trip (reducer precedent). EmitCacheWarmingDecision returns the event's own action unless a handler overrides it; the last override wins (pi: emitCacheWarmingDecision; v0.86.0).
func (*ExtensionRunner) EmitContext ¶
func (r *ExtensionRunner) EmitContext(ctx context.Context, messages []agent.AgentMessage) []agent.AgentMessage
EmitContext runs the request-time transforms in two phases (pi: emitContext, v0.87.0). `context` handlers see the conversation only and Pi restores the prompt and tool state after each; `context_with_system` handlers then see the full transcript and their output is used as returned.
func (*ExtensionRunner) EmitError ¶
func (r *ExtensionRunner) EmitError(err ExtensionError)
EmitError reports an error to all listeners (pi: emitError).
func (*ExtensionRunner) EmitInput ¶
func (r *ExtensionRunner) EmitInput( ctx context.Context, text string, images []types.ImageContent, source InputSource, streamingBehavior string, ) (*InputEventResult, error)
EmitInput runs input handlers as a transform chain; "handled" short-circuits (pi: emitInput).
func (*ExtensionRunner) EmitMessageEnd ¶
func (r *ExtensionRunner) EmitMessageEnd(ctx context.Context, event *MessageEndEvent) (agent.AgentMessage, error)
EmitMessageEnd runs message_end handlers and returns the replacement message, if any handler produced one (pi: emitMessageEnd).
func (*ExtensionRunner) EmitResourcesDiscover ¶
func (r *ExtensionRunner) EmitResourcesDiscover(ctx context.Context, cwd string, reason string) (*ResourcesDiscoverResult, error)
EmitResourcesDiscover runs resources_discover handlers (pi: emitResourcesDiscover).
func (*ExtensionRunner) EmitToolCall ¶
func (r *ExtensionRunner) EmitToolCall(ctx context.Context, event *ToolCallEvent) (*ToolCallEventResult, error)
EmitToolCall runs tool_call handlers and returns the first blocking result (pi: emitToolCall).
func (*ExtensionRunner) EmitToolResult ¶
func (r *ExtensionRunner) EmitToolResult(ctx context.Context, event *ToolResultEvent) (*ToolResultEventResult, error)
EmitToolResult runs tool_result handlers and returns the merged result (pi: emitToolResult).
func (*ExtensionRunner) EmitUserBash ¶ added in v0.86.0
func (r *ExtensionRunner) EmitUserBash(ctx context.Context, event *UserBashEvent) (*UserBashEventResult, error)
EmitUserBash runs user_bash handlers and returns the interception, if any (pi: emitUserBash). nil result = run locally. A throwing handler is reported and re-thrown (error return); an invalid result fails closed so the `!` command never silently falls back to local execution (#9068).
func (*ExtensionRunner) GetActiveTools ¶
func (r *ExtensionRunner) GetActiveTools() []string
GetActiveTools returns the active tool names (pi: getActiveTools).
func (*ExtensionRunner) GetAllRegisteredTools ¶
func (r *ExtensionRunner) GetAllRegisteredTools() []RegisteredTool
GetAllRegisteredTools collects the registered tools from all extensions, first registration per name wins (pi: getAllRegisteredTools).
func (*ExtensionRunner) GetCommand ¶
func (r *ExtensionRunner) GetCommand(name string) *ResolvedCommand
GetCommand finds a command by invocation name (pi: getCommand).
func (*ExtensionRunner) GetCommandDiagnostics ¶
func (r *ExtensionRunner) GetCommandDiagnostics() []ResourceDiagnostic
GetCommandDiagnostics returns command-name dedup diagnostics (pi: getCommandDiagnostics). The diagnostics arrive with the loader batch (P7); empty until then (declared).
func (*ExtensionRunner) GetEntryRenderer ¶
func (r *ExtensionRunner) GetEntryRenderer(customType string) EntryRenderer
GetEntryRenderer returns the renderer for a custom entry type (pi: getEntryRenderer; nil = no content — extension renderers arrive with the sidecar host, Phase 7).
func (*ExtensionRunner) GetExtensionPaths ¶
func (r *ExtensionRunner) GetExtensionPaths() []string
GetExtensionPaths lists the loaded extension paths (pi: getExtensionPaths).
func (*ExtensionRunner) GetFlagValues ¶
func (r *ExtensionRunner) GetFlagValues() map[string]any
GetFlagValues returns the registered flag values (pi: getFlagValues).
func (*ExtensionRunner) GetMessageRenderer ¶
func (r *ExtensionRunner) GetMessageRenderer(customType string) MessageRenderer
GetMessageRenderer returns the renderer for a custom message type (pi: getMessageRenderer; nil = default rendering).
func (*ExtensionRunner) GetModelRegistry ¶
func (r *ExtensionRunner) GetModelRegistry() *ModelRegistry
GetModelRegistry exposes the model registry (pi: getModelRegistry).
func (*ExtensionRunner) GetRegisteredCommands ¶
func (r *ExtensionRunner) GetRegisteredCommands() []ResolvedCommand
GetRegisteredCommands returns the resolved commands, recomputing the diagnostics (pi: getRegisteredCommands).
func (*ExtensionRunner) GetShortcutDiagnostics ¶
func (r *ExtensionRunner) GetShortcutDiagnostics() []ResourceDiagnostic
GetShortcutDiagnostics returns shortcut diagnostics (pi: getShortcutDiagnostics); populated by GetShortcuts.
func (*ExtensionRunner) GetShortcuts ¶
func (r *ExtensionRunner) GetShortcuts(resolvedKeybindings tui.KeybindingsConfig) map[tui.KeyId]*ExtensionShortcut
GetShortcuts resolves the extension shortcuts, computing conflict diagnostics against the builtin keybindings (pi: getShortcuts).
func (*ExtensionRunner) HasHandlers ¶
func (r *ExtensionRunner) HasHandlers(eventType string) bool
HasHandlers reports whether any extension registers handlers for the event type (pi: hasHandlers).
func (*ExtensionRunner) HasUI ¶
func (r *ExtensionRunner) HasUI() bool
HasUI reports whether dialog-capable UI is available (pi: hasUI).
func (*ExtensionRunner) Invalidate ¶
func (r *ExtensionRunner) Invalidate(message string)
Invalidate marks the runner stale (pi: invalidate). pi defaults the message when called without one.
func (*ExtensionRunner) OnError ¶
func (r *ExtensionRunner) OnError(listener ExtensionErrorListener) func()
OnError registers an error listener and returns the unsubscribe function (pi: onError).
func (*ExtensionRunner) SetFlagValue ¶
func (r *ExtensionRunner) SetFlagValue(name string, value any)
SetFlagValue sets one flag value (pi: setFlagValue).
func (*ExtensionRunner) SetUIContext ¶
func (r *ExtensionRunner) SetUIContext(uiContext ExtensionUIContext, mode ExtensionMode)
SetUIContext binds the UI context (pi: setUIContext). nil uiContext keeps the no-op context (pi: `if (uiContext)`).
func (*ExtensionRunner) Shutdown ¶
func (r *ExtensionRunner) Shutdown()
Shutdown requests graceful shutdown (pi: shutdown).
type ExtensionRunnerRef ¶
type ExtensionRunnerRef struct {
// Current is the active runner; nil = none (pi: current?).
Current *ExtensionRunner
}
ExtensionRunnerRef is pi's `{ current?: ExtensionRunner }` mutable ref.
type ExtensionRuntime ¶
type ExtensionRuntime struct {
// FlagValues holds registered extension flag values (pi: flagValues:
// Map<string, boolean | string>; values are only ever bool/string).
FlagValues map[string]any
// Action members, throwing stubs until bindCore (pi: the notInitialized
// stubs). nil = not initialized.
SendMessage func(ctx context.Context, message *CustomMessagePayload, options *SendMessageOptions)
SendUserMessage func(ctx context.Context, content string, options *SendUserMessageOptions)
AppendEntry func(customType string, data any) string
SetSessionName func(name string)
GetSessionName func() (string, bool)
SetLabel func(entryID string, label string)
GetActiveTools func() []string
GetAllTools func() []ToolInfo
SetActiveTools func(toolNames []string)
RefreshTools func()
GetCommands func() []SlashCommandInfo
SetModel func(ctx context.Context, model *types.Model) bool
GetThinkingLevel func() agent.ThinkingLevel
SetThinkingLevel func(level agent.ThinkingLevel)
// PendingProviderRegistrations / pendingNativeProviderRegistrations
// arrive with Phase 7 (pi: pendingProviderRegistrations).
// RegisterProvider/RegisterNativeProvider/UnregisterProvider are bound
// by bindCore (pi: registerProvider/registerNativeProvider/
// unregisterProvider members; the pre-bind queueing arrives with Phase
// 7).
RegisterProvider func(name string, config ProviderConfig)
RegisterNativeProvider func(provider any)
UnregisterProvider func(name string)
// contains filtered or unexported fields
}
ExtensionRuntime is the shared runtime state referenced by extension APIs (pi: ExtensionRuntime = ExtensionRuntimeState + ExtensionActions; the pending registration queues and event-bus tracking arrive with Phase 7).
func CreateExtensionRuntime ¶
func CreateExtensionRuntime() *ExtensionRuntime
CreateExtensionRuntime creates the shared runtime with throwing action stubs (pi: createExtensionRuntime in loader.ts). pi's stubs throw on invocation; pig's are nil and consumers guard.
func (*ExtensionRuntime) AssertActive ¶
func (r *ExtensionRuntime) AssertActive()
AssertActive panics when the runtime is stale after replacement or reload (pi: assertActive, which throws).
func (*ExtensionRuntime) Invalidate ¶
func (r *ExtensionRuntime) Invalidate(message string)
Invalidate marks the runtime stale (pi: invalidate).
type ExtensionShortcut ¶
type ExtensionShortcut struct {
// Shortcut is the key id (pi: shortcut: KeyId).
Shortcut tui.KeyId
// Description is shown in UI; "" = none (pi: description?).
Description string
// Handler runs when the shortcut fires (pi: handler: (ctx) =>
// Promise<void> | void → sync).
Handler func(ctx context.Context, ec *ExtensionContext)
// ExtensionPath is the declaring extension (pi: extensionPath).
ExtensionPath string
}
ExtensionShortcut is one extension-registered keyboard shortcut (pi: ExtensionShortcut).
type ExtensionThemeInfo ¶
ExtensionThemeInfo is one available theme (pi: getAllThemes' element {name, path | undefined}; Path "" = undefined).
type ExtensionUIContext ¶
type ExtensionUIContext interface {
// Select shows a selector and returns the user's choice (pi: select).
Select(ctx context.Context, title string, options []string, opts *ExtensionUIDialogOptions) (string, bool)
// Confirm shows a confirmation dialog (pi: confirm).
Confirm(ctx context.Context, title string, message string, opts *ExtensionUIDialogOptions) bool
// Input shows a text input dialog (pi: input).
Input(ctx context.Context, title string, placeholder string, opts *ExtensionUIDialogOptions) (string, bool)
// Notify shows a notification (pi: notify). level: "info"|"warning"|"error";
// "" = pi's undefined (default styling).
Notify(ctx context.Context, message string, level string)
// OnTerminalInput listens to raw terminal input (interactive mode only)
// and returns an unsubscribe function (pi: onTerminalInput).
OnTerminalInput(ctx context.Context, handler TerminalInputHandler) func()
// SetStatus sets status text in the footer/status bar; "" clears (pi:
// setStatus).
SetStatus(ctx context.Context, key string, text string)
// SetWorkingMessage sets the working/loading message shown during
// streaming; "" restores the default (pi: setWorkingMessage).
SetWorkingMessage(ctx context.Context, message string)
// SetWorkingVisible shows or hides the built-in interactive working
// loader row during streaming (pi: setWorkingVisible).
SetWorkingVisible(ctx context.Context, visible bool)
// SetWorkingIndicator configures the interactive working indicator (pi:
// setWorkingIndicator); nil restores the default animated spinner.
SetWorkingIndicator(ctx context.Context, options *WorkingIndicatorOptions)
// SetHiddenThinkingLabel sets the label shown for hidden thinking blocks;
// "" restores the default (pi: setHiddenThinkingLabel).
SetHiddenThinkingLabel(ctx context.Context, label string)
// SetWidget sets a widget above or below the editor (pi: setWidget's two
// overloads, merged into one `content any` parameter — Go has no
// overloads). Accepted values: nil removes the widget (pi: undefined);
// []string renders text lines (truncated at MaxWidgetLines);
// ExtensionWidgetFactory renders a custom component.
SetWidget(ctx context.Context, key string, content any, options *ExtensionWidgetOptions)
// footer when factory is nil (pi: setFooter).
SetFooter(ctx context.Context, factory ExtensionFooterFactory)
// SetHeader sets a custom header component (shown at startup, above
// chat), or restores the built-in header when factory is nil (pi:
// setHeader).
SetHeader(ctx context.Context, factory ExtensionHeaderFactory)
// SetTitle sets the terminal window/tab title (pi: setTitle).
SetTitle(ctx context.Context, title string)
// Custom shows a custom component with keyboard focus and blocks until
// the component calls done (pi: custom<T>'s Promise — the value passed to
// done is returned; the extension's factory closure captures its own
// typed variable, Go interfaces cannot be generic per method). overlay
// mode renders on top of existing content.
Custom(ctx context.Context, factory ExtensionCustomFactory, options *ExtensionCustomOptions) any
// PasteToEditor pastes text into the editor, triggering paste handling
// (collapse for large content) (pi: pasteToEditor).
PasteToEditor(ctx context.Context, text string)
// SetEditorText sets the text in the core input editor (pi:
// setEditorText).
SetEditorText(ctx context.Context, text string)
// GetEditorText returns the current text from the core input editor (pi:
// getEditorText — getExpandedText() ?? getText()).
GetEditorText(ctx context.Context) string
// Editor shows a multi-line editor for text editing (pi: editor's
// Promise<string | undefined>; blocks until submitted/cancelled, ok
// reports whether a value was returned).
Editor(ctx context.Context, title string, prefill string) (string, bool)
// AddAutocompleteProvider stacks additional autocomplete behavior on top
// of the built-in provider (pi: addAutocompleteProvider).
AddAutocompleteProvider(ctx context.Context, factory AutocompleteProviderFactory)
// SetEditorComponent sets a custom editor component via factory, or
// restores the default editor when factory is nil (pi:
// setEditorComponent).
SetEditorComponent(ctx context.Context, factory EditorFactory)
// GetEditorComponent returns the currently configured custom editor
// factory, or nil when using the default editor (pi: getEditorComponent).
GetEditorComponent(ctx context.Context) EditorFactory
// GetAllThemes returns all available themes with their names and file
// paths (pi: getAllThemes). Path "" = pi's undefined.
GetAllThemes(ctx context.Context) []ExtensionThemeInfo
// GetTheme loads a theme by name without switching to it; nil = not
// found (pi: getTheme: Theme | undefined). The return is any because
// core cannot import the theme package (modes/interactive/theme); the
// value is a *theme.Theme. The theme loader half lands with T6.
GetTheme(ctx context.Context, name string) any
// SetTheme sets the current theme by name (pi: setTheme's
// string overload; the Theme-instance overload has no core-representable
// parameter type and lands with the theme loader half).
SetTheme(ctx context.Context, themeName string) ThemeSetResult
// GetToolsExpanded returns the current tool output expansion state (pi:
// getToolsExpanded).
GetToolsExpanded(ctx context.Context) bool
// SetToolsExpanded sets the tool output expansion state (pi:
// setToolsExpanded).
SetToolsExpanded(ctx context.Context, expanded bool)
}
ExtensionUIContext is the UI surface extensions can use (pi: ExtensionUIContext).
type ExtensionUIDialogOptions ¶
type ExtensionUIDialogOptions struct {
// Placeholder for input dialogs. (pig addition for the shared struct;
// pi passes the input placeholder as input()'s second parameter, which
// the Go Input method also carries.)
Placeholder string
// Timeout in milliseconds; the dialog auto-dismisses with a live
// countdown display (pi: timeout?). 0 = none.
Timeout int
}
ExtensionUIDialogOptions are the shared dialog options (pi: ExtensionUIDialogOptions).
type ExtensionWidgetFactory ¶
ExtensionWidgetFactory renders a custom widget component (pi: setWidget's component-factory overload `(tui, theme) => Component & {dispose?}`). The second return is the optional dispose function (nil = none; pi's `dispose?()`).
type ExtensionWidgetOptions ¶
type ExtensionWidgetOptions struct {
// Placement: "above" or "below" the editor (pi: placement).
Placement string
}
ExtensionWidgetOptions are the widget placement options (pi: ExtensionWidgetOptions).
type FileAuthStorageBackend ¶
type FileAuthStorageBackend struct {
// contains filtered or unexported fields
}
FileAuthStorageBackend is the auth.json-backed storage backend (pi: FileAuthStorageBackend).
func NewFileAuthStorageBackend ¶
func NewFileAuthStorageBackend(authPath string) *FileAuthStorageBackend
NewFileAuthStorageBackend builds a backend for authPath; an empty path defaults to <agentDir>/auth.json (pi: constructor default).
func (*FileAuthStorageBackend) WithLock ¶
func (b *FileAuthStorageBackend) WithLock(ctx context.Context, fn LockFunction) error
func (*FileAuthStorageBackend) WithLockAsync ¶
func (b *FileAuthStorageBackend) WithLockAsync(ctx context.Context, fn LockFunction) error
type FileEntry ¶
type FileEntry interface {
// EntryType returns the JSON "type" discriminant ("session" for headers).
EntryType() string
}
FileEntry is a raw file entry: the session header or one session-tree entry (pi: FileEntry = SessionHeader | SessionEntry).
func LoadEntriesFromFile ¶
LoadEntriesFromFile loads and decodes a session file, skipping malformed lines and validating the header (pi: loadEntriesFromFile; exported for testing). Returns nil for missing/invalid files.
func ParseSessionEntries ¶
ParseSessionEntries parses JSONL content into file entries, skipping malformed lines (pi: parseSessionEntries; exported for the compaction tests).
type FileModelsStore ¶
type FileModelsStore struct {
// contains filtered or unexported fields
}
FileModelsStore is the locked JSON-backed catalog storage (pi: FileModelsStore).
func NewFileModelsStore ¶
func NewFileModelsStore(path string) *FileModelsStore
NewFileModelsStore builds a catalog store; an empty path defaults to <agentDir>/models-store.json (pi: constructor default).
func (*FileModelsStore) Delete ¶
func (s *FileModelsStore) Delete(ctx context.Context, providerID string) error
func (*FileModelsStore) Read ¶
func (s *FileModelsStore) Read(ctx context.Context, providerID string) (*ai.ModelsStoreEntry, error)
func (*FileModelsStore) Write ¶
func (s *FileModelsStore) Write(ctx context.Context, providerID string, entry *ai.ModelsStoreEntry) error
type FileOperations ¶
type FileOperations = compaction.FileOperations
FileOperations tracks the file paths touched by a session branch or compaction range (pi: FileOperations).
func CreateFileOps ¶
func CreateFileOps() *FileOperations
CreateFileOps creates an empty file-operation accumulator (pi: createFileOps).
type FileSettingsStorage ¶
type FileSettingsStorage struct {
// contains filtered or unexported fields
}
FileSettingsStorage persists settings as JSON files under lock (pi: FileSettingsStorage).
func NewFileSettingsStorage ¶
func NewFileSettingsStorage(cwd string, agentDir string) *FileSettingsStorage
NewFileSettingsStorage builds the file-backed storage (pi: constructor).
func (*FileSettingsStorage) WithLock ¶
func (s *FileSettingsStorage) WithLock(scope SettingsScope, fn func(current *string) *string) error
WithLock runs fn under the settings file lock (pi: withLock). The file is read (when present) and, when fn returns new content, the directory is created on demand and the file written — all under lock.
type FindInitialModelOptions ¶
type FindInitialModelOptions struct {
CliProvider string
CliModel string
ScopedModels []ScopedModel
IsContinuing bool
DefaultProvider string
DefaultModelID string
DefaultThinkingLevel agent.ThinkingLevel
// ModelThinkingLevels maps "provider/modelId" to a per-model thinking
// level (pi: modelThinkingLevels).
ModelThinkingLevels map[string]agent.ThinkingLevel
ModelRuntime ModelResolverRuntime
}
FindInitialModelOptions are FindInitialModel's inputs (pi: the options object; empty strings = undefined).
type FooterDataProvider ¶
type FooterDataProvider struct {
// contains filtered or unexported fields
}
FooterDataProvider provides git branch and extension statuses for the footer.
func NewFooterDataProvider ¶
func NewFooterDataProvider(cwd string) *FooterDataProvider
NewFooterDataProvider creates the provider and sets up the git watcher.
func (*FooterDataProvider) ClearExtensionStatuses ¶
func (p *FooterDataProvider) ClearExtensionStatuses()
ClearExtensionStatuses clears extension statuses (internal).
func (*FooterDataProvider) Dispose ¶
func (p *FooterDataProvider) Dispose()
Dispose cleans up (internal).
func (*FooterDataProvider) GetAvailableProviderCount ¶
func (p *FooterDataProvider) GetAvailableProviderCount() int
GetAvailableProviderCount returns the number of unique providers with available models (for footer display).
func (*FooterDataProvider) GetExtensionStatuses ¶
func (p *FooterDataProvider) GetExtensionStatuses() map[string]string
GetExtensionStatuses returns the extension status texts set via ctx.ui.setStatus(). The returned map is a copy (pig: read-only view).
func (*FooterDataProvider) GetGitBranch ¶
func (p *FooterDataProvider) GetGitBranch() *string
GetGitBranch returns the current git branch; nil if not in repo, "detached" if detached HEAD.
func (*FooterDataProvider) OnBranchChange ¶
func (p *FooterDataProvider) OnBranchChange(callback func()) func()
OnBranchChange subscribes to git branch changes. Returns unsubscribe function.
func (*FooterDataProvider) SetAvailableProviderCount ¶
func (p *FooterDataProvider) SetAvailableProviderCount(count int)
SetAvailableProviderCount updates the available provider count (internal).
func (*FooterDataProvider) SetCwd ¶
func (p *FooterDataProvider) SetCwd(cwd string)
SetCwd re-targets the provider at a new cwd.
func (*FooterDataProvider) SetExtensionStatus ¶
func (p *FooterDataProvider) SetExtensionStatus(key string, text *string)
SetExtensionStatus sets an extension status (internal: pi ctx.ui.setStatus).
type ForkCommandOptions ¶
type ForkCommandOptions struct {
// Position: "before" or "at" (pi: position?); "" = pi's undefined.
Position string
// WithSession receives the replacement session context (pi:
// withSession?).
WithSession func(ctx context.Context, sessionCtx *ReplacedSessionContext) error
}
ForkCommandOptions are the fork options (pi: fork's options parameter).
type ForkOptions ¶
type ForkOptions struct {
// Position is "before" (default) or "at" (pi: position).
Position string
// WithSession runs with the replacement session context (pi:
// withSession).
WithSession func(replacedCtx *ReplacedSessionContext) error
}
ForkOptions are the fork inputs (pi's inline options).
type ForkResult ¶
ForkResult is the fork outcome (pi's { cancelled, selectedText? }).
type ForkUserMessage ¶
ForkUserMessage is one user message candidate for the fork selector (pi: getUserMessagesForForking's return members).
type FullscreenExitOutput ¶
type FullscreenExitOutput = string
FullscreenExitOutput selects what the fullscreen renderer prints on exit.
const ( FullscreenExitOutputTranscript FullscreenExitOutput = "transcript" FullscreenExitOutputResumeHint FullscreenExitOutput = "resume-hint" )
type GenerateBranchSummaryOptions ¶
type GenerateBranchSummaryOptions struct {
// Model is the model to use for summarization.
Model *ai.Model
// APIKey is the API key for the model; "" = none (pi: apiKey?).
APIKey string
// Headers are request headers for the model; nil = none (pi: headers?).
Headers map[string]string
// Env holds provider-scoped environment values for the model; nil = none
// (pi: env?).
Env ai.ProviderEnv
// CustomInstructions are optional custom instructions for summarization;
// "" = none (pi: customInstructions?).
CustomInstructions string
// ReplaceInstructions makes customInstructions replace the default
// prompt instead of being appended (pi: replaceInstructions?).
ReplaceInstructions bool
// ReserveTokens is the token budget reserved for prompt + LLM response;
// nil = 16384 (pi: reserveTokens?).
ReserveTokens *int
// StreamFn is the optional session stream function, used to preserve SDK
// request behavior without mutating agent state (pi: streamFn?).
StreamFn agent.StreamFn
// Retry is the retry policy for transient summarization errors; reuses
// coding-agent's settings.retry (pi: retry?).
Retry *ai.RetryPolicy
// Callbacks are optional callbacks for retry reporting (e.g. TUI retry
// indicators) (pi: callbacks?).
Callbacks *ai.RetryCallbacks
}
GenerateBranchSummaryOptions are the options for GenerateBranchSummary (pi: GenerateBranchSummaryOptions; the signal member is dropped — cancellation travels as the Go context).
type GenerateBugReportSummaryOptions ¶ added in v0.86.0
type GenerateBugReportSummaryOptions struct {
Messages []agent.AgentMessage
Hint string
Model *types.Model
APIKey string
Headers map[string]string
Env types.ProviderEnv
ThinkingLevel agent.ThinkingLevel
StreamFn agent.StreamFn
Retry *ai.RetryPolicy
SessionID string
}
GenerateBugReportSummaryOptions are the generateBugReportSummary parameters (pi: GenerateBugReportSummaryOptions). pi's options.signal is dropped — cancellation travels as the Go ctx (AbortSignal → context rule).
type HTTPIdleTimeoutChoice ¶
HTTPIdleTimeoutChoice is one picker entry (pi: HTTP_IDLE_TIMEOUT_CHOICES member).
type ImageSettings ¶
type ImageSettings struct {
AutoResize *bool // default: true (resize images to 2000x2000 max for better model compatibility)
BlockImages *bool // default: false - when true, prevents all images from being sent to LLM providers
}
ImageSettings holds the image handling settings shape (pi: ImageSettings).
type InMemoryAuthStorageBackend ¶
type InMemoryAuthStorageBackend struct {
// contains filtered or unexported fields
}
InMemoryAuthStorageBackend keeps the file content in memory (pi: InMemoryAuthStorageBackend). pi serializes operations on a promise chain and races each caller against its signal: a cancelled waiter never runs fn, and a cancelled active callback settles before the chain is released without committing. pig holds a mutex for the same serialization and runs fn on a goroutine so the caller observes cancellation immediately.
func (*InMemoryAuthStorageBackend) WithLock ¶
func (b *InMemoryAuthStorageBackend) WithLock(ctx context.Context, fn LockFunction) error
func (*InMemoryAuthStorageBackend) WithLockAsync ¶
func (b *InMemoryAuthStorageBackend) WithLockAsync(ctx context.Context, fn LockFunction) error
type InMemoryCodingAgentModelsStore ¶
type InMemoryCodingAgentModelsStore = ai.InMemoryModelsStore
InMemoryCodingAgentModelsStore is the non-persistent ModelsStore used by the coding agent (pi: InMemoryCodingAgentModelsStore; identical in behavior to ai's InMemoryModelsStore).
type InMemorySettingsStorage ¶
type InMemorySettingsStorage struct {
// contains filtered or unexported fields
}
InMemorySettingsStorage keeps both scopes in memory (pi: InMemorySettingsStorage).
func (*InMemorySettingsStorage) WithLock ¶
func (s *InMemorySettingsStorage) WithLock(scope SettingsScope, fn func(current *string) *string) error
WithLock runs fn against the in-memory content (pi: withLock).
type InitialModelResult ¶
type InitialModelResult struct {
Model *ai.Model
ThinkingLevel agent.ThinkingLevel
FallbackMessage string
}
InitialModelResult is findInitialModel's outcome (pi: InitialModelResult).
func FindInitialModel ¶
func FindInitialModel(options FindInitialModelOptions) InitialModelResult
FindInitialModel finds the initial model by priority: CLI args, first scoped model, saved default, then first available (pi: findInitialModel).
type InputEvent ¶
type InputEvent struct {
Type string `json:"type"`
Text string `json:"text"`
Images []types.ImageContent `json:"images,omitempty"`
Source InputSource `json:"source"`
// StreamingBehavior: "steer" | "followUp"; "" = idle (pi:
// streamingBehavior?).
StreamingBehavior string `json:"streamingBehavior,omitempty"`
}
InputEvent fires when the user submits input (pi: InputEvent).
func (*InputEvent) EventType ¶
func (e *InputEvent) EventType() string
type InputEventResult ¶
type InputEventResult struct {
// Action: "continue" | "transform" | "handled".
Action string `json:"action"`
// Text is the transformed text (action "transform").
Text string `json:"text,omitempty"`
// Images replaces the attachments (action "transform"); nil = keep (pi:
// images?).
Images []types.ImageContent `json:"images,omitempty"`
}
InputEventResult is the input handler result (pi: InputEventResult union → struct + Action discriminant).
type InputSource ¶
type InputSource string
InputSource is where an input to prompt() came from (pi: InputSource).
const ( InputSourceInteractive InputSource = "interactive" InputSourceRPC InputSource = "rpc" InputSourceExtension InputSource = "extension" )
type KeybindingsManager ¶
type KeybindingsManager struct {
*tui.KeybindingsManager
// contains filtered or unexported fields
}
KeybindingsManager is the coding-agent keybindings manager (pi: KeybindingsManager extends TuiKeybindingsManager; pig embeds).
func CreateKeybindingsManager ¶
func CreateKeybindingsManager(agentDir string) *KeybindingsManager
CreateKeybindingsManager loads user bindings from the agent dir (pi: KeybindingsManager.create).
func NewKeybindingsManager ¶
func NewKeybindingsManager(userBindings tui.KeybindingsConfig, configPath string) *KeybindingsManager
NewKeybindingsManager builds a manager over the coding-agent definitions (pi: constructor).
func (*KeybindingsManager) GetEffectiveConfig ¶
func (m *KeybindingsManager) GetEffectiveConfig() tui.KeybindingsConfig
GetEffectiveConfig returns the resolved bindings (pi: getEffectiveConfig).
func (*KeybindingsManager) Reload ¶
func (m *KeybindingsManager) Reload()
Reload re-reads the config file (pi: reload).
type LabelEntry ¶
type LabelEntry struct {
EntryBase
TargetID string `json:"targetId"`
// Label nil = clear the label.
Label *string `json:"label,omitempty"`
}
LabelEntry is a user-defined bookmark/marker on an entry (pi: LabelEntry).
type LoadExtensionError ¶
LoadExtensionError is one extension load failure (pi: LoadExtensionsResult errors members).
type LoadExtensionsResult ¶
type LoadExtensionsResult struct {
Extensions []*Extension
Errors []LoadExtensionError
// Runtime is the shared runtime; actions are throwing stubs until the
// runner binds (pi: runtime).
Runtime *ExtensionRuntime
}
LoadExtensionsResult is the result of loading extensions (pi: LoadExtensionsResult).
type LoadPromptTemplatesOptions ¶
type LoadPromptTemplatesOptions struct {
// Cwd is the working directory for project-local templates.
Cwd string
// AgentDir is the agent config directory for global templates.
AgentDir string
// PromptPaths are explicit prompt template paths (files or directories).
PromptPaths []string
// IncludeDefaults includes the default prompt directories.
IncludeDefaults bool
}
LoadPromptTemplatesOptions carries the loadPromptTemplates options (pi: LoadPromptTemplatesOptions).
type LoadPromptTemplatesResult ¶ added in v0.87.0
type LoadPromptTemplatesResult struct {
Templates []PromptTemplate
Diagnostics []ResourceDiagnostic
}
LoadPromptTemplatesResult bundles the loaded templates with diagnostics (pi: LoadPromptTemplatesResult, #9830).
func LoadPromptTemplates ¶
func LoadPromptTemplates(options LoadPromptTemplatesOptions) LoadPromptTemplatesResult
LoadPromptTemplates loads all prompt templates from:
- Global: agentDir/prompts/
- Project: cwd/{CONFIG_DIR_NAME}/prompts/
- Explicit prompt paths
(pi: loadPromptTemplates.)
type LoadSkillsFromDirOptions ¶
type LoadSkillsFromDirOptions struct {
// Dir is the directory to scan for skills.
Dir string
// Source is the source identifier for these skills.
Source string
}
LoadSkillsFromDirOptions carries loadSkillsFromDir options (pi: LoadSkillsFromDirOptions).
type LoadSkillsOptions ¶
type LoadSkillsOptions struct {
// Cwd is the working directory for project-local skills.
Cwd string
// AgentDir is the agent config directory for global skills.
AgentDir string
// SkillPaths are explicit skill paths (files or directories).
SkillPaths []string
// IncludeDefaults includes the default skills directories.
IncludeDefaults bool
}
LoadSkillsOptions carries the loadSkills options (pi: LoadSkillsOptions).
type LoadSkillsResult ¶
type LoadSkillsResult struct {
Skills []Skill
Diagnostics []ResourceDiagnostic
}
LoadSkillsResult bundles loaded skills and diagnostics (pi: LoadSkillsResult).
func LoadSkills ¶
func LoadSkills(options LoadSkillsOptions) LoadSkillsResult
LoadSkills loads skills from all configured locations (pi: loadSkills). Returns skills and any validation diagnostics.
func LoadSkillsFromDir ¶
func LoadSkillsFromDir(options LoadSkillsFromDirOptions) LoadSkillsResult
LoadSkillsFromDir loads skills from a directory (pi: loadSkillsFromDir).
Discovery rules:
- if a directory contains SKILL.md, treat it as a skill root and do not recurse further
- otherwise, load direct .md children in the root
- recurse into subdirectories to find SKILL.md
type LockFunction ¶
LockFunction is the withLock callback (pi: (current: string | undefined) => LockResult<T>). It receives the current file content (nil when the file does not exist) and returns the operation result plus the next file content to persist (nil = leave the file unchanged).
type MarkdownSettings ¶
type MarkdownSettings struct {
CodeBlockIndent *string // default: " "
Mermaid *MermaidRenderingMode // default: "streaming"
}
MarkdownSettings holds the markdown rendering settings shape (pi: MarkdownSettings).
type MarkdownTransformContext ¶
type MarkdownTransformContext struct {
// MessageType: "user" | "assistant" | "assistant-thinking" (pi:
// messageType union).
MessageType string
// IsStreaming reports whether the message is still streaming (pi:
// isStreaming).
IsStreaming bool
// AvailableWidth is the exact width available for content (pi:
// availableWidth).
AvailableWidth int
}
MarkdownTransformContext is the transform context handed to markdown transformers (pi: MarkdownTransformContext).
type MarkdownTransformer ¶
type MarkdownTransformer func(markdown string, context MarkdownTransformContext) string
MarkdownTransformer transforms user/assistant Markdown before the transcript renders it (pi: MarkdownTransformer). Returning nil keeps the current markdown (pi: non-string return ignored).
type MermaidRenderingMode ¶
type MermaidRenderingMode = string
MermaidRenderingMode selects when mermaid diagrams render.
const ( MermaidRenderingOff MermaidRenderingMode = "off" MermaidRenderingFinal MermaidRenderingMode = "final" MermaidRenderingStreaming MermaidRenderingMode = "streaming" )
Mermaid rendering mode values (pi: "off" | "final" | "streaming").
type MessageEndEvent ¶
type MessageEndEvent struct {
Type string `json:"type"`
Message agent.AgentMessage `json:"message"`
}
MessageEndEvent fires when a message ends (pi: MessageEndEvent).
func (*MessageEndEvent) EventType ¶
func (e *MessageEndEvent) EventType() string
type MessageEndEventResult ¶
type MessageEndEventResult struct {
// Message replaces the finalized message; must keep the original role.
Message agent.AgentMessage `json:"message,omitempty"`
}
MessageEndEventResult is the message_end handler result (pi: MessageEndEventResult). nil Message = no replacement.
type MessageRenderOptions ¶
type MessageRenderOptions struct {
Expanded bool
// OutputPad is the horizontal padding configured by the outputPad
// setting (pi: outputPad).
OutputPad int
}
MessageRenderOptions carries the message renderer options (pi: MessageRenderOptions).
type MessageRenderer ¶
type MessageRenderer func(message *harness.CustomMessage, options MessageRenderOptions, theme UITheme) tui.Component
MessageRenderer renders a CustomMessage to a component; nil = default rendering (pi: MessageRenderer<T>). Panics inside the renderer are recovered by the consumer (pi: try/catch fallthrough).
type MessageStartEvent ¶
type MessageStartEvent struct {
Type string `json:"type"`
Message agent.AgentMessage `json:"message"`
}
MessageStartEvent fires when a message starts (pi: MessageStartEvent).
func (*MessageStartEvent) EventType ¶
func (e *MessageStartEvent) EventType() string
type MessageUpdateEvent ¶
type MessageUpdateEvent struct {
Type string `json:"type"`
Message agent.AgentMessage `json:"message"`
AssistantMessageEvent types.AssistantMessageEvent `json:"assistantMessageEvent"`
}
MessageUpdateEvent fires during assistant streaming (pi: MessageUpdateEvent).
func (*MessageUpdateEvent) EventType ¶
func (e *MessageUpdateEvent) EventType() string
type MissingSessionCwdError ¶
type MissingSessionCwdError struct {
// contains filtered or unexported fields
}
MissingSessionCwdError is the controlled error raised when a session's stored cwd is gone (pi: MissingSessionCwdError).
func NewMissingSessionCwdError ¶
func NewMissingSessionCwdError(issue SessionCwdIssue) *MissingSessionCwdError
NewMissingSessionCwdError builds the error (pi: constructor).
func (*MissingSessionCwdError) Error ¶
func (e *MissingSessionCwdError) Error() string
func (*MissingSessionCwdError) Issue ¶
func (e *MissingSessionCwdError) Issue() SessionCwdIssue
Issue returns the underlying issue (pi: readonly issue field).
type ModelChangeEntry ¶
type ModelChangeEntry struct {
EntryBase
Provider string `json:"provider"`
ModelID string `json:"modelId"`
}
ModelChangeEntry records a model switch (pi: ModelChangeEntry).
type ModelConfig ¶
type ModelConfig struct {
// contains filtered or unexported fields
}
ModelConfig is one immutable load of models.json (pi: ModelConfig).
func LoadModelConfig ¶
func LoadModelConfig(modelsJSONPath string) *ModelConfig
LoadModelConfig loads models.json; an empty path yields an empty config (pi: ModelConfig.load(undefined)).
func (*ModelConfig) GetError ¶
func (c *ModelConfig) GetError() string
GetError returns the load/validation error, if any (pi: getError).
func (*ModelConfig) GetProvider ¶
func (c *ModelConfig) GetProvider(providerID string) *ModelsJsonProvider
GetProvider returns one provider entry (pi: getProvider).
func (*ModelConfig) GetProviderIds ¶
func (c *ModelConfig) GetProviderIds() []string
GetProviderIds lists provider ids in document order (pi: getProviderIds).
type ModelCycleResult ¶
type ModelCycleResult struct {
Model *types.Model
ThinkingLevel agent.ThinkingLevel
// IsScoped reports cycling through scoped models (--models flag) vs
// all available.
IsScoped bool
}
ModelCycleResult is the result from CycleModel (pi: ModelCycleResult).
type ModelMutationOptions ¶
type ModelMutationOptions struct {
// Persist writes the new value to global defaults. Defaults to
// session-only.
Persist bool
}
ModelMutationOptions are the options for model/thinking mutations (pi: ModelMutationOptions).
type ModelPriceSource ¶
ModelPriceSource is the minimal pricing lookup, satisfied by ModelRuntime (pi: ModelPriceSource). Cost is $/million tokens.
type ModelPriceSourceFunc ¶
ModelPriceSourceFunc adapts a function to ModelPriceSource (pig seam for ModelRuntime).
type ModelRegistry ¶
type ModelRegistry struct {
// contains filtered or unexported fields
}
ModelRegistry is the extension-facing facade over ModelRuntime (pi: ModelRegistry).
func NewModelRegistry ¶
func NewModelRegistry(runtime *ModelRuntime) *ModelRegistry
NewModelRegistry wraps a runtime (pi: constructor).
func (*ModelRegistry) Complete ¶
func (r *ModelRegistry) Complete(ctx context.Context, model *ai.Model, llmContext *ai.Context, options *ai.ModelsStreamOptions) (*ai.AssistantMessage, error)
Complete dispatches one completion (pi: complete).
func (*ModelRegistry) Find ¶
func (r *ModelRegistry) Find(provider, modelID string) *ai.Model
Find looks up one model; nil when absent (pi: find).
func (*ModelRegistry) GetAll ¶
func (r *ModelRegistry) GetAll() []ai.Model
GetAll lists all models (pi: getAll).
func (*ModelRegistry) GetApiKeyAndHeaders ¶
func (r *ModelRegistry) GetApiKeyAndHeaders(ctx context.Context, model ai.Model) ResolvedRequestAuth
GetApiKeyAndHeaders resolves request auth for a model (pi: getApiKeyAndHeaders).
func (*ModelRegistry) GetApiKeyForProvider ¶
func (r *ModelRegistry) GetApiKeyForProvider(ctx context.Context, provider string) string
GetApiKeyForProvider resolves the provider's API key, swallowing errors (pi: getApiKeyForProvider).
func (*ModelRegistry) GetAvailable ¶
func (r *ModelRegistry) GetAvailable() []ai.Model
GetAvailable lists available models (pi: getAvailable).
func (*ModelRegistry) GetError ¶
func (r *ModelRegistry) GetError() string
GetError aggregates runtime errors (pi: getError).
func (*ModelRegistry) GetProvider ¶
func (r *ModelRegistry) GetProvider(provider string) ai.Provider
GetProvider returns one provider; nil when absent (pi: getProvider).
func (*ModelRegistry) GetProviderAuth ¶
func (r *ModelRegistry) GetProviderAuth(ctx context.Context, provider string) (*auth.AuthResult, error)
GetProviderAuth resolves provider auth (pi: getProviderAuth).
func (*ModelRegistry) GetProviderAuthStatus ¶
func (r *ModelRegistry) GetProviderAuthStatus(provider string) AuthStatus
GetProviderAuthStatus reports the provider auth status (pi: getProviderAuthStatus).
func (*ModelRegistry) GetProviderDisplayName ¶
func (r *ModelRegistry) GetProviderDisplayName(provider string) string
GetProviderDisplayName returns the display name, falling back to the id (pi: getProviderDisplayName).
func (*ModelRegistry) GetRegisteredNativeProvider ¶
func (r *ModelRegistry) GetRegisteredNativeProvider(providerName string) ai.Provider
GetRegisteredNativeProvider returns one native registration (pi: getRegisteredNativeProvider).
func (*ModelRegistry) GetRegisteredProviderConfig ¶
func (r *ModelRegistry) GetRegisteredProviderConfig(providerName string) *ProviderConfigInput
GetRegisteredProviderConfig returns one registration (pi: getRegisteredProviderConfig).
func (*ModelRegistry) GetRegisteredProviderIds ¶
func (r *ModelRegistry) GetRegisteredProviderIds() []string
GetRegisteredProviderIds lists registered provider ids (pi: getRegisteredProviderIds).
func (*ModelRegistry) HasConfiguredAuth ¶
func (r *ModelRegistry) HasConfiguredAuth(model ai.Model) bool
HasConfiguredAuth reports whether the model's provider is configured (pi: hasConfiguredAuth).
func (*ModelRegistry) IsUsingOAuth ¶
func (r *ModelRegistry) IsUsingOAuth(model ai.Model) bool
IsUsingOAuth reports OAuth-backed auth (pi: isUsingOAuth).
func (*ModelRegistry) Refresh ¶
func (r *ModelRegistry) Refresh(ctx context.Context, options *ai.ModelsRefreshOptions) ai.ModelsRefreshResult
Refresh reloads models.json (pi: refresh; "await before making synchronous registry reads").
func (*ModelRegistry) RegisterNativeProvider ¶
func (r *ModelRegistry) RegisterNativeProvider(provider ai.Provider) error
RegisterNativeProvider registers a Go-native provider (pi: registerProvider Provider overload).
func (*ModelRegistry) RegisterProvider ¶
func (r *ModelRegistry) RegisterProvider(providerName string, config *ProviderConfigInput) error
RegisterProvider registers a provider config by name (pi: registerProvider string overload).
func (*ModelRegistry) Stream ¶ added in v0.86.0
func (r *ModelRegistry) Stream(ctx context.Context, model *ai.Model, llmContext *ai.Context, options *ai.ModelsStreamOptions) *ai.AssistantMessageEventStream
Stream streams through the configured provider with request-time authentication (pi: stream).
func (*ModelRegistry) StreamSimple ¶ added in v0.86.0
func (r *ModelRegistry) StreamSimple(ctx context.Context, model *ai.Model, llmContext *ai.Context, options *ai.ModelsSimpleStreamOptions) *ai.AssistantMessageEventStream
StreamSimple streams with provider-neutral options and request-time authentication (pi: streamSimple).
func (*ModelRegistry) UnregisterProvider ¶
func (r *ModelRegistry) UnregisterProvider(providerName string)
UnregisterProvider removes an extension registration (pi: unregisterProvider).
type ModelResolverRuntime ¶
type ModelResolverRuntime interface {
// GetModels lists all models (pi: getModels() with no provider filter).
GetModels() []ai.Model
// HasConfiguredAuth reports whether provider auth is configured (pi:
// hasConfiguredAuth).
HasConfiguredAuth(providerID string) bool
// GetAvailable lists models of providers with configured auth (pi:
// getAvailable()); cancellation rides the context.
GetAvailable(ctx context.Context) ([]ai.Model, error)
// GetAvailableSnapshot returns the last-known available list (pi:
// getAvailableSnapshot).
GetAvailableSnapshot() []ai.Model
// GetModel looks up one model (pi: getModel); ok is false when absent.
GetModel(providerID, modelID string) (ai.Model, bool)
}
ModelResolverRuntime is the ModelRuntime surface the resolver consumes (pi: the concrete ModelRuntime class).
func NewModelRuntimeResolver ¶
func NewModelRuntimeResolver(runtime *ModelRuntime) ModelResolverRuntime
NewModelRuntimeResolver adapts a ModelRuntime to the ModelResolverRuntime consumer interface (pi passes the ModelRuntime class directly to resolveCliModel/resolveModelScope; see modelRuntimeResolver above).
type ModelRuntime ¶
type ModelRuntime struct {
// contains filtered or unexported fields
}
ModelRuntime is the configured Models collection (pi: ModelRuntime).
func CreateModelRuntime ¶
func CreateModelRuntime(ctx context.Context, options *CreateModelRuntimeOptions) *ModelRuntime
CreateModelRuntime creates a fully configured runtime (pi: ModelRuntime.create).
func NewModelRuntime ¶
func NewModelRuntime(credentials *RuntimeCredentials, config *ModelConfig, modelsPath string, modelsStore ai.ModelsStore, providerList []ai.Provider, modelNetworkEnabled bool) *ModelRuntime
NewModelRuntime assembles the runtime over explicit inputs (pi: private constructor).
func (*ModelRuntime) CancelDeferred ¶
func (r *ModelRuntime) CancelDeferred(ctx context.Context, model *ai.Model, handle *ai.DeferredHandle, options *ai.ModelsDeferredCancelOptions) error
CancelDeferred cancels one deferred response (pi: cancelDeferred).
func (*ModelRuntime) CheckAuth ¶
CheckAuth reports provider auth configuration without refreshing OAuth (pi: checkAuth).
func (*ModelRuntime) Complete ¶
func (r *ModelRuntime) Complete(ctx context.Context, model *ai.Model, llmContext *ai.Context, options *ai.ModelsStreamOptions) (*ai.AssistantMessage, error)
Complete is Stream plus Result (pi: complete).
func (*ModelRuntime) CompleteSimple ¶
func (r *ModelRuntime) CompleteSimple(ctx context.Context, model *ai.Model, llmContext *ai.Context, options *ai.ModelsSimpleStreamOptions) (*ai.AssistantMessage, error)
CompleteSimple is StreamSimple plus Result (pi: completeSimple).
func (*ModelRuntime) FetchDeferred ¶
func (r *ModelRuntime) FetchDeferred(ctx context.Context, model *ai.Model, handle *ai.DeferredHandle, options *ai.ModelsDeferredFetchOptions) (*ai.AssistantMessage, error)
FetchDeferred fetches a deferred response to completion (pi: fetchDeferred; v0.85.1 makes it a thin wrapper over streamDeferred's result).
func (*ModelRuntime) GetAuth ¶
func (r *ModelRuntime) GetAuth(ctx context.Context, providerID string, overrides *ModelRuntimeAuthOverrides) (*auth.AuthResult, error)
GetAuth resolves provider-scoped auth (pi: getAuth(string) overload).
func (*ModelRuntime) GetAuthForModel ¶
func (r *ModelRuntime) GetAuthForModel(ctx context.Context, model *ai.Model, overrides *ModelRuntimeAuthOverrides) (*auth.AuthResult, error)
GetAuthForModel resolves provider auth plus static and configured model headers (pi: getAuth(Model) overload).
func (*ModelRuntime) GetAvailable ¶
GetAvailable refreshes the availability snapshot and returns it (pi: getAvailable() with no provider id).
func (*ModelRuntime) GetAvailableForProvider ¶
func (r *ModelRuntime) GetAvailableForProvider(ctx context.Context, providerID string) ([]ai.Model, error)
GetAvailableForProvider returns one provider's available models (pi: getAvailable(providerId)).
func (*ModelRuntime) GetAvailableSnapshot ¶
func (r *ModelRuntime) GetAvailableSnapshot() []ai.Model
GetAvailableSnapshot returns the cached available list (pi: getAvailableSnapshot).
func (*ModelRuntime) GetCompatibilityRequestConfig ¶
func (r *ModelRuntime) GetCompatibilityRequestConfig(model ai.Model) CompatibilityRequestConfig
GetCompatibilityRequestConfig is a compatibility fallback for ModelRegistry when provider auth is unconfigured (pi: getCompatibilityRequestConfig).
func (*ModelRuntime) GetError ¶
func (r *ModelRuntime) GetError() string
GetError aggregates config, composition, and availability errors (pi: getError).
func (*ModelRuntime) GetModel ¶
func (r *ModelRuntime) GetModel(providerID, modelID string) (ai.Model, bool)
GetModel looks up one model (pi: getModel).
func (*ModelRuntime) GetModels ¶
func (r *ModelRuntime) GetModels(providerID string) []ai.Model
GetModels lists models, optionally restricted to one provider (pi: getModels(providerId?)).
func (*ModelRuntime) GetProvider ¶
func (r *ModelRuntime) GetProvider(providerID string) ai.Provider
GetProvider returns one provider; nil when absent (pi: getProvider).
func (*ModelRuntime) GetProviderAuthStatus ¶
func (r *ModelRuntime) GetProviderAuthStatus(providerID string) AuthStatus
GetProviderAuthStatus reports the auth status across layers (pi: getProviderAuthStatus).
func (*ModelRuntime) GetProviders ¶
func (r *ModelRuntime) GetProviders() []ai.Provider
GetProviders lists the registered providers (pi: getProviders).
func (*ModelRuntime) GetRegisteredNativeProvider ¶
func (r *ModelRuntime) GetRegisteredNativeProvider(providerID string) ai.Provider
GetRegisteredNativeProvider returns one native extension provider (pi: getRegisteredNativeProvider).
func (*ModelRuntime) GetRegisteredProviderConfig ¶
func (r *ModelRuntime) GetRegisteredProviderConfig(providerID string) *ProviderConfigInput
GetRegisteredProviderConfig returns one extension registration (pi: getRegisteredProviderConfig).
func (*ModelRuntime) GetRegisteredProviderIds ¶
func (r *ModelRuntime) GetRegisteredProviderIds() []string
GetRegisteredProviderIds lists registered extension provider ids (pi: getRegisteredProviderIds).
func (*ModelRuntime) HasConfiguredAuth ¶
func (r *ModelRuntime) HasConfiguredAuth(providerID string) bool
HasConfiguredAuth reports whether provider auth is configured (pi: hasConfiguredAuth).
func (*ModelRuntime) IsUsingOAuth ¶
func (r *ModelRuntime) IsUsingOAuth(providerID string) bool
IsUsingOAuth reports whether the provider currently authenticates via OAuth (pi: isUsingOAuth).
func (*ModelRuntime) IsUsingSubscription ¶
func (r *ModelRuntime) IsUsingSubscription(providerID string) bool
IsUsingSubscription reports whether the OAuth auth is subscription-backed (pi: isUsingSubscription).
func (*ModelRuntime) ListCredentials ¶
func (r *ModelRuntime) ListCredentials(ctx context.Context) ([]auth.CredentialInfo, error)
ListCredentials lists credential metadata (pi: listCredentials).
func (*ModelRuntime) Login ¶
func (r *ModelRuntime) Login(ctx context.Context, providerID string, authType auth.AuthType, interaction auth.AuthInteraction) (auth.Credential, error)
Login runs a provider login flow and synchronizes state (pi: login).
func (*ModelRuntime) Logout ¶
func (r *ModelRuntime) Logout(ctx context.Context, providerID string) error
Logout removes the stored credential and synchronizes state (pi: logout).
func (*ModelRuntime) Refresh ¶
func (r *ModelRuntime) Refresh(ctx context.Context, options *ai.ModelsRefreshOptions) ai.ModelsRefreshResult
Refresh reloads models.json, recomposes providers, and refreshes catalogs and availability (pi: refresh).
func (*ModelRuntime) RegisterNativeProvider ¶
func (r *ModelRuntime) RegisterNativeProvider(provider ai.Provider) error
RegisterNativeProvider registers a Go-native provider (pi: registerNativeProvider).
func (*ModelRuntime) RegisterProvider ¶
func (r *ModelRuntime) RegisterProvider(providerID string, config *ProviderConfigInput) error
RegisterProvider registers an extension provider config (pi: registerProvider).
func (*ModelRuntime) RemoveRuntimeApiKey ¶
func (r *ModelRuntime) RemoveRuntimeApiKey(ctx context.Context, providerID string) error
RemoveRuntimeApiKey clears a runtime override and synchronizes state (pi: removeRuntimeApiKey).
func (*ModelRuntime) SetRuntimeApiKey ¶
func (r *ModelRuntime) SetRuntimeApiKey(ctx context.Context, providerID string, apiKey string) error
SetRuntimeApiKey sets a runtime override and synchronizes state (pi: setRuntimeApiKey).
func (*ModelRuntime) Stream ¶
func (r *ModelRuntime) Stream(ctx context.Context, model *ai.Model, llmContext *ai.Context, options *ai.ModelsStreamOptions) *ai.AssistantMessageEventStream
Stream dispatches one streaming request (pi: stream).
func (*ModelRuntime) StreamDeferred ¶
func (r *ModelRuntime) StreamDeferred(ctx context.Context, model *ai.Model, handle *ai.DeferredHandle, options *ai.ModelsDeferredFetchOptions) *ai.AssistantMessageEventStream
StreamDeferred streams a deferred response lazily, resolving auth on demand (pi: streamDeferred, v0.85.1; fetchDeferred became its .Result() thin wrapper).
func (*ModelRuntime) StreamSimple ¶
func (r *ModelRuntime) StreamSimple(ctx context.Context, model *ai.Model, llmContext *ai.Context, options *ai.ModelsSimpleStreamOptions) *ai.AssistantMessageEventStream
StreamSimple dispatches one simple streaming request (pi: streamSimple).
func (*ModelRuntime) UnregisterProvider ¶
func (r *ModelRuntime) UnregisterProvider(providerID string)
UnregisterProvider removes an extension registration (pi: unregisterProvider).
type ModelRuntimeAuthOverrides ¶
type ModelRuntimeAuthOverrides struct {
APIKey string
Env types.ProviderEnv
// MinOAuthValidityMs requires this much remaining OAuth-token validity;
// defaults to five minutes. 0 = the default (pi: undefined); use a
// negative value to disable.
MinOAuthValidityMs int64
}
ModelRuntimeAuthOverrides adjust one auth resolution (pi: ModelRuntimeAuthOverrides; pi's embedded AuthOperationOptions.signal rides the context).
type ModelRuntimeRequestOptions ¶
type ModelRuntimeRequestOptions struct {
APIKey string
Headers types.ProviderHeaders
Env types.ProviderEnv
TransformHeaders func(headers types.ProviderHeaders) (types.ProviderHeaders, error)
}
ModelRuntimeRequestOptions carries the request fields prepareRequest consumes across the pi option shapes (apiKey, headers, env, transformHeaders).
type ModelScopeDiagnostic ¶
type ModelScopeDiagnostic struct {
Type string // "warning"
Code string // "no-match" | "invalid-thinking-level"
Message string
Pattern string
}
ModelScopeDiagnostic is one scope warning (pi: ModelScopeDiagnostic).
type ModelSelectEvent ¶
type ModelSelectEvent struct {
Type string `json:"type"`
Model *types.Model `json:"model"`
PreviousModel *types.Model `json:"previousModel"`
Source ModelSelectSource `json:"source"`
}
ModelSelectEvent fires when a new model is selected (pi: ModelSelectEvent).
func (*ModelSelectEvent) EventType ¶
func (e *ModelSelectEvent) EventType() string
type ModelSelectSource ¶
type ModelSelectSource string
ModelSelectSource is how a model got selected (pi: ModelSelectSource).
const ( ModelSelectSourceSet ModelSelectSource = "set" ModelSelectSourceCycle ModelSelectSource = "cycle" ModelSelectSourceRestore ModelSelectSource = "restore" )
type ModelsJsonChatTemplateKwarg ¶
type ModelsJsonChatTemplateKwarg struct {
Scalar any
Var *ModelsJsonChatTemplateKwargVariable
}
ModelsJsonChatTemplateKwarg is a scalar or {$var} kwarg (pi: ChatTemplateKwargSchema: string | number | boolean | null | variable).
func (ModelsJsonChatTemplateKwarg) MarshalJSON ¶
func (k ModelsJsonChatTemplateKwarg) MarshalJSON() ([]byte, error)
func (*ModelsJsonChatTemplateKwarg) UnmarshalJSON ¶
func (k *ModelsJsonChatTemplateKwarg) UnmarshalJSON(data []byte) error
type ModelsJsonChatTemplateKwargVariable ¶
type ModelsJsonChatTemplateKwargVariable struct {
Var string `json:"$var"` // "thinking.enabled" | "thinking.effort"
OmitWhenOff *bool `json:"omitWhenOff,omitempty"`
}
ModelsJsonChatTemplateKwargVariable is the {$var, omitWhenOff} kwarg form (pi: ChatTemplateKwargVariableSchema).
type ModelsJsonCost ¶
type ModelsJsonCost struct {
Input float64 `json:"input"`
Output float64 `json:"output"`
CacheRead float64 `json:"cacheRead"`
CacheWrite float64 `json:"cacheWrite"`
Tiers []ModelsJsonCostTier `json:"tiers,omitempty"`
}
ModelsJsonCost is the required-rate cost object of a model definition (pi: ModelCostSchema).
type ModelsJsonCostTier ¶
type ModelsJsonCostTier struct {
InputTokensAbove float64 `json:"inputTokensAbove"`
Input float64 `json:"input"`
Output float64 `json:"output"`
CacheRead float64 `json:"cacheRead"`
CacheWrite float64 `json:"cacheWrite"`
}
ModelsJsonCostTier is one request-wide pricing tier (pi: ModelCostTierSchema).
type ModelsJsonImageLimits ¶ added in v0.87.0
type ModelsJsonImageLimits struct {
Resize *ModelsJsonImageResize `json:"resize,omitempty"`
MaxPerMessage *float64 `json:"maxPerMessage,omitempty"`
MaxPerRequest *float64 `json:"maxPerRequest,omitempty"`
}
ModelsJsonImageLimits is the models.json inputLimits.images object (pi: the nested images schema).
type ModelsJsonImageResize ¶ added in v0.87.0
type ModelsJsonImageResize struct {
MaxWidth *float64 `json:"maxWidth,omitempty"`
MaxHeight *float64 `json:"maxHeight,omitempty"`
MaxBytes *float64 `json:"maxBytes,omitempty"`
JpegQuality *float64 `json:"jpegQuality,omitempty"`
}
ModelsJsonImageResize is the models.json resize profile (pi: ImageResizeSchema).
type ModelsJsonInputLimits ¶ added in v0.87.0
type ModelsJsonInputLimits struct {
MaxRequestBytes *float64 `json:"maxRequestBytes,omitempty"`
Images *ModelsJsonImageLimits `json:"images,omitempty"`
}
ModelsJsonInputLimits is the models.json inputLimits object (pi: ModelInputLimitsSchema, v0.87.0 #9631).
type ModelsJsonModel ¶
type ModelsJsonModel struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
API string `json:"api,omitempty"`
BaseURL string `json:"baseUrl,omitempty"`
Reasoning *bool `json:"reasoning,omitempty"`
ThinkingLevelMap *ModelsJsonThinkingLevelMap `json:"thinkingLevelMap,omitempty"`
Input []string `json:"input,omitempty"` // "text" | "image"
InputLimits *ModelsJsonInputLimits `json:"inputLimits,omitempty"`
Cost *ModelsJsonCost `json:"cost,omitempty"`
PromptCache *ModelsJsonPromptCache `json:"promptCache,omitempty"`
ContextWindow *float64 `json:"contextWindow,omitempty"`
MaxTokens *float64 `json:"maxTokens,omitempty"`
SamplingParams map[string]any `json:"samplingParams,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Compat json.RawMessage `json:"compat,omitempty"`
}
ModelsJsonModel is one model definition (pi: ModelDefinitionSchema).
type ModelsJsonModelOverride ¶
type ModelsJsonModelOverride struct {
Name string `json:"name,omitempty"`
Reasoning *bool `json:"reasoning,omitempty"`
ThinkingLevelMap *ModelsJsonThinkingLevelMap `json:"thinkingLevelMap,omitempty"`
Input []string `json:"input,omitempty"`
InputLimits *ModelsJsonInputLimits `json:"inputLimits,omitempty"`
Cost *ModelsJsonOverrideCost `json:"cost,omitempty"`
PromptCache *ModelsJsonPromptCache `json:"promptCache,omitempty"`
ContextWindow *float64 `json:"contextWindow,omitempty"`
MaxTokens *float64 `json:"maxTokens,omitempty"`
SamplingParams map[string]any `json:"samplingParams,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Compat json.RawMessage `json:"compat,omitempty"`
}
ModelsJsonModelOverride is one model override (pi: ModelOverrideSchema; no id — overrides attach by model id key).
type ModelsJsonOpenRouterRouting ¶
type ModelsJsonOpenRouterRouting struct {
AllowFallbacks *bool `json:"allow_fallbacks,omitempty"`
RequireParameters *bool `json:"require_parameters,omitempty"`
DataCollection string `json:"data_collection,omitempty"` // "deny" | "allow"
ZDR *bool `json:"zdr,omitempty"`
EnforceDistillableText *bool `json:"enforce_distillable_text,omitempty"`
Order []string `json:"order,omitempty"`
Only []string `json:"only,omitempty"`
Ignore []string `json:"ignore,omitempty"`
Quantizations []string `json:"quantizations,omitempty"`
Sort any `json:"sort,omitempty"` // string | {by, partition}
MaxPrice map[string]any `json:"max_price,omitempty"` // string|number values
PreferredMinThroughput any `json:"preferred_min_throughput,omitempty"` // number | percentile cutoffs
PreferredMaxLatency any `json:"preferred_max_latency,omitempty"` // number | percentile cutoffs
}
ModelsJsonOpenRouterRouting is the openrouter routing compat block (pi: OpenRouterRoutingSchema).
type ModelsJsonOverrideCost ¶
type ModelsJsonOverrideCost struct {
Input *float64 `json:"input,omitempty"`
Output *float64 `json:"output,omitempty"`
CacheRead *float64 `json:"cacheRead,omitempty"`
CacheWrite *float64 `json:"cacheWrite,omitempty"`
Tiers []ModelsJsonCostTier `json:"tiers,omitempty"`
}
ModelsJsonOverrideCost is the all-optional cost object of a model override (pi: ModelOverrideSchema.cost).
type ModelsJsonPercentileCutoffs ¶
type ModelsJsonPercentileCutoffs struct {
P50 *float64 `json:"p50,omitempty"`
P75 *float64 `json:"p75,omitempty"`
P90 *float64 `json:"p90,omitempty"`
P99 *float64 `json:"p99,omitempty"`
}
ModelsJsonPercentileCutoffs is the p50/p75/p90/p99 cutoff object (pi: PercentileCutoffsSchema).
type ModelsJsonPromptCache ¶ added in v0.86.0
type ModelsJsonPromptCache struct {
Short *float64 `json:"short,omitempty"`
Long *float64 `json:"long,omitempty"`
}
ModelsJsonPromptCache is a best-effort prompt cache lifetime in seconds per retention tier (pi: ModelPromptCacheSchema; values must be > 0).
type ModelsJsonProvider ¶
type ModelsJsonProvider struct {
Name string `json:"name,omitempty"`
BaseURL string `json:"baseUrl,omitempty"`
APIKey string `json:"apiKey,omitempty"`
API string `json:"api,omitempty"`
OAuth string `json:"oauth,omitempty"` // "radius"
Headers map[string]string `json:"headers,omitempty"`
Compat json.RawMessage `json:"compat,omitempty"`
AuthHeader *bool `json:"authHeader,omitempty"`
Models []*ModelsJsonModel `json:"models,omitempty"`
ModelOverrides map[string]*ModelsJsonModelOverride `json:"modelOverrides,omitempty"`
}
ModelsJsonProvider is one provider config (pi: ProviderConfigSchema).
type ModelsJsonThinkingLevelMap ¶
type ModelsJsonThinkingLevelMap struct {
Off *string `json:"off,omitempty"`
Minimal *string `json:"minimal,omitempty"`
Low *string `json:"low,omitempty"`
Medium *string `json:"medium,omitempty"`
High *string `json:"high,omitempty"`
Xhigh *string `json:"xhigh,omitempty"`
Max *string `json:"max,omitempty"`
// Present records the keys the JSON carried (pig addition: the
// missing/null distinction matters to ThinkingLevelMap merging).
Present map[string]bool `json:"-"`
}
ModelsJsonThinkingLevelMap maps pi thinking levels to provider-specific values (pi: ThinkingLevelMapSchema, string | null members). A nil entry that is Present means an explicit null (the level is unsupported); a missing key is absent from Present.
func (*ModelsJsonThinkingLevelMap) UnmarshalJSON ¶
func (m *ModelsJsonThinkingLevelMap) UnmarshalJSON(data []byte) error
type ModelsJsonVercelGatewayRouting ¶
type ModelsJsonVercelGatewayRouting struct {
Only []string `json:"only,omitempty"`
Order []string `json:"order,omitempty"`
}
ModelsJsonVercelGatewayRouting is the vercel gateway routing compat block (pi: VercelGatewayRoutingSchema).
type NavigateTreeCommandOptions ¶
type NavigateTreeCommandOptions struct {
}
NavigateTreeCommandOptions are the navigateTree options (pi: navigateTree's options parameter).
type NavigateTreeOptions ¶
type NavigateTreeOptions struct {
// branch.
Summarize bool
CustomInstructions string
// CustomInstructions instead of appending.
ReplaceInstructions bool
Label string
}
NavigateTreeOptions are the navigateTree options (pi: the options object).
type NavigateTreeResult ¶
type NavigateTreeResult struct {
// nil = none (pi: editorText?).
EditorText *string
Cancelled bool
Aborted bool
// summaryEntry?).
SummaryEntry *BranchSummaryEntry
}
NavigateTreeResult is the navigateTree result (pi: the result object).
type NewSessionCommandOptions ¶
type NewSessionCommandOptions struct {
// ParentSession points at the parent session (pi: parentSession?).
ParentSession string
// Setup runs with the new session manager before withSession (pi:
// setup?).
Setup func(ctx context.Context, sessionManager *SessionManager) error
// WithSession receives the replacement session context (pi:
// withSession?).
WithSession func(ctx context.Context, sessionCtx *ReplacedSessionContext) error
}
NewSessionCommandOptions are the newSession options (pi: newSession's options parameter).
type NewSessionOptions ¶
type NewSessionOptions struct {
ID *string `json:"id,omitempty"`
ParentSession *string `json:"parentSession,omitempty"`
}
NewSessionOptions parameterize new-session creation (pi: NewSessionOptions).
type NormalizedBuildSystemPromptOptions ¶ added in v0.86.0
type NormalizedBuildSystemPromptOptions struct {
CustomPrompt string
ForceSystemPrompt string // "" = absent (pi: forceSystemPrompt?: string)
SelectedTools []string
ToolSnippets map[string]string
ToolGuidelines map[string][]string
PromptGuidelines []string
AppendSystemPrompt string
Sections *types.SystemSections
Cwd string
ContextFiles []ContextFile
Skills []Skill
}
NormalizedBuildSystemPromptOptions is the mutable, collection-complete shape exposed to extensions (pi: NormalizedBuildSystemPromptOptions).
func NormalizeBuildSystemPromptOptions ¶ added in v0.86.0
func NormalizeBuildSystemPromptOptions(input BuildSystemPromptOptions) NormalizedBuildSystemPromptOptions
NormalizeBuildSystemPromptOptions normalizes prompt input into the mutable, collection-complete shape exposed to extensions (pi: normalizeBuildSystemPromptOptions).
type PackageSource ¶
type PackageSource struct {
// Source is the package spec; in string form it holds the whole value.
Source string
// ObjectForm records that the settings.json value was the object form
// (string form round-trips as a bare string). Not serialized.
ObjectForm bool
Autoload *bool `json:"autoload,omitempty"`
Extensions []string `json:"extensions,omitempty"`
Skills []string `json:"skills,omitempty"`
Prompts []string `json:"prompts,omitempty"`
Themes []string `json:"themes,omitempty"`
}
PackageSource is one npm/git package source (pi: PackageSource union). The string form loads all resources from the package; the object form filters which resources to load; Autoload=false starts empty and only applies explicit resource patterns.
type ParseModelPatternOptions ¶
type ParseModelPatternOptions struct {
// AllowInvalidThinkingLevelFallback defaults to true when the options
// are omitted (pi: options?.allowInvalidThinkingLevelFallback ?? true).
AllowInvalidThinkingLevelFallback *bool
}
ParseModelPatternOptions parameterize ParseModelPattern (pi: the options argument; nil = default).
type ParsedModelResult ¶
type ParsedModelResult struct {
Model *ai.Model
// ThinkingLevel is the explicit pattern suffix; empty = undefined.
ThinkingLevel agent.ThinkingLevel
Warning string
}
ParsedModelResult is one parseModelPattern outcome (pi: ParsedModelResult).
func ParseModelPattern ¶
func ParseModelPattern(pattern string, availableModels []ai.Model, options *ParseModelPatternOptions) ParsedModelResult
ParseModelPattern parses a pattern to extract model and thinking level, handling models with colons in their ids (e.g. OpenRouter's :exacto suffix): try the full pattern first; otherwise split on the last colon and recurse when the suffix is a valid thinking level (pi: parseModelPattern).
type ParsedSkillBlock ¶
type ParsedSkillBlock struct {
Name string
Location string
Content string
// UserMessage is the optional trailing user text; nil = absent (pi:
// userMessage: string | undefined).
UserMessage *string
}
ParsedSkillBlock is a parsed skill block from a user message (pi: ParsedSkillBlock).
func ParseSkillBlock ¶
func ParseSkillBlock(text string) *ParsedSkillBlock
ParseSkillBlock parses a skill block from message text. Returns nil if the text doesn't contain a skill block.
type PathMetadata ¶
type PathMetadata struct {
Source string
Scope SourceScope
Origin string // "package" | "top-level"
// BaseDir is the directory the path was resolved from (pi: baseDir?);
// "" = none.
BaseDir string
}
PathMetadata describes one resolved resource path (pi: PathMetadata).
type ProjectTrustContext ¶
type ProjectTrustContext struct {
Cwd string
Mode ExtensionMode
HasUI bool
UI ProjectTrustUI
}
ProjectTrustContext is the context for project-trust flows (pi: ProjectTrustContext). UI is restricted to the four dialog members (Pick<ExtensionUIContext, ...>); pig models the pick as a separate interface over the same implementation.
type ProjectTrustDecision ¶
type ProjectTrustDecision = *bool
ProjectTrustDecision is a trust decision: true, false, or null (pi: ProjectTrustDecision = boolean | null).
type ProjectTrustOption ¶
type ProjectTrustOption struct {
Label string
Trusted bool
Updates []ProjectTrustUpdate
SavedPath string
}
ProjectTrustOption is one trust prompt option (pi: ProjectTrustOption; savedPath "" = undefined).
func GetProjectTrustOptions ¶
func GetProjectTrustOptions(cwd string, options *struct{ IncludeSessionOnly bool }) []ProjectTrustOption
GetProjectTrustOptions builds the trust prompt options (pi: getProjectTrustOptions).
type ProjectTrustSetting ¶
type ProjectTrustSetting = DefaultProjectTrust
ProjectTrustSetting is the defaultProjectTrust setting value (pi: DefaultProjectTrust from settings-manager.ts).
type ProjectTrustStore ¶
type ProjectTrustStore struct {
// contains filtered or unexported fields
}
ProjectTrustStore persists trust decisions in trust.json (pi: ProjectTrustStore).
func NewProjectTrustStore ¶
func NewProjectTrustStore(agentDir string) *ProjectTrustStore
NewProjectTrustStore builds the store for one agent dir (pi: constructor).
func (*ProjectTrustStore) Get ¶
func (s *ProjectTrustStore) Get(cwd string) (ProjectTrustDecision, error)
Get returns the nearest stored decision (pi: get; nil = none; throw → error).
func (*ProjectTrustStore) GetEntry ¶
func (s *ProjectTrustStore) GetEntry(cwd string) (*ProjectTrustStoreEntry, error)
GetEntry returns the nearest trust entry (pi: getEntry; nil = none).
func (*ProjectTrustStore) Set ¶
func (s *ProjectTrustStore) Set(cwd string, decision ProjectTrustDecision) error
Set stores one decision (pi: set; nil decision = delete).
func (*ProjectTrustStore) SetMany ¶
func (s *ProjectTrustStore) SetMany(decisions []ProjectTrustUpdate) error
SetMany stores multiple decisions (pi: setMany).
type ProjectTrustStoreEntry ¶
ProjectTrustStoreEntry is one stored trust decision (pi: ProjectTrustStoreEntry).
type ProjectTrustUI ¶
type ProjectTrustUI interface {
Select(ctx context.Context, title string, options []string, opts *ExtensionUIDialogOptions) (string, bool)
Confirm(ctx context.Context, title string, message string, opts *ExtensionUIDialogOptions) bool
Input(ctx context.Context, title string, placeholder string, opts *ExtensionUIDialogOptions) (string, bool)
Notify(ctx context.Context, message string, level string)
}
ProjectTrustUI is the dialog subset of ExtensionUIContext (pi: Pick<ExtensionUIContext, "select" | "confirm" | "input" | "notify">).
type ProjectTrustUpdate ¶
type ProjectTrustUpdate struct {
Path string
Decision ProjectTrustDecision
}
ProjectTrustUpdate is one pending trust-store write (pi: ProjectTrustUpdate).
type ProjectedSessionEntry ¶ added in v0.87.0
type ProjectedSessionEntry struct {
// SourceEntry is the raw append-only entry that owns this projected
// contribution.
SourceEntry SessionEntry
// Messages are the model-visible messages after context edits; empty
// for state-only entries and omissions.
Messages []agent.AgentMessage
}
ProjectedSessionEntry is one selected entry with its model-visible messages after context edits (pi: ProjectedSessionEntry).
type PromptLoaderResult ¶
type PromptLoaderResult struct {
Prompts []PromptTemplate
Diagnostics []ResourceDiagnostic
}
PromptLoaderResult bundles prompts and diagnostics (pi's inline { prompts, diagnostics } shape).
type PromptOptions ¶
type PromptOptions struct {
// ExpandPromptTemplates dispatches extension commands and expands skill
// commands and prompt templates (default: true).
ExpandPromptTemplates *bool
// Images are the image attachments.
Images []types.ImageContent
// StreamingBehavior queues the message while streaming: "steer"
// (interrupt) or "followUp" (wait). Required if streaming.
StreamingBehavior string
// Source is the source of input for extension input event handlers.
// Defaults to "interactive".
Source InputSource
// PreflightResult is an internal hook used by RPC mode to observe
// prompt preflight acceptance or rejection.
PreflightResult func(success bool)
}
PromptOptions are the options for AgentSession.Prompt (pi: PromptOptions).
type PromptTemplate ¶
type PromptTemplate struct {
Name string
Description string
ArgumentHint string // pi: argumentHint? ("" = undefined)
Content string
SourceInfo SourceInfo
// FilePath is the absolute path to the template file.
FilePath string
}
PromptTemplate represents a prompt template loaded from a markdown file (pi: PromptTemplate).
type ProviderConfig ¶
type ProviderConfig struct {
// Name is the provider id being registered.
Name string
// Type is the registration kind; "" = pi's undefined (pi: type?).
Type string
// BaseURL is the endpoint base URL (pi: baseUrl).
BaseURL string
// APIKey, when set, is resolved per request (pi: apiKey).
APIKey string
// Models are the provider's model definitions (pi: models).
Models []ProviderModelConfig
}
ProviderConfig is the provider registration config (pi: ProviderConfig, defined in extensions/types.ts; the full shape arrives with the extensions/sidecar batch).
type ProviderConfigInput ¶
type ProviderConfigInput struct {
Name string
BaseURL string
APIKey string
API ai.Api
// StreamSimple is the custom stream implementation (pi: streamSimple).
StreamSimple func(ctx context.Context, model *ai.Model, llmContext *ai.TranscriptContext, options *ai.SimpleStreamOptions) *ai.AssistantMessageEventStream
Headers map[string]string
// AuthHeader distinguishes "unset" (nil) from explicit false so the
// models.json layer can still supply it (pi: authHeader?: boolean).
AuthHeader *bool
OAuth *ExtensionOAuthConfig
Models []ProviderConfigInputModel
// RefreshModels refreshes the dynamic model list (pi: refreshModels).
RefreshModels func(ctx context.Context, refreshCtx *ai.RefreshModelsContext) ([]ProviderConfigInputModel, error)
}
ProviderConfigInput is the input type of the extension registerProvider API (pi: ProviderConfigInput). Empty strings = pi's undefined.
type ProviderConfigInputModel ¶
type ProviderConfigInputModel struct {
ID string
Name string
API ai.Api
BaseURL string
Reasoning bool
ThinkingLevelMap types.ThinkingLevelMap
Input []ai.ModelInput
// InputLimits carries the provider input limits and image resize profile
// (pi: inputLimits, v0.87.0 #9631).
InputLimits *types.ModelInputLimits
Cost ai.ModelCost
// PromptCache is the best-effort prompt cache lifetime per retention
// tier (pi: promptCache).
PromptCache types.ModelPromptCache
ContextWindow int64
MaxTokens int64
SamplingParams map[string]any
Headers map[string]string
Compat ai.ModelCompat
}
ProviderConfigInputModel is one extension-registered model definition (pi: ProviderConfigInput["models"] item).
type ProviderModelConfig ¶
type ProviderModelConfig struct {
ID string `json:"id"`
Name string `json:"name"`
Reasoning bool `json:"reasoning"`
ContextWindow int64 `json:"contextWindow"`
MaxTokens int64 `json:"maxTokens"`
Cost struct {
Input float64 `json:"input"`
Output float64 `json:"output"`
CacheRead float64 `json:"cacheRead"`
CacheWrite float64 `json:"cacheWrite"`
} `json:"cost"`
// InputLimits is the provider input limits and cache-safe image
// preprocessing metadata (pi: inputLimits, v0.87.0 #9631). pig's
// registration surface stays slim (input/thinkingLevelMap remain
// unported); this field rides through to the model record.
InputLimits *types.ModelInputLimits `json:"inputLimits,omitempty"`
}
ProviderModelConfig is one model of a registered provider (pi: ProviderModelConfig).
type ProviderRetrySettings ¶
type ProviderRetrySettings struct {
TimeoutMs *int64 // SDK/provider request timeout in milliseconds
MaxRetries *int64 // SDK/provider retry attempts
MaxRetryDelayMs *int64 // default: 60000 (max server-requested delay before failing)
}
ProviderRetrySettings holds the SDK/provider retry settings shape (pi: ProviderRetrySettings).
type ProviderRetrySettingsValues ¶
type ProviderRetrySettingsValues struct {
TimeoutMs *int64
MaxRetries *int64
MaxRetryDelayMs int64
}
ProviderRetrySettingsValues is the resolved provider retry shape (pi: getProviderRetrySettings's inline object literal).
type QueueUserInputOptions ¶ added in v0.86.0
type QueueUserInputOptions struct {
// Source is the input source reported to "input" extension handlers;
// "" = interactive (pi: options.source defaults to "interactive").
Source InputSource
}
QueueUserInputOptions parameterizes Steer/FollowUp (pi: the options param of steer()/followUp(); v0.86.0).
type ReadOnlyAuthStorage ¶
type ReadOnlyAuthStorage struct {
// contains filtered or unexported fields
}
ReadOnlyAuthStorage is a read-only CredentialStore over auth.json (pi: ReadOnlyAuthStorage).
func NewReadOnlyAuthStorage ¶
func NewReadOnlyAuthStorage(authPath string) *ReadOnlyAuthStorage
NewReadOnlyAuthStorage builds a read-only store; an empty path defaults to <agentDir>/auth.json (pi: constructor default).
func (*ReadOnlyAuthStorage) Delete ¶
func (s *ReadOnlyAuthStorage) Delete(ctx context.Context, providerID string) error
func (*ReadOnlyAuthStorage) List ¶
func (s *ReadOnlyAuthStorage) List(ctx context.Context) ([]auth.CredentialInfo, error)
func (*ReadOnlyAuthStorage) Modify ¶
func (s *ReadOnlyAuthStorage) Modify(ctx context.Context, providerID string, fn func(current auth.Credential) (auth.Credential, error)) (auth.Credential, error)
func (*ReadOnlyAuthStorage) Read ¶
func (s *ReadOnlyAuthStorage) Read(ctx context.Context, providerID string) (auth.Credential, error)
type ReadonlyFooterDataProvider ¶
type ReadonlyFooterDataProvider interface {
}
ReadonlyFooterDataProvider is the read-only footer data surface given to extension footer factories (pi: ReadonlyFooterDataProvider = Pick<FooterDataProvider, "getGitBranch" | "getExtensionStatuses" | "getAvailableProviderCount" | "onBranchChange">).
type ReadonlySessionManager ¶
type ReadonlySessionManager interface {
GetCwd() string
GetSessionDir() string
GetSessionID() string
GetSessionFile() string
GetLeafID() *string
GetLeafEntry() SessionEntry
GetEntry(id string) SessionEntry
GetLabel(id string) (string, bool)
GetBranch(fromID string) []SessionEntry
BuildContextEntries() []SessionEntry
BuildSessionProjection() SessionProjection
GetHeader() *SessionHeader
GetEntries() []SessionEntry
GetTree() []*SessionTreeNode
GetSessionName() (string, bool)
}
ReadonlySessionManager is the read-only SessionManager surface (pi: ReadonlySessionManager = Pick<SessionManager, ...>).
type RegisteredCommand ¶
type RegisteredCommand struct {
Name string
Description string
// GetArgumentCompletions provides autocomplete items (pi:
// getArgumentCompletions?); arrives with the TUI batch.
GetArgumentCompletions func(argumentPrefix string) any
// Handler runs the command (pi: handler).
Handler func(ctx context.Context, args string, commandCtx *ExtensionCommandContext) error
// SourceInfo is where the command came from.
SourceInfo SourceInfo
}
RegisteredCommand is one extension-registered command (pi: RegisteredCommand).
type RegisteredTool ¶
type RegisteredTool struct {
Definition *tools.ToolDefinition
SourceInfo SourceInfo
}
RegisteredTool is one extension-registered tool (pi: RegisteredTool).
type ReloadOptions ¶
type ReloadOptions struct {
// BeforeSessionStart runs before the reload session_start event.
BeforeSessionStart func(ctx context.Context) error
}
ReloadOptions carry the optional reload hooks (pi: reload options).
type ReplacedSessionContext ¶
type ReplacedSessionContext struct {
ExtensionCommandContext
// SendMessage sends a custom message via the replacement session (pi:
// sendMessage).
SendMessage func(ctx context.Context, message *CustomMessagePayload, options *SendMessageOptions)
// SendUserMessage sends a user message via the replacement session (pi:
// sendUserMessage).
SendUserMessage func(ctx context.Context, content string, options *SendUserMessageOptions)
}
ReplacedSessionContext is the fresh command-capable context bound to the replacement session after a session switch, passed to withSession callbacks (pi: ReplacedSessionContext extends ExtensionCommandContext with sendMessage/sendUserMessage overrides; pig re-points the two fields).
type ResolveCliModelOptions ¶
type ResolveCliModelOptions struct {
CliProvider string
CliModel string
CliThinking agent.ThinkingLevel
ModelRuntime ModelResolverRuntime
}
ResolveCliModelOptions are ResolveCliModel's inputs (pi: the options object).
type ResolveCliModelResult ¶
type ResolveCliModelResult struct {
Model *ai.Model
// ThinkingLevel is the parsed "<pattern>:<thinking>" suffix; empty =
// undefined. Callers apply it.
ThinkingLevel agent.ThinkingLevel
Warning string
// Error is a message suitable for CLI display; when set, Model is nil.
Error string
}
ResolveCliModelResult is one CLI model resolution (pi: ResolveCliModelResult).
func ResolveCliModel ¶
func ResolveCliModel(options ResolveCliModelOptions) ResolveCliModelResult
ResolveCliModel resolves a single model from CLI flags: --provider <provider> --model <pattern>, --model <provider>/<pattern>, or fuzzy matching (pi: resolveCliModel).
type ResolveModelScopeResult ¶
type ResolveModelScopeResult struct {
ScopedModels []ScopedModel
Diagnostics []ModelScopeDiagnostic
}
ResolveModelScopeResult is the structured scope outcome (pi: ResolveModelScopeResult).
func ResolveModelScopeFromModels ¶
func ResolveModelScopeFromModels(patterns []string, models []ai.Model) ResolveModelScopeResult
ResolveModelScopeFromModels resolves model patterns to actual models with optional thinking levels (pi: resolveModelScopeFromModels). Pattern format: "pattern:level"; glob patterns (* ? [) match against provider/modelId and bare model id.
func ResolveModelScopeWithDiagnostics ¶
func ResolveModelScopeWithDiagnostics(ctx context.Context, patterns []string, modelRuntime ModelResolverRuntime) (ResolveModelScopeResult, error)
ResolveModelScopeWithDiagnostics resolves scope against the runtime's available models without writing warnings (pi: resolveModelScopeWithDiagnostics).
type ResolveProjectTrustedOptions ¶
type ResolveProjectTrustedOptions struct {
Cwd string
TrustStore *ProjectTrustStore
TrustOverride *bool
DefaultProjectTrust ProjectTrustSetting
// ExtensionsResult is pi's LoadExtensionsResult for the project_trust
// extension event; always nil until the extensions batch lands (declared
// above).
ExtensionsResult any
// ProjectTrustHasUI is pi's projectTrustContext.hasUI.
ProjectTrustHasUI bool
// OnExtensionError receives extension event errors (unused until the
// extensions branch lands).
OnExtensionError func(message string)
}
ResolveProjectTrustedOptions carries the resolveProjectTrusted options (pi: ResolveProjectTrustedOptions).
type ResolvedCommand ¶
type ResolvedCommand struct {
RegisteredCommand
InvocationName string
}
ResolvedCommand is a command with its deduplicated invocation name (pi: ResolvedCommand).
type ResolvedPaths ¶
type ResolvedPaths struct {
Extensions []ResolvedResource
Skills []ResolvedResource
Prompts []ResolvedResource
Themes []ResolvedResource
}
ResolvedPaths groups the four resource kinds (pi: ResolvedPaths).
func ResolveSettingsResourcePaths ¶
func ResolveSettingsResourcePaths(settingsManager *SettingsManager, cwd string, agentDir string) ResolvedPaths
ResolveSettingsResourcePaths resolves resource paths from settings local entries plus auto-discovery, without package sources (pi: resolve() with the resolvePackageSources half deferred to the package-manager batch — no configured packages can resolve until npm/git installation lands).
type ResolvedRequestAuth ¶
type ResolvedRequestAuth struct {
Ok bool
// Error is set when Ok is false.
Error string
// APIKey/Headers/BaseUrl/Env are set when Ok is true.
APIKey string
Headers types.ProviderHeaders
BaseURL string
Env map[string]string
}
ResolvedRequestAuth is getApiKeyAndHeaders' outcome (pi: ResolvedRequestAuth union). Ok distinguishes the two forms.
type ResolvedResource ¶
type ResolvedResource struct {
Path string
Enabled bool
Metadata PathMetadata
}
ResolvedResource is one resolved path with enablement (pi: ResolvedResource).
type ResourceCollision ¶
type ResourceCollision struct {
// ResourceType is "extension" | "skill" | "prompt" | "theme"; the skill
// name, command/tool/flag name, prompt name, or theme name.
ResourceType string `json:"resourceType"`
Name string `json:"name"`
WinnerPath string `json:"winnerPath"`
LoserPath string `json:"loserPath"`
WinnerSource string `json:"winnerSource,omitempty"` // e.g., "npm:foo", "git:...", "local"
LoserSource string `json:"loserSource,omitempty"`
}
ResourceCollision describes a name collision between two loaded resources (pi: ResourceCollision).
type ResourceDiagnostic ¶
type ResourceDiagnostic struct {
Type string `json:"type"` // "warning" | "error" | "collision"
Message string `json:"message"`
Path string `json:"path,omitempty"`
Collision *ResourceCollision `json:"collision,omitempty"`
}
ResourceDiagnostic is one resource loading diagnostic (pi: ResourceDiagnostic).
type ResourceExtensionPath ¶
type ResourceExtensionPath struct {
Path string
Metadata ResourceExtensionPathMetadata
}
ResourceExtensionPath is one extension-contributed resource path (pi: { path, metadata }).
type ResourceExtensionPathMetadata ¶
type ResourceExtensionPathMetadata struct {
// Source labels the contributing extension (pi: source).
Source string
// Scope is always "temporary" for extension-contributed paths.
Scope string
// Origin is always "top-level" for extension-contributed paths.
Origin string
// BaseDir is the extension's directory; "" = none (pi: baseDir?).
BaseDir string
}
ResourceExtensionPathMetadata describes where an extension-contributed resource came from (pi: buildExtensionResourcePaths' metadata literal).
type ResourceExtensionPaths ¶
type ResourceExtensionPaths struct {
SkillPaths []ResourceExtensionPath
PromptPaths []ResourceExtensionPath
ThemePaths []ResourceExtensionPath
}
ResourceExtensionPaths bundles the extension-contributed resource paths (pi: ResourceExtensionPaths).
type ResourceLoader ¶
type ResourceLoader interface {
// GetExtensions returns the loaded extensions result (pi:
// getExtensions).
GetExtensions() *LoadExtensionsResult
// GetSkills returns the discovered skills (pi: getSkills).
GetSkills() ([]Skill, []ResourceDiagnostic)
// GetPrompts returns the discovered prompt templates (pi: getPrompts).
GetPrompts() ([]PromptTemplate, []ResourceDiagnostic)
// GetAgentsFiles returns the AGENTS.md-style context files (pi:
// getAgentsFiles).
GetAgentsFiles() []AgentsFile
// GetSystemPrompt returns the custom system prompt override; ok=false =
// none (pi: getSystemPrompt: string | undefined).
GetSystemPrompt() (string, bool)
// GetSystemPromptSource returns the override source path; ok=false =
// none (pi: getSystemPromptSource).
GetSystemPromptSource() (string, bool)
// GetAppendSystemPrompt returns the append system prompt segments (pi:
// getAppendSystemPrompt).
GetAppendSystemPrompt() []string
// GetAppendSystemPromptSources returns the append source paths (pi:
// getAppendSystemPromptSources).
GetAppendSystemPromptSources() []string
// GetThemes returns the loaded themes and diagnostics (pi: getThemes;
// themes arrive with the theme batch).
GetThemes() ([]any, []ResourceDiagnostic)
// ExtendResources merges extension-contributed resource paths (pi:
// extendResources).
ExtendResources(paths ResourceExtensionPaths)
// Reload reloads all resources (pi: reload(options?)).
Reload(options *ResourceLoaderReloadOptions) error
}
ResourceLoader supplies the session-scoped resources to AgentSession (pi: ResourceLoader).
type ResourceLoaderReloadOptions ¶
type ResourceLoaderReloadOptions struct {
// ResolveProjectTrust decides project trust during reload (pi:
// resolveProjectTrust). Called with the pre-trust extensions result when
// set.
ResolveProjectTrust func(extensionsResult *LoadExtensionsResult) (bool, error)
}
ResourceLoaderReloadOptions carries reload-time inputs (pi: ResourceLoaderReloadOptions).
type ResourceType ¶
type ResourceType = string
ResourceType is one of the four resource kinds (pi: ResourceType).
const ( ResourceExtensions ResourceType = "extensions" ResourceSkills ResourceType = "skills" ResourcePrompts ResourceType = "prompts" ResourceThemes ResourceType = "themes" )
type ResourcesDiscoverEvent ¶
type ResourcesDiscoverEvent struct {
Type string `json:"type"`
Cwd string `json:"cwd"`
// Reason: "startup" or "reload".
Reason string `json:"reason"`
}
ResourcesDiscoverEvent asks extensions for extra resource paths (pi: ResourcesDiscoverEvent).
func (*ResourcesDiscoverEvent) EventType ¶
func (e *ResourcesDiscoverEvent) EventType() string
type ResourcesDiscoverResult ¶
type ResourcesDiscoverResult struct {
SkillPaths []string `json:"skillPaths,omitempty"`
PromptPaths []string `json:"promptPaths,omitempty"`
ThemePaths []string `json:"themePaths,omitempty"`
}
ResourcesDiscoverResult carries the paths an extension contributes (pi: ResourcesDiscoverResult).
type RetrySettings ¶
type RetrySettings struct {
Enabled *bool // default: true
MaxRetries *int64 // default: 3
BaseDelayMs *int64 // default: 2000 (exponential backoff: 2s, 4s, 8s)
// MaxAgentDelayMs caps each computed agent retry delay (default: 60000)
// (pi: maxAgentDelayMs; v0.86.0).
MaxAgentDelayMs *int64
Provider *ProviderRetrySettings // pi: provider?
}
RetrySettings holds the agent retry settings shape (pi: RetrySettings).
type RetrySettingsValues ¶
type RetrySettingsValues struct {
Enabled bool
MaxRetries int64
BaseDelayMs int64
// MaxAgentDelayMs caps each computed agent retry delay (pi:
// maxAgentDelayMs; v0.86.0).
MaxAgentDelayMs int64
}
RetrySettingsValues is the resolved retry shape (pi: getRetrySettings's inline object literal).
type RunMigrationsResult ¶ added in v0.86.0
RunMigrationsResult is runMigrations's return object (pi: { migratedAuthProviders, deprecationWarnings }).
func RunMigrations ¶ added in v0.86.0
func RunMigrations(cwd string) RunMigrationsResult
RunMigrations runs all migrations. Called once on startup (pi: runMigrations).
type RuntimeCredentials ¶
type RuntimeCredentials struct {
// contains filtered or unexported fields
}
RuntimeCredentials overlays runtime API-key overrides on a persistent credential store (pi: RuntimeCredentials).
func NewRuntimeCredentials ¶
func NewRuntimeCredentials(store auth.CredentialStore) *RuntimeCredentials
NewRuntimeCredentials builds an overlay on store (pi: constructor).
func (*RuntimeCredentials) Delete ¶
func (c *RuntimeCredentials) Delete(ctx context.Context, providerID string) error
func (*RuntimeCredentials) HasRuntimeApiKey ¶
func (c *RuntimeCredentials) HasRuntimeApiKey(providerID string) bool
HasRuntimeApiKey reports whether a runtime override exists (pi: hasRuntimeApiKey).
func (*RuntimeCredentials) List ¶
func (c *RuntimeCredentials) List(ctx context.Context) ([]auth.CredentialInfo, error)
func (*RuntimeCredentials) Modify ¶
func (c *RuntimeCredentials) Modify(ctx context.Context, providerID string, fn func(current auth.Credential) (auth.Credential, error)) (auth.Credential, error)
func (*RuntimeCredentials) Read ¶
func (c *RuntimeCredentials) Read(ctx context.Context, providerID string) (auth.Credential, error)
func (*RuntimeCredentials) RemoveRuntimeApiKey ¶
func (c *RuntimeCredentials) RemoveRuntimeApiKey(providerID string)
RemoveRuntimeApiKey clears one runtime override (pi: removeRuntimeApiKey).
func (*RuntimeCredentials) SetRuntimeApiKey ¶
func (c *RuntimeCredentials) SetRuntimeApiKey(providerID string, apiKey string)
SetRuntimeApiKey sets a non-persistent runtime override (pi: setRuntimeApiKey).
type RuntimeNewSessionOptions ¶
type RuntimeNewSessionOptions struct {
// ParentSession is the parent session file for the new session (pi:
// parentSession).
ParentSession string
// Setup runs on the new session manager before the context is rebuilt
// (pi: setup).
Setup func(sessionManager *SessionManager) error
// WithSession runs with the replacement session context (pi:
// withSession).
WithSession func(replacedCtx *ReplacedSessionContext) error
}
RuntimeNewSessionOptions are the newSession inputs (pi's inline options; named to avoid the SessionManager's NewSessionOptions).
type ScopedModel ¶
type ScopedModel struct {
Model ai.Model
// ThinkingLevel is the level explicitly specified in the pattern (e.g.,
// "model:high"); empty otherwise.
ThinkingLevel agent.ThinkingLevel
}
ScopedModel is one pattern match with its optional explicit thinking level (pi: ScopedModel; empty ThinkingLevel = undefined).
func ResolveModelScope ¶
func ResolveModelScope(ctx context.Context, patterns []string, modelRuntime ModelResolverRuntime) ([]ScopedModel, error)
ResolveModelScope resolves model patterns and preserves CLI warning output (pi: resolveModelScope).
type ScrollViewScrollbar ¶
type ScrollViewScrollbar = string
ScrollViewScrollbar selects fullscreen scroll-view scrollbar behavior (pi: ScrollViewScrollbar from pi-tui; canonical type lands with the tui batch).
const ( ScrollViewScrollbarAuto ScrollViewScrollbar = "auto" ScrollViewScrollbarAlways ScrollViewScrollbar = "always" ScrollViewScrollbarHidden ScrollViewScrollbar = "hidden" )
type SendMessageOptions ¶
type SendMessageOptions struct {
// TriggerTurn starts a new LLM turn when not streaming (pi:
// triggerTurn?).
TriggerTurn *bool
// DeliverAs: "steer", "followUp", or "nextTurn" (pi: deliverAs?); "" =
// pi's undefined.
DeliverAs string
}
SendMessageOptions are the sendMessage delivery options (pi: sendMessage's options parameter).
type SendUserMessageOptions ¶
type SendUserMessageOptions struct {
// DeliverAs: "steer" or "followUp" (pi: deliverAs?); "" = pi's
// undefined.
DeliverAs string
}
SendUserMessageOptions are the sendUserMessage delivery options (pi: sendUserMessage's options parameter).
type SessionBeforeCompactEvent ¶
type SessionBeforeCompactEvent struct {
Type string `json:"type"`
// Preparation is the compaction preparation.
Preparation *CompactionPreparation `json:"preparation"`
// BranchEntries are the entries on the current branch.
BranchEntries []SessionEntry `json:"branchEntries"`
// CustomInstructions are the manual /compact instructions; "" = none
// (pi: customInstructions?).
CustomInstructions string `json:"customInstructions,omitempty"`
// Reason: "manual" | "threshold" | "overflow".
Reason string `json:"reason"`
// WillRetry is true when the aborted turn is retried after this
// compaction (overflow recovery).
WillRetry bool `json:"willRetry"`
}
SessionBeforeCompactEvent fires before compaction starts (pi: SessionBeforeCompactEvent). pi's signal member is dropped; cancellation travels as the Emit context.
func (*SessionBeforeCompactEvent) EventType ¶
func (e *SessionBeforeCompactEvent) EventType() string
type SessionBeforeCompactResult ¶
type SessionBeforeCompactResult struct {
Cancel bool `json:"cancel,omitempty"`
// Compaction replaces the default summary generator when set.
Compaction *CompactionResult `json:"compaction,omitempty"`
}
SessionBeforeCompactResult is the handler result (pi: SessionBeforeCompactResult).
type SessionBeforeForkEvent ¶
type SessionBeforeForkEvent struct {
Type string `json:"type"`
// EntryID is the fork target entry (pi: entryId).
EntryID string `json:"entryId"`
// Position: "before" | "at".
Position string `json:"position"`
}
SessionBeforeForkEvent fires before a fork; a handler returning cancel aborts the fork (pi: SessionBeforeForkEvent).
func (*SessionBeforeForkEvent) EventType ¶
func (e *SessionBeforeForkEvent) EventType() string
type SessionBeforeForkResult ¶
type SessionBeforeForkResult struct {
Cancel bool `json:"cancel,omitempty"`
}
SessionBeforeForkResult is the handler result of session_before_fork (pi: { cancel?: true }).
type SessionBeforeSwitchEvent ¶
type SessionBeforeSwitchEvent struct {
Type string `json:"type"`
// Reason: "new" | "resume".
Reason string `json:"reason"`
// TargetSessionFile is the destination file; "" = none (pi:
// targetSessionFile?).
TargetSessionFile string `json:"targetSessionFile,omitempty"`
}
SessionBeforeSwitchEvent fires before a session switch (new/resume); a handler returning cancel aborts the switch (pi: SessionBeforeSwitchEvent).
func (*SessionBeforeSwitchEvent) EventType ¶
func (e *SessionBeforeSwitchEvent) EventType() string
type SessionBeforeSwitchResult ¶
type SessionBeforeSwitchResult struct {
Cancel bool `json:"cancel,omitempty"`
}
SessionBeforeSwitchResult is the handler result of session_before_switch (pi: { cancel?: true }).
type SessionBeforeTreeEvent ¶
type SessionBeforeTreeEvent struct {
Type string `json:"type"`
Preparation *TreePreparation `json:"preparation"`
}
SessionBeforeTreeEvent fires before navigating in the session tree (pi: SessionBeforeTreeEvent; pi's signal member is dropped).
func (*SessionBeforeTreeEvent) EventType ¶
func (e *SessionBeforeTreeEvent) EventType() string
type SessionBeforeTreeResult ¶
type SessionBeforeTreeResult struct {
Cancel bool `json:"cancel,omitempty"`
// Summary replaces the default summarizer when set (pi: summary?).
Summary *SessionBeforeTreeSummary `json:"summary,omitempty"`
// CustomInstructions override the summarization instructions; nil =
// unchanged (pi: customInstructions?).
CustomInstructions *string `json:"customInstructions,omitempty"`
// ReplaceInstructions overrides whether customInstructions replace the
// default prompt; nil = unchanged (pi: replaceInstructions?).
ReplaceInstructions *bool `json:"replaceInstructions,omitempty"`
// Label overrides the branch summary label; nil = unchanged (pi:
// label?).
Label *string `json:"label,omitempty"`
}
SessionBeforeTreeResult is the handler result (pi: SessionBeforeTreeResult).
type SessionBeforeTreeSummary ¶
type SessionBeforeTreeSummary struct {
Summary string `json:"summary"`
Details any `json:"details,omitempty"`
Usage *types.Usage `json:"usage,omitempty"`
}
SessionBeforeTreeSummary is the custom summary payload (pi: SessionBeforeTreeResult's summary object).
type SessionBoundaryDraft ¶ added in v0.87.0
type SessionBoundaryDraft interface {
// contains filtered or unexported methods
}
SessionBoundaryDraft is one proposed session entry (pi: SessionBoundaryDraft = CustomEntryDraft | CustomMessageEntryDraft | ContextEditEntryDraft | CompactionEntryDraft, v0.87.0).
type SessionCompactEvent ¶
type SessionCompactEvent struct {
Type string `json:"type"`
// CompactionEntry is the saved compaction entry.
CompactionEntry *CompactionEntry `json:"compactionEntry"`
FromExtension bool `json:"fromExtension"`
// Reason: "manual" | "threshold" | "overflow".
Reason string `json:"reason"`
// WillRetry is true when the aborted turn is retried after this
// compaction (overflow recovery).
WillRetry bool `json:"willRetry"`
}
SessionCompactEvent fires after context compaction succeeds (pi: SessionCompactEvent).
func (*SessionCompactEvent) EventType ¶
func (e *SessionCompactEvent) EventType() string
type SessionCompactFailedEvent ¶
type SessionCompactFailedEvent struct {
Type string `json:"type"`
// Reason: "manual" | "threshold" | "overflow".
Reason string `json:"reason"`
// ErrorMessage is the error text for non-abort failures; "" = none (pi:
// errorMessage?).
ErrorMessage string `json:"errorMessage,omitempty"`
// Aborted is true when compaction was cancelled or aborted.
Aborted bool `json:"aborted"`
// WillRetry is true when the aborted turn would have been retried after
// this compaction (overflow recovery).
WillRetry bool `json:"willRetry"`
// FromExtension is true when the failing compaction content came from a
// session_before_compact handler.
FromExtension bool `json:"fromExtension"`
}
SessionCompactFailedEvent fires after context compaction fails or is aborted (pi: SessionCompactFailedEvent).
func (*SessionCompactFailedEvent) EventType ¶
func (e *SessionCompactFailedEvent) EventType() string
type SessionContext ¶
type SessionContext struct {
Messages []agent.AgentMessage
ThinkingLevel string
Model *SessionModelRef
}
SessionContext is the resolved LLM context of a session (pi: SessionContext).
func BuildSessionContext ¶
func BuildSessionContext(entries []SessionEntry, leafID *string, byID map[string]SessionEntry) SessionContext
BuildSessionContext builds the finalized model context from the canonical session projection (pi: buildSessionContext; leafID nil = TS undefined → last entry).
type SessionCwdIssue ¶
SessionCwdIssue describes a session whose stored cwd no longer exists (pi: SessionCwdIssue; sessionFile "" = undefined).
func GetMissingSessionCwdIssue ¶
func GetMissingSessionCwdIssue(sessionManager SessionCwdSource, fallbackCwd string) *SessionCwdIssue
GetMissingSessionCwdIssue returns the issue when the stored session cwd does not exist (pi: getMissingSessionCwdIssue).
type SessionCwdSource ¶
SessionCwdSource is the session-manager surface session-cwd consumes (pi: inline SessionCwdSource; GetSessionFile "" = undefined).
type SessionEntry ¶
type SessionEntry interface {
FileEntry
// Base exposes the shared id/parentId/timestamp fields.
Base() *EntryBase
}
SessionEntry is the session-tree entry union (pi: SessionEntry).
func BuildContextEntries ¶
func BuildContextEntries(entries []SessionEntry, leafID *string, byID map[string]SessionEntry) []SessionEntry
BuildContextEntries builds the active, compaction-aware session entry list. This follows the leaf path; if the path contains compaction entries, the latest compaction is represented by the compaction entry itself, followed by the kept entries starting at firstKeptEntryId and all entries after the compaction entry. Older summarized entries are omitted (pi: buildContextEntries; leafID nil = TS undefined → last entry).
type SessionHeader ¶
type SessionHeader struct {
Type string `json:"type"` // "session"
// Version is absent in v1 sessions.
Version *int `json:"version,omitempty"`
ID string `json:"id"`
Timestamp string `json:"timestamp"`
Cwd string `json:"cwd"`
// ParentSession is the path to the parent session (if this session was
// forked).
ParentSession *string `json:"parentSession,omitempty"`
}
SessionHeader is the first line of a session file (pi: SessionHeader).
func (*SessionHeader) EntryType ¶
func (h *SessionHeader) EntryType() string
type SessionHeaderScanLimitError ¶
type SessionHeaderScanLimitError struct {
FilePath string
}
SessionHeaderScanLimitError reports a header beyond the bounded scan (pi: SessionHeaderScanLimitError).
func (*SessionHeaderScanLimitError) Error ¶
func (e *SessionHeaderScanLimitError) Error() string
type SessionImportFileNotFoundError ¶
type SessionImportFileNotFoundError struct {
FilePath string
}
SessionImportFileNotFoundError is thrown when /import references a JSONL file path that does not exist (pi: SessionImportFileNotFoundError).
func (*SessionImportFileNotFoundError) Error ¶
func (e *SessionImportFileNotFoundError) Error() string
type SessionInfo ¶
type SessionInfo struct {
Path string
ID string
// Cwd is the working directory where the session was started; empty for
// old sessions.
Cwd string
// Name is the user-defined display name from session_info entries.
Name *string
// ParentSessionPath points at the parent session (if this session was
// forked).
ParentSessionPath *string
Created time.Time
Modified time.Time
MessageCount int
FirstMessage string
AllMessagesText string
}
SessionInfo describes one discovered session file (pi: SessionInfo).
func ListAllSessions ¶
func ListAllSessions(ctx context.Context, sessionDir string, onProgress SessionListProgress) []SessionInfo
ListAllSessions lists all sessions across all project directories, most recently modified first (pi: SessionManager.listAll; v0.86.0 reworks discovery ordering, partial progress, and ctx abort). sessionDir "" = the agent sessions root; onProgress may be nil.
func ListSessions ¶
func ListSessions(ctx context.Context, cwd string, sessionDir string, onProgress SessionListProgress) []SessionInfo
ListSessions lists all sessions for a directory, most recently modified first (pi: SessionManager.list; v0.86.0 adds partialSessions progress and ctx abort). sessionDir "" = the default per-cwd directory; onProgress may be nil.
type SessionInfoChangedEvent ¶
SessionInfoChangedEvent fires when the session metadata changes (pi: SessionInfoChangedEvent). nil Name = cleared (pi: name: string | undefined).
func (*SessionInfoChangedEvent) EventType ¶
func (e *SessionInfoChangedEvent) EventType() string
type SessionInfoEntry ¶
SessionInfoEntry carries session metadata, e.g. a user-defined display name (pi: SessionInfoEntry).
type SessionListProgress ¶
type SessionListProgress func(loaded int, total int, partialSessions []SessionInfo)
SessionListProgress reports (loaded, total) during session listing (pi: SessionListProgress; v0.86.0 adds partialSessions — sessions loaded so far sorted by activity, present on periodic updates, nil otherwise). pig: invoked from worker goroutines, serialized behind a mutex; must not re-enter the SessionManager.
type SessionManager ¶
type SessionManager struct {
// contains filtered or unexported fields
}
SessionManager manages conversation sessions as append-only trees stored in JSONL files (pi: SessionManager).
Each session entry has an id and parentId forming a tree structure. The "leaf" pointer tracks the current position. Appending creates a child of the current leaf. Branching moves the leaf to an earlier entry, allowing new branches without modifying history.
Use BuildSessionContext to get the resolved message list for the LLM, which handles compaction summaries and follows the path from root to current leaf.
pig: a single mutex guards the mutable state (pi relies on the single-threaded event loop; same convention as agent.Agent).
func ContinueRecentSession ¶
func ContinueRecentSession(cwd string, sessionDir string) (*SessionManager, error)
ContinueRecentSession continues the most recent session, or creates new if none (pi: SessionManager.continueRecent). sessionDir "" = the default per-cwd directory.
func CreateSessionManager ¶
func CreateSessionManager(cwd string, sessionDir string, options *NewSessionOptions) (*SessionManager, error)
CreateSessionManager creates a new persisted session (pi: SessionManager.create). sessionDir "" = the default per-cwd directory.
func ForkSession ¶
func ForkSession(sourcePath string, targetCwd string, sessionDir string, options *NewSessionOptions) (*SessionManager, error)
ForkSession forks a session from another project directory into the current project: creates a new session in the target cwd with the full history from the source session (pi: SessionManager.forkFrom). sessionDir "" = the default for targetCwd.
func InMemorySession ¶
func InMemorySession(cwd string, options *NewSessionOptions, entries ...[]FileEntry) (*SessionManager, error)
InMemorySession creates an in-memory session (no file persistence), optionally from entries held outside the filesystem (pi: SessionManager.inMemory). cwd "" = the process working directory.
func OpenSession ¶
func OpenSession(path string, sessionDir string, cwdOverride *string) (*SessionManager, error)
OpenSession opens a specific session file (pi: SessionManager.open). sessionDir "" = derive from the file's parent. cwdOverride nil = use the session header cwd.
func (*SessionManager) AppendCompaction ¶
func (m *SessionManager) AppendCompaction(summary string, firstKeptEntryID *string, tokensBefore int64, details any, fromHook *bool, usage *types.Usage) (string, error)
AppendCompaction appends a compaction summary as child of current leaf, then advances leaf. Returns the entry id (pi: appendCompaction). The complete prompt state at this boundary is captured from the current session context (pi v0.86.0).
func (*SessionManager) AppendContextEdit ¶ added in v0.87.0
func (m *SessionManager) AppendContextEdit(targetID string, replacement *ContextEditReplacement) (string, error)
AppendContextEdit appends a branch-local edit to an earlier model-visible entry. Returns the entry id (pi: appendContextEdit; throws → error return).
func (*SessionManager) AppendCustomEntry ¶
func (m *SessionManager) AppendCustomEntry(customType string, data any) (string, error)
AppendCustomEntry appends a custom entry (for extensions) as child of current leaf, then advances leaf. Returns the entry id (pi: appendCustomEntry).
func (*SessionManager) AppendCustomMessageEntry ¶
func (m *SessionManager) AppendCustomMessageEntry(customType string, content any, display bool, details any) (string, error)
AppendCustomMessageEntry appends a custom message entry (for extensions) that participates in LLM context. customType is the extension identifier for filtering on reload; content is a string or text/image parts; display controls TUI rendering; details is optional extension-specific metadata (not sent to LLM). Returns the entry id (pi: appendCustomMessageEntry).
func (*SessionManager) AppendLabelChange ¶
func (m *SessionManager) AppendLabelChange(targetID string, label *string) (string, error)
AppendLabelChange sets or clears a label on an entry. Labels are user-defined markers for bookmarking/navigation. Pass nil or an empty string to clear the label. Returns the entry id (pi: appendLabelChange; throws for unknown targets → error return).
func (*SessionManager) AppendMessage ¶
func (m *SessionManager) AppendMessage(message agent.AgentMessage) (string, error)
AppendMessage appends a message as child of current leaf, then advances the leaf. Returns the entry id. Does not allow writing compaction summary and branch summary messages directly: these are top-level entries in the session, so it is easier to find them; they need to be appended via AppendCompaction and BranchWithSummary (pi: appendMessage; the TS parameter is `Message | CustomMessage | BashExecutionMessage`, pig's open AgentMessage channel).
func (*SessionManager) AppendModelChange ¶
func (m *SessionManager) AppendModelChange(provider string, modelID string) (string, error)
AppendModelChange appends a model change as child of current leaf, then advances leaf. Returns the entry id (pi: appendModelChange).
func (*SessionManager) AppendSessionInfo ¶
func (m *SessionManager) AppendSessionInfo(name string) (string, error)
AppendSessionInfo appends a session info entry (e.g. display name). Returns the entry id (pi: appendSessionInfo).
func (*SessionManager) AppendThinkingLevelChange ¶
func (m *SessionManager) AppendThinkingLevelChange(thinkingLevel string) (string, error)
AppendThinkingLevelChange appends a thinking level change as child of current leaf, then advances leaf. Returns the entry id (pi: appendThinkingLevelChange).
func (*SessionManager) AppendUsage ¶ added in v0.86.0
func (m *SessionManager) AppendUsage(kind string, provider string, model string, usage *types.Usage, note string) (*UsageEntry, error)
AppendCompaction appends a compaction summary as child of current leaf, then advances leaf. Returns the entry id (pi: appendCompaction; fromHook nil = TS undefined). AppendUsage appends model-attributed usage that does not participate in LLM context. Returns the appended entry (pi: appendUsage; v0.86.0).
func (*SessionManager) Branch ¶
func (m *SessionManager) Branch(branchFromID string) error
Branch starts a new branch from an earlier entry. Moves the leaf pointer to the specified entry. The next Append* call will create a child of that entry, forming a new branch. Existing entries are not modified or deleted (pi: branch; throws for unknown targets → error return).
func (*SessionManager) BranchWithSummary ¶
func (m *SessionManager) BranchWithSummary(branchFromID string, summary string, details any, fromHook *bool, usage *types.Usage) (string, error)
BranchWithSummary starts a new branch with a summary of the abandoned path. Same as Branch, but also appends a branch_summary entry that captures context from the abandoned conversation path. branchFromID "" = pi's null (new root). Returns the entry id (pi: branchWithSummary; throws for unknown targets → error return).
func (*SessionManager) BuildContextEntries ¶
func (m *SessionManager) BuildContextEntries() []SessionEntry
BuildContextEntries builds the active, compaction-aware entry list for context/rendering, using tree traversal from current leaf (pi: buildContextEntries). A null leaf (before any entries) yields an empty list.
func (*SessionManager) BuildSessionContext ¶
func (m *SessionManager) BuildSessionContext() SessionContext
BuildSessionContext builds the finalized model context from the canonical session projection, using tree traversal from current leaf (pi: buildSessionContext). A null leaf yields the default context.
func (*SessionManager) BuildSessionProjection ¶ added in v0.87.0
func (m *SessionManager) BuildSessionProjection() SessionProjection
BuildSessionProjection builds the provenance-preserving, compaction-aware model context (what gets sent to the LLM), using tree traversal from current leaf (pi: buildSessionProjection). A null leaf yields the default projection.
func (*SessionManager) CreateBranchedSession ¶
func (m *SessionManager) CreateBranchedSession(leafID string) (string, error)
CreateBranchedSession creates a new session file containing only the path from root to the specified leaf. Useful for extracting a single conversation path from a branched session. Returns the new session file path, or "" when not persisting (pi: createBranchedSession; throws for unknown targets → error return).
func (*SessionManager) GetBranch ¶
func (m *SessionManager) GetBranch(fromID string) []SessionEntry
GetBranch walks from entry to root, returning all entries in path order. Includes all entry types (messages, compaction, model changes, etc.). fromID "" = the current leaf. Use BuildSessionContext to get the resolved messages for the LLM (pi: getBranch).
func (*SessionManager) GetChildren ¶
func (m *SessionManager) GetChildren(parentID string) []SessionEntry
GetChildren returns all direct children of an entry (pi: getChildren).
func (*SessionManager) GetCwd ¶
func (m *SessionManager) GetCwd() string
GetCwd returns the session working directory (pi: getCwd).
func (*SessionManager) GetEntries ¶
func (m *SessionManager) GetEntries() []SessionEntry
GetEntries returns all session entries (excludes header) as a shallow copy. The session is append-only: use Append* to add entries and Branch to change the leaf pointer. Entries cannot be modified or deleted (pi: getEntries).
func (*SessionManager) GetEntry ¶
func (m *SessionManager) GetEntry(id string) SessionEntry
GetEntry returns the entry with the given id, or nil (pi: getEntry).
func (*SessionManager) GetHeader ¶
func (m *SessionManager) GetHeader() *SessionHeader
GetHeader returns the session header, or nil (pi: getHeader).
func (*SessionManager) GetLabel ¶
func (m *SessionManager) GetLabel(id string) (string, bool)
GetLabel returns the label for an entry, if any (pi: getLabel).
func (*SessionManager) GetLeafEntry ¶
func (m *SessionManager) GetLeafEntry() SessionEntry
GetLeafEntry returns the current leaf entry, or nil (pi: getLeafEntry).
func (*SessionManager) GetLeafID ¶
func (m *SessionManager) GetLeafID() *string
GetLeafID returns the current leaf entry id; nil = null (pi: getLeafId).
func (*SessionManager) GetSessionDir ¶
func (m *SessionManager) GetSessionDir() string
GetSessionDir returns the session directory (pi: getSessionDir).
func (*SessionManager) GetSessionFile ¶
func (m *SessionManager) GetSessionFile() string
GetSessionFile returns the session file path; "" = unset (pi: getSessionFile: string | undefined).
func (*SessionManager) GetSessionID ¶
func (m *SessionManager) GetSessionID() string
GetSessionID returns the session id (pi: getSessionId).
func (*SessionManager) GetSessionName ¶
func (m *SessionManager) GetSessionName() (string, bool)
GetSessionName returns the current session name from the latest session_info entry, if any (pi: getSessionName). Empty names explicitly clear the session title.
func (*SessionManager) GetTree ¶
func (m *SessionManager) GetTree() []*SessionTreeNode
GetTree returns the session as a tree structure: a shallow defensive copy of all entries. A well-formed session has exactly one root (first entry with parentId === null). Orphaned entries (broken parent chain) are also returned as roots (pi: getTree).
func (*SessionManager) IsPersisted ¶
func (m *SessionManager) IsPersisted() bool
IsPersisted reports whether the session is file-backed (pi: isPersisted).
func (*SessionManager) NewSession ¶
func (m *SessionManager) NewSession(options *NewSessionOptions) (string, error)
NewSession starts a new session and returns the session file path (empty when not persisting; pi: newSession; invalid ids throw → error return).
func (*SessionManager) ResetLeaf ¶
func (m *SessionManager) ResetLeaf()
ResetLeaf resets the leaf pointer to null (before any entries). The next Append* call will create a new root entry (parentId = null). Use this when navigating to re-edit the first user message (pi: resetLeaf).
func (*SessionManager) SetSessionFile ¶
func (m *SessionManager) SetSessionFile(sessionFile string) error
SetSessionFile switches to a different session file (used for resume and branching; pi: setSessionFile; throws → error return).
func (*SessionManager) UsesDefaultSessionDir ¶
func (m *SessionManager) UsesDefaultSessionDir() bool
UsesDefaultSessionDir reports whether the session lives in the default per-cwd directory (pi: usesDefaultSessionDir).
type SessionMessageEntry ¶
type SessionMessageEntry struct {
EntryBase
Message agent.AgentMessage `json:"message"`
}
SessionMessageEntry holds one AgentMessage (pi: SessionMessageEntry).
type SessionModelRef ¶
SessionModelRef is the model reference carried by SessionContext (pi: SessionContext.model: { provider, modelId } | null).
type SessionProjection ¶ added in v0.87.0
type SessionProjection struct {
Entries []ProjectedSessionEntry
Messages []agent.AgentMessage
ThinkingLevel string
Model *SessionModelRef
}
SessionProjection is the provenance-preserving, compaction-aware model context (pi: SessionProjection; v0.87.0).
func BuildSessionProjection ¶ added in v0.87.0
func BuildSessionProjection(entries []SessionEntry, leafID *string, byID map[string]SessionEntry) SessionProjection
BuildSessionProjection builds the provenance-preserving, compaction-aware model context from entries using tree traversal. If leafID is provided, walks from that entry to root. Handles compaction, branch summaries, and context edits along the path (pi: buildSessionProjection; leafID nil = TS undefined → last entry).
type SessionShutdownEvent ¶
type SessionShutdownEvent struct {
Type string `json:"type"`
// Reason: "quit" | "reload" | "new" | "resume" | "fork".
Reason string `json:"reason"`
// TargetSessionFile is the destination file for session replacement; ""
// = none (pi: targetSessionFile?).
TargetSessionFile string `json:"targetSessionFile,omitempty"`
}
SessionShutdownEvent fires before an extension runtime is torn down (pi: SessionShutdownEvent).
func (*SessionShutdownEvent) EventType ¶
func (e *SessionShutdownEvent) EventType() string
type SessionStartEvent ¶
type SessionStartEvent struct {
Type string `json:"type"`
// Reason: "startup" | "reload" | "new" | "resume" | "fork".
Reason string `json:"reason"`
// PreviousSessionFile is present for "new", "resume", and "fork"; "" =
// absent (pi: previousSessionFile?).
PreviousSessionFile string `json:"previousSessionFile,omitempty"`
}
SessionStartEvent fires when a session is started, loaded, or reloaded (pi: SessionStartEvent).
func (*SessionStartEvent) EventType ¶
func (e *SessionStartEvent) EventType() string
type SessionStats ¶
type SessionStats struct {
SessionFile string // "" = sessions disabled (pi: undefined)
SessionID string
UserMessages int
AssistantMessages int
ToolCalls int
ToolResults int
TotalMessages int
Tokens struct {
Input int64
Output int64
CacheRead int64
CacheWrite int64
Total int64
}
Cost float64
ContextUsage *ContextUsage
}
SessionStats are the session statistics for /session (pi: SessionStats).
type SessionTreeEvent ¶
type SessionTreeEvent struct {
Type string `json:"type"`
// NewLeafID is the position navigated to; nil = root (pi: newLeafId:
// string | null).
NewLeafID *string `json:"newLeafId"`
// OldLeafID is the position navigating from; nil = root (pi: oldLeafId:
// string | null).
OldLeafID *string `json:"oldLeafId"`
// SummaryEntry is the generated branch summary entry, if any (pi:
// summaryEntry?).
SummaryEntry *BranchSummaryEntry `json:"summaryEntry,omitempty"`
// FromExtension is set only when a summary was generated (pi:
// fromExtension?: boolean); nil = absent.
FromExtension *bool `json:"fromExtension,omitempty"`
}
SessionTreeEvent fires after navigating in the session tree (pi: SessionTreeEvent).
func (*SessionTreeEvent) EventType ¶
func (e *SessionTreeEvent) EventType() string
type SessionTreeNode ¶
type SessionTreeNode struct {
Entry SessionEntry
Children []*SessionTreeNode
// Resolved label for this entry, if any.
Label *string
// Timestamp of the latest label change for this entry, if any.
LabelTimestamp *string
}
SessionTreeNode is a getTree node: a defensive copy of the session structure (pi: SessionTreeNode).
type Settings ¶
Settings holds one settings object (pi: Settings interface; see header for the representation deviation). Field inventory follows pi's interface, in declaration order:
lastChangelogVersion?: string defaultProvider?: string defaultModel?: string defaultThinkingLevel?: ThinkingLevel modelThinkingLevels?: Record<string, ThinkingLevel> — keyed "provider/modelId" transport?: TransportSetting — default "auto" steeringMode?: "all" | "one-at-a-time" followUpMode?: "all" | "one-at-a-time" theme?: string compaction?: CompactionSettings branchSummary?: BranchSummarySettings retry?: RetrySettings hideThinkingBlock?: boolean showCacheMissNotices?: boolean — default false - show cache cost and provider recovery notices externalEditor?: string — takes precedence over VISUAL/EDITOR shellPath?: string — supports leading ~ expansion quietStartup?: boolean defaultProjectTrust?: DefaultProjectTrust — default "ask"; global only shellCommandPrefix?: string npmCommand?: string[] collapseChangelog?: boolean enableInstallTelemetry?: boolean — default true enableAnalytics?: boolean — default false; opt-in trackingId?: string — generated on first opt-in packages?: PackageSource[] extensions?: string[] skills?: string[] prompts?: string[] themes?: string[] enableSkillCommands?: boolean — default true terminal?: TerminalSettings images?: ImageSettings enabledModels?: string[] defaultTools?: string[] doubleEscapeAction?: "fork" | "tree" | "none" — default "tree" treeFilterMode?: "default" | "no-tools" | "user-only" | "labeled-only" | "all" thinkingBudgets?: ThinkingBudgetsSettings editorPaddingX?: number — default 0 outputPad?: 0 | 1 — default 1 autocompleteMaxVisible?: number — default 5 showHardwareCursor?: boolean markdown?: MarkdownSettings warnings?: WarningSettings sessionDir?: string httpProxy?: string httpIdleTimeoutMs?: number cacheWarming?: CacheWarmingMode — default "streaming"; global only because each refresh costs money (v0.86.0) websocketConnectTimeoutMs?: number tuiMode?: TuiMode — default "regular" fullscreenExitOutput?: FullscreenExitOutput — default "transcript" fullscreenScrollbar?: ScrollViewScrollbar — default "auto" fullscreenCopyOnSelect?: boolean — default true; no effect in regular TUI mode (v0.85.1) cjkSegmenter?: "bigram" | "sst" | "gse" — pig-only; default via PIG_CJK_SEGMENTER env, else "bigram" showResourceStats?: boolean — pig-only; footer resource stats (MEM always, G/FD/CPU alerts on anomaly), default false
type SettingsError ¶
type SettingsError struct {
Scope SettingsScope
Path string
Error error
}
SettingsError records one settings load/persist failure (pi: SettingsError; path?: string → empty string = absent).
type SettingsManager ¶
type SettingsManager struct {
// contains filtered or unexported fields
}
SettingsManager is the layered settings manager (pi: SettingsManager class). All state is guarded by one mutex (pi relies on the JS event loop).
func CreateSettingsManager ¶
func CreateSettingsManager(cwd string, agentDir string, options *SettingsManagerCreateOptions) *SettingsManager
CreateSettingsManager creates a SettingsManager that loads from files (pi: SettingsManager.create).
func InMemorySettingsManager ¶
func InMemorySettingsManager(settings Settings, options *SettingsManagerCreateOptions) *SettingsManager
InMemorySettingsManager creates an in-memory SettingsManager (pi: SettingsManager.inMemory).
func SettingsManagerFromStorage ¶
func SettingsManagerFromStorage(storage SettingsStorage, options *SettingsManagerCreateOptions) *SettingsManager
SettingsManagerFromStorage creates a SettingsManager from an arbitrary storage backend (pi: SettingsManager.fromStorage).
func (*SettingsManager) ApplyOverrides ¶
func (m *SettingsManager) ApplyOverrides(overrides Settings)
ApplyOverrides applies additional overrides on top of current settings (pi: applyOverrides).
func (*SettingsManager) DrainErrors ¶
func (m *SettingsManager) DrainErrors() []SettingsError
DrainErrors returns and clears collected settings errors (pi: drainErrors).
func (*SettingsManager) Flush ¶
func (m *SettingsManager) Flush()
Flush waits for pending writes (pi: flush). pig writes synchronously, so this only waits for in-flight access.
func (*SettingsManager) GetAllModelThinkingLevels ¶
func (m *SettingsManager) GetAllModelThinkingLevels() map[string]agent.ThinkingLevel
GetAllModelThinkingLevels returns a copy of all per-model thinking level overrides (pi: getAllModelThinkingLevels; non-string members are skipped — pi would propagate the type lie, header declaration).
func (*SettingsManager) GetAutocompleteMaxVisible ¶
func (m *SettingsManager) GetAutocompleteMaxVisible() int64
GetAutocompleteMaxVisible returns the autocomplete dropdown size (pi: getAutocompleteMaxVisible).
func (*SettingsManager) GetBlockImages ¶
func (m *SettingsManager) GetBlockImages() bool
GetBlockImages returns the image block toggle (pi: getBlockImages).
func (*SettingsManager) GetBranchSummarySettings ¶
func (m *SettingsManager) GetBranchSummarySettings() BranchSummarySettingsValues
GetBranchSummarySettings returns the resolved branch summary settings (pi: getBranchSummarySettings).
func (*SettingsManager) GetBranchSummarySkipPrompt ¶
func (m *SettingsManager) GetBranchSummarySkipPrompt() bool
GetBranchSummarySkipPrompt returns the branch summary prompt toggle (pi: getBranchSummarySkipPrompt).
func (*SettingsManager) GetCJKSegmenter ¶
func (m *SettingsManager) GetCJKSegmenter() string
GetCJKSegmenter returns the CJK word-segmentation backend (pig-only; no pi counterpart — Intl.Segmenter ships inside the JS runtime). An invalid stored value resolves to "bigram", matching the tui resolver's never-error contract (configuration can only degrade word navigation, never break it).
func (*SettingsManager) GetCacheWarmingMode ¶ added in v0.86.0
func (m *SettingsManager) GetCacheWarmingMode() CacheWarmingMode
GetCacheWarmingMode reads the cache-warming profile from global settings only, because warming costs money (pi: getCacheWarmingMode; v0.86.0). Unset/unknown values resolve to "streaming".
func (*SettingsManager) GetClearOnShrink ¶
func (m *SettingsManager) GetClearOnShrink() bool
GetClearOnShrink returns the clear-on-shrink toggle (pi: getClearOnShrink — settings, then PI_CLEAR_ON_SHRINK=1, then false).
func (*SettingsManager) GetCodeBlockIndent ¶
func (m *SettingsManager) GetCodeBlockIndent() string
GetCodeBlockIndent returns the markdown code block indent (pi: getCodeBlockIndent).
func (*SettingsManager) GetCollapseChangelog ¶
func (m *SettingsManager) GetCollapseChangelog() bool
GetCollapseChangelog returns the changelog collapse toggle (pi: getCollapseChangelog).
func (*SettingsManager) GetCompactionEnabled ¶
func (m *SettingsManager) GetCompactionEnabled() bool
GetCompactionEnabled returns whether compaction is enabled (pi: getCompactionEnabled).
func (*SettingsManager) GetCompactionKeepRecentTokens ¶
func (m *SettingsManager) GetCompactionKeepRecentTokens(model *types.Model) (int64, error)
GetCompactionKeepRecentTokens returns the compaction retention (pi: getCompactionKeepRecentTokens — throws on invalid settings; pig returns an error). model nil = TS undefined.
func (*SettingsManager) GetCompactionReserveTokens ¶
func (m *SettingsManager) GetCompactionReserveTokens(model *types.Model) (int64, error)
GetCompactionReserveTokens returns the compaction reserve (pi: getCompactionReserveTokens — throws on invalid settings; pig returns an error per the GetHTTPIdleTimeoutMs convention). model nil = TS undefined.
func (*SettingsManager) GetCompactionSettings ¶
func (m *SettingsManager) GetCompactionSettings(model *types.Model) (CompactionSettingsValues, error)
GetCompactionSettings returns the resolved compaction settings (pi: getCompactionSettings — throws on invalid settings; pig returns an error). model nil = TS undefined.
func (*SettingsManager) GetDefaultModel ¶
func (m *SettingsManager) GetDefaultModel() (string, bool)
GetDefaultModel returns the default model (pi: getDefaultModel).
func (*SettingsManager) GetDefaultProjectTrust ¶
func (m *SettingsManager) GetDefaultProjectTrust() DefaultProjectTrust
GetDefaultProjectTrust returns the default project trust (pi: getDefaultProjectTrust; reads global settings only, invalid → "ask").
func (*SettingsManager) GetDefaultProvider ¶
func (m *SettingsManager) GetDefaultProvider() (string, bool)
GetDefaultProvider returns the default provider (pi: getDefaultProvider).
func (*SettingsManager) GetDefaultThinkingLevel ¶
func (m *SettingsManager) GetDefaultThinkingLevel() (agent.ThinkingLevel, bool)
GetDefaultThinkingLevel returns the default thinking level (pi: getDefaultThinkingLevel).
func (*SettingsManager) GetDefaultTools ¶
func (m *SettingsManager) GetDefaultTools() ([]string, bool)
GetDefaultTools returns the initial built-in tool selection (pi: getDefaultTools — an empty list is preserved).
func (*SettingsManager) GetDoubleEscapeAction ¶
func (m *SettingsManager) GetDoubleEscapeAction() string
GetDoubleEscapeAction returns the double-escape action (pi: getDoubleEscapeAction).
func (*SettingsManager) GetEditorPaddingX ¶
func (m *SettingsManager) GetEditorPaddingX() int64
GetEditorPaddingX returns the editor horizontal padding (pi: getEditorPaddingX).
func (*SettingsManager) GetEnableAnalytics ¶
func (m *SettingsManager) GetEnableAnalytics() bool
GetEnableAnalytics returns the analytics opt-in toggle (pi: getEnableAnalytics).
func (*SettingsManager) GetEnableInstallTelemetry ¶
func (m *SettingsManager) GetEnableInstallTelemetry() bool
GetEnableInstallTelemetry returns the install telemetry toggle (pi: getEnableInstallTelemetry).
func (*SettingsManager) GetEnableSkillCommands ¶
func (m *SettingsManager) GetEnableSkillCommands() bool
GetEnableSkillCommands returns whether skills register as commands (pi: getEnableSkillCommands).
func (*SettingsManager) GetEnabledModels ¶
func (m *SettingsManager) GetEnabledModels() ([]string, bool)
GetEnabledModels returns the model cycling patterns (pi: getEnabledModels).
func (*SettingsManager) GetExtensionPaths ¶
func (m *SettingsManager) GetExtensionPaths() []string
GetExtensionPaths returns a copy of the extension paths (pi: getExtensionPaths).
func (*SettingsManager) GetExternalEditorCommand ¶
func (m *SettingsManager) GetExternalEditorCommand() string
GetExternalEditorCommand resolves the external editor command by precedence (pi: getExternalEditorCommand).
func (*SettingsManager) GetFollowUpMode ¶
func (m *SettingsManager) GetFollowUpMode() string
GetFollowUpMode returns the follow-up mode (pi: getFollowUpMode — falsy → "one-at-a-time").
func (*SettingsManager) GetFullscreenCopyOnSelect ¶
func (m *SettingsManager) GetFullscreenCopyOnSelect() bool
GetFullscreenCopyOnSelect returns whether selecting text in the fullscreen transcript copies to the clipboard (pi: getFullscreenCopyOnSelect — v0.85.1; default true; no effect in regular TUI mode).
func (*SettingsManager) GetFullscreenExitOutput ¶
func (m *SettingsManager) GetFullscreenExitOutput() FullscreenExitOutput
GetFullscreenExitOutput returns the fullscreen exit output (pi: getFullscreenExitOutput — non-"resume-hint" → "transcript").
func (*SettingsManager) GetFullscreenScrollbar ¶
func (m *SettingsManager) GetFullscreenScrollbar() ScrollViewScrollbar
GetFullscreenScrollbar returns the fullscreen scrollbar mode (pi: getFullscreenScrollbar — only "always"/"hidden" pass through).
func (*SettingsManager) GetGlobalSettings ¶
func (m *SettingsManager) GetGlobalSettings() Settings
GetGlobalSettings returns a deep copy of the global settings (pi: getGlobalSettings).
func (*SettingsManager) GetHTTPIdleTimeoutMs ¶
func (m *SettingsManager) GetHTTPIdleTimeoutMs() (int64, error)
GetHTTPIdleTimeoutMs returns the HTTP idle timeout (pi: getHttpIdleTimeoutMs; pi throws on invalid values — pig returns error).
func (*SettingsManager) GetHideThinkingBlock ¶
func (m *SettingsManager) GetHideThinkingBlock() bool
GetHideThinkingBlock returns whether thinking blocks are hidden (pi: getHideThinkingBlock).
func (*SettingsManager) GetImageAutoResize ¶
func (m *SettingsManager) GetImageAutoResize() bool
GetImageAutoResize returns the image auto-resize toggle (pi: getImageAutoResize).
func (*SettingsManager) GetImageWidthCells ¶
func (m *SettingsManager) GetImageWidthCells() int64
GetImageWidthCells returns the inline image width (pi: getImageWidthCells; non-finite → 60, floored and clamped to ≥ 1).
func (*SettingsManager) GetLastChangelogVersion ¶
func (m *SettingsManager) GetLastChangelogVersion() (string, bool)
GetLastChangelogVersion returns the last shown changelog version (pi: getLastChangelogVersion).
func (*SettingsManager) GetMermaidRenderingMode ¶
func (m *SettingsManager) GetMermaidRenderingMode() MermaidRenderingMode
GetMermaidRenderingMode returns the mermaid rendering mode (pi: getMermaidRenderingMode — only "off"/"final" pass through).
func (*SettingsManager) GetModelThinkingLevel ¶
func (m *SettingsManager) GetModelThinkingLevel(provider string, modelID string) (agent.ThinkingLevel, bool)
GetModelThinkingLevel returns the per-model thinking level override (pi: getModelThinkingLevel).
func (*SettingsManager) GetNpmCommand ¶
func (m *SettingsManager) GetNpmCommand() ([]string, bool)
GetNpmCommand returns a copy of the npm command argv (pi: getNpmCommand).
func (*SettingsManager) GetOutputPad ¶
func (m *SettingsManager) GetOutputPad() int
GetOutputPad returns the chat output padding (pi: getOutputPad — only an exact 0 yields 0).
func (*SettingsManager) GetPackages ¶
func (m *SettingsManager) GetPackages() []PackageSource
GetPackages returns a copy of the package sources (pi: getPackages).
func (*SettingsManager) GetProjectSettings ¶
func (m *SettingsManager) GetProjectSettings() Settings
GetProjectSettings returns a deep copy of the project settings (pi: getProjectSettings).
func (*SettingsManager) GetPromptTemplatePaths ¶
func (m *SettingsManager) GetPromptTemplatePaths() []string
GetPromptTemplatePaths returns a copy of the prompt template paths (pi: getPromptTemplatePaths).
func (*SettingsManager) GetProviderRetrySettings ¶
func (m *SettingsManager) GetProviderRetrySettings() ProviderRetrySettingsValues
GetProviderRetrySettings returns the resolved provider retry settings (pi: getProviderRetrySettings).
func (*SettingsManager) GetQuietStartup ¶
func (m *SettingsManager) GetQuietStartup() bool
GetQuietStartup returns the quiet startup toggle (pi: getQuietStartup).
func (*SettingsManager) GetRetryEnabled ¶
func (m *SettingsManager) GetRetryEnabled() bool
GetRetryEnabled returns whether retries are enabled (pi: getRetryEnabled).
func (*SettingsManager) GetRetrySettings ¶
func (m *SettingsManager) GetRetrySettings() RetrySettingsValues
GetRetrySettings returns the resolved retry settings (pi: getRetrySettings).
func (*SettingsManager) GetSessionDir ¶
func (m *SettingsManager) GetSessionDir() (string, bool)
GetSessionDir returns the custom session storage directory with ~ expanded (pi: getSessionDir).
func (*SettingsManager) GetShellCommandPrefix ¶
func (m *SettingsManager) GetShellCommandPrefix() (string, bool)
GetShellCommandPrefix returns the shell command prefix (pi: getShellCommandPrefix).
func (*SettingsManager) GetShellPath ¶
func (m *SettingsManager) GetShellPath() (string, bool)
GetShellPath returns the custom shell path with ~ expanded (pi: getShellPath).
func (*SettingsManager) GetShowCacheMissNotices ¶
func (m *SettingsManager) GetShowCacheMissNotices() bool
GetShowCacheMissNotices returns whether cache-miss notices show (pi: getShowCacheMissNotices).
func (*SettingsManager) GetShowHardwareCursor ¶
func (m *SettingsManager) GetShowHardwareCursor() bool
GetShowHardwareCursor returns the hardware cursor toggle (pi: getShowHardwareCursor — settings, then PI_HARDWARE_CURSOR=1).
func (*SettingsManager) GetShowImages ¶
func (m *SettingsManager) GetShowImages() bool
GetShowImages returns whether inline images show (pi: getShowImages).
func (*SettingsManager) GetShowResourceStats ¶
func (m *SettingsManager) GetShowResourceStats() bool
GetShowResourceStats returns whether the footer shows process resource stats (pig-only; no pi counterpart — pi's footer shows token stats only). Default false: the segment stays hidden until explicitly enabled.
func (*SettingsManager) GetShowTerminalProgress ¶
func (m *SettingsManager) GetShowTerminalProgress() bool
GetShowTerminalProgress returns the terminal progress toggle (pi: getShowTerminalProgress).
func (*SettingsManager) GetSkillPaths ¶
func (m *SettingsManager) GetSkillPaths() []string
GetSkillPaths returns a copy of the skill paths (pi: getSkillPaths).
func (*SettingsManager) GetSteeringMode ¶
func (m *SettingsManager) GetSteeringMode() string
GetSteeringMode returns the steering mode (pi: getSteeringMode — falsy → "one-at-a-time").
func (*SettingsManager) GetTerminalCapabilityOverrides ¶
func (m *SettingsManager) GetTerminalCapabilityOverrides() TerminalCapabilityOverrides
GetTerminalCapabilityOverrides returns user-forced terminal capability overrides (pi: getTerminalCapabilityOverrides, v0.85.1).
func (*SettingsManager) GetTheme ¶
func (m *SettingsManager) GetTheme() (string, bool)
GetTheme returns the fixed theme name; slash-separated automatic theme settings return undefined (pi: getTheme).
func (*SettingsManager) GetThemePaths ¶
func (m *SettingsManager) GetThemePaths() []string
GetThemePaths returns a copy of the theme paths (pi: getThemePaths).
func (*SettingsManager) GetThemeSetting ¶
func (m *SettingsManager) GetThemeSetting() (string, bool)
GetThemeSetting returns the raw theme setting, including slash-separated automatic themes (pi: getThemeSetting).
func (*SettingsManager) GetThinkingBudgets ¶
func (m *SettingsManager) GetThinkingBudgets() (*ThinkingBudgetsSettings, bool)
GetThinkingBudgets returns the thinking budget overrides (pi: getThinkingBudgets; pi returns the live nested object, pig a fresh struct — declared).
func (*SettingsManager) GetTrackingId ¶
func (m *SettingsManager) GetTrackingId() (string, bool)
GetTrackingId returns the analytics tracking identifier (pi: getTrackingId).
func (*SettingsManager) GetTransport ¶
func (m *SettingsManager) GetTransport() TransportSetting
GetTransport returns the transport setting (pi: getTransport).
func (*SettingsManager) GetTreeFilterMode ¶
func (m *SettingsManager) GetTreeFilterMode() string
GetTreeFilterMode returns the /tree filter default (pi: getTreeFilterMode — invalid values → "default").
func (*SettingsManager) GetTuiMode ¶
func (m *SettingsManager) GetTuiMode() TuiMode
GetTuiMode returns the renderer mode (pi: getTuiMode — non-"fullscreen" → "regular").
func (*SettingsManager) GetWarnings ¶
func (m *SettingsManager) GetWarnings() WarningSettings
GetWarnings returns a copy of the warning toggles (pi: getWarnings).
func (*SettingsManager) GetWebSocketConnectTimeoutMs ¶
func (m *SettingsManager) GetWebSocketConnectTimeoutMs() (*int64, error)
GetWebSocketConnectTimeoutMs returns the WebSocket connect timeout (pi: getWebSocketConnectTimeoutMs; nil = unset).
func (*SettingsManager) IsProjectTrusted ¶
func (m *SettingsManager) IsProjectTrusted() bool
IsProjectTrusted reports whether the project is trusted (pi: isProjectTrusted).
func (*SettingsManager) Reload ¶
func (m *SettingsManager) Reload()
Reload reloads both scopes from storage (pi: reload). pi awaits the write queue first; pig writes synchronously so there is nothing to wait for.
func (*SettingsManager) RemoveModelThinkingLevel ¶
func (m *SettingsManager) RemoveModelThinkingLevel(provider string, modelID string)
RemoveModelThinkingLevel drops a per-model thinking level override (pi: removeModelThinkingLevel).
func (*SettingsManager) SetAutocompleteMaxVisible ¶
func (m *SettingsManager) SetAutocompleteMaxVisible(maxVisible int64)
SetAutocompleteMaxVisible records the autocomplete dropdown size, clamped to 3..20 (pi: setAutocompleteMaxVisible).
func (*SettingsManager) SetBlockImages ¶
func (m *SettingsManager) SetBlockImages(blocked bool)
SetBlockImages records the image block toggle (pi: setBlockImages).
func (*SettingsManager) SetCJKSegmenter ¶
func (m *SettingsManager) SetCJKSegmenter(mode string)
SetCJKSegmenter records the CJK word-segmentation backend (pig-only). Invalid values are ignored, mirroring the tui resolver's never-error contract (configuration can only degrade word navigation, never break it). Mid-session changes persist here; the in-process backend applies them from the next start (or immediately when it has not resolved yet).
func (*SettingsManager) SetCacheWarmingMode ¶ added in v0.86.0
func (m *SettingsManager) SetCacheWarmingMode(mode CacheWarmingMode)
SetCacheWarmingMode persists the cache-warming profile (pi: setCacheWarmingMode; v0.86.0).
func (*SettingsManager) SetClearOnShrink ¶
func (m *SettingsManager) SetClearOnShrink(enabled bool)
SetClearOnShrink records the clear-on-shrink toggle (pi: setClearOnShrink).
func (*SettingsManager) SetCollapseChangelog ¶
func (m *SettingsManager) SetCollapseChangelog(collapse bool)
SetCollapseChangelog records the changelog collapse toggle (pi: setCollapseChangelog).
func (*SettingsManager) SetCompactionEnabled ¶
func (m *SettingsManager) SetCompactionEnabled(enabled bool)
SetCompactionEnabled records the compaction toggle (pi: setCompactionEnabled).
func (*SettingsManager) SetDefaultModel ¶
func (m *SettingsManager) SetDefaultModel(modelID string)
SetDefaultModel records the default model (pi: setDefaultModel).
func (*SettingsManager) SetDefaultModelAndProvider ¶
func (m *SettingsManager) SetDefaultModelAndProvider(provider string, modelID string)
SetDefaultModelAndProvider records both defaults (pi: setDefaultModelAndProvider).
func (*SettingsManager) SetDefaultProjectTrust ¶
func (m *SettingsManager) SetDefaultProjectTrust(defaultProjectTrust DefaultProjectTrust)
SetDefaultProjectTrust records the default project trust (pi: setDefaultProjectTrust).
func (*SettingsManager) SetDefaultProvider ¶
func (m *SettingsManager) SetDefaultProvider(provider string)
SetDefaultProvider records the default provider (pi: setDefaultProvider).
func (*SettingsManager) SetDefaultThinkingLevel ¶
func (m *SettingsManager) SetDefaultThinkingLevel(level agent.ThinkingLevel)
SetDefaultThinkingLevel records the default thinking level (pi: setDefaultThinkingLevel).
func (*SettingsManager) SetDoubleEscapeAction ¶
func (m *SettingsManager) SetDoubleEscapeAction(action string)
SetDoubleEscapeAction records the double-escape action (pi: setDoubleEscapeAction).
func (*SettingsManager) SetEditorPaddingX ¶
func (m *SettingsManager) SetEditorPaddingX(padding int64)
SetEditorPaddingX records the editor horizontal padding, clamped to 0..3 (pi: setEditorPaddingX).
func (*SettingsManager) SetEnableAnalytics ¶
func (m *SettingsManager) SetEnableAnalytics(enabled bool)
SetEnableAnalytics records the analytics opt-in; generates a tracking identifier on first opt-in (pi: setEnableAnalytics).
func (*SettingsManager) SetEnableInstallTelemetry ¶
func (m *SettingsManager) SetEnableInstallTelemetry(enabled bool)
SetEnableInstallTelemetry records the install telemetry toggle (pi: setEnableInstallTelemetry).
func (*SettingsManager) SetEnableSkillCommands ¶
func (m *SettingsManager) SetEnableSkillCommands(enabled bool)
SetEnableSkillCommands records the skill-commands toggle (pi: setEnableSkillCommands).
func (*SettingsManager) SetEnabledModels ¶
func (m *SettingsManager) SetEnabledModels(patterns []string)
SetEnabledModels records the model cycling patterns (pi: setEnabledModels; undefined → delete).
func (*SettingsManager) SetExtensionPaths ¶
func (m *SettingsManager) SetExtensionPaths(paths []string)
SetExtensionPaths records the extension paths (pi: setExtensionPaths).
func (*SettingsManager) SetFollowUpMode ¶
func (m *SettingsManager) SetFollowUpMode(mode string)
SetFollowUpMode records the follow-up mode (pi: setFollowUpMode).
func (*SettingsManager) SetFullscreenCopyOnSelect ¶
func (m *SettingsManager) SetFullscreenCopyOnSelect(enabled bool)
SetFullscreenCopyOnSelect records the fullscreen copy-on-select toggle (pi: setFullscreenCopyOnSelect — v0.85.1).
func (*SettingsManager) SetFullscreenExitOutput ¶
func (m *SettingsManager) SetFullscreenExitOutput(output FullscreenExitOutput)
SetFullscreenExitOutput records the fullscreen exit output (pi: setFullscreenExitOutput).
func (*SettingsManager) SetFullscreenScrollbar ¶
func (m *SettingsManager) SetFullscreenScrollbar(mode ScrollViewScrollbar)
SetFullscreenScrollbar records the fullscreen scrollbar mode (pi: setFullscreenScrollbar).
func (*SettingsManager) SetHTTPIdleTimeoutMs ¶
func (m *SettingsManager) SetHTTPIdleTimeoutMs(timeoutMs float64) error
SetHTTPIdleTimeoutMs records the HTTP idle timeout (pi: setHttpIdleTimeoutMs; pi throws on invalid values — pig returns error).
func (*SettingsManager) SetHideThinkingBlock ¶
func (m *SettingsManager) SetHideThinkingBlock(hide bool)
SetHideThinkingBlock records the thinking-block toggle (pi: setHideThinkingBlock).
func (*SettingsManager) SetImageAutoResize ¶
func (m *SettingsManager) SetImageAutoResize(enabled bool)
SetImageAutoResize records the image auto-resize toggle (pi: setImageAutoResize).
func (*SettingsManager) SetImageWidthCells ¶
func (m *SettingsManager) SetImageWidthCells(width int64)
SetImageWidthCells records the inline image width (pi: setImageWidthCells).
func (*SettingsManager) SetLastChangelogVersion ¶
func (m *SettingsManager) SetLastChangelogVersion(version string)
SetLastChangelogVersion records the last shown changelog version (pi: setLastChangelogVersion).
func (*SettingsManager) SetMermaidRenderingMode ¶
func (m *SettingsManager) SetMermaidRenderingMode(mode MermaidRenderingMode)
SetMermaidRenderingMode records the mermaid rendering mode (pi: setMermaidRenderingMode).
func (*SettingsManager) SetModelThinkingLevel ¶
func (m *SettingsManager) SetModelThinkingLevel(provider string, modelID string, level agent.ThinkingLevel)
SetModelThinkingLevel records a per-model thinking level override (pi: setModelThinkingLevel).
func (*SettingsManager) SetNpmCommand ¶
func (m *SettingsManager) SetNpmCommand(command []string)
SetNpmCommand records the npm command argv (pi: setNpmCommand; undefined → delete).
func (*SettingsManager) SetOutputPad ¶
func (m *SettingsManager) SetOutputPad(padding int)
SetOutputPad records the chat output padding (pi: setOutputPad).
func (*SettingsManager) SetPackages ¶
func (m *SettingsManager) SetPackages(packages []PackageSource)
SetPackages records the package sources (pi: setPackages).
func (*SettingsManager) SetProjectExtensionPaths ¶
func (m *SettingsManager) SetProjectExtensionPaths(paths []string) error
SetProjectExtensionPaths records the project extension paths (pi: setProjectExtensionPaths).
func (*SettingsManager) SetProjectPackages ¶
func (m *SettingsManager) SetProjectPackages(packages []PackageSource) error
SetProjectPackages records the project package sources (pi: setProjectPackages).
func (*SettingsManager) SetProjectPromptTemplatePaths ¶
func (m *SettingsManager) SetProjectPromptTemplatePaths(paths []string) error
SetProjectPromptTemplatePaths records the project prompt template paths (pi: setProjectPromptTemplatePaths).
func (*SettingsManager) SetProjectSkillPaths ¶
func (m *SettingsManager) SetProjectSkillPaths(paths []string) error
SetProjectSkillPaths records the project skill paths (pi: setProjectSkillPaths).
func (*SettingsManager) SetProjectThemePaths ¶
func (m *SettingsManager) SetProjectThemePaths(paths []string) error
SetProjectThemePaths records the project theme paths (pi: setProjectThemePaths).
func (*SettingsManager) SetProjectTrusted ¶
func (m *SettingsManager) SetProjectTrusted(trusted bool)
SetProjectTrusted updates project trust and reloads project settings accordingly (pi: setProjectTrusted).
func (*SettingsManager) SetPromptTemplatePaths ¶
func (m *SettingsManager) SetPromptTemplatePaths(paths []string)
SetPromptTemplatePaths records the prompt template paths (pi: setPromptTemplatePaths).
func (*SettingsManager) SetQuietStartup ¶
func (m *SettingsManager) SetQuietStartup(quiet bool)
SetQuietStartup records the quiet startup toggle (pi: setQuietStartup).
func (*SettingsManager) SetRetryEnabled ¶
func (m *SettingsManager) SetRetryEnabled(enabled bool)
SetRetryEnabled records the retry toggle (pi: setRetryEnabled).
func (*SettingsManager) SetShellCommandPrefix ¶
func (m *SettingsManager) SetShellCommandPrefix(prefix string)
SetShellCommandPrefix records the shell command prefix (pi: setShellCommandPrefix; undefined → delete).
func (*SettingsManager) SetShellPath ¶
func (m *SettingsManager) SetShellPath(path string)
SetShellPath records the custom shell path (pi: setShellPath).
func (*SettingsManager) SetShowCacheMissNotices ¶
func (m *SettingsManager) SetShowCacheMissNotices(show bool)
SetShowCacheMissNotices records the cache-miss notice toggle (pi: setShowCacheMissNotices).
func (*SettingsManager) SetShowHardwareCursor ¶
func (m *SettingsManager) SetShowHardwareCursor(enabled bool)
SetShowHardwareCursor records the hardware cursor toggle (pi: setShowHardwareCursor).
func (*SettingsManager) SetShowImages ¶
func (m *SettingsManager) SetShowImages(show bool)
SetShowImages records the inline-image toggle (pi: setShowImages).
func (*SettingsManager) SetShowResourceStats ¶
func (m *SettingsManager) SetShowResourceStats(show bool)
SetShowResourceStats records the footer resource-stats toggle (pig-only).
func (*SettingsManager) SetShowTerminalProgress ¶
func (m *SettingsManager) SetShowTerminalProgress(enabled bool)
SetShowTerminalProgress records the terminal progress toggle (pi: setShowTerminalProgress).
func (*SettingsManager) SetSkillPaths ¶
func (m *SettingsManager) SetSkillPaths(paths []string)
SetSkillPaths records the skill paths (pi: setSkillPaths).
func (*SettingsManager) SetSteeringMode ¶
func (m *SettingsManager) SetSteeringMode(mode string)
SetSteeringMode records the steering mode (pi: setSteeringMode).
func (*SettingsManager) SetTheme ¶
func (m *SettingsManager) SetTheme(theme string)
SetTheme records the theme (pi: setTheme).
func (*SettingsManager) SetThemePaths ¶
func (m *SettingsManager) SetThemePaths(paths []string)
SetThemePaths records the theme paths (pi: setThemePaths).
func (*SettingsManager) SetTransport ¶
func (m *SettingsManager) SetTransport(transport TransportSetting)
SetTransport records the transport setting (pi: setTransport).
func (*SettingsManager) SetTreeFilterMode ¶
func (m *SettingsManager) SetTreeFilterMode(mode string)
SetTreeFilterMode records the /tree filter default (pi: setTreeFilterMode).
func (*SettingsManager) SetTuiMode ¶
func (m *SettingsManager) SetTuiMode(mode TuiMode)
SetTuiMode records the renderer mode (pi: setTuiMode).
func (*SettingsManager) SetWarnings ¶
func (m *SettingsManager) SetWarnings(warnings WarningSettings)
SetWarnings records the warning toggles (pi: setWarnings).
type SettingsManagerCreateOptions ¶
type SettingsManagerCreateOptions struct {
ProjectTrusted *bool
}
SettingsManagerCreateOptions carries creation options (pi: SettingsManagerCreateOptions).
type SettingsScope ¶
type SettingsScope = string
SettingsScope selects which settings layer a storage operation targets.
const ( SettingsScopeGlobal SettingsScope = "global" SettingsScopeProject SettingsScope = "project" )
type SettingsStorage ¶
type SettingsStorage interface {
WithLock(scope SettingsScope, fn func(current *string) *string) error
}
SettingsStorage abstracts settings persistence (pi: SettingsStorage). pi's withLock throws; pig returns error (header declaration).
type ShutdownHandler ¶
type ShutdownHandler func()
ShutdownHandler requests graceful shutdown (pi: ShutdownHandler).
type Skill ¶
type Skill struct {
Name string
Description string
FilePath string
BaseDir string
SourceInfo SourceInfo
// DisableModelInvocation hides the skill from the system prompt (it can
// only be invoked explicitly via /skill:name commands).
DisableModelInvocation bool
}
Skill is one loaded skill (pi: Skill).
type SkillDiscoveryMode ¶
type SkillDiscoveryMode = string
SkillDiscoveryMode distinguishes the two skill layouts (pi: SkillDiscoveryMode).
const ( SkillModePi SkillDiscoveryMode = "pi" SkillModeAgents SkillDiscoveryMode = "agents" )
type SkillFrontmatter ¶
type SkillFrontmatter struct {
Name string
Description string
DisableModelInvocation bool
DisableModelInvocationSet bool
}
SkillFrontmatter is the parsed skill frontmatter shape (pi: SkillFrontmatter; unknown fields pass through the map).
type SlashCommandInfo ¶
type SlashCommandInfo struct {
Name string
Description string
Source SlashCommandSource
SourceInfo SourceInfo
}
SlashCommandInfo describes one slash command (pi: SlashCommandInfo).
type SlashCommandSource ¶
type SlashCommandSource string
SlashCommandSource discriminates where a slash command came from (pi: SlashCommandSource).
const ( SlashCommandSourceExtension SlashCommandSource = "extension" SlashCommandSourcePrompt SlashCommandSource = "prompt" SlashCommandSourceSkill SlashCommandSource = "skill" )
type SourceInfo ¶
type SourceInfo = utils.SourceInfo
SourceInfo records where a loaded resource came from (pi: SourceInfo).
func CreateSourceInfo ¶
func CreateSourceInfo(path string, metadata PathMetadata) SourceInfo
CreateSourceInfo builds a SourceInfo from package-manager path metadata (pi: createSourceInfo). Previously deferred with the package-manager batch; PathMetadata now lives in package_manager_paths.go.
func CreateSyntheticSourceInfo ¶
func CreateSyntheticSourceInfo(path string, options SyntheticSourceInfoOptions) SourceInfo
CreateSyntheticSourceInfo builds a SourceInfo without package metadata (pi: createSyntheticSourceInfo).
type SourceOrigin ¶
type SourceOrigin = utils.SourceOrigin
SourceOrigin identifies how a resource was referenced (pi: SourceOrigin).
type SourceScope ¶
type SourceScope = utils.SourceScope
SourceScope identifies where a resource came from (pi: SourceScope).
type SummaryWithUsage ¶
SummaryWithUsage is a generated summary plus its provider usage (the inline `{ text, usage }` return of pi's generateSummaryWithUsage).
func GenerateSummaryWithUsage ¶
func GenerateSummaryWithUsage( ctx context.Context, currentMessages []agent.AgentMessage, model *ai.Model, reserveTokens int64, apiKey string, headers map[string]string, customInstructions string, previousSummary string, thinkingLevel types.ThinkingLevel, streamFn agent.StreamFn, env ai.ProviderEnv, retry *ai.RetryPolicy, callbacks *ai.RetryCallbacks, sessionID string, ) (*SummaryWithUsage, error)
GenerateSummaryWithUsage generates or updates a conversation summary and returns its provider usage (pi: generateSummaryWithUsage; parameter ordering follows pi with ctx first — pi's signal member is dropped).
type SwitchSessionCommandOptions ¶
type SwitchSessionCommandOptions struct {
WithSession func(ctx context.Context, sessionCtx *ReplacedSessionContext) error
}
SwitchSessionCommandOptions are the switchSession options (pi: switchSession's options parameter).
type SwitchSessionOptions ¶
type SwitchSessionOptions struct {
// CwdOverride forces the session cwd (pi: cwdOverride; nil = none).
CwdOverride *string
// WithSession runs with the replacement session context (pi:
// withSession).
WithSession func(replacedCtx *ReplacedSessionContext) error
// ProjectTrustContextFactory resolves trust for the target cwd (pi:
// projectTrustContextFactory).
ProjectTrustContextFactory func(cwd string) any
}
SwitchSessionOptions are the switchSession inputs (pi's inline options).
type SyntheticSourceInfoOptions ¶
type SyntheticSourceInfoOptions struct {
Source string
Scope SourceScope
Origin SourceOrigin
BaseDir string
}
SyntheticSourceInfoOptions carries createSyntheticSourceInfo's optional fields (pi: inline options object; "" = undefined).
type TerminalCapabilityOverrides ¶
type TerminalCapabilityOverrides = tui.TerminalCapabilityOverrides
TerminalCapabilityOverrides is the user-forced subset of terminal capabilities (pi: Partial<TerminalCapabilities> from getTerminalCapabilityOverrides; the canonical type lives in pi-tui, so pig aliases tui.TerminalCapabilityOverrides; pi's images:null force-off maps to Images=false here).
type TerminalInputHandler ¶
type TerminalInputHandler func(data string) *TerminalInputResult
TerminalInputHandler receives raw terminal input and may consume or rewrite it (pi: TerminalInputHandler). nil return = undefined (forward unchanged).
type TerminalInputResult ¶
type TerminalInputResult struct {
// Consume swallows the input instead of forwarding it (pi: consume?).
Consume bool
// Data replaces the forwarded input; "" = leave unchanged (pi: data?).
Data string
}
TerminalInputResult is the handler's return (pi: `{ consume?, data? } | undefined`; nil return = undefined).
type TerminalSettings ¶
type TerminalSettings struct {
ShowImages *bool // default: true (only relevant if terminal supports images)
ImageWidthCells *int64 // default: 60 (preferred inline image width in terminal cells)
ClearOnShrink *bool // default: false (clear empty rows when content shrinks)
ShowTerminalProgress *bool // default: false (OSC 9;4 terminal progress indicators)
// Hyperlinks / Images / TrueColor mirror pi's boolean | "auto" unions
// (Images additionally "kitty" | "iterm2"; false forces off). pig keeps
// the raw JSON values in the settings map; v0.85.1 additions.
Hyperlinks any
Images any
TrueColor any
}
TerminalSettings holds the terminal rendering settings shape (pi: TerminalSettings).
type ThemeLoaderResult ¶
type ThemeLoaderResult struct {
Themes []any
Diagnostics []ResourceDiagnostic
}
ThemeLoaderResult bundles themes and diagnostics (pi's inline { themes, diagnostics } shape). Theme is deferred with the theme batch; the result keeps the diagnostics half.
type ThemeSetResult ¶
type ThemeSetResult struct {
Success bool
// Error is set when Success is false; "" = none (pi: error?).
Error string
}
ThemeSetResult reports a theme switch attempt (pi: { success: boolean; error?: string }).
type ThinkingBudgetsSettings ¶
ThinkingBudgetsSettings holds custom token budgets for thinking levels (pi: ThinkingBudgetsSettings). pi's numbers are TS numbers; pig keeps float64 for JSON fidelity.
type ThinkingLevelChangeEntry ¶
ThinkingLevelChangeEntry records a thinking level change (pi: ThinkingLevelChangeEntry).
type ThinkingLevelSelectEvent ¶
type ThinkingLevelSelectEvent struct {
Type string `json:"type"`
Level agent.ThinkingLevel `json:"level"`
PreviousLevel agent.ThinkingLevel `json:"previousLevel"`
}
ThinkingLevelSelectEvent fires when a new thinking level is selected (pi: ThinkingLevelSelectEvent).
func (*ThinkingLevelSelectEvent) EventType ¶
func (e *ThinkingLevelSelectEvent) EventType() string
type TimingLabel ¶
type TimingLabel = string
TimingLabel is "main" | "extensions" (pi: TimingLabel).
const ( TimingMain TimingLabel = "main" TimingExtensions TimingLabel = "extensions" )
type ToolCallEvent ¶
type ToolCallEvent struct {
Type string `json:"type"`
ToolName string `json:"toolName"`
ToolCallID string `json:"toolCallId"`
Input any `json:"input"`
}
ToolCallEvent fires before a tool executes (pi: ToolCallEvent).
func (*ToolCallEvent) EventType ¶
func (e *ToolCallEvent) EventType() string
type ToolCallEventResult ¶
type ToolCallEventResult struct {
// Block blocks tool execution (pi: block?).
Block bool `json:"block,omitempty"`
// Reason explains the block (pi: reason?).
Reason string `json:"reason,omitempty"`
// Terminate hints that the agent should stop after the current tool
// batch when this call is blocked (pi: terminate?).
Terminate bool `json:"terminate,omitempty"`
}
ToolCallEventResult is the tool_call handler result (pi: ToolCallEventResult).
type ToolExecutionEndEvent ¶
type ToolExecutionEndEvent struct {
Type string `json:"type"`
ToolCallID string `json:"toolCallId"`
ToolName string `json:"toolName"`
Result agent.AgentToolResult `json:"result"`
IsError bool `json:"isError"`
}
ToolExecutionEndEvent fires when a tool finishes executing (pi: ToolExecutionEndEvent).
func (*ToolExecutionEndEvent) EventType ¶
func (e *ToolExecutionEndEvent) EventType() string
type ToolExecutionStartEvent ¶
type ToolExecutionStartEvent struct {
Type string `json:"type"`
ToolCallID string `json:"toolCallId"`
ToolName string `json:"toolName"`
Args any `json:"args"`
}
ToolExecutionStartEvent fires when a tool starts executing (pi: ToolExecutionStartEvent).
func (*ToolExecutionStartEvent) EventType ¶
func (e *ToolExecutionStartEvent) EventType() string
type ToolExecutionUpdateEvent ¶
type ToolExecutionUpdateEvent struct {
Type string `json:"type"`
ToolCallID string `json:"toolCallId"`
ToolName string `json:"toolName"`
Args any `json:"args"`
PartialResult any `json:"partialResult"`
}
ToolExecutionUpdateEvent fires during tool execution (pi: ToolExecutionUpdateEvent).
func (*ToolExecutionUpdateEvent) EventType ¶
func (e *ToolExecutionUpdateEvent) EventType() string
type ToolInfo ¶
type ToolInfo struct {
Name string
Description string
// Parameters is the JSON Schema of the tool input.
Parameters any
// PromptGuidelines are the tool's system-prompt guidelines.
PromptGuidelines []string
SourceInfo SourceInfo
}
ToolInfo describes one configured tool (pi: ToolInfo).
type ToolRenderContext ¶
type ToolRenderContext = tools.ToolRenderContext
ToolRenderContext is the context passed to tool renderers (pi: ToolRenderContext<TState, TArgs>; generics collapse to any). Aliased from tools.ToolRenderContext.
type ToolRenderResultOptions ¶
type ToolRenderResultOptions = tools.ToolRenderResultOptions
ToolRenderResultOptions carries the tool result render options (pi: ToolRenderResultOptions). Aliased from tools.ToolRenderResultOptions.
type ToolResultEvent ¶
type ToolResultEvent struct {
Type string `json:"type"`
ToolName string `json:"toolName"`
ToolCallID string `json:"toolCallId"`
Input any `json:"input"`
Content []types.Content `json:"content"`
Details any `json:"details"`
IsError bool `json:"isError"`
Usage *types.Usage `json:"usage,omitempty"`
}
ToolResultEvent fires after a tool executes (pi: ToolResultEvent).
func (*ToolResultEvent) EventType ¶
func (e *ToolResultEvent) EventType() string
type ToolResultEventResult ¶
type ToolResultEventResult struct {
// Content replaces the result content; nil = unchanged (pi: content?).
Content []types.Content `json:"content,omitempty"`
// Details replaces the result details (pi: details?).
Details any `json:"details,omitempty"`
// IsError overrides the error flag; nil = unchanged (pi: isError?).
IsError *bool `json:"isError,omitempty"`
// Usage overrides the usage (pi: usage?).
Usage *types.Usage `json:"usage,omitempty"`
}
ToolResultEventResult is the tool_result handler result (pi: ToolResultEventResult).
type TrailingEntries ¶ added in v0.86.0
TrailingEntries produces export-only entries appended after the branch (pi: TrailingEntries). It receives the last branch entry's parent id (nil when the branch is empty) and the export timestamp.
type TransportSetting ¶
TransportSetting selects the provider transport (pi: TransportSetting = Transport from pi-ai).
type TreePreparation ¶
type TreePreparation struct {
TargetID string `json:"targetId"`
// OldLeafID is the position navigating from; nil = session root (pi:
// oldLeafId: string | null).
OldLeafID *string `json:"oldLeafId"`
// CommonAncestorID is the deepest node shared by both paths; nil = none
// (pi: commonAncestorId: string | null).
CommonAncestorID *string `json:"commonAncestorId"`
// EntriesToSummarize are the abandoned entries, chronological order.
EntriesToSummarize []SessionEntry `json:"entriesToSummarize"`
UserWantsSummary bool `json:"userWantsSummary"`
// CustomInstructions are the summarization instructions; "" = none (pi:
// customInstructions?).
CustomInstructions string `json:"customInstructions,omitempty"`
// ReplaceInstructions replaces the default prompt with
// customInstructions (pi: replaceInstructions?).
ReplaceInstructions bool `json:"replaceInstructions,omitempty"`
// Label is the label to attach to the branch summary entry; "" = none
// (pi: label?).
Label string `json:"label,omitempty"`
}
TreePreparation is the preparation data for tree navigation (pi: TreePreparation).
type TuiMode ¶
type TuiMode = string
TuiMode selects the interactive renderer mode (pi: TuiMode = RendererTuiMode from pi-tui; the canonical type lands with the tui batch).
type TurnEndEvent ¶
type TurnEndEvent struct {
Type string `json:"type"`
TurnIndex int `json:"turnIndex"`
Message agent.AgentMessage `json:"message"`
// ToolResults are the turn's tool result messages (empty when the turn
// had no tool calls).
ToolResults []types.ToolResultMessage `json:"toolResults"`
// MessageEntryID is the persisted session entry of the assistant message.
MessageEntryID string `json:"messageEntryId"`
// ToolResultEntryIDs are the persisted session entries of ToolResults,
// in order (pi flatMaps unresolved IDs out).
ToolResultEntryIDs []string `json:"toolResultEntryIds"`
// Outcome classifies the completed turn.
Outcome AgentActivityOutcome `json:"outcome"`
BoundaryState
}
TurnEndEvent fires at the end of each turn (pi: TurnEndEvent, v0.87.0 boundary shape). Handlers may append entries via a BoundaryResult and request one continuation.
func (*TurnEndEvent) EventType ¶
func (e *TurnEndEvent) EventType() string
type TurnEndEventResult ¶ added in v0.87.0
type TurnEndEventResult = BoundaryResult
TurnEndEventResult and AgentBeforeSettleEventResult are the boundary handler results (pi: TurnEndEventResult / AgentBeforeSettleEventResult, v0.87.0).
type TurnStartEvent ¶
type TurnStartEvent struct {
Type string `json:"type"`
TurnIndex int `json:"turnIndex"`
Timestamp int64 `json:"timestamp"`
}
TurnStartEvent fires at the start of each turn (pi: TurnStartEvent).
func (*TurnStartEvent) EventType ¶
func (e *TurnStartEvent) EventType() string
type UIPromptEndEvent ¶
type UIPromptEndEvent struct {
Type string `json:"type"`
Reason string `json:"reason"`
Kind UIPromptKind `json:"kind"`
Title *string `json:"title,omitempty"`
}
UIPromptEndEvent fires when Pi is no longer waiting on a blocking user-facing extension UI prompt (pi: UIPromptEndEvent, v0.85.1).
func (*UIPromptEndEvent) EventType ¶
func (e *UIPromptEndEvent) EventType() string
type UIPromptKind ¶
type UIPromptKind string
UIPromptKind names the blocking user-facing extension UI prompt (pi: UIPromptKind, v0.85.1).
const ( UIPromptKindSelect UIPromptKind = "select" UIPromptKindConfirm UIPromptKind = "confirm" UIPromptKindInput UIPromptKind = "input" UIPromptKindEditor UIPromptKind = "editor" UIPromptKindCustom UIPromptKind = "custom" )
type UIPromptStartEvent ¶
type UIPromptStartEvent struct {
Type string `json:"type"`
Reason string `json:"reason"`
Kind UIPromptKind `json:"kind"`
// Title is the dialog title; nil = pi's omitted optional key.
Title *string `json:"title,omitempty"`
}
UIPromptStartEvent fires when Pi starts waiting on a blocking user-facing extension UI prompt (pi: UIPromptStartEvent, v0.85.1).
func (*UIPromptStartEvent) EventType ¶
func (e *UIPromptStartEvent) EventType() string
type UITheme ¶
UITheme is the theme surface available to UI renderers (pi passes the concrete Theme from modes/interactive/theme). Aliased from tools.UITheme; *theme.Theme satisfies it.
type UploadBugReportOptions ¶ added in v0.86.0
UploadBugReportOptions are the uploadBugReport parameters (pi: UploadBugReportOptions).
type UsageCostBreakdownEntry ¶
UsageCostBreakdownEntry is one bucket of the cost breakdown (pi: UsageCostBreakdownEntry).
func GetUsageCostBreakdown ¶
func GetUsageCostBreakdown(entries []SessionEntry) []UsageCostBreakdownEntry
GetUsageCostBreakdown groups attributable assistant usage by model and all other usage into a separate bucket (pi: getUsageCostBreakdown). pi iterates the totals Map for output; pig keeps an insertion-ordered key list so the order is deterministic before sorting.
type UsageEntry ¶ added in v0.86.0
type UsageEntry struct {
EntryBase
// Kind is an arbitrary usage category, such as "cache_warm".
Kind string `json:"kind"`
Provider string `json:"provider"`
Model string `json:"model"`
Usage *types.Usage `json:"usage"`
// Note is an optional human-readable qualifier for usage notices.
Note string `json:"note,omitempty"`
}
UsageEntry records model-attributed usage that does not participate in LLM context (pi: UsageEntry; v0.86.0, e.g. cache warming refreshes).
type UsageTotals ¶
UsageTotals accumulates token and cost totals (pi: UsageTotals).
func CreateUsageTotals ¶
func CreateUsageTotals() UsageTotals
CreateUsageTotals returns zeroed totals (pi: createUsageTotals).
type UserBashEvent ¶ added in v0.86.0
type UserBashEvent struct {
Type string `json:"type"`
// Command is the command to execute.
Command string `json:"command"`
// ExcludeFromContext is true for the !! prefix (excluded from LLM
// context).
ExcludeFromContext bool `json:"excludeFromContext"`
// Cwd is the current working directory.
Cwd string `json:"cwd"`
}
UserBashEvent fires before the shell executes a `!` command (pi: UserBashEvent).
func (*UserBashEvent) EventType ¶ added in v0.86.0
func (e *UserBashEvent) EventType() string
type UserBashEventResult ¶ added in v0.86.0
type UserBashEventResult struct {
// Operations customizes execution (pi: { operations }).
Operations *tools.BashOperations
// Result fully replaces execution (pi: { result }).
Result *BashResult
}
UserBashEventResult intercepts a `!` command (pi: UserBashEventResult — the `{ operations } | { result }` union; exactly one half is set).
type WarningSettings ¶
type WarningSettings struct {
AnthropicExtraUsage *bool // default: true
}
WarningSettings holds the warning toggle settings shape (pi: WarningSettings).
type WorkingIndicatorOptions ¶
type WorkingIndicatorOptions struct {
// Frames are custom animation frames; ["●"] = static, [] = hidden (pi:
// frames). Custom frames render verbatim.
Frames []string
// IntervalMs is the frame interval in milliseconds for animated
// indicators (pi: intervalMs).
IntervalMs int
}
WorkingIndicatorOptions configure the interactive working indicator (pi: WorkingIndicatorOptions).
Source Files
¶
- agent_session.go
- agent_session_runtime.go
- agent_session_services.go
- auth_guidance.go
- auth_storage.go
- bash_executor.go
- branch_summarization.go
- bug_report.go
- bug_report_upload.go
- cache_stats.go
- cache_warmer.go
- compaction.go
- compaction_utils.go
- crash_log.go
- defaults.go
- diagnostics.go
- doc.go
- event_bus.go
- experimental.go
- export_html.go
- extensions_runner.go
- extensions_types.go
- extensions_wrapper.go
- footer_data_provider.go
- http_dispatcher.go
- keybindings.go
- migrations.go
- model_config.go
- model_registry.go
- model_resolver.go
- model_runtime.go
- models_store.go
- output_guard.go
- package_manager_paths.go
- project_trust.go
- prompt_templates.go
- provider_attribution.go
- provider_composer.go
- radius.go
- remote_catalog_provider.go
- resolve_config_value.go
- resource_loader.go
- resource_loader_default.go
- runtime_credentials.go
- sdk.go
- session_cwd.go
- session_export.go
- session_manager.go
- settings_diagnostics.go
- settings_manager.go
- skills.go
- slash_commands.go
- source_info.go
- system_prompt.go
- telemetry.go
- timings.go
- trust_manager.go
- usage_totals.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package compaction corresponds to pi's packages/coding-agent/src/core/compaction.
|
Package compaction corresponds to pi's packages/coding-agent/src/core/compaction. |
|
ansi_to_html.go (pi: core/export-html/ansi-to-html.ts, v0.86.0)
|
ansi_to_html.go (pi: core/export-html/ansi-to-html.ts, v0.86.0) |
|
pi: src/core/tools/bash.ts — the coding-agent shell tool (shared by bash and powershell via createShellToolDefinition).
|
pi: src/core/tools/bash.ts — the coding-agent shell tool (shared by bash and powershell via createShellToolDefinition). |