extension

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 42 Imported by: 1

Documentation

Overview

Package extension defines the contract every pig extension speaks. It mirrors upstream pi's ExtensionAPI surface 1:1 so a TS extension can be ported to Go almost line-for-line, and so each upstream version bump is an additive diff rather than a structural one.

Source of truth:

.upstream/current/packages/coding-agent/src/core/extensions/types.ts

This package contains only the public API contract: types, the fat API interface, and the Extension author-facing interface. Hosts (the inproc dispatch runner and subprocess transport adapter) live under coding/extension/host/ and depend on this package, never the reverse.

Faithfulness rules

  • Method order on the API interface matches upstream ExtensionAPI declaration order. Section dividers mirror upstream comments.
  • Every field on every event struct carries a json:"camelCaseName" tag matching upstream's TS field name. The parity gates in test/upstream-parity/ enforce this on every CI run.
  • Field names use idiomatic Go casing with terminal initialism uplift (Id→ID, Url→URL, Api→API, Json→JSON). For example, upstream `toolCallId` becomes Go `ToolCallID`. The parity reflection check uses [parity.CamelToGoField] which knows the closed initialism set; extending it requires a coordinated update to that helper plus a docs/parity/DIVERGENCES.md U1 sync-ritual entry.
  • Observable differences use a numbered source marker and ledger record.

Opaque compatibility types

Upstream references many domain types (AgentMessage, Model, CompactionEntry, AbortSignal, Component, etc.) that don't yet have concrete Go equivalents in PiG. Types that cross the current dynamic JSON or renderer boundaries are explicit opaque aliases in opaque_types.go. Concrete events and SDK methods use typed Go values where the contract is stable.

Shell command execution for extensions.

Mirrors upstream core/exec.ts. Provides the implementation backing extension.API.Exec: a simple process spawn with timeout and abort support.

upstream: coding-agent/src/core/exec.ts (107 LOC)

Index

Constants

View Source
const (
	DiagnosticWarning   = "warning"
	DiagnosticError     = "error"
	DiagnosticCollision = "collision"
)

Diagnostic type constants matching upstream's literal union.

View Source
const (
	LoginBrandWidth            = 41
	LoginBrandHeight           = 5
	LoginHeroWidth             = 32
	LoginHeroHeight            = 14
	LoginMascotWidth           = 16
	LoginMascotHeight          = 14
	LoginPaletteLimit          = 32
	LoginNameWidthLimit        = 24
	LoginDescriptionWidthLimit = 48
	LoginTaglineWidthLimit     = 76
	LoginMetadataWidthLimit    = 80
)

pig additive (D60): Pig validates a typed login definition because subprocess extensions cannot pass Pi's live TUI component factories.

View Source
const (
	MarkdownMessageUser              = markdowntransform.MarkdownMessageUser
	MarkdownMessageAssistant         = markdowntransform.MarkdownMessageAssistant
	MarkdownMessageAssistantThinking = markdowntransform.MarkdownMessageAssistantThinking
)
View Source
const (
	ListMcpResourcesTool         = "list_mcp_resources"
	ListMcpResourceTemplatesTool = "list_mcp_resource_templates"
	ReadMcpResourceTool          = "read_mcp_resource"
)

The MCP resource tools reach every server with resources.

Ports packages/coding-agent/src/core/mcp-servers.ts (LIST_MCP_RESOURCES_TOOL, LIST_MCP_RESOURCE_TEMPLATES_TOOL, READ_MCP_RESOURCE_TOOL).

View Source
const DefaultStaleRuntimeMessage = "" /* 363-byte string literal not displayed */

DefaultStaleRuntimeMessage is the error an invalidated runtime reports when Invalidate gets no message.

View Source
const SpriteIDLimit = 32

pig divergence (D2): an extension adds a sprite to PiG's /sprite catalogue with the same kind of data as its native login (D60): pixel grids of palette symbols, a palette and display text. The host validates it and draws it; a sprite never replaces the header by itself.

View Source
const VirtualModelAPI = "pi-virtual"

VirtualModelAPI is the API id of virtual catalog entries. Requests for it fail unless routed first.

upstream: virtual-models.ts:29 (VIRTUAL_MODEL_API)

View Source
const VirtualModelStateEntry = "pi.virtual-model-state"

VirtualModelStateEntry is the custom entry type that stores router state on the session branch.

upstream: virtual-models.ts:32 (VIRTUAL_MODEL_STATE_ENTRY)

Variables

View Source
var (
	// ErrStaleContext is returned by API calls made through an
	// ExtensionContext whose runner has been replaced (typically after
	// /reload or a session swap). Mirrors upstream's invalidate() sentinel
	// in core/extensions/runner.ts.
	ErrStaleContext = errors.New("extension: context is stale (runner replaced)")

	// ErrBusy is returned when an action is rejected because the agent is
	// streaming or compacting. Mirrors upstream's reload guard in
	// modes/interactive/interactive-mode.ts handleReloadCommand.
	ErrBusy = errors.New("extension: agent is busy (streaming or compacting)")

	// ErrCapabilityNotDeclared is returned when an extension calls an API
	// surface it didn't declare in its manifest capabilities list.
	ErrCapabilityNotDeclared = errors.New("extension: capability not declared in manifest")

	// ErrUnknownEvent is returned when a host attempts to dispatch an event
	// name that no registered handler understands. Hosts may treat this as
	// an info-level no-op; it exists for tests and diagnostics.
	ErrUnknownEvent = errors.New("extension: unknown event")
)

Sentinel errors surfaced by extension hosts (the inproc dispatch runner and subprocess transport adapter) to extensions. Authors compare with errors.Is.

View Source
var ErrHandlerStopped = errors.New("extension handler stopped by the host")

ErrHandlerStopped marks a handler call the host itself cut short: it stopped the extension (shutdown, a termination signal, /reload) or cancelled the dispatch. The handler did not fail, so runners do not report it as an ExtensionError. Upstream never interrupts a running handler; its signal path disposes the runtime and exits without reporting the interrupted work.

View Source
var ErrRuntimeNotInitialized = errors.New("Extension runtime not initialized. Action methods cannot be called during extension loading.")

ErrRuntimeNotInitialized is returned by an action called while extensions are still loading. upstream: loader.ts:157-159 (notInitialized)

View Source
var ErrUIUnavailable = errors.New("UI not available")

ErrUIUnavailable reports that a UI-only operation cannot run in the current mode.

Functions

func BeforeAgentStartSelectedTools

func BeforeAgentStartSelectedTools(ctx context.Context) json.RawMessage

BeforeAgentStartSelectedTools returns the current wire value, retaining untyped edits until prompt admission. A native collection replacement supersedes the preceding wire value.

func CallInitiated

func CallInitiated(ctx context.Context)

CallInitiated reports that the call carried by ctx has applied its synchronous part. It is a no-op without a mark and safe to call repeatedly when the mark is idempotent.

func DialogSettleFromContext

func DialogSettleFromContext(ctx context.Context) func()

DialogSettleFromContext returns the settle function the host attached to the dialog call ctx belongs to, or nil.

func DispatchStartedFromContext

func DispatchStartedFromContext(ctx context.Context) func()

DispatchStartedFromContext returns the function the dispatch calls when its first handler has started, or nil.

func ErrorStack

func ErrorStack(err error) string

ErrorStack returns the stack carried by err or an error it wraps, or "". Runners use it for ExtensionError.Stack: upstream reports the handler's `err.stack`, never the host's own dispatch stack.

func ExpandMcpURL

func ExpandMcpURL(raw string) string

ExpandMcpURL expands the environment references of a server URL the way header and env values are resolved (`$VAR`, `${VAR}`, `$$`). A URL that cannot be expanded now (a `!command`, or a variable that is unset) stays as written, so a literal URL that contains a `$` keeps working. Validation, the transport and the OAuth URL use the expansion; the stored config keeps the reference.

pig divergence (D156): Pi uses the URL as written (Pi #10654).

func IsBashToolResult

func IsBashToolResult(event ToolResultEvent) bool

IsBashToolResult reports whether event is the result of the bash tool. upstream: types.ts:1315 isBashToolResult, e.toolName === "bash". It narrows nothing: the Session emits CustomToolResultEvent for every tool, and a caller that needs a variant type-asserts after the test.

func IsEditToolResult

func IsEditToolResult(event ToolResultEvent) bool

IsEditToolResult reports whether event is the result of the edit tool. upstream: types.ts:1324 isEditToolResult.

func IsFindToolResult

func IsFindToolResult(event ToolResultEvent) bool

IsFindToolResult reports whether event is the result of the find tool. upstream: types.ts:1333 isFindToolResult.

func IsGrepToolResult

func IsGrepToolResult(event ToolResultEvent) bool

IsGrepToolResult reports whether event is the result of the grep tool. upstream: types.ts:1330 isGrepToolResult.

func IsLoopbackRedirectURI

func IsLoopbackRedirectURI(value string) bool

IsLoopbackRedirectURI reports whether a redirect URI can be served by the loopback callback server: an `http` URI on `localhost`, `127.0.0.1`, or `[::1]` without query or fragment. The URI is parsed as `new URL(value)` does.

func IsLsToolResult

func IsLsToolResult(event ToolResultEvent) bool

IsLsToolResult reports whether event is the result of the ls tool. upstream: types.ts:1336 isLsToolResult.

func IsMcpToolName

func IsMcpToolName(name string) bool

IsMcpToolName reports whether a tool comes from MCP: a server tool (`mcp__<server>__<tool>`) or a resource tool.

Ports packages/coding-agent/src/core/mcp-servers.ts (isMcpToolName).

func IsPowerShellToolResult

func IsPowerShellToolResult(event ToolResultEvent) bool

IsPowerShellToolResult reports whether event is the result of the powershell tool. upstream: types.ts:1318 isPowerShellToolResult.

func IsReadToolResult

func IsReadToolResult(event ToolResultEvent) bool

IsReadToolResult reports whether event is the result of the read tool. upstream: types.ts:1321 isReadToolResult.

func IsToolCallEventType

func IsToolCallEventType(toolName string, event ToolCallEvent) bool

IsToolCallEventType reports whether event is a tool call of the named tool. It narrows nothing: a caller that needs the variant type-asserts after the test, as upstream's type guard narrows the event. Mirrors upstream types.ts isToolCallEventType, which compares event.toolName with toolName.

func IsWriteToolResult

func IsWriteToolResult(event ToolResultEvent) bool

IsWriteToolResult reports whether event is the result of the write tool. upstream: types.ts:1327 isWriteToolResult.

func MarshalInputEventResult

func MarshalInputEventResult(r InputEventResult) ([]byte, error)

MarshalInputEventResult serialises a sealed-interface variant to upstream wire shape with the `action` discriminator.

Why a free function not a method on the interface: defining a marshal method on the interface would force every variant to implement it (verbose); using a free function keeps marker structs trivial. Hosts dispatching events call this; authors returning a value from OnInput have their value passed through this helper by the runtime.

func MarshalModelObjects

func MarshalModelObjects[M ai.AnyModel](models []M) ([]byte, error)

MarshalModelObjects is the JSON array of the ModelObject of each model, skipping nil models. The objects are joined as they are, so no member is escaped again (JSON.stringify escapes no <, > or &).

func MarshalToolResultEvent

func MarshalToolResultEvent(e ToolResultEvent) ([]byte, error)

MarshalToolResultEvent serialises any of the nine ToolResultEvent variants.

func McpNamespace

func McpNamespace(server string) string

McpNamespace is the namespace of a server's tools: `mcp__<server>` with `-` replaced by `_`, like the tool names.

Ports packages/coding-agent/src/core/mcp-servers.ts (mcpNamespace).

func ModelObject

func ModelObject(model ai.AnyModel) (json.RawMessage, error)

ModelObject is the JSON of the model object Pi hands an extension (ctx.model, model_select, ctx.modelRegistry, a provider object's model argument): Pi's model object with its members in Pi's order. A model from a catalog record (the built-in catalog, a models store or an extension's registered definition) is ai.CatalogModelJSON, the record's members in the record's order; any other model is its persisted record (ai.EncodeModelsCatalog), whose members follow provider-composer.ts:230-248. A nil model is nil.

A chat model with no provider id takes its provider's, and one without a record and with no input modalities reads as text (and image when it supports images), as Pi's composer defaults input to ["text"]; a record's input is its own.

func NodeTimerDelay

func NodeTimerDelay(ms float64) time.Duration

NodeTimerDelay is the delay Node gives setTimeout(fn, ms): it truncates a fractional value and runs a delay outside [1, 2^31-1], or NaN, after one millisecond.

func OwnsSignal

func OwnsSignal(ctx context.Context) bool

OwnsSignal reports whether ctx belongs to a nested call that runs with the signal its caller passed in options.signal. Other tool calls run with the run's signal.

func ProviderStreamSimpleSelected

func ProviderStreamSimpleSelected(ctx context.Context) bool

func ResolveBeforeAgentStartSelectedTools

func ResolveBeforeAgentStartSelectedTools(ctx context.Context, before []string) ([]string, bool, error)

ResolveBeforeAgentStartSelectedTools compares the final selection before filtering non-string registry misses, as AgentSession.prompt does. Invalid lists reject prompt admission after every handler has had a chance to repair them.

func SetBeforeAgentStartSelectedTools

func SetBeforeAgentStartSelectedTools(ctx context.Context, raw json.RawMessage)

SetBeforeAgentStartSelectedTools retains the complete foreign value for later handlers. Only string entries can name registered Go tools; malformed selections are rejected after the handler chain, not swallowed as handler failures.

func SetNoopUITheme

func SetNoopUITheme(provider func() Theme)

SetNoopUITheme registers the function NoopUIContext.Theme answers from. Pi's no-op UI context (runner.ts noOpUIContext) and its RPC UI both hand an extension the global theme as `ctx.ui.theme`, so an in-process extension running headless reads the same palette the TUI would. A nil provider unregisters.

func ToolNameMatcher

func ToolNameMatcher(entries map[string]struct{}) func(name string) bool

ToolNameMatcher returns a predicate for tool names that match any entry, each an exact name or a pattern where `*` matches any characters. A nil entries set has no matcher: the result is nil.

Ports packages/coding-agent/src/core/mcp-servers.ts (createToolNameMatcher).

func ToolResultDetailsFor

func ToolResultDetailsFor(details any) any

ToolResultDetailsFor converts a tool result's Details to its SDK wire shape when the value implements ToolDetailsConverter; other details (custom-tool JSON, the already-SDK-shaped edit details, or nil) pass through unchanged.

func WithBeforeAgentStartOptions

func WithBeforeAgentStartOptions(ctx context.Context, options *BuildSystemPromptOptions) context.Context

WithBeforeAgentStartOptions attaches the shared per-run options to a handler dispatch. Hosts use this without changing the value-typed BeforeAgentStartEvent.SystemPromptOptions API.

func WithCallInitiation

func WithCallInitiation(ctx context.Context, mark func()) context.Context

WithCallInitiation returns ctx carrying mark, which the handler of a Promise-shaped call runs once its synchronous part has been applied.

func WithCallOrder

func WithCallOrder(ctx context.Context, order *CallOrder) context.Context

WithCallOrder returns ctx carrying the reservation of the call it is passed into.

func WithCommandContext

func WithCommandContext(ctx context.Context, cc *CommandContext) context.Context

WithCommandContext attaches a CommandContext to a context.Context.

func WithContext

func WithContext(parent context.Context, c *Context) context.Context

WithContext attaches a per-extension Context to a context.Context. Hosts call this once at event-dispatch time; the resulting context.Context is then threaded through to extension handlers.

Authors do not call WithContext directly.

func WithDialogSettle

func WithDialogSettle(ctx context.Context, settle func()) context.Context

WithDialogSettle returns ctx carrying settle, which a UIContext's Select, Confirm, Input or Editor runs when the user's answer reaches it, before it hands the answer to the goroutine that waits in the dialog.

Pi resolves a dialog's promise on the stdin line that answers it, so two dialogs answered back to back continue in the order the answers arrived. Go wakes the two waiting goroutines in no order. The host records the order where the answers arrive (settle) and keeps it where the extension's results are sent.

func WithDispatchStarted

func WithDispatchStarted(ctx context.Context, started func()) context.Context

WithDispatchStarted returns ctx carrying started, which an event dispatch made with it calls once its first handler has started: an in-process handler when it returns, an extension process's handler when its request is written to the process. Pi starts the tool_result hooks of a parallel batch in the order their tools settled, each running to its first await before the next starts; the caller holds the hooks of later calls back until started runs. started must be idempotent.

func WithModelStreamRequest

func WithModelStreamRequest(ctx context.Context, request ModelStreamRequest) context.Context

WithModelStreamRequest binds transport callbacks to one model operation.

func WithOwnSignal

func WithOwnSignal(ctx context.Context) context.Context

WithOwnSignal marks ctx as the context of a nested call that runs with the signal its caller passed in options.signal.

upstream: runner.ts:979-981 (`{ ...options, signal: options.signal ?? signal }`)

func WithProviderStreamSimple

func WithProviderStreamSimple(ctx context.Context, simple bool) context.Context

WithProviderStreamSimple carries the selected Pi stream method through the host request.

func WithToolContext

func WithToolContext(parent context.Context, tc *ToolContext) context.Context

WithToolContext attaches a ToolContext to a context.Context. Hosts call it; authors do not.

Types

type AIContext

type AIContext = ai.TranscriptContext

AIContext mirrors @earendil-works/pi-ai Context (the per-call provider context, distinct from pig's ExtensionContext).

type API

type API interface {

	// OnProjectTrust registers a handler for "project_trust"; it receives the ProjectTrustContext of the decision.
	// upstream: types.ts:1558 (on("project_trust", handler: ProjectTrustHandler))
	OnProjectTrust(handler ProjectTrustHandler) func()

	// OnResourcesDiscover registers a handler for "resources_discover".
	// upstream: types.ts:1071
	OnResourcesDiscover(handler ExtensionHandler[ResourcesDiscoverEvent, ResourcesDiscoverResult]) func()

	// OnSessionStart registers a handler for "session_start".
	// upstream: types.ts:1143
	OnSessionStart(handler ExtensionHandlerNoResult[SessionStartEvent]) func()

	// OnSessionInfoChanged registers a handler for "session_info_changed"
	// (upstream types.ts SessionInfoChangedEvent; adopted upstream in 0.80.3).
	OnSessionInfoChanged(handler ExtensionHandlerNoResult[SessionInfoChangedEvent]) func()

	// OnMcpServersChange registers a handler for "mcp_servers_change", fired when
	// an extension registers or unregisters an MCP server after the extensions
	// are bound. Handling it marks an extension as the one that connects
	// registered servers.
	// upstream: types.ts:1562 (on("mcp_servers_change", ...))
	OnMcpServersChange(handler ExtensionHandlerNoResult[McpServersChangeEvent]) func()

	// OnSessionBeforeSwitch registers a handler for "session_before_switch".
	// upstream: types.ts:1145
	OnSessionBeforeSwitch(handler ExtensionHandler[SessionBeforeSwitchEvent, SessionBeforeSwitchResult]) func()

	// OnSessionBeforeFork registers a handler for "session_before_fork".
	// upstream: types.ts:1077
	OnSessionBeforeFork(handler ExtensionHandler[SessionBeforeForkEvent, SessionBeforeForkResult]) func()

	// OnSessionBeforeCompact registers a handler for "session_before_compact".
	// upstream: types.ts:1078
	OnSessionBeforeCompact(handler ExtensionHandler[SessionBeforeCompactEvent, SessionBeforeCompactResult]) func()

	// OnSessionCompact registers a handler for "session_compact".
	// upstream: types.ts:1082
	OnSessionCompact(handler ExtensionHandlerNoResult[SessionCompactEvent]) func()

	// OnSessionCompactFailed registers a handler for "session_compact_failed",
	// fired after manual or automatic compaction fails or is aborted.
	// upstream: types.ts:1374
	OnSessionCompactFailed(handler ExtensionHandlerNoResult[SessionCompactFailedEvent]) func()

	// OnSessionShutdown registers a handler for "session_shutdown".
	// upstream: types.ts:1083
	OnSessionShutdown(handler ExtensionHandlerNoResult[SessionShutdownEvent]) func()

	// OnSessionBeforeTree registers a handler for "session_before_tree".
	// upstream: types.ts:1084
	OnSessionBeforeTree(handler ExtensionHandler[SessionBeforeTreeEvent, SessionBeforeTreeResult]) func()

	// OnSessionTree registers a handler for "session_tree".
	// upstream: types.ts:1085
	OnSessionTree(handler ExtensionHandlerNoResult[SessionTreeEvent]) func()

	// OnContext registers a handler for "context".
	// upstream: types.ts:1086
	OnContext(handler ExtensionHandler[ContextEvent, ContextEventResult]) func()

	// OnContextWithSystem registers a handler for "context_with_system".
	// upstream: types.ts ExtensionAPI.on("context_with_system")
	OnContextWithSystem(handler ExtensionHandler[ContextWithSystemEvent, ContextEventResult]) func()

	// OnBeforeProviderRequest registers a handler for "before_provider_request".
	// upstream: types.ts:1087
	OnBeforeProviderRequest(handler ExtensionHandler[BeforeProviderRequestEvent, BeforeProviderRequestEventResult]) func()

	// OnAfterProviderResponse registers a handler for "after_provider_response".
	// upstream: types.ts:1091
	OnAfterProviderResponse(handler ExtensionHandlerNoResult[AfterProviderResponseEvent]) func()

	// OnBeforeProviderHeaders registers a handler for "before_provider_headers".
	// Handlers mutate evt.Headers in place before the request is sent.
	// upstream: types.ts:1199
	OnBeforeProviderHeaders(handler ExtensionHandlerNoResult[BeforeProviderHeadersEvent]) func()

	// OnProviderStreamEvent registers a handler for "provider_stream_event",
	// fired for a parsed provider stream event before it is normalized.
	// upstream: types.ts:1580 (on("provider_stream_event", ...))
	OnProviderStreamEvent(handler ExtensionHandlerNoResult[ProviderStreamEvent]) func()

	// OnBeforeAgentStart registers a handler for "before_agent_start".
	// upstream: types.ts:1092
	OnBeforeAgentStart(handler ExtensionHandler[BeforeAgentStartEvent, BeforeAgentStartEventResult]) func()

	// OnAgentStart registers a handler for "agent_start".
	// upstream: types.ts:1093
	OnAgentStart(handler ExtensionHandlerNoResult[AgentStartEvent]) func()

	// OnAgentEnd registers a handler for "agent_end".
	// upstream: types.ts:1399
	OnAgentEnd(handler ExtensionHandlerNoResult[AgentEndEvent]) func()

	// OnAgentBeforeSettle registers an awaited final-settlement boundary handler.
	// Handlers may propose durable entries and request one runnable continuation.
	// upstream: types.ts:1401
	OnAgentBeforeSettle(handler func(ctx context.Context, evt *AgentBeforeSettleEvent) (AgentBeforeSettleEventResult, error)) func()

	// OnAgentSettled registers a handler for "agent_settled", fired after an
	// agent run has fully settled (no retry, compaction, or queued continuation).
	// upstream: types.ts:1204
	OnAgentSettled(handler ExtensionHandlerNoResult[AgentSettledEvent]) func()

	// OnUiPromptStart registers a handler for "ui_prompt_start", fired
	// without awaiting handlers when the outermost blocking ctx.ui prompt
	// (select, confirm, input, editor, custom) begins.
	// upstream: types.ts:1404
	OnUiPromptStart(handler ExtensionHandlerNoResult[UIPromptStartEvent]) func()

	// OnUiPromptEnd registers a handler for "ui_prompt_end", fired without
	// awaiting handlers when the outermost blocking ctx.ui prompt settles.
	// upstream: types.ts:1405
	OnUiPromptEnd(handler ExtensionHandlerNoResult[UIPromptEndEvent]) func()

	// OnCacheWarmingDecision registers a handler that may override the scheduled prompt-cache refresh decision.
	// Handlers are awaited in registration order and the last explicit action wins.
	// upstream: types.ts:1589 (ExtensionHandler<CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult>)
	OnCacheWarmingDecision(handler ExtensionHandler[CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult]) func()

	// OnTurnStart registers a handler for "turn_start".
	// upstream: types.ts:1095
	OnTurnStart(handler ExtensionHandlerNoResult[TurnStartEvent]) func()

	// OnTurnEnd registers an awaited turn-boundary handler. Like OnAgentBeforeSettle, a handler may
	// propose durable entries and request one runnable continuation.
	// upstream: types.ts:1613 (ExtensionHandler<TurnEndEvent, TurnEndEventResult>)
	OnTurnEnd(handler ExtensionHandler[TurnEndEvent, TurnEndEventResult]) func()

	// OnMessageStart registers a handler for "message_start".
	// upstream: types.ts:1097
	OnMessageStart(handler ExtensionHandlerNoResult[MessageStartEvent]) func()

	// OnMessageUpdate registers a handler for "message_update".
	// upstream: types.ts:1098
	OnMessageUpdate(handler ExtensionHandlerNoResult[MessageUpdateEvent]) func()

	// OnMessageEnd registers a handler for "message_end".
	// upstream: types.ts:1099
	OnMessageEnd(handler ExtensionHandler[MessageEndEvent, MessageEndEventResult]) func()

	// OnToolExecutionStart registers a handler for "tool_execution_start".
	// upstream: types.ts:1100
	OnToolExecutionStart(handler ExtensionHandlerNoResult[ToolExecutionStartEvent]) func()

	// OnToolExecutionUpdate registers a handler for "tool_execution_update".
	// upstream: types.ts:1101
	OnToolExecutionUpdate(handler ExtensionHandlerNoResult[ToolExecutionUpdateEvent]) func()

	// OnToolExecutionEnd registers a handler for "tool_execution_end".
	// upstream: types.ts:1102
	OnToolExecutionEnd(handler ExtensionHandlerNoResult[ToolExecutionEndEvent]) func()

	// OnModelSelect registers a handler for "model_select".
	// upstream: types.ts:1103
	OnModelSelect(handler ExtensionHandlerNoResult[ModelSelectEvent]) func()

	// OnThinkingLevelSelect registers a handler for "thinking_level_select".
	// upstream: types.ts:1122 (added in v0.71.0).
	OnThinkingLevelSelect(handler ExtensionHandlerNoResult[ThinkingLevelSelectEvent]) func()

	// OnToolCall registers a handler for "tool_call". The event is the union
	// [ToolCallEvent]. Type-switch on its concrete variant.
	// upstream: types.ts:1104
	OnToolCall(handler ExtensionHandler[ToolCallEvent, ToolCallEventResult]) func()

	// OnToolResult registers a handler for "tool_result". The event is the
	// union [ToolResultEvent].
	// upstream: types.ts:1105
	OnToolResult(handler ExtensionHandler[ToolResultEvent, ToolResultEventResult]) func()

	// OnUserBash registers a handler for "user_bash".
	// upstream: types.ts:1106
	OnUserBash(handler ExtensionHandler[UserBashEvent, UserBashEventResult]) func()

	// OnInput registers a handler for "input".
	// upstream: types.ts:1107
	OnInput(handler ExtensionHandler[InputEvent, InputEventResult]) func()

	// RegisterTool registers a tool that the LLM can call.
	// upstream: types.ts:1114 (registerTool)
	RegisterTool(tool ToolDefinition)

	// RegisterCommand registers a custom command. Mirrors upstream's
	// `registerCommand(name, options: Omit<RegisteredCommand, "name" | "sourceInfo">)`.
	// upstream: types.ts:1123
	RegisterCommand(name string, options CommandOptions)

	// RegisterShortcut registers a keyboard shortcut.
	// upstream: types.ts:1126
	RegisterShortcut(shortcut KeyID, options ShortcutOptions)

	// RegisterFlag registers a CLI flag.
	// upstream: types.ts:1135
	RegisterFlag(name string, options FlagOptions)

	// GetFlag returns the value of a registered CLI flag. Upstream returns
	// `boolean | string | undefined`; Go returns `any` (nil when unset).
	// upstream: types.ts:1145
	GetFlag(name string) any

	// RegisterMessageRenderer registers a custom renderer for a CustomMessageEntry.
	// upstream: types.ts:1152
	RegisterMessageRenderer(customType string, renderer MessageRenderer)

	// RegisterEntryRenderer registers a custom renderer for a CustomEntry. Custom
	// entries do not participate in LLM context.
	// upstream: types.ts:1266
	RegisterEntryRenderer(customType string, renderer EntryRenderer)

	// RegisterToolRenderer chooses how tool calls are drawn. Resolvers run in
	// extension load order.
	// upstream: types.ts registerToolRenderer
	RegisterToolRenderer(resolver ToolRendererResolver)

	// RegisterMarkdownTransformer registers a display-only Markdown transform.
	// upstream: types.ts:1287
	RegisterMarkdownTransformer(transformer MarkdownTransformer)

	// SendMessage sends a custom message to the session. Pass nil options for defaults.
	// upstream: types.ts:1159
	SendMessage(message SendMessagePayload, options *SendMessageOptions)

	// SendUserMessage sends a user message to the agent. Always triggers a turn.
	// content is `string` or `[]any` carrying TextContent / ImageContent values
	// (matches upstream's `string | (TextContent | ImageContent)[]`).
	// upstream: types.ts:1168
	SendUserMessage(content any, options *SendUserMessageOptions)

	// AppendEntry appends a custom entry to the session for state persistence
	// (not sent to LLM).
	// upstream: types.ts:1174
	AppendEntry(customType string, data any)

	// SetSessionName sets the session display name (shown in session selector).
	// upstream: types.ts:1181
	SetSessionName(name string)

	// GetSessionName returns the current session name. Upstream returns
	// `string | undefined`; Go returns the empty string when unset.
	// upstream: types.ts:1184
	GetSessionName() string

	// SetLabel sets or clears a label on an entry. Pass empty string to clear.
	// upstream: types.ts:1187
	SetLabel(entryID string, label string)

	// Exec executes a shell command. Pass nil options for defaults. Upstream
	// returns `Promise<ExecResult>`; Go returns `(ExecResult, error)`.
	// Cancellation flows through `options.Signal` (which is a context.Context
	// after the D3 migration; see docs/parity/DIVERGENCES.md).
	// upstream: types.ts:1190
	Exec(command string, args []string, options *ExecOptions) (ExecResult, error)

	// GetActiveTools returns the names of the active tools, which are the tools
	// declared to the model.
	// upstream: types.ts:1193
	GetActiveTools() []string

	// GetAllTools returns all configured tools with parameter schema, prompt
	// guidelines, exposure, and source metadata.
	// upstream: types.ts:1196
	GetAllTools() []ToolInfo

	// GetSettings returns a copy of the effective settings (global and project
	// settings merged, with overrides).
	// upstream: types.ts:1708 (getSettings)
	GetSettings() Settings

	// SetActiveTools sets the active tools by name. Unknown and `hidden` tools
	// are ignored. Tools with `codemode` or `deferred` exposure stay callable
	// from codemode scripts whether active or not.
	// upstream: types.ts:1199
	SetActiveTools(toolNames []string)

	// GetCommands returns the available slash commands in the current session.
	// upstream: types.ts:1202
	GetCommands() []SlashCommandInfo

	// SetModel sets the current model. Upstream returns
	// `Promise<boolean>` (false when no API key available); Go returns
	// `(bool, error)`: error is non-nil only on host-side failures.
	// upstream: types.ts:1209
	SetModel(model Model) (bool, error)

	// GetThinkingLevel returns the current thinking level.
	// upstream: types.ts:1212
	GetThinkingLevel() ThinkingLevel

	// SetThinkingLevel sets the thinking level (clamped to model capabilities).
	// upstream: types.ts:1215
	SetThinkingLevel(level ThinkingLevel)

	// RegisterProvider registers or overrides a model provider. See [ProviderConfig]
	// for the field-level semantics (upstream JSDoc preserved).
	// upstream: types.ts:1264
	RegisterProvider(name string, config ProviderConfig)

	// RegisterNativeProvider is the Provider-object overload of RegisterProvider: it registers a provider whose
	// auth, model listing and streaming are its own functions ([ai.ModelsProvider] is Pi's Provider).
	// upstream: types.ts:1830 registerProvider(provider: Provider), loader.ts:456-464
	RegisterNativeProvider(provider *ai.ModelsProvider)

	// UnregisterProvider unregisters a previously registered provider. Has
	// no effect if the provider is not currently registered.
	// upstream: types.ts:1280
	UnregisterProvider(name string)

	// RegisterMcpServer registers an MCP server for this session, with the same
	// config as an `mcpServers` entry in `mcp.json`. The server connects next to
	// the configured servers: on session_start when registered during extension
	// load, right away when registered later. Registering a name again replaces
	// the extension's earlier registration.
	//
	// The registration is not saved; register again on every load. A server of
	// the same name in `mcp.json` takes precedence. It returns an error for
	// invalid configs and for names another extension registered (upstream
	// throws). When no loaded extension handles MCP servers (for example because
	// another MCP extension replaced the built-in one), the registration is
	// reported as an extension error.
	// upstream: types.ts:1833 (registerMcpServer)
	RegisterMcpServer(name string, config McpServerConfig) error

	// UnregisterMcpServer removes an MCP server this extension registered and
	// closes its connection.
	// upstream: types.ts:1836 (unregisterMcpServer)
	UnregisterMcpServer(name string)

	// GetMcpServers returns every MCP server registered by extensions, for
	// extensions that connect MCP servers.
	// upstream: types.ts:1839 (getMcpServers)
	GetMcpServers() []RegisteredMcpServer

	// RegisterVirtualModel registers a virtual model: a selectable catalog entry
	// that routes each request to a physical model. The selection (`ctx.model`,
	// `model_change` entries) names the virtual model; assistant messages record
	// the physical model and thinking level the router picked.
	//
	// The provider may be any provider id, including one with physical models,
	// and may list several virtual models. Registering the same provider and id
	// again replaces the virtual model. See docs/virtual-models.md.
	// upstream: types.ts:1852 (registerVirtualModel)
	RegisterVirtualModel(model ExtensionVirtualModel)

	// UnregisterVirtualModel removes a virtual model registered with
	// [API.RegisterVirtualModel].
	// upstream: types.ts:1855 (unregisterVirtualModel)
	UnregisterVirtualModel(provider, id string)

	// Events returns the shared event bus for extension communication.
	//
	// pig translation rule (interface property → method): upstream exposes
	// this as the property `events: EventBus`. Go interfaces cannot have
	// fields, so the API surfaces a method that returns the host's single
	// shared instance. See docs/parity/DIVERGENCES.md "TS→Go translation rituals".
	// upstream: types.ts:1283
	Events() EventBus
}

API is the surface passed to extension factory functions. It mirrors upstream's `ExtensionAPI` interface 1:1: every event registrable via upstream's `pi.on(event, handler)` overload has a typed `On<Event>` method here, every other method on `ExtensionAPI` has a Go counterpart (camelCase → PascalCase), and the upstream `events: EventBus` property surfaces as the API.Events method.

Method order matches upstream declaration order so a side-by-side review against types.ts is mechanical. Every method's doc comment cites its upstream line in `types.ts`.

Go mapping:

  • Every On<Event> method returns the function that removes its handler, as upstream's `on` returns `() => void`; calling it again does nothing.
  • Events is a method because Go interfaces cannot contain fields.
  • Handlers receive context.Context and return errors.

upstream: types.ts:1066–1296

type AbortSignal deprecated

type AbortSignal = context.Context

AbortSignal was the upstream cancellation primitive (DOM AbortSignal). Pig uses context.Context for cancellation (see docs/parity/DIVERGENCES.md D3). This deprecated alias preserves source compatibility while giving callers the real cancellation contract instead of an untyped value.

Deprecated: use context.Context.

type AfterProviderResponseEvent

type AfterProviderResponseEvent struct {
	Type    string            `json:"type"`
	Status  int               `json:"status"`
	Headers map[string]string `json:"headers"`
}

AfterProviderResponseEvent: upstream types.ts AfterProviderResponseEvent.

type AgentActivityOutcome

type AgentActivityOutcome string

AgentActivityOutcome mirrors upstream's completed/aborted/error boundary state.

const (
	AgentActivityCompleted AgentActivityOutcome = "completed"
	AgentActivityAborted   AgentActivityOutcome = "aborted"
	AgentActivityError     AgentActivityOutcome = "error"
)

type AgentBeforeSettleEvent

type AgentBeforeSettleEvent struct {
	Type string `json:"type"`
	BoundaryState
}

AgentBeforeSettleEvent: upstream types.ts AgentBeforeSettleEvent. It is awaited after retry, recovery, compaction, and queued continuations stop.

func (AgentBeforeSettleEvent) MarshalJSON

func (e AgentBeforeSettleEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the members in Pi's order: type, outcome, then the boundary's entries, continue and context (extensions/runner.ts emitBoundary).

type AgentBeforeSettleEventResult

type AgentBeforeSettleEventResult = BoundaryResult

AgentBeforeSettleEventResult mirrors upstream's BoundaryResult alias.

type AgentEndEvent

type AgentEndEvent struct {
	Type     string         `json:"type"`
	Messages []AgentMessage `json:"messages"`
}

AgentEndEvent: upstream types.ts AgentEndEvent.

type AgentMessage

type AgentMessage = agent.AgentMessage

AgentMessage mirrors @earendil-works/pi-agent-core AgentMessage.

type AgentSettledEvent

type AgentSettledEvent struct {
	Type string `json:"type"`
	// Aborted is whether the run ended because it was aborted, for example with Escape.
	Aborted bool `json:"aborted"`
}

AgentSettledEvent: upstream types.ts AgentSettledEvent. Fired after an agent run has fully settled and no automatic retry, compaction, or queued continuation will run.

type AgentStartEvent

type AgentStartEvent struct {
	Type string `json:"type"`
}

AgentStartEvent: upstream types.ts AgentStartEvent.

type AgentTool

type AgentTool struct {
	Name                string            `json:"name"`
	Label               string            `json:"label"`
	Description         string            `json:"description"`
	Parameters          json.RawMessage   `json:"parameters"`
	OutputSchema        json.RawMessage   `json:"outputSchema,omitempty"`
	ConstrainedSampling json.RawMessage   `json:"constrainedSampling,omitempty"`
	ExecutionMode       ToolExecutionMode `json:"executionMode,omitempty"`
}

AgentTool is the read-only view of a tool that a tool call sees through ToolContext.Tools and ToolLoadout. Go mechanic (not a divergence): upstream's AgentTool carries `execute`. A tool runs only through ToolContext.ExecuteTool, so the view holds the declaration fields and no function.

upstream: .upstream/v0.99.1/packages/agent/src/types.ts (AgentTool)

type AgentToolCall

type AgentToolCall = ai.ToolCall

AgentToolCall mirrors pi-agent-core AgentToolCall: the tool call block a tool call runs for.

type AgentToolCallOutcome

type AgentToolCallOutcome struct {
	ToolCall AgentToolCall   `json:"toolCall"`
	Result   AgentToolResult `json:"result"`
	IsError  bool            `json:"isError"`
	// DurationMs is the milliseconds execute() took, measured with a monotonic clock; absent when the tool did not run. upstream: agent/src/types.ts:454 AgentToolCallOutcome.durationMs
	DurationMs *int64 `json:"durationMs,omitempty"`
}

AgentToolCallOutcome mirrors pi-agent-core AgentToolCallOutcome: the final outcome of a tool call after the hooks ran.

upstream: .upstream/v0.99.1/packages/agent/src/types.ts (AgentToolCallOutcome)

type AgentToolResult

type AgentToolResult = agent.AgentToolResult

AgentToolResult mirrors @earendil-works/pi-agent-core AgentToolResult<TDetails>.

type AgentToolUpdateCallback

type AgentToolUpdateCallback = agent.ToolUpdateCallback

AgentToolUpdateCallback mirrors AgentToolUpdateCallback<TDetails>.

type ArgumentCompletionsFunc

type ArgumentCompletionsFunc = func(argumentPrefix string) ([]AutocompleteItem, error)

ArgumentCompletionsFunc mirrors upstream's getArgumentCompletions callback on RegisteredCommand. Returns a list of completion items, or nil to fall through to the default provider.

pig translation rule (Promise<T[] | null> → ([]T, error)): upstream returns `AutocompleteItem[] | null | Promise<AutocompleteItem[] | null>`. The Go signature returns the slice + error directly; if the host needs cancellation it wraps the call in a goroutine + ctx.Done() select: same shape upstream takes (the function has no signal/ctx parameter upstream either).

type AssistantMessageEvent

type AssistantMessageEvent = any

AssistantMessageEvent mirrors @earendil-works/pi-ai AssistantMessageEvent.

type AssistantMessageEventStream

type AssistantMessageEventStream = *ai.AssistantMessageEventStream

AssistantMessageEventStream mirrors AssistantMessageEventStream.

type AttributedResourcePath

type AttributedResourcePath struct {
	Path          string `json:"path"`
	ExtensionPath string `json:"extensionPath"`
}

AttributedResourcePath pairs a resource path with the extension that declared it. Used by EmitResourcesDiscover to surface where each skill/prompt/theme path came from.

upstream: anonymous type at runner.ts:944-947

skillPaths: Array<{ path: string; extensionPath: string }>;

pig names this type because Go's anonymous-type composition is less ergonomic than TS's; same wire shape.

type AutocompleteCompletion

type AutocompleteCompletion struct {
	Lines      []string `json:"lines"`
	CursorLine int      `json:"cursorLine"`
	CursorCol  int      `json:"cursorCol"`
}

AutocompleteCompletion carries the complete replacement and UTF-16 cursor position returned by a provider.

type AutocompleteItem

type AutocompleteItem struct {
	Value       string `json:"value"`
	Label       string `json:"label,omitempty"`
	Description string `json:"description,omitempty"`
}

AutocompleteItem mirrors @earendil-works/pi-tui AutocompleteItem.

Concrete shape so subprocess autocomplete responses can deserialise into a typed value the host can pass to the TUI editor without an extra translation step.

type AutocompleteProvider

type AutocompleteProvider struct {
	TriggerCharacters           []string
	GetSuggestions              func(context.Context, []string, int, int, bool) (*AutocompleteSuggestions, error)
	ApplyCompletion             func(context.Context, []string, int, int, AutocompleteItem, string) (AutocompleteCompletion, error)
	ShouldTriggerFileCompletion func(context.Context, []string, int, int) (bool, error)
}

AutocompleteProvider mirrors @earendil-works/pi-tui AutocompleteProvider.

func SetupAutocompleteProvider

func SetupAutocompleteProvider(ctx context.Context, base *AutocompleteProvider, factories []AutocompleteProviderFactory) (*AutocompleteProvider, error)

SetupAutocompleteProvider folds retained factories over a fresh base and merges their trigger characters in first-seen order.

type AutocompleteProviderFactory

type AutocompleteProviderFactory func(context.Context, *AutocompleteProvider) (*AutocompleteProvider, error)

AutocompleteProviderFactory mirrors upstream AutocompleteProviderFactory.

type AutocompleteSuggestions

type AutocompleteSuggestions struct {
	Items  []AutocompleteItem `json:"items"`
	Prefix string             `json:"prefix"`
}

AutocompleteSuggestions mirrors @earendil-works/pi-tui AutocompleteSuggestions.

type BashOperations

type BashOperations interface {
	Exec(ctx context.Context, command, cwd string, options BashOperationsExecOptions) (BashOperationsResult, error)
}

BashOperations mirrors upstream BashOperations (core/tools/bash.ts): pluggable command execution, local by default and remote (for example SSH) when an extension supplies it, such as from a user_bash handler's { operations } result. Exec returns an error whose message is "aborted" when ctx was cancelled and "timeout:<seconds>" when the timeout fired, as upstream's callers match on those messages.

type BashOperationsExecOptions

type BashOperationsExecOptions struct {
	// OnData receives raw output bytes (stdout and stderr) as they arrive,
	// from one goroutine at a time. The slice is valid only during the call
	// (the local operations lend their pipe read buffer); copy what you keep.
	OnData func(data []byte)
	// Timeout is the requested timeout in seconds; nil means none.
	Timeout *float64
	// Env replaces the inherited environment when non-nil.
	Env []string
}

BashOperationsExecOptions mirrors the options upstream BashOperations.exec receives (core/tools/bash.ts). Cancellation is the context.

type BashOperationsResult

type BashOperationsResult struct {
	ExitCode *int
}

BashOperationsResult mirrors upstream { exitCode: number | null }: a signal termination reports 128 + the signal number, and nil is a failed command.

type BashResult

type BashResult = any

BashResult mirrors core/bash-executor.BashResult. A native result must contain exitCode; its nil value represents undefined, not JSON null. A nil optional fullOutputPath is also undefined. Pre-encoded JSON retains its own null values.

type BashToolDetails

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

BashToolDetails mirrors upstream bash.ts:31. Attached only when output was truncated.

type BashToolInput

type BashToolInput struct {
	Command string   `json:"command"`
	Timeout *float64 `json:"timeout,omitempty"`
	// Extra holds members the schema does not declare; upstream's input is a plain object that keeps them.
	Extra map[string]json.RawMessage `json:"-"`
}

BashToolInput is upstream's BashToolInput (bash.ts bashSchema).

func (BashToolInput) MarshalJSON

func (in BashToolInput) MarshalJSON() ([]byte, error)

func (*BashToolInput) UnmarshalJSON

func (in *BashToolInput) UnmarshalJSON(data []byte) error

type BashToolResultEvent

type BashToolResultEvent struct {
	ToolResultEventBase
	ToolName string           `json:"toolName"` // "bash"
	Details  *BashToolDetails `json:"details,omitempty"`
}

BashToolResultEvent: upstream types.ts BashToolResultEvent.

func (BashToolResultEvent) MarshalJSON

func (e BashToolResultEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the event in Pi's member order; see [marshalToolResultEvent].

type BeforeAgentStartCombinedResult

type BeforeAgentStartCombinedResult struct {
	// Messages is the slice of custom messages collected from every
	// handler that returned `result.message`. Empty when no handler
	// pushed a message.
	Messages []CustomMessageRef `json:"messages,omitempty"`

	// SystemPrompt is the final mutated system prompt, non-nil only if at
	// least one handler set `result.systemPrompt` (an empty prompt included).
	SystemPrompt *string `json:"systemPrompt,omitempty"`

	// SystemPromptOptions is the per-run options object the handlers shared. It is set when the incoming options or a handler supplied sections, or a handler edited selectedTools. It does not alias the caller's base options.
	SystemPromptOptions *BuildSystemPromptOptions `json:"systemPromptOptions,omitempty"`

	// SelectedToolsEdited retains an explicit edit even when filtering non-string registry misses produces the original list.
	SelectedToolsEdited bool `json:"-"`
}

BeforeAgentStartCombinedResult is the aggregated result from all before_agent_start handlers. Returned by the runner's EmitBeforeAgentStart.

upstream: runner.ts:103-107 (interface BeforeAgentStartCombinedResult)

interface BeforeAgentStartCombinedResult {
	messages?: NonNullable<BeforeAgentStartEventResult["message"]>[];
	systemPrompt?: string;
}

Upstream declares this type as `interface` private to runner.ts; pig exports it because Go callers need to type-assert on it after EmitBeforeAgentStart returns. Field semantics match upstream verbatim.

type BeforeAgentStartEvent

type BeforeAgentStartEvent struct {
	Type string
	// MessageType is BeforeAgentStartUser or BeforeAgentStartCustom; empty is a user run.
	MessageType BeforeAgentStartMessageType
	Prompt      string
	Images      []ImageContent
	Message     *CustomMessage
	// SystemPrompt is Pi's event.systemPrompt getter: Get renders the run's shared options when read, so a handler sees its own edits through BeforeAgentStartOptions at once.
	SystemPrompt *SystemPrompt
	// SystemPromptOptions is the per-handler value view of the run's options. Use BeforeAgentStartOptions with the dispatch context to replace collections on the shared per-run object.
	SystemPromptOptions BuildSystemPromptOptions
}

BeforeAgentStartEvent: upstream types.ts:932-957 BeforeAgentStartEvent, the union of BeforeAgentStartUserEvent (a submitted prompt, an RPC prompt or sendUserMessage: Prompt and Images) and BeforeAgentStartCustomEvent (sendMessage with triggerTurn while idle: Message), told apart by MessageType.

func (BeforeAgentStartEvent) MarshalJSON

func (e BeforeAgentStartEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the run's trigger members, then type, systemPromptOptions and systemPrompt, the order Pi's event has (V8 defines the getter of runner.ts's object literal, which spreads the trigger, after its data members). systemPrompt is the prompt the options render now.

type BeforeAgentStartEventResult

type BeforeAgentStartEventResult struct {
	Message *CustomMessageRef `json:"message,omitempty"`
	// SystemPrompt replaces the run's system prompt when set, including when
	// it is empty; nil leaves it unchanged (upstream `systemPrompt?: string`).
	SystemPrompt *string `json:"systemPrompt,omitempty"`
}

BeforeAgentStartEventResult: upstream types.ts BeforeAgentStartEventResult.

type BeforeAgentStartMessageType

type BeforeAgentStartMessageType string

BeforeAgentStartMessageType names what started a run: the discriminator of upstream types.ts:932-957's BeforeAgentStartEvent union, "user" | "custom".

const (
	// BeforeAgentStartUser is a run started by a submitted prompt, an RPC prompt or sendUserMessage.
	BeforeAgentStartUser BeforeAgentStartMessageType = "user"
	// BeforeAgentStartCustom is a run started by sendMessage with triggerTurn while idle.
	BeforeAgentStartCustom BeforeAgentStartMessageType = "custom"
)

BeforeAgentStartMessageType values name what started the run.

type BeforeAgentStartTrigger

type BeforeAgentStartTrigger struct {
	// MessageType is BeforeAgentStartUser or BeforeAgentStartCustom; empty is a user run.
	MessageType BeforeAgentStartMessageType
	Prompt      string
	Images      []ImageContent
	Message     *CustomMessage
}

BeforeAgentStartTrigger is the message that starts a run: upstream runner.ts:169-171 BeforeAgentStartTrigger, the before_agent_start event's messageType with its prompt and images or its custom message.

func CustomMessageTrigger

func CustomMessageTrigger(message CustomMessage) BeforeAgentStartTrigger

CustomMessageTrigger is the trigger of a run that an idle sendMessage with triggerTurn starts.

func UserPromptTrigger

func UserPromptTrigger(prompt string, images []ImageContent) BeforeAgentStartTrigger

UserPromptTrigger is the trigger of a run that a user message starts.

type BeforeProviderHeadersEvent

type BeforeProviderHeadersEvent struct {
	Type    string          `json:"type"`
	Headers ProviderHeaders `json:"headers"`
}

BeforeProviderHeadersEvent: upstream types.ts BeforeProviderHeadersEvent. Handlers mutate Headers in place before the request is sent.

type BeforeProviderRequestEvent

type BeforeProviderRequestEvent struct {
	Type    string `json:"type"`
	Payload any    `json:"payload"`
}

BeforeProviderRequestEvent: upstream types.ts BeforeProviderRequestEvent.

type BeforeProviderRequestEventResult

type BeforeProviderRequestEventResult = any

BeforeProviderRequestEventResult: upstream type alias for `unknown`.

type BoundaryBaseEvent

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

BoundaryBaseEvent is the closed input union of actionable turn_end and agent_before_settle events. The runner supplies each handler's proposal and preview.

type BoundaryContextPreview

type BoundaryContextPreview struct {
	ContextEntries  []ProjectedSessionEntry `json:"contextEntries"`
	ContextMessages []AgentMessage          `json:"contextMessages"`
	LLMMessages     []ai.Message            `json:"llmMessages"`
	PendingMessages []AgentMessage          `json:"pendingMessages"`
	CanContinue     bool                    `json:"canContinue"`
}

BoundaryContextPreview is the recomputed session/model context after the currently proposed entries.

type BoundaryResult

type BoundaryResult struct {
	Entries  *[]SessionBoundaryDraft `json:"entries,omitempty"`
	Continue *bool                   `json:"continue,omitempty"`
}

BoundaryResult chains proposed entries and explicit continuation. Pointer fields preserve omitted versus explicit empty/false results.

type BoundaryState

type BoundaryState struct {
	Entries  []SessionBoundaryDraft `json:"entries"`
	Continue bool                   `json:"continue"`
	Context  BoundaryContextPreview `json:"context"`
	Outcome  AgentActivityOutcome   `json:"outcome"`
}

BoundaryState is shared by turn_end and agent_before_settle upstream.

type BranchSummaryEntry

type BranchSummaryEntry = sessionentry.BranchSummaryEntry

BranchSummaryEntry mirrors core/session-manager BranchSummaryEntry.

type BuildSystemPromptOptions

type BuildSystemPromptOptions struct {
	// CustomPrompt is the user-supplied prompt that replaces the default
	// (from --system-prompt, SYSTEM.md, or custom templates).
	CustomPrompt string `json:"customPrompt,omitempty"`
	// CustomPromptSet preserves a present empty customPrompt without changing the existing string field. A nonempty CustomPrompt is always present.
	CustomPromptSet bool `json:"-"`
	// ForceSystemPrompt is the exact full prompt a before_agent_start handler returned as systemPrompt; later handlers observe it (runner.ts:1346-1348). Nil is Pi's undefined; an empty string is a forced empty prompt.
	ForceSystemPrompt *string `json:"forceSystemPrompt,omitempty"`
	// SelectedTools is the list of tool names included in the prompt.
	// Defaults upstream to [read, bash, edit, write].
	SelectedTools []string `json:"selectedTools,omitzero"`
	// HiddenTools are the selected tools whose declarations requests leave out (`prepareLoadout` hidden declarations). They are
	// reachable only through another tool, so the tool list and rules leave them out too. The Session sets it before every
	// request; an edit by a handler does not change what the request carries.
	HiddenTools []string `json:"hiddenTools,omitzero"`
	// ToolSnippets maps tool name → one-line description used in the
	// "Available tools" section.
	ToolSnippets map[string]string `json:"toolSnippets,omitzero"`
	// ToolGuidelines contributes rules only while its tool is active.
	ToolGuidelines map[string][]string `json:"toolGuidelines,omitzero"`
	// PromptGuidelines holds bullet lines appended to the default
	// guidelines section.
	PromptGuidelines []string `json:"promptGuidelines,omitzero"`
	// AppendSystemPrompt is the joined text appended after the main
	// prompt body (from --append-system-prompt flags / settings).
	AppendSystemPrompt string `json:"appendSystemPrompt"`
	// Sections holds additional XML-wrapped sections in authored order. Event handlers mutate the per-run collection, not the Session's base options.
	Sections *ai.OrderedSections `json:"sections,omitempty"`
	// Cwd is the working directory shown to the LLM.
	Cwd string `json:"cwd"`
	// ContextFiles are pre-loaded AGENTS.md / CLAUDE.md files in the
	// order they appear in the prompt.
	ContextFiles []SystemPromptContextFile `json:"contextFiles,omitzero"`
	// Skills lists skills surfaced in the prompt's skills section.
	Skills []SystemPromptSkill `json:"skills,omitzero"`
}

BuildSystemPromptOptions mirrors upstream `core/system-prompt.ts::BuildSystemPromptOptions`.

Extensions receive this struct on every `before_agent_start` event via `event.systemPromptOptions` so they can inspect what pi has already assembled (custom prompt, tools, append text, context files, skills) without re-discovering resources.

Extensions receive upstream's NormalizedBuildSystemPromptOptions (system-prompt.ts:37-46): every collection is present, so an empty selectedTools is `[]`, not an omitted key. MarshalJSON writes that shape; the struct tags describe only decoding.

upstream: packages/coding-agent/src/core/system-prompt.ts:9-69

func BeforeAgentStartOptions

func BeforeAgentStartOptions(ctx context.Context) *BuildSystemPromptOptions

BeforeAgentStartOptions returns the shared per-run options during before_agent_start, or nil outside that dispatch. Assign collection replacements through this pointer; edits remain visible to later handlers even when the handler returns an error. The pointer never aliases the Session's base options.

func NormalizeBuildSystemPromptOptions

func NormalizeBuildSystemPromptOptions(input BuildSystemPromptOptions) BuildSystemPromptOptions

NormalizeBuildSystemPromptOptions supplies the collection-complete shape exposed to extensions while copying the per-run mutable collections.

Ports packages/coding-agent/src/core/system-prompt.ts

func (BuildSystemPromptOptions) MarshalJSON

func (o BuildSystemPromptOptions) MarshalJSON() ([]byte, error)

MarshalJSON writes the collection-complete shape that upstream's normalizeBuildSystemPromptOptions (system-prompt.ts:48-64) exposes to extensions: empty collections stay present, while customPrompt is omitted when it is undefined.

func (*BuildSystemPromptOptions) UnmarshalJSON

func (o *BuildSystemPromptOptions) UnmarshalJSON(data []byte) error

UnmarshalJSON retains customPrompt presence for command and event option round trips.

type CacheWarmingAction

type CacheWarmingAction string

CacheWarmingAction selects whether the scheduled prompt-cache refresh runs.

const (
	CacheWarmingActionWarm CacheWarmingAction = "warm"
	CacheWarmingActionStop CacheWarmingAction = "stop"
)

type CacheWarmingDecisionEvent

type CacheWarmingDecisionEvent struct {
	Type                    string             `json:"type"`
	WarmCost                float64            `json:"warmCost"`
	MissCost                float64            `json:"missCost"`
	ContinuationProbability float64            `json:"continuationProbability"`
	Action                  CacheWarmingAction `json:"action"`
}

CacheWarmingDecisionEvent carries the economics and default action before a cache refresh.

type CacheWarmingDecisionEventResult

type CacheWarmingDecisionEventResult struct {
	Action *CacheWarmingAction `json:"action,omitempty"`
}

CacheWarmingDecisionEventResult overrides the decision when Action is present.

type CallOrder

type CallOrder struct {
	Wait    func()
	Release func()
}

CallOrder is a reserved place in a tool's call order. Pi runs each call's synchronous prefix in call order, so `Promise.all([tools.a(), tools.b()])` issues `a` first; Go's goroutines give no such order, so the host reserves each call's place in call order (ToolDefinition.ReserveCallOrder) and a call issues its request only after every earlier reservation released. Wait returns when every earlier reservation was released; Release, which is idempotent, hands the place on and must run however the call ends.

func CallOrderFromContext

func CallOrderFromContext(ctx context.Context) (*CallOrder, bool)

CallOrderFromContext returns the reservation the host made for this call, if any.

type CancelledResult

type CancelledResult struct {
	Cancelled bool `json:"cancelled"`
}

CancelledResult is the return type for session-mutation commands (newSession, fork, navigateTree, switchSession). Upstream returns `{ cancelled: boolean }`: Go uses a named struct for clarity.

upstream: types.ts (inline `Promise<{ cancelled: boolean }>` on each method)

type Capability

type Capability = string

Capability is a typed string for well-known extension capability names. Authors may use unknown strings; hosts only enforce the well-known set.

const (
	CapOnEvent           Capability = "onEvent" // umbrella for all on*() subscribers
	CapRegisterTool      Capability = "registerTool"
	CapRegisterCommand   Capability = "registerCommand"
	CapRegisterShortcut  Capability = "registerShortcut"
	CapRegisterFlag      Capability = "registerFlag"
	CapRegisterRenderer  Capability = "registerMessageRenderer"
	CapRegisterProvider  Capability = "registerProvider"
	CapSendMessage       Capability = "sendMessage"
	CapSendUserMessage   Capability = "sendUserMessage"
	CapAppendEntry       Capability = "appendEntry"
	CapSessionMetadata   Capability = "sessionMetadata"
	CapExec              Capability = "exec"
	CapToolIntrospection Capability = "toolIntrospection"
	CapModelControl      Capability = "modelControl"
	CapThinkingLevel     Capability = "thinkingLevel"
	CapEvents            Capability = "events" // EventBus pub/sub
)

Well-known capability names. These mirror the extension API surface groups.

type CommandActions

type CommandActions struct {
	// WaitForIdle blocks until the agent finishes streaming.
	WaitForIdle        func() error
	WaitForIdleContext func(context.Context) error
	// WaitForIdleBlocks reports whether WaitForIdle would wait now. A mode that settles an idle wait at once, as Pi's `if (this.isIdle) return`, binds it so the host does not count the calling command as suspended; nil means it waits.
	WaitForIdleBlocks func() bool

	// NewSession starts a new session.
	NewSession        func(opts *NewSessionOptions) (CancelledResult, error)
	NewSessionContext func(context.Context, *NewSessionOptions) (CancelledResult, error)

	// Fork creates a new branch from entryId.
	Fork        func(entryID string, opts *ForkOptions) (CancelledResult, error)
	ForkContext func(context.Context, string, *ForkOptions) (CancelledResult, error)

	// NavigateTree moves to a different point in the session tree.
	NavigateTree        func(targetID string, opts *NavigateTreeOptions) (CancelledResult, error)
	NavigateTreeContext func(context.Context, string, *NavigateTreeOptions) (CancelledResult, error)

	// SwitchSession switches to a different session file.
	SwitchSession        func(sessionPath string, opts *SwitchSessionOptions) (CancelledResult, error)
	SwitchSessionContext func(context.Context, string, *SwitchSessionOptions) (CancelledResult, error)

	// Reload reloads extensions, skills, prompts, themes.
	Reload        func() error
	ReloadContext func(context.Context) error
}

CommandActions is the host-side injection of command-specific callbacks. These are the extra surfaces available only in command handlers (via CommandContext), not in event handlers.

Mirrors upstream ExtensionCommandContextActions (types.ts:1484-1506). All fields are optional; nil functions produce safe no-ops.

upstream: types.ts:1484-1506

type CommandContext

type CommandContext struct {
	*Context
	// contains filtered or unexported fields
}

CommandContext extends Context with command-specific actions available only inside slash-command handlers. Mirrors upstream ExtensionCommandContext (types.ts:328-363).

Retrieve from a context.Context via CommandContextFromContext.

upstream: runner.ts:736-772 (createCommandContext)

func CommandContextFromContext

func CommandContextFromContext(ctx context.Context) *CommandContext

CommandContextFromContext retrieves the CommandContext attached by WithCommandContext. Returns nil if none is set.

func NewCommandContext

func NewCommandContext(base *Context, cmdActions CommandActions) *CommandContext

NewCommandContext constructs a CommandContext from the base context and command-specific actions. Called by the runner when dispatching a slash command registered by an extension. SendUserMessage is inherited from the base Context, which carries it for every dispatch.

upstream: runner.ts:736-772

func (*CommandContext) Fork

func (c *CommandContext) Fork(entryID string, opts *ForkOptions) (CancelledResult, error)

Fork creates a new branch from entryID.

func (*CommandContext) GetSystemPromptOptions

func (c *CommandContext) GetSystemPromptOptions() (*BuildSystemPromptOptions, error)

GetSystemPromptOptions returns the base inputs pi currently uses to build the system prompt (custom prompt, active tools, tool snippets, prompt guidelines, appended text, cwd, loaded context files, and skills). It reports the current base inputs only; it does not include per-turn before_agent_start chained changes, later context-event message mutations, or before_provider_request rewrites.

When no data source is wired, returns zero-value options carrying the runner cwd, matching upstream's `getSystemPromptOptions ?? (() => ({ cwd: this.cwd }))` default.

upstream: runner.ts:653-656 (createCommandContext getSystemPromptOptions), types.ts:339

func (*CommandContext) NavigateTree

func (c *CommandContext) NavigateTree(targetID string, opts *NavigateTreeOptions) (CancelledResult, error)

NavigateTree moves to a different point in the session tree.

func (*CommandContext) NewSession

func (c *CommandContext) NewSession(opts *NewSessionOptions) (CancelledResult, error)

NewSession starts a new session.

func (*CommandContext) Reload

func (c *CommandContext) Reload() error

Reload reloads extensions, skills, prompts, themes.

func (*CommandContext) SwitchSession

func (c *CommandContext) SwitchSession(sessionPath string, opts *SwitchSessionOptions) (CancelledResult, error)

SwitchSession switches to a different session file.

func (*CommandContext) WaitForIdle

func (c *CommandContext) WaitForIdle() error

WaitForIdle blocks until the agent finishes streaming.

type CommandHandler

type CommandHandler = func(ctx context.Context, args string) error

CommandHandler is invoked when an extension command is run. Mirrors upstream's RegisteredCommand.handler signature.

CommandHandler receives cancellation and per-extension values through the Go context. Use FromContext to access the extension context.

type CommandOptions

type CommandOptions struct {
	Description            string                  `json:"description,omitempty"`
	GetArgumentCompletions ArgumentCompletionsFunc `json:"-"`
	Handler                CommandHandler          `json:"-"`
}

CommandOptions is the registration payload for API.RegisterCommand : upstream's `Omit<RegisteredCommand, "name" | "sourceInfo">`.

type CompactOptions

type CompactOptions struct {
	CustomInstructions string                        `json:"customInstructions,omitempty"`
	OnComplete         func(result CompactionResult) `json:"-"`
	OnError            func(err error)               `json:"-"`
}

CompactOptions mirrors upstream `CompactOptions` (types.ts:284-288). Configures a compaction operation triggered via Context.Compact.

  • CustomInstructions: optional user-provided guidance for the summarization model.
  • OnComplete: callback invoked with the CompactionResult once the async compaction finishes. Nil disables the callback (fire-and- forget).
  • OnError: callback invoked when compaction fails. Nil routes the error to the runner's error listeners.

upstream: types.ts:284-288

type CompactionEntry

type CompactionEntry = sessionentry.CompactionEntry

CompactionEntry mirrors core/session-manager CompactionEntry (types.ts:786 SessionCompactEvent.compactionEntry).

type CompactionPreparation

type CompactionPreparation = compactiontypes.CompactionPreparation

CompactionPreparation mirrors core/compaction CompactionPreparation.

type CompactionResult

type CompactionResult struct {
	Summary              string    `json:"summary"`
	FirstKeptEntryID     string    `json:"firstKeptEntryId"`
	TokensBefore         int       `json:"tokensBefore"`
	EstimatedTokensAfter *int      `json:"estimatedTokensAfter,omitempty"`
	Usage                *ai.Usage `json:"usage,omitempty"`
	Details              any       `json:"details,omitempty"`
}

CompactionResult is the result of a compaction (core/compaction/compaction.ts:105 CompactionResult<T = unknown>). Details is the extension-specific data T.

func (*CompactionResult) UnmarshalJSON

func (r *CompactionResult) UnmarshalJSON(data []byte) error

UnmarshalJSON keeps the member order of the `details` object the extension wrote.

type Component

type Component = tui.Component

Component is @earendil-works/pi-tui Component: what a renderer or widget factory returns (a subprocess extension's is a proxy that renders the extension's lines over the wire).

type Context

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

Context is the per-extension runtime context. Mirrors upstream's ExtensionContext (types.ts:ExtensionContext).

Authors retrieve the Context from a context.Context via FromContext. The host attaches it at event-dispatch time using WithContext.

Go carries cancellation and per-extension values through one context.Context. Authors retrieve the extension Context with FromContext.

Context exposes the runtime, UI, session, model, and cancellation surfaces backed by ContextActions. Optional actions use their documented zero-value behavior when the host does not bind them.

func FromContext

func FromContext(ctx context.Context) *Context

FromContext retrieves the per-extension Context that the host attached via WithContext. Returns nil if none was attached (e.g. a unit test that constructs handlers without a host).

Typical usage in an extension handler:

api.OnToolCall(func(ctx context.Context, event extension.ToolCallEvent) extension.ToolCallEventResult {
    extCtx := extension.FromContext(ctx)
    if extCtx != nil {
        cwd, _ := extCtx.CWD()
        // ... use cwd
    }
    return extension.ToolCallEventResult{}
})

func NewContext

func NewContext(cwd string, uiContext UIContext, assertActive func() error, actions ContextActions) *Context

NewContext constructs a Context with the given parameters. This is the constructor that hosts (Runner) use; extension authors never call this directly.

uiContext is the per-mode UI binding (matches upstream's `runner.uiContext` field at runner.ts:225). Pass NoopUIContext when no UI is available; nil is normalized to NoopUIContext so callers of Context.UI always receive a non-nil dispatchable.

assertActive is the runner's staleness guard; every getter/method on Context calls it first.

actions carries the optional injection callbacks that back Model/IsIdle/Shutdown/etc. Pass a zero-value `ContextActions{}` for the no-op defaults (matches upstream's bindCore-pre-bind state).

upstream: runner.ts:566-630 (createContext factory)

func (*Context) Abort

func (c *Context) Abort() error

Abort cancels the current agent operation. Returns an error if the runner has been invalidated.

Default semantics when no actions injector is bound: no-op (matches upstream's `() => {}` default at runner.ts:240).

upstream: runner.ts:602-605 (`abort: () => { ... }`)

func (*Context) CWD

func (c *Context) CWD() (string, error)

CWD returns the working directory captured at Runner construction. Returns an error if the runner has been invalidated.

upstream: runner.ts:581 (`get cwd()`)

func (*Context) Compact

func (c *Context) Compact(opts *CompactOptions) error

Compact triggers compaction without awaiting completion. Returns an error if the runner has been invalidated.

Default semantics when no actions injector is bound: no-op (matches upstream's `() => {}` default at runner.ts:234).

upstream: runner.ts:618-621 (`compact: (options) => { ... }`)

func (*Context) GetActiveTools

func (c *Context) GetActiveTools() []string

GetActiveTools returns the names of currently active tools. Returns nil if no tool-scoping actions are wired.

func (*Context) GetAllTools

func (c *Context) GetAllTools() []ToolInfo

pig additive (D23): these methods support Piglet tool scoping. GetAllTools returns metadata about all registered tools. Returns nil if no tool-scoping actions are wired.

func (*Context) GetContextUsage

func (c *Context) GetContextUsage() (*ContextUsage, error)

GetContextUsage returns the current context-window usage for the active model, or nil if unknown. Returns an error if the runner has been invalidated.

Default semantics when no actions injector is bound: returns nil (matches upstream's `() => undefined` default at runner.ts:233).

upstream: runner.ts:614-617 (`getContextUsage: () => { ... }`)

func (*Context) GetFlagValue

func (c *Context) GetFlagValue(name string) any

GetFlagValue returns the value of an extension-registered flag. Returns nil if no flag-value actions are wired.

func (*Context) GetMcpServers

func (c *Context) GetMcpServers() []RegisteredMcpServer

GetMcpServers returns the MCP servers extensions registered, in registration order. It returns nil if the runner's runtime is not bound.

upstream: loader.ts:475-478 (getMcpServers)

func (*Context) GetSystemPrompt

func (c *Context) GetSystemPrompt() (string, error)

GetSystemPrompt returns the current system prompt text. Returns an error if the runner has been invalidated.

Default semantics when no actions injector is bound: returns the empty string (matches upstream's `() => ""` default).

upstream: runner.ts:622-625 (`getSystemPrompt: () => { ... }`)

func (*Context) HasPendingMessages

func (c *Context) HasPendingMessages() (bool, error)

HasPendingMessages reports whether queued messages are awaiting processing. Returns an error if the runner has been invalidated.

Default semantics when no actions injector is bound: returns false (matches upstream's `() => false` default at runner.ts:232).

upstream: runner.ts:606-609 (`hasPendingMessages: () => { ... }`)

func (*Context) HasUI

func (c *Context) HasUI() (bool, error)

HasUI reports whether the runner has a real (non-noop) UI context attached. Mirrors upstream's pointer-identity check (runner.ts:361: `this.uiContext !== noOpUIContext`).

Returns an error if the runner has been invalidated.

upstream: runner.ts:359-362

func (*Context) IsIdle

func (c *Context) IsIdle() (bool, error)

IsIdle reports whether the agent is currently idle (not streaming). Returns an error if the runner has been invalidated.

Default semantics when no actions injector is bound: returns true (matches upstream's `() => true` default at runner.ts:228).

upstream: runner.ts:594-597 (`isIdle: () => { ... return runner.isIdleFn(); }`)

func (*Context) IsProjectTrusted

func (c *Context) IsProjectTrusted() (bool, error)

IsProjectTrusted reports whether the current project is trusted, so an extension can refuse to read project-scoped configuration or run project code before the user has trusted it. Returns an error if the runner has been invalidated.

Default semantics when no actions injector is bound: returns true (matches upstream's `() => true` default at runner.ts:280).

upstream: runner.ts:718-721 (`isProjectTrusted: () => { ... }`)

func (*Context) Mode

func (c *Context) Mode() (ExtensionMode, error)

Mode returns the current run mode (tui/rpc/json/print), including changes made after this context was created. An unbound getter returns print. Stale contexts return an error. upstream: packages/coding-agent/src/core/extensions/runner.ts:createContext

func (*Context) Model

func (c *Context) Model() (Model, error)

Model returns the currently selected model, or nil if none is set. Returns an error if the runner has been invalidated.

Model is opaque at the extension boundary so providers retain their concrete model representation.

upstream: runner.ts:590 (`get model()`)

func (*Context) ModelRegistry

func (c *Context) ModelRegistry() (ModelRegistry, error)

ModelRegistry returns the per-runtime ModelRegistry. Returns an error if the runner has been invalidated.

upstream: runner.ts:586 (`get modelRegistry()`)

func (*Context) RefreshTools

func (c *Context) RefreshTools() error

RefreshTools rebuilds the session's tool registry from the tools extensions hold, so a tool an extension registered after load is admitted and, when it activates on registration, declared. An in-process extension calls it after Extension.SetRegisteredTool; it does nothing before the host binds the action.

upstream: loader.ts:273-284 (registerTool), types.ts:1598 (RefreshToolsHandler)

func (*Context) ScopedModels

func (c *Context) ScopedModels() ([]ScopedModel, error)

ScopedModels returns the current read-only scope through the callback captured when this context was created. An unbound callback returns an empty list. Do not mutate the returned slice or models. upstream: packages/coding-agent/src/core/extensions/runner.ts:createContext

func (*Context) SendUserMessage

func (c *Context) SendUserMessage(content any, opts *SendUserMessageOptions) error

SendUserMessage injects a user message into the agent loop and triggers a turn when the agent is idle.

Upstream exposes this method on ExtensionAPI. Go handlers receive Context directly, so the method is available here.

func (*Context) SessionManager

func (c *Context) SessionManager() (ReadonlySessionManager, error)

SessionManager returns the per-runtime SessionManager. Returns an error if the runner has been invalidated.

SessionManager is the read-only ReadonlySessionManager view (runner.ts:582 types it so); the host owns its concrete implementation.

upstream: runner.ts:582 (`get sessionManager()`)

func (*Context) SetActiveTools

func (c *Context) SetActiveTools(names []string)

SetActiveTools sets the active tool list by name. No-op if no tool-scoping actions are wired.

func (*Context) Shutdown

func (c *Context) Shutdown() error

Shutdown triggers graceful agent shutdown. Returns an error if the runner has been invalidated.

Default semantics when no actions injector is bound: no-op (matches upstream's `() => {}` default at runner.ts:241).

upstream: runner.ts:610-613 (`shutdown: () => { ... }`)

func (*Context) Signal

func (c *Context) Signal() (context.Context, error)

Signal returns the active run's cancellation, or nil while no run is active. Every read during one run returns the same context, and aborting the run cancels it, so a handler that holds it sees the abort while the handler is still in flight. Returns an error if the runner has been invalidated.

Default semantics when no actions injector is bound: returns nil (matches upstream's `() => undefined` default at runner.ts:369).

upstream: runner.ts:917-920 (`get signal()`)

func (*Context) ThinkingLevel

func (c *Context) ThinkingLevel() (ThinkingLevel, error)

ThinkingLevel returns the current thinking level through the callback captured when this context was created. An unbound callback returns "", as upstream's optional `thinkingLevel` is absent when the session runtime provides none. upstream: packages/coding-agent/src/core/extensions/runner.ts:914 (get thinkingLevel)

func (*Context) UI

func (c *Context) UI() (UIContext, error)

UI returns the per-mode UIContext. Returns the package-level NoopUIContext singleton when no UI was bound (matches upstream's pre-bind state at runner.ts:255).

Returns an error if the runner has been invalidated.

upstream: runner.ts:572-575 (`get ui()` returns `runner.uiContext`)

type ContextActions

type ContextActions struct {
	// SessionManager backs Context.SessionManager().
	// upstream: types.ts:301 (read-only)
	SessionManager ReadonlySessionManager

	// ModelRegistry backs Context.ModelRegistry().
	// upstream: types.ts:303
	ModelRegistry ModelRegistry

	// GetModel backs Context.Model(). Returns nil if no model is
	// currently selected.
	// upstream: types.ts:305 (Model<any> | undefined)
	GetModel func() Model

	// GetScopedModels returns the current read-only model scope. Context creation captures this callback, not its result.
	// upstream: packages/coding-agent/src/core/extensions/runner.ts:createContext
	GetScopedModels func() []ScopedModel

	// GetThinkingLevel backs Context.ThinkingLevel(): the level the session runtime provides, read each time.
	// upstream: packages/coding-agent/src/core/extensions/runner.ts:914 (`runner.runtime.getThinkingLevel()`)
	GetThinkingLevel func() ThinkingLevel

	// IsIdle backs Context.IsIdle().
	// upstream: types.ts:307
	IsIdle func() bool

	// IsProjectTrusted backs Context.IsProjectTrusted().
	// upstream: types.ts:332
	IsProjectTrusted func() bool

	// GetSignal backs Context.Signal(). It returns the active run's cancellation, or nil while no run is active.
	// upstream: types.ts:2158, runner.ts:917-920
	GetSignal func() context.Context

	// HasPendingMessages backs Context.HasPendingMessages().
	// upstream: types.ts:313
	HasPendingMessages func() bool

	// SendUserMessage backs Context.SendUserMessage(). Injects a user
	// message into the agent loop. Populated by the runner from
	// ExtensionActions, which is where a host supplies it.
	// upstream: types.ts:1306 (ExtensionAPI.sendUserMessage)
	SendUserMessage SendUserMessageHandler

	// Abort backs Context.Abort(). Cancels the current agent action.
	// upstream: types.ts:311
	Abort func()

	// Shutdown backs Context.Shutdown(). Triggers graceful agent
	// shutdown.
	// upstream: types.ts:315
	Shutdown func()

	// GetContextUsage backs Context.GetContextUsage().
	// upstream: types.ts:317
	GetContextUsage func() *ContextUsage

	// Compact backs Context.Compact(opts).
	// upstream: types.ts:319
	Compact func(opts *CompactOptions)

	// GetSystemPrompt backs Context.GetSystemPrompt(). The host callback
	// returns the latest prompt, including changes made by earlier
	// before_agent_start handlers.
	// upstream: types.ts:321
	GetSystemPrompt func() string

	// GetSystemPromptOptions backs CommandContext.GetSystemPromptOptions().
	// Returns the base inputs pi currently uses to build the system
	// prompt (custom prompt, tools, snippets, guidelines, append text,
	// cwd, context files, skills). nil → method returns zero-value
	// options, matching upstream's
	// `getSystemPromptOptions ?? (() => ({ cwd: this.cwd }))` default.
	// upstream: types.ts:1512, runner.ts:303,653
	GetSystemPromptOptions func() *BuildSystemPromptOptions

	// GetMode reads the current runner mode. Nil means print.
	// upstream: runner.ts:createContext
	GetMode func() ExtensionMode

	// GetUIContext reads the current runner UI binding. Nil uses the constructor's UI binding.
	// upstream: runner.ts:createContext
	GetUIContext func() UIContext

	// GetAllTools returns metadata about all registered tools.
	// Used by piglet scoping to enumerate available tools.
	GetAllTools func() []ToolInfo

	// GetActiveTools returns the names of currently active tools.
	GetActiveTools func() []string

	// SetActiveTools sets the active tool list by name.
	// Tools not in the list are hidden from the agent.
	SetActiveTools func(names []string)

	// RefreshTools rebuilds the session's tool registry from the tools extensions hold, so a tool registered after load
	// reaches the model. It returns the error that admitting a registered tool reports.
	// upstream: types.ts:1598 (RefreshToolsHandler), loader.ts:273-284 (registerTool calls runtime.refreshTools)
	RefreshTools func() error

	// GetMcpServers returns the MCP servers extensions registered, in registration order.
	// upstream: loader.ts:475-478 (getMcpServers)
	GetMcpServers func() []RegisteredMcpServer

	// GetFlagValue returns the value of an extension-registered flag.
	GetFlagValue func(name string) any

	// ToolActions back the [ToolContext] of a tool call: executeTool and
	// getCallableTools of upstream's ExtensionContextActions.
	// upstream: types.ts:2161-2169
	ToolActions
}

ContextActions is the host-side injection of per-runtime callbacks that back Context's surfaces. Mirrors upstream's `ExtensionContextActions` (types.ts:1467-1481): the single struct passed to `bindCore` to wire dynamic context surfaces (model selection, idle state, abort handling, etc.) without making the Context constructor signature unwieldy.

All fields are optional. Nil function fields produce upstream- equivalent default behavior:

GetModel              nil → Model() returns nil (upstream: () => undefined)
IsIdle                nil → IsIdle() returns true (upstream: () => true)
HasPendingMessages    nil → HasPendingMessages() returns false (upstream: () => false)
Shutdown              nil → Shutdown() is no-op (upstream: () => {})
GetContextUsage       nil → GetContextUsage() returns nil (upstream: () => undefined)
Compact               nil → Compact() is no-op (upstream: () => {})
GetSystemPrompt       nil → GetSystemPrompt() returns "" (upstream: () => "")

SessionManager and ModelRegistry are direct value injections (not closures) because upstream stores them as Runner fields, not callbacks; nil values are honored.

pig additive (D23): ContextActions supplies Piglet tool-scoping operations.

type ContextEditReplacement

type ContextEditReplacement = sessionentry.ContextEditReplacement

ContextEditReplacement is the replacement of a context_edit entry (session-manager.ts ContextEditEntry["replacement"]).

type ContextEvent

type ContextEvent struct {
	Type     string         `json:"type"`
	Messages []AgentMessage `json:"messages"`
}

ContextEvent: upstream types.ts ContextEvent.

type ContextEventResult

type ContextEventResult struct {
	Messages []AgentMessage `json:"messages,omitempty"`
}

ContextEventResult: upstream types.ts ContextEventResult.

type ContextUsage

type ContextUsage struct {
	Tokens        *int     `json:"tokens"`
	ContextWindow int      `json:"contextWindow"`
	Percent       *float64 `json:"percent"`
}

ContextUsage mirrors upstream `ContextUsage` (types.ts:276-283). Reports the agent's current context-window utilization for the active model.

Field semantics (from upstream JSDoc):

  • Tokens: estimated context tokens, or nil if unknown (e.g. right after compaction, before the next LLM response).
  • ContextWindow: model's maximum context size in tokens.
  • Percent: usage as percentage of context window, or nil if Tokens is unknown.

Pointer-typed nullable fields distinguish unknown from zero; percentages retain JavaScript number precision.

upstream: types.ts:276-283

type ContextWithSystemEvent

type ContextWithSystemEvent struct {
	Type     string         `json:"type"`
	Messages []AgentMessage `json:"messages"`
}

ContextWithSystemEvent: upstream types.ts ContextWithSystemEvent. Handlers see the full transcript, system messages included, after the context handlers; their returned messages are used as returned.

type CustomEntry

type CustomEntry = sessionentry.CustomEntry

CustomEntry mirrors core CustomEntry<T>: a session entry appended via AppendEntry that does not participate in LLM context. Like CustomMessage, the generic payload is carried untyped (the wire boundary is JSON) and renderers type-assert as needed.

type CustomFactory

type CustomFactory func(tui TUI, theme *tui.Theme, keybindings KeybindingsManager, done func(result any)) (DisposableComponent, error)

CustomFactory builds the component UIContext.Custom shows, for an extension that runs in the host process (upstream `ctx.ui.custom(factory)`). theme is the active theme and keybindings the merged keybinding table of the interactive mode (both concrete types of the tui package); done ends the call with a result and may run on any goroutine. The component renders and reads input on the interactive loop; it may also implement interface{ Dispose() }, which runs once after done. upstream: packages/coding-agent/src/core/extensions/types.ts:187 (custom)

type CustomMessage

type CustomMessage struct {
	CustomType string
	// Content is a string or an array of text and image content blocks.
	Content any
	Display bool
	// Details is the extension's own data for the renderer; nil leaves it unset.
	Details any
	// Timestamp is the message's time in milliseconds since the Unix epoch.
	Timestamp int64
}

CustomMessage is the custom message an extension's message renderer receives (core/messages.ts:46 CustomMessage<T>).

func (CustomMessage) MarshalJSON

func (m CustomMessage) MarshalJSON() ([]byte, error)

MarshalJSON writes the object Pi's renderer reads: role is always "custom" and details is left out when unset.

func (CustomMessage) MessageRole

func (CustomMessage) MessageRole() string

MessageRole is "custom": a CustomMessage is a SessionMessage, a member of the union session-manager.ts appendMessage takes.

type CustomMessageRef

type CustomMessageRef struct {
	CustomType string `json:"customType"`
	Content    any    `json:"content"`
	Display    bool   `json:"display"`
	Details    any    `json:"details,omitempty"`
}

CustomMessageRef mirrors upstream's `Pick<CustomMessage, "customType" | "content" | "display" | "details">`.

func (*CustomMessageRef) UnmarshalJSON

func (m *CustomMessageRef) UnmarshalJSON(data []byte) error

UnmarshalJSON keeps the member order of the `details` object the extension wrote.

type CustomOptions

type CustomOptions struct {
	// Overlay shows the component over the screen instead of in the editor slot.
	Overlay bool
	// OverlayOptions positions an overlay.
	OverlayOptions OverlayOptionsSource
	// OnHandle receives the overlay's handle as soon as the overlay is shown, to hide, focus or unfocus it.
	OnHandle func(handle *tui.OverlayHandle)
}

CustomOptions is the `options` of an in-process UIContext.Custom. upstream: packages/coding-agent/src/core/extensions/types.ts:187 `{ overlay?: boolean; overlayOptions?: OverlayOptions | (() => OverlayOptions); onHandle?: (handle: OverlayHandle) => void }`

type CustomToolCallEvent

type CustomToolCallEvent struct {
	ToolCallEventBase
	ToolName string         `json:"toolName"`
	Input    map[string]any `json:"input"`
}

CustomToolCallEvent: upstream types.ts CustomToolCallEvent. It also stands for the nine upstream per-tool variants (Bash, PowerShell, Read, Edit, Write, Grep, Find and Ls ToolCallEvent), which differ from it only in the compile-time type of `input`; the Session emits this type for every tool.

func (CustomToolCallEvent) InputJSON

func (e CustomToolCallEvent) InputJSON() ([]byte, error)

InputJSON is the input as JSON in the order a JavaScript object holds its members: the order the model wrote them in, with the edits applied to the order the way an assignment applies them. The wire bytes are used as they are while they still describe Input, so a number keeps its exact text. Once an in-process handler has edited the map, a member the wire bytes list keeps its place, a member they do not list follows in sorted order, and a removed member is gone. A map has no insertion order, so the order of two members an in-process handler added is sorted.

func (CustomToolCallEvent) MarshalJSON

func (e CustomToolCallEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the event as agent-session.ts:_beforeToolCall builds it: type, toolName, toolCallId, parentToolCallId, input. Go's struct order would put the embedded base first, and a map sorts the members of `input`. A subprocess extension receives this text, and JSON.stringify of Pi's event keeps the order above.

type CustomToolResultEvent

type CustomToolResultEvent struct {
	ToolResultEventBase
	ToolName string `json:"toolName"`
	Details  any    `json:"details,omitempty"`
}

CustomToolResultEvent: upstream types.ts CustomToolResultEvent.

func (CustomToolResultEvent) MarshalJSON

func (e CustomToolResultEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the event in Pi's member order; see [marshalToolResultEvent].

type DelegatedRemoteEditor

type DelegatedRemoteEditor interface {
	Delegated() bool
}

DelegatedRemoteEditor is a RemoteEditor whose component subclasses the host's stock editor, as a Pi extension's CustomEditor subclass extends the default editor. The host keeps its own editor's text, history, completion and app-action handling and the component reaches them through RemoteEditorBaseHost.

type DeliverAs

type DeliverAs string

DeliverAs is the queueing discriminator for API.SendMessage / API.SendUserMessage. Upstream literal-string union.

upstream: types.ts:1161, 1170

const (
	DeliverAsSteer    DeliverAs = "steer"
	DeliverAsFollowUp DeliverAs = "followUp"
	DeliverAsNextTurn DeliverAs = "nextTurn"
)

type DialogInitiationReporter

type DialogInitiationReporter interface {
	ReportsDialogInitiation() bool
}

DialogInitiationReporter is implemented by a UIContext whose Select, Confirm, Input, and Editor call CallInitiated once the dialog is installed. Other UIContexts are treated as initiated when the host dispatches the call.

type DialogValueUIContext

type DialogValueUIContext interface {
	SelectValue(ctx context.Context, title string, options []string, opts ExtensionUIDialogOptions) (json.RawMessage, error)
	ConfirmValue(ctx context.Context, title, message string, opts ExtensionUIDialogOptions) (json.RawMessage, error)
	InputValue(ctx context.Context, title string, placeholder *string, opts ExtensionUIDialogOptions) (json.RawMessage, error)
	EditorValue(ctx context.Context, title string, prefill *string) (json.RawMessage, error)
}

DialogValueUIContext is implemented by a UIContext whose dialogs resolve with the JSON value the user's client sent, as Pi's RPC mode does: rpc-mode.ts:137-150 and 254-266 resolve `"value" in r ? r.value : undefined` and `"confirmed" in r ? r.confirmed : false` without checking the type, so an extension can observe a number, `null`, an object or an array. The extension host answers an SDK's ui.select, ui.confirm, ui.input and ui.editor calls through these methods when the bound UI has them, and falls back to the string and bool methods of UIContext otherwise. Each returns the member's raw JSON; an undefined result (cancelled, timed out, aborted, or a response without a value) is context.Canceled for select, input and editor, and `false` for confirm. A nil placeholder or prefill is Pi's undefined: the dialog opens without that member, as PlaceholderOmitter and PrefillOmitter do for the string-typed forms.

type DisposableComponent

type DisposableComponent interface {
	tui.Component
	Dispose()
}

DisposableComponent is `Component & { dispose?(): void }`: a component whose Dispose runs when the surface that shows it is replaced or restored. A component with nothing to release implements Dispose as a no-op.

type EditToolDetails

type EditToolDetails struct {
	Diff             string `json:"diff"`
	Patch            string `json:"patch"`
	FirstChangedLine int    `json:"firstChangedLine,omitempty"`
}

EditToolDetails is the upstream SDK contract for built-in edit-tool result details (edit.ts:61). Extensions and PostToolUse hooks receive this shape on tool_result events for the `edit` tool: a display diff, a standard unified patch, and the first changed line for navigation.

type EditToolInput

type EditToolInput struct {
	Path  string                `json:"path"`
	Edits []EditToolInputChange `json:"edits"`
	// Extra holds members the schema does not declare; upstream's input is a plain object that keeps them.
	Extra map[string]json.RawMessage `json:"-"`
}

EditToolInput is upstream's EditToolInput (edit.ts editSchema).

func (EditToolInput) MarshalJSON

func (in EditToolInput) MarshalJSON() ([]byte, error)

func (*EditToolInput) UnmarshalJSON

func (in *EditToolInput) UnmarshalJSON(data []byte) error

type EditToolInputChange

type EditToolInputChange struct {
	OldText string `json:"oldText"`
	NewText string `json:"newText"`
}

EditToolInputChange is one targeted replacement of an EditToolInput (edit.ts replaceEditSchema).

type EditToolResultEvent

type EditToolResultEvent struct {
	ToolResultEventBase
	ToolName string           `json:"toolName"` // "edit"
	Details  *EditToolDetails `json:"details,omitempty"`
}

EditToolResultEvent: upstream types.ts EditToolResultEvent.

func (EditToolResultEvent) MarshalJSON

func (e EditToolResultEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the event in Pi's member order; see [marshalToolResultEvent].

type EditorComponent

type EditorComponent = tui.EditorComponent

EditorComponent mirrors @earendil-works/pi-tui EditorComponent.

type EditorFactory

type EditorFactory func(host tui.TUI, theme tui.EditorTheme, keybindings KeybindingsManager) tui.EditorComponent

EditorFactory builds an extension's editor component (types.ts:143 `(tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager) => EditorComponent`). keybindings is the merged keybinding table (tui.GetTUIKeybindings), as for CustomFactory.

func RemoteEditorFactory

func RemoteEditorFactory(editor RemoteEditor) EditorFactory

RemoteEditorFactory is the editor factory of an editor that runs in an extension's process. The component it builds is the editor itself seen from the host: the host installs the editor's frames, text and callbacks through RemoteEditor and never renders or types into the component, so Render, Text and HandleInput act on the process only for a caller that is not the host.

type EditorTheme

type EditorTheme = tui.EditorTheme

EditorTheme mirrors @earendil-works/pi-tui EditorTheme.

type EntryRenderOptions

type EntryRenderOptions struct {
	Expanded bool `json:"expanded"`
}

EntryRenderOptions is passed to an EntryRenderer. Mirrors upstream EntryRenderOptions.

type EntryRenderer

type EntryRenderer = func(
	entry CustomEntry,
	options EntryRenderOptions,
	theme Theme,
) Component

EntryRenderer mirrors upstream EntryRenderer<T>. Renders a custom session entry (appended via AppendEntry; not sent to the LLM) into a TUI Component, or returns nil to fall back to the default renderer.

As with MessageRenderer, the Go signature drops the TS generic parameter T: the entry's data is carried on CustomEntry.Data (`any`) and the renderer type-asserts as needed.

type ErrorListener

type ErrorListener = func(*ExtensionError)

ErrorListener is the callback signature registered via Runner.AddErrorListener. Listeners run synchronously in the dispatch goroutine; long-running work should be moved to a dedicated goroutine by the listener itself.

upstream: runner.ts:469 (private errorListeners: Set<ErrorListener>)

type EventBus

type EventBus interface {
	// Emit broadcasts data on channel to every current listener. Synchronous:
	// handlers run before Emit returns. A handler's failure does not reach the
	// emitter or the other listeners; the host reports it as
	// `Event handler error (<channel>):` (event-bus.ts:19-23).
	Emit(channel string, data any)

	// On registers handler for channel and returns an idempotent function that
	// removes it. Handlers are dispatched in registration order.
	On(channel string, handler func(data any)) (unsubscribe func())
}

EventBus is the extension-to-extension event bus. Mirrors upstream's core/event-bus.ts EventBus, exposed on ExtensionAPI as the property `events: EventBus`, with upstream's method names.

Go exposes upstream's `events` property through API.Events.

upstream: event-bus.ts:3-6

type EventBusController

type EventBusController interface {
	EventBus

	// Clear removes every listener of every channel (EventEmitter.removeAllListeners).
	Clear()
}

EventBusController is an EventBus its owner can also clear.

upstream: event-bus.ts:8-10

func CreateEventBus

func CreateEventBus() EventBusController

CreateEventBus returns an in-memory EventBusController. Emit snapshots the channel's listeners, so a handler that subscribes or unsubscribes during an emit does not change that emit's recipients. A handler that panics is reported on stderr as `Event handler error (<channel>): <value>` and neither reaches the emitter nor stops the remaining listeners.

upstream: event-bus.ts:12-33 (createEventBus)

type ExecOptions

type ExecOptions struct {
	// Timeout in milliseconds. Pi's timeout is a JavaScript number: a positive value starts a timer and anything else starts none.
	Timeout float64 `json:"timeout,omitempty"`
	// CWD overrides the working directory. Empty uses the extension's CWD.
	CWD string `json:"cwd,omitempty"`
	// Signal is upstream's options.signal: when it is done the command ends as when ExecCommand's own context ends, with SIGTERM to the command alone. It does not cross the wire; a subprocess extension's signal reaches the host as the call's own cancellation.
	Signal AbortSignal `json:"-"`
}

ExecOptions configures a shell command execution.

upstream: core/exec.ts ExecOptions

type ExecResult

type ExecResult struct {
	Stdout string `json:"stdout"`
	Stderr string `json:"stderr"`
	Code   int    `json:"code"`
	Killed bool   `json:"killed"`
}

ExecResult is the outcome of a shell command execution.

upstream: core/exec.ts ExecResult

func ExecCommand

func ExecCommand(ctx context.Context, cwd, command string, args []string, opts *ExecOptions) (ExecResult, error)

ExecCommand runs a shell command synchronously and returns the result. This is the default implementation backing API.Exec when the host doesn't provide an override.

The command is spawned directly (no shell wrapping). Use args to pass arguments. If opts.CWD is empty, cwd is used as the working directory. Like upstream, a program that cannot start does not fail the call: the result has code 1 and empty output. Arguments that Node's spawn rejects, an empty command or a NUL in the command, an argument, or the working directory, fail the call with Node's ERR_INVALID_ARG_VALUE message, which upstream's spawn throws. On Windows the program is looked up as Node's spawn looks it up (nodespawn.LookPath), so a name that matches only through PATHEXT, such as npm for npm.cmd, cannot start. A batch file name fails the call with Node's "spawn EINVAL" error, which upstream's spawn throws.

Like upstream, the call waits for the child, then for its output pipes to end or to fall idle for 100 ms (utils/child-process.ts waitForChildProcess), so a descendant that keeps a pipe open does not block it, and output the descendant writes while the pipes stay active is kept.

Timeout, context cancellation and opts.Signal signal the child alone with SIGTERM (Process.Kill on Windows, where Node's kill terminates the process). Like upstream, nothing follows it: Node sets proc.killed once SIGTERM is delivered, so upstream's SIGKILL after 5 seconds never runs, and no descendant is signalled. The result's code is the child's exit code; a child that a signal ended has none, and upstream resolves it as 0 (`code ?? 0`). On Windows a child that the kill ended has none either: libuv reports the signal it was sent instead of the exit status 1, so the code is 0 there too.

upstream: core/exec.ts execCommand

type ExecuteToolOptions

type ExecuteToolOptions struct {
	// Signal cancels the nested call. Defaults to the calling tool's context. Go mechanic (not a divergence): upstream's AbortSignal is a context.Context, as in [ExecOptions].
	Signal context.Context `json:"-"`
	// OnUpdate receives partial results of the nested tool, in addition to `tool_execution_update` events.
	OnUpdate agent.ToolUpdateSink `json:"-"`
}

ExecuteToolOptions mirrors upstream ExecuteToolOptions.

upstream: types.ts:367-372 (ExecuteToolOptions)

type Extension

type Extension struct {
	// Name is the human-readable name of the extension, typically derived
	// from the manifest or directory name. Used for display in the UI.
	Name string

	// Path is the original (unresolved) path the extension was loaded from.
	// This is typically the path the user passed via --extension or that the
	// loader discovered. May be relative.
	Path string

	// ResolvedPath is the absolute, canonical path used for diagnostics,
	// telemetry, and "Using <path>" UI strings.
	ResolvedPath string

	// Replaceable leaves the extension out when another extension registers a
	// tool, command, or flag with a name it registers during loading, instead of
	// reporting a conflict. The CLI's built-in MCP, codemode, and tool search
	// extensions use it. upstream: types.ts:2209 (Extension.replaceable)
	Replaceable bool

	// SourceInfo describes the extension's origin and ownership metadata. The
	// current public contract carries this value opaquely.
	SourceInfo SourceInfo

	// Handlers is the legacy construction shape. NewRunner imports it into the
	// concurrency-safe handler registry before dispatch.
	Handlers map[string][]HandlerFn

	// Tools is the startup construction shape, keyed by name. Runtime readers use RegisteredTools or RegisteredTool to include synchronized late registrations.
	Tools map[string]RegisteredTool

	// ToolOrder records tool registration order. Go maps do not retain
	// insertion order; loaders populate this alongside Tools so tool lists
	// keep upstream's registration order (a Map in extension.tools).
	ToolOrder []string

	// MessageRenderers is keyed by the custom message type the renderer handles.
	MessageRenderers map[string]MessageRenderer

	// EntryRenderers is keyed by the custom entry type the renderer handles.
	// Custom entries (appended via AppendEntry) do not participate in LLM context.
	EntryRenderers map[string]EntryRenderer

	// ToolRenderers are the extension's tool renderer resolvers, in registration order.
	// upstream: types.ts Extension.toolRenderers
	ToolRenderers []ToolRendererResolver

	// MarkdownTransformer is the extension's display-only Markdown transform,
	// if it registered one; a later registration replaces an earlier one.
	// upstream: types.ts Extension.markdownTransformer
	MarkdownTransformer MarkdownTransformer

	// Commands is keyed by the command name (without leading slash).
	Commands map[string]RegisteredCommand

	// CommandOrder records command registration order. Go maps do not retain
	// insertion order; loaders populate this alongside Commands so resolved
	// invocation names match upstream extension and registration order.
	CommandOrder []string

	// Flags is keyed by the flag name.
	Flags map[string]ExtensionFlag

	// FlagOrder records the first registration of each flag name. Loaders populate it alongside Flags, so --help lists flags in upstream registration order.
	FlagOrder []string

	// Shortcuts is keyed by the canonical KeyID (e.g. "ctrl+shift+r").
	Shortcuts map[KeyID]ExtensionShortcut

	// Hidden omits the extension from the startup Extensions list.
	// upstream: .upstream/v0.99.1/packages/coding-agent/src/core/extensions/types.ts:2208 (Extension.hidden)
	Hidden bool

	// EventLoopTurn, when set, returns once the extension's own event loop took one turn and the host applied the calls that turn sent. Pi runs every extension on the event loop its tools run on; a host whose extension runs elsewhere sets it so the callbacks a handler queued run before a tool's result reaches the extensions.
	// pig additive (D19): only the Node subprocess runtime sets it.
	EventLoopTurn func(context.Context) error
	// contains filtered or unexported fields
}

Extension is the state container populated by an extension's factory during loading. It is the cross-tier contract between the host and the extension implementation: factories write registrations into the API, the API writes them into this struct, and the Runner reads from it during dispatch.

A pre-populated `[]Extension` is what gets handed to a Runner. Loaders produce these; runners consume them. The runner does not mutate them.

Field-level translation rule: Go's idiomatic field naming and JSON tag preservation are applied; see docs/parity/DIVERGENCES.md "TS→Go translation rituals" section. The maps, sets, and overall shape mirror upstream verbatim.

upstream: types.ts:1513-1523 (export interface Extension)

func (*Extension) AddEventHandler

func (e *Extension) AddEventHandler(event string, id int, handler HandlerFn)

AddEventHandler appends one identity-bearing handler in registration order.

func (*Extension) AddJSONEventHandler

func (e *Extension) AddJSONEventHandler(event string, id int, handler HandlerFn)

AddJSONEventHandler is AddEventHandler for a handler that reads its event only through the event's JSON encoding, as a subprocess extension's handler does. A dispatcher may hand such a handler an event whose Go values are not all materialized when its encoding is complete.

func (*Extension) Command

func (e *Extension) Command(name string) (RegisteredCommand, bool)

Command returns the current command registered under name.

func (*Extension) CommandsVersion

func (e *Extension) CommandsVersion() (uint64, bool)

CommandsVersion reports a counter that moves with every change to the extension's registered commands, so a reader that derived something from them can tell it is stale. The boolean is false for an extension whose declarations are not yet synchronized: its commands have no version.

func (*Extension) EntryRendererFor

func (e *Extension) EntryRendererFor(customType string) (EntryRenderer, bool)

EntryRendererFor returns the renderer registered for customType, including one registered after load.

func (*Extension) EventHandlers

func (e *Extension) EventHandlers(event string) []HandlerFn

EventHandlers returns a stable dispatch snapshot. Registration changes made while it is being iterated apply only to the next dispatch.

func (*Extension) InitializeDeclarationRegistry

func (e *Extension) InitializeDeclarationRegistry()

InitializeDeclarationRegistry moves the construction fields (Commands, CommandOrder, Flags, FlagOrder, Shortcuts) into the synchronized registry. Call it before the Extension is shared; afterwards the Registered* readers and Set* writers use the registry, and the fields are no longer read or written.

func (*Extension) InitializeEventHandlers

func (e *Extension) InitializeEventHandlers()

InitializeEventHandlers imports legacy Handlers once. Call before sharing an Extension between host and runner copies.

func (*Extension) InitializeToolRegistry

func (e *Extension) InitializeToolRegistry()

InitializeToolRegistry enables synchronized runtime registration before an Extension is shared with runners.

func (*Extension) JSONEventHandlers

func (e *Extension) JSONEventHandlers(event string) ([]HandlerFn, []bool)

JSONEventHandlers is EventHandlers with, for each handler, whether it was added with AddJSONEventHandler.

func (*Extension) MessageRendererFor

func (e *Extension) MessageRendererFor(customType string) (MessageRenderer, bool)

MessageRendererFor returns the renderer registered for customType, including one registered after load.

func (*Extension) RegisteredCommands

func (e *Extension) RegisteredCommands() []RegisteredCommand

RegisteredCommands returns the commands in registration order, including those registered after load.

func (*Extension) RegisteredFlag

func (e *Extension) RegisteredFlag(name string) (ExtensionFlag, bool)

RegisteredFlag returns the current flag registered under name.

func (*Extension) RegisteredFlags

func (e *Extension) RegisteredFlags() []ExtensionFlag

RegisteredFlags returns the flags in the order of each name's first registration.

func (*Extension) RegisteredRenderers

func (e *Extension) RegisteredRenderers() (messages map[string]MessageRenderer, entries map[string]EntryRenderer)

RegisteredRenderers returns copies of the message and entry renderer maps.

func (*Extension) RegisteredShortcuts

func (e *Extension) RegisteredShortcuts() []ExtensionShortcut

RegisteredShortcuts returns the shortcuts in registration order; shortcuts written to the Shortcuts field directly follow in key order.

func (*Extension) RegisteredTool

func (e *Extension) RegisteredTool(name string) (RegisteredTool, bool)

RegisteredTool looks up the current definition without copying the registry.

func (*Extension) RegisteredToolNames

func (e *Extension) RegisteredToolNames() []string

RegisteredToolNames are the keys of the extension's tools (upstream `extension.tools.keys()`): registration order, then any name the order does not list, sorted. It includes tools registered after load.

func (*Extension) RegisteredTools

func (e *Extension) RegisteredTools() []RegisteredTool

RegisteredTools returns an ordered snapshot, including tools registered after load.

func (*Extension) RemoveEventHandler

func (e *Extension) RemoveEventHandler(event string, id int)

RemoveEventHandler removes the exact registered identity. It is idempotent.

func (*Extension) ReplaceDeclarations

func (e *Extension) ReplaceDeclarations(source *Extension)

ReplaceDeclarations makes the commands, flags, shortcuts and message and entry renderers exactly source's, in source's order, when the owning runtime restarts. Readers holding the Extension see the new declarations.

func (*Extension) ReplaceEventHandlers

func (e *Extension) ReplaceEventHandlers(source *Extension)

ReplaceEventHandlers makes e's handlers exactly source's, in place, so every copy of e that shares its registry dispatches to the new set from the next dispatch on. A restarted subprocess registers afresh; its runner keeps the copy it was built with.

func (*Extension) ReplaceRegisteredTools

func (e *Extension) ReplaceRegisteredTools(source *Extension)

ReplaceRegisteredTools replaces the shared registry when the owning runtime restarts.

func (*Extension) SetCommandSourceInfo

func (e *Extension) SetCommandSourceInfo(info SourceInfo)

SetCommandSourceInfo assigns info to every command that has no source info of its own, now and on later registrations and restarts.

func (*Extension) SetEntryRenderer

func (e *Extension) SetEntryRenderer(customType string, renderer EntryRenderer)

SetEntryRenderer registers the renderer for a custom entry type, replacing an earlier one.

func (*Extension) SetMessageRenderer

func (e *Extension) SetMessageRenderer(customType string, renderer MessageRenderer)

SetMessageRenderer registers the renderer for a custom message type, replacing an earlier one. Pi's registerMessageRenderer writes the extension's own Map (loader.ts), which the runner reads live (runner.ts getMessageRenderer), so a renderer registered after load takes effect. Once InitializeDeclarationRegistry ran the registry is synchronized; before that the construction field is used.

func (*Extension) SetRegisteredCommand

func (e *Extension) SetRegisteredCommand(name string, command RegisteredCommand)

SetRegisteredCommand registers command under name: a new name is appended in registration order and an existing one is replaced in place.

func (*Extension) SetRegisteredFlag

func (e *Extension) SetRegisteredFlag(name string, flag ExtensionFlag)

SetRegisteredFlag registers flag under name; the order keeps each name's first registration.

func (*Extension) SetRegisteredShortcut

func (e *Extension) SetRegisteredShortcut(key KeyID, shortcut ExtensionShortcut)

SetRegisteredShortcut registers shortcut under key: a new key is appended in registration order and an existing one is replaced in place.

func (*Extension) SetRegisteredTool

func (e *Extension) SetRegisteredTool(tool RegisteredTool)

SetRegisteredTool replaces a definition in place or appends a new name in registration order.

func (*Extension) SetRegisteredTools

func (e *Extension) SetRegisteredTools(tools []RegisteredTool)

SetRegisteredTools is SetRegisteredTool for several tools under one lock, so a reader of the registry sees all of them or none, as Pi's registry looks to code that runs after a synchronous run of registerTool calls.

type ExtensionActions

type ExtensionActions struct {
	// upstream: types.ts:2064: SendMessageHandler
	SendMessage func(message CustomMessageRef, options *SendMessageOptions) error
	// upstream: types.ts:2069: SendUserMessageHandler
	SendUserMessage SendUserMessageHandler
	// upstream: types.ts:2074: AppendEntryHandler
	AppendEntry func(customType string, data any) error
	// upstream: types.ts:2076: SetSessionNameHandler
	SetSessionName func(name string) error
	// upstream: types.ts:2078: GetSessionNameHandler
	GetSessionName func() string
	// upstream: types.ts:2106: SetLabelHandler
	SetLabel func(entryID string, label *string) error
	// upstream: types.ts:2080: GetActiveToolsHandler
	GetActiveTools func() []string
	// upstream: types.ts:2090: GetAllToolsHandler
	GetAllTools func() []ToolInfo
	// upstream: types.ts:2092: GetSettingsHandler
	GetSettings func() Settings
	// upstream: types.ts:2096: SetActiveToolsHandler
	SetActiveTools func(toolNames []string)
	// upstream: types.ts:2098: RefreshToolsHandler
	RefreshTools func() error
	// upstream: types.ts:2094: GetCommandsHandler
	GetCommands func() []SlashCommandInfo
	// upstream: types.ts:2100: SetModelHandler. ctx carries the calling extension's call lifetime (D3).
	SetModel func(ctx context.Context, model Model) (bool, error)
	// upstream: types.ts:2102: GetThinkingLevelHandler
	GetThinkingLevel func() ThinkingLevel
	// upstream: types.ts:2104: SetThinkingLevelHandler
	SetThinkingLevel func(level ThinkingLevel)
}

ExtensionActions is the host-side injection of agent-loop callbacks available to extensions via `ctx.actions.*` (the runtime side; this struct is consumed by [host.Runner.BindCore]). Mirrors upstream `ExtensionActions` (types.ts:2147-2163). Each field has the shape of the upstream handler type named beside it; Go handlers return the error upstream's handler would throw.

upstream: types.ts:2147-2163

type ExtensionError

type ExtensionError struct {
	// ExtensionPath is the resolved filesystem path of the extension
	// whose handler failed. Mirrors upstream `extensionPath`.
	ExtensionPath string `json:"extensionPath"`

	// Event is the event-type string the handler was registered for
	// (e.g. "tool_call", "session_start"). Mirrors upstream `event`.
	Event string `json:"event"`

	// Error is the human-readable message. In Go this is `err.Error()`;
	// upstream is `err.message`. Mirrors upstream `error`.
	Error string `json:"error"`

	// Stack is the optional stack of the failure itself, as upstream's
	// `err.stack`: the thrown error's stack for a subprocess extension, or
	// the panicking goroutine's stack for an in-process handler. It is empty
	// for a plain returned error, which carries no stack. See [ErrorStack].
	Stack string `json:"stack,omitempty"`
}

ExtensionError is the structured error surfaced when a registered handler throws (TS) / returns a non-nil error (Go) during event dispatch. Hosts collect these without aborting the dispatch chain and surface them through `Runner.AddErrorListener`.

upstream: types.ts:1537-1542

export interface ExtensionError {
	extensionPath: string;
	event: string;
	error: string;
	stack?: string;
}

Wire format note. JSON tags match upstream camelCase exactly so the type round-trips cleanly through current and future extension transports.

type ExtensionEvent

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

ExtensionEvent is the union of every event an extension handler receives (types.ts:1377 ExtensionEvent). It is a closed union: only the event types of this package implement it, which is what the Pi union lists; the tool_call and tool_result members are the sealed ToolCallEvent and ToolResultEvent unions, whose variants implement it as well.

type ExtensionFactory

type ExtensionFactory func(api API) error

ExtensionFactory is an extension written as Go code the binary was built with: it receives the extension API and registers tools, commands, flags, shortcuts, providers and event handlers on it, and returns the error upstream's factory throws.

Only the source of a binary's own main package supplies one, by value, to the loader in package factoryload (docs/specs/extension-factory-trust.md). No run-time input, Package, Piglet or wire peer can produce one. The subprocess SDKs keep upstream's `pi` argument on their own side of the wire.

upstream: core/extensions/types.ts:2017 (ExtensionFactory)

type ExtensionFlag

type ExtensionFlag struct {
	Name          string   `json:"name"`
	Description   string   `json:"description,omitempty"`
	Type          FlagType `json:"type"`
	Default       any      `json:"default,omitempty"`
	ExtensionPath string   `json:"extensionPath"`
}

ExtensionFlag mirrors upstream's ExtensionFlag: the loader's view of a registered flag, including its source extension. Hosts hand this to the CLI parser.

type ExtensionHandler

type ExtensionHandler[E, R any] = func(ctx context.Context, evt E) (R, error)

ExtensionHandler is types.ts ExtensionHandler<E, R>: the handler of event E whose result is R, which ExtensionAPI.on takes per event. Go carries the ExtensionContext argument in ctx (see FromContext) and reports a handler failure as the returned error, where upstream's handler throws or rejects. An event whose handler has no result is registered with a function that returns only an error.

type ExtensionHandlerNoResult

type ExtensionHandlerNoResult[E any] = func(ctx context.Context, evt E) error

ExtensionHandler is Pi's ExtensionHandler<E> with its default result (types.ts:1559): a handler receives the event and the context and returns nothing but an error. A handler that returns a result has its own function type, because a Go function type has one result arity.

type ExtensionMode

type ExtensionMode string

ExtensionMode is the run mode pi is operating in, exposed to extensions via Context.Mode(). Extensions guard terminal-only UI (custom components, dialogs) on mode == ModeTUI.

upstream: packages/coding-agent/src/core/extensions/types.ts:298 (`export type ExtensionMode = "tui" | "rpc" | "json" | "print"`)

const (
	// ModeTUI is the interactive terminal UI. Set by interactive mode
	// (interactive-mode.ts:1511 `mode: "tui"`).
	ModeTUI ExtensionMode = "tui"
	// ModeRPC is the headless JSONL command/event loop. Set by rpc mode
	// (rpc-mode.ts:320 `mode: "rpc"`).
	ModeRPC ExtensionMode = "rpc"
	// ModeJSON is print mode emitting all events as JSON. Set by print
	// mode when its output mode is "json" (print-mode.ts:74).
	ModeJSON ExtensionMode = "json"
	// ModePrint is print mode emitting only the final text response.
	// The upstream Runner default (runner.ts:229).
	ModePrint ExtensionMode = "print"
)

type ExtensionOAuthConfig

type ExtensionOAuthConfig struct {
	Name           string
	IsSubscription bool
	Login          func(context.Context, ai.OAuthLoginCallbacks) (ai.Credential, error)
	RefreshToken   func(context.Context, ai.Credential) (ai.Credential, error)
	GetAPIKey      func(ai.Credential) string
	ModifyModels   func([]*ai.Model, ai.Credential) []*ai.Model
}

ExtensionOAuthConfig is the OAuth configuration of a provider registered with ProviderConfigInput (provider-composer.ts:40); the composer adapts it to native provider auth.

type ExtensionRuntime

type ExtensionRuntime struct {
	// ExtensionActions are the action handlers of upstream ExtensionRuntime, which extends ExtensionActions. Runner.BindCore installs the host's handlers and every extension context calls through them; they are nil until a runner binds.
	ExtensionActions
	// FlagValues holds the value of each extension flag: defaults set during registration, command-line values set afterwards.
	// upstream: types.ts ExtensionRuntimeState.flagValues
	FlagValues map[string]any
	// contains filtered or unexported fields
}

ExtensionRuntime shares pending and bound provider actions between extension loading and the Runner. It stores no model catalog and does not execute factories.

func CreateExtensionRuntime

func CreateExtensionRuntime() *ExtensionRuntime

CreateExtensionRuntime creates the pre-bind provider registration state.

func (*ExtensionRuntime) AssertActive

func (r *ExtensionRuntime) AssertActive() error

AssertActive returns the stale message as an error once the runtime was invalidated, and nil before. upstream: loader.ts assertActive

func (*ExtensionRuntime) BindProviderActions

func (r *ExtensionRuntime) BindProviderActions(actions ProviderActions, report func(*ExtensionError))

BindProviderActions drains the loading queues in order, reports each failure before continuing, and installs immediate actions. Provider registrations drain first, then native providers, then virtual models. Actions left nil leave their queue pending. The owner serializes binding with other binds. Callbacks run outside state locks and may register or unregister providers and virtual models.

upstream: runner.ts:265-294, 413-417, 497-541 (bindCore)

func (*ExtensionRuntime) BoundProviderActions

func (r *ExtensionRuntime) BoundProviderActions() ProviderActions

BoundProviderActions returns the provider actions a host already bound to this runtime. A field is nil until its queue was drained by BindProviderActions.

func (*ExtensionRuntime) CheckMcpServer

func (r *ExtensionRuntime) CheckMcpServer(extensionPath, name string, config json.RawMessage) (McpServerConfig, error)

CheckMcpServer runs the checks of ExtensionRuntime.RegisterMcpServer without registering: the config is valid and no other extension registered the name. It returns the validated config and the error the registration would return.

upstream: loader.ts:456-465 (registerMcpServer)

func (*ExtensionRuntime) CreateContext

func (r *ExtensionRuntime) CreateContext() (*Context, error)

CreateContext builds an extension Context. It returns ErrRuntimeNotInitialized before the runner binds.

upstream: loader.ts:190 (createContext: notInitialized), runner.ts:436

func (*ExtensionRuntime) FlagValue

func (r *ExtensionRuntime) FlagValue(name string) (any, bool)

FlagValue returns the value of an extension flag and whether the flag has one. upstream: loader.ts:329-337 (runtime.flagValues.has/get)

func (*ExtensionRuntime) Invalidate

func (r *ExtensionRuntime) Invalidate(message ...string)

Invalidate marks the runtime stale after runtime replacement or reload. Only the first call takes effect; an empty message selects DefaultStaleRuntimeMessage. upstream: loader.ts invalidate

func (*ExtensionRuntime) McpServers

func (r *ExtensionRuntime) McpServers() *McpServerRegistry

McpServers is the registry of the servers registered with `pi.registerMcpServer()`. Its List returns copies in registration order.

upstream: types.ts:2138 (ExtensionRuntime.mcpServers), loader.ts:495-497 (getMcpServers)

func (*ExtensionRuntime) PendingNativeProviderRegistrations

func (r *ExtensionRuntime) PendingNativeProviderRegistrations() []PendingNativeProviderRegistration

PendingNativeProviderRegistrations returns the queued native providers in registration order.

func (*ExtensionRuntime) PendingProviderRegistrations

func (r *ExtensionRuntime) PendingProviderRegistrations() []PendingProviderRegistration

PendingProviderRegistrations returns the current queue in registration order. Repeated provider names remain separate entries.

func (*ExtensionRuntime) PendingVirtualModelRegistrations

func (r *ExtensionRuntime) PendingVirtualModelRegistrations() []PendingVirtualModelRegistration

PendingVirtualModelRegistrations returns the queue in registration order.

upstream: loader.ts:225-227 (pendingVirtualModelRegistrations)

func (*ExtensionRuntime) RegisterMcpServer

func (r *ExtensionRuntime) RegisterMcpServer(extensionPath, name string, config json.RawMessage) error

RegisterMcpServer validates config as an `mcpServers` entry named name, checks that no other extension registered the name, and registers a copy for extensionPath. A registration replaces the extension's earlier one. The change listener runs after the registry changed.

It returns `Invalid MCP server registered by extension "<path>": <message>` for an invalid config and `MCP server "<name>" is already registered by extension "<owner>"` for a name another extension registered.

It returns `MCP server "<name>" conflicts with registered server "<other>"` for a name that shares the namespace of a registered server.

upstream: loader.ts:464-481 (registerMcpServer stores `structuredClone(validated)`, the alias-resolved copy, at 479)

func (*ExtensionRuntime) RegisterNativeProvider

func (r *ExtensionRuntime) RegisterNativeProvider(ctx context.Context, provider *ai.ModelsProvider, extensionPath ...string) error

RegisterNativeProvider queues a Provider object while extensions load and applies it to the bound registry afterward, as upstream's registerNativeProvider does before and after bindCore. extensionPath defaults to "<unknown>". upstream: loader.ts:215 registerNativeProvider, runner.ts:481-497

func (*ExtensionRuntime) RegisterNativeProviderCarrier

func (r *ExtensionRuntime) RegisterNativeProviderCarrier(ctx context.Context, carrier *NativeProvider, extensionPath ...string) error

RegisterNativeProviderCarrier is RegisterNativeProvider for a Provider object that lives in a subprocess extension: the carrier holds the object's members with the operation's context.Context each callback receives, and the pending registration exposes the object assembled from it.

func (*ExtensionRuntime) RegisterProvider

func (r *ExtensionRuntime) RegisterProvider(name string, config ProviderConfig, extensionPath ...string) error

RegisterProvider queues during loading and invokes the bound registry synchronously afterward. Configuration callbacks are retained, not serialized.

func (*ExtensionRuntime) RegisterVirtualModel

func (r *ExtensionRuntime) RegisterVirtualModel(definition VirtualModelDefinition, extensionPath string) error

RegisterVirtualModel queues a virtual model during loading and applies it through the bound ProviderActions afterward. Registering the same provider and id again replaces the virtual model.

upstream: loader.ts:225-227, runner.ts:497-537 (registerVirtualModel)

func (*ExtensionRuntime) ReplaceFactoryAPI

func (r *ExtensionRuntime) ReplaceFactoryAPI(path string, retire func(message string))

ReplaceFactoryAPI records retire as the way to make the API of the compiled-in extension loaded from path stale, and retires the API a previous load of the same path left. A reload runs a built-in factory again on the runtime the replacement runner keeps, so the API the earlier run captured stops working with the stale message, as upstream's runtime.invalidate makes the old runtime's API fail.

upstream: loader.ts:193-203 (invalidate), agent-session.ts _buildRuntime (a reload creates a new runtime and runs every factory again)

func (*ExtensionRuntime) ReportError

func (r *ExtensionRuntime) ReportError(err *ExtensionError) bool

ReportError delivers err to the bound runner's error listeners. It reports false when no runner has bound.

func (*ExtensionRuntime) SetContextFactory

func (r *ExtensionRuntime) SetContextFactory(create func() (*Context, error))

SetContextFactory installs the function that builds the extension Context a virtual model's Route receives. The runner sets it when it binds.

upstream: runner.ts:436 (runtime.createContext)

func (*ExtensionRuntime) SetErrorReporter

func (r *ExtensionRuntime) SetErrorReporter(report func(*ExtensionError))

SetErrorReporter installs the bound runner's error reporting. pig additive (D107): a subprocess host reports diagnostics that arise outside any handler, such as a rejected extension view, through it.

func (*ExtensionRuntime) SetFlagDefault

func (r *ExtensionRuntime) SetFlagDefault(name string, value any)

SetFlagDefault sets a flag's value unless the flag already has one. upstream: loader.ts:408-412, :538-540 (flagValues.set for a registered default)

func (*ExtensionRuntime) SetMcpServersChangeListener

func (r *ExtensionRuntime) SetMcpServersChangeListener(listener func())

SetMcpServersChangeListener sets the function called after every registration change. The runner sets it when it binds, to emit `mcp_servers_change`; nil removes it.

upstream: runner.ts:459-462 (mcpServers.setChangeListener)

func (*ExtensionRuntime) TrackEventBusSubscription

func (r *ExtensionRuntime) TrackEventBusSubscription(unsubscribe func()) func()

TrackEventBusSubscription retains an event-bus subscription until the runtime is invalidated: Invalidate runs every retained unsubscribe, in subscription order. It returns the unsubscribe function that runs the original once and forgets it. upstream: loader.ts:201-210 trackEventBusSubscription, :198-199 invalidate

func (*ExtensionRuntime) UnregisterMcpServer

func (r *ExtensionRuntime) UnregisterMcpServer(extensionPath, name string)

UnregisterMcpServer removes a server extensionPath registered. Servers of other extensions are left alone.

upstream: loader.ts:470-473 (unregisterMcpServer)

func (*ExtensionRuntime) UnregisterProvider

func (r *ExtensionRuntime) UnregisterProvider(name string, extensionPath ...string)

UnregisterProvider removes every queued registration of name before binding, and invokes the registry immediately afterward. The optional extensionPath is accepted as upstream's second parameter; neither upstream branch reads it. upstream: loader.ts:220 `unregisterProvider: (name) =>`, runner.ts:534

func (*ExtensionRuntime) UnregisterVirtualModel

func (r *ExtensionRuntime) UnregisterVirtualModel(provider, id string)

UnregisterVirtualModel removes every queued registration of the provider and id before binding, and applies the removal through the bound ProviderActions afterward.

upstream: loader.ts:229-233, runner.ts:538-541 (unregisterVirtualModel)

type ExtensionShortcut

type ExtensionShortcut struct {
	Shortcut      KeyID           `json:"shortcut"`
	Description   string          `json:"description,omitempty"`
	Handler       ShortcutHandler `json:"-"`
	ExtensionPath string          `json:"extensionPath"`
}

ExtensionShortcut mirrors upstream's ExtensionShortcut: the loader's view of a registered shortcut, including its source extension.

type ExtensionUIContext

type ExtensionUIContext = UIContext

ExtensionUIContext is upstream's name for UIContext (types.ts:120).

type ExtensionUIDialogOptions

type ExtensionUIDialogOptions struct {
	// Timeout is the dialog's auto-dismiss time in milliseconds, nil for none.
	Timeout *float64 `json:"timeout,omitempty"`
}

ExtensionUIDialogOptions mirrors upstream ExtensionUIDialogOptions. Its `signal` is the dialog call's context.Context (D3), so only the timeout is a field.

type ExtensionVirtualModel

type ExtensionVirtualModel = VirtualModelDefinition

ExtensionVirtualModel is a virtual model registered through API.RegisterVirtualModel. Its Route runs with the extension Context in ctx.

upstream: types.ts:1864-1867 (ExtensionVirtualModel)

type ExtensionWidgetOptions

type ExtensionWidgetOptions struct {
	// Placement is where the widget is rendered. Empty means WidgetPlacementAboveEditor.
	Placement WidgetPlacement `json:"placement,omitempty"`
}

ExtensionWidgetOptions mirrors upstream ExtensionWidgetOptions (core/extensions/types.ts:125); a nil pointer is omitted options.

type FindToolDetails

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

FindToolDetails mirrors upstream find.ts:32.

type FindToolInput

type FindToolInput struct {
	Pattern string   `json:"pattern"`
	Path    *string  `json:"path,omitempty"`
	Limit   *float64 `json:"limit,omitempty"`
	// Extra holds members the schema does not declare; upstream's input is a plain object that keeps them.
	Extra map[string]json.RawMessage `json:"-"`
}

FindToolInput is upstream's FindToolInput (find.ts findSchema).

func (FindToolInput) MarshalJSON

func (in FindToolInput) MarshalJSON() ([]byte, error)

func (*FindToolInput) UnmarshalJSON

func (in *FindToolInput) UnmarshalJSON(data []byte) error

type FindToolResultEvent

type FindToolResultEvent struct {
	ToolResultEventBase
	ToolName string           `json:"toolName"` // "find"
	Details  *FindToolDetails `json:"details,omitempty"`
}

FindToolResultEvent: upstream types.ts FindToolResultEvent.

func (FindToolResultEvent) MarshalJSON

func (e FindToolResultEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the event in Pi's member order; see [marshalToolResultEvent].

type FlagOptions

type FlagOptions struct {
	Description string   `json:"description,omitempty"`
	Type        FlagType `json:"type"`
	// Default is bool when Type == FlagBoolean and string when
	// Type == FlagString. Nil when no default.
	Default any `json:"default,omitempty"`
}

FlagOptions is the registration payload for API.RegisterFlag. Mirrors the inline option object on upstream ExtensionAPI.registerFlag.

type FlagType

type FlagType string

FlagType is the value type of a CLI flag registered by an extension. Mirrors upstream's "boolean" | "string" union.

const (
	FlagBoolean FlagType = "boolean"
	FlagString  FlagType = "string"
)

type FooterFactory

type FooterFactory func(host tui.TUI, theme *tui.Theme, footerData ReadonlyFooterDataProvider) DisposableComponent

FooterFactory builds an extension's footer component (types.ts ExtensionUIContext.setFooter: `(tui: TUI, theme: Theme, footerData: ReadonlyFooterDataProvider) => Component & { dispose?(): void }`).

func FrameFooter

func FrameFooter(lines []string, width int) FooterFactory

FrameFooter is the footer factory of an extension process.

func ViewFooter

func ViewFooter(view FramedView) FooterFactory

ViewFooter is the footer factory of a frame drawn from a view.

type ForkOptions

type ForkOptions struct {
	Position    string                              `json:"position,omitempty"` // "before" | "at"
	WithSession func(*ReplacedSessionContext) error `json:"-"`
}

ForkOptions mirrors upstream's fork options.

upstream: types.ts:342-343

type FramedView

type FramedView struct {
	View  ViewSurface
	Width int
}

FramedView is a header or footer frame drawn from a ViewSurface: Width is the terminal width a Node frame's lines were laid out at, or 0 for an authoritative view the host renders at any width.

func (FramedView) Dispose

func (FramedView) Dispose()

Dispose is a no-op: the bridge that made the view closes it when the slot changes.

func (FramedView) Invalidate

func (f FramedView) Invalidate()

Invalidate drops the view's cached lines.

func (FramedView) Render

func (f FramedView) Render(width int) []string

Render draws the view at width, so a framed view is the header or footer component its factory builds. A host that recognizes a FramedView installs the view instead, to keep its structure and its laid-out width.

type GrepToolDetails

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

GrepToolDetails mirrors upstream grep.ts:41. Sparse fields retain the requested numeric limit without rounding.

type GrepToolInput

type GrepToolInput struct {
	Pattern    string   `json:"pattern"`
	Path       *string  `json:"path,omitempty"`
	Glob       *string  `json:"glob,omitempty"`
	IgnoreCase *bool    `json:"ignoreCase,omitempty"`
	Literal    *bool    `json:"literal,omitempty"`
	Context    *float64 `json:"context,omitempty"`
	Limit      *float64 `json:"limit,omitempty"`
	// Extra holds members the schema does not declare; upstream's input is a plain object that keeps them.
	Extra map[string]json.RawMessage `json:"-"`
}

GrepToolInput is upstream's GrepToolInput (grep.ts grepSchema).

func (GrepToolInput) MarshalJSON

func (in GrepToolInput) MarshalJSON() ([]byte, error)

func (*GrepToolInput) UnmarshalJSON

func (in *GrepToolInput) UnmarshalJSON(data []byte) error

type GrepToolResultEvent

type GrepToolResultEvent struct {
	ToolResultEventBase
	ToolName string           `json:"toolName"` // "grep"
	Details  *GrepToolDetails `json:"details,omitempty"`
}

GrepToolResultEvent: upstream types.ts GrepToolResultEvent.

func (GrepToolResultEvent) MarshalJSON

func (e GrepToolResultEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the event in Pi's member order; see [marshalToolResultEvent].

type HandlerFn

type HandlerFn = func(args ...any) (any, error)

HandlerFn is the type-erased storage shape for event handlers.

The typed API methods (`OnToolCall`, `OnSessionStart`, ...) accept strongly-typed handler functions and wrap them into HandlerFn for storage in `Extension.Handlers`. The Runner reverses the wrap when dispatching: for each event firing, it looks up handlers by event name, calls each with the typed payload boxed as `any`, and casts the returned `any` back to the typed *EventResult shape.

This is the implementation detail of D1, which uses type erasure where Go cannot express upstream's generic event-handler map. Typed API methods and SDK helpers keep HandlerFn out of normal extension authoring.

upstream: types.ts:1380 (type HandlerFn = (...args: unknown[]) => Promise<unknown>)

type HeaderFactory

type HeaderFactory func(host tui.TUI, theme *tui.Theme) DisposableComponent

HeaderFactory builds an extension's header component (types.ts ExtensionUIContext.setHeader: `(tui: TUI, theme: Theme) => Component & { dispose?(): void }`). A component that has a Dispose method is disposed when the header is replaced or restored.

func FrameHeader

func FrameHeader(lines []string, width int) HeaderFactory

FrameHeader is the header factory of an extension process: the component it builds is the frame the process rendered, at the width it rendered it.

func ViewHeader

func ViewHeader(view FramedView) HeaderFactory

ViewHeader is the header factory of a frame drawn from a view.

type HiddenThinkingLabelClearer

type HiddenThinkingLabelClearer interface {
	ClearHiddenThinkingLabel()
}

HiddenThinkingLabelClearer is implemented by a UIContext that tells an absent hidden-thinking label from an empty one, as WorkingMessageClearer does for the working message: Pi's setHiddenThinkingLabel(label?: string) shows `label ?? defaultHiddenThinkingLabel` (interactive-mode.ts:2383). The extension host calls ClearHiddenThinkingLabel when an extension sends no label and falls back to SetHiddenThinkingLabel("") for a UIContext that does not implement it.

type ImageContent

type ImageContent = ai.ImageContent

ImageContent mirrors @earendil-works/pi-ai ImageContent.

type InlineExtension

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

InlineExtension is types.ts:2008 `InlineExtension`: an ExtensionFactory, or a NamedInlineExtension that also names the extension and says how it loads. The set is closed: only those two forms implement it.

type InputEvent

type InputEvent struct {
	Type   string         `json:"type"`
	Text   string         `json:"text"`
	Images []ImageContent `json:"images,omitempty"`
	Source InputSource    `json:"source"`
	// StreamingBehavior indicates context when input arrives during streaming.
	// "steer" = mid-stream steer, "followUp" = queued follow-up.
	// Empty when the agent is idle. Mirrors upstream v0.77.0.
	StreamingBehavior string `json:"streamingBehavior,omitempty"`
}

InputEvent: upstream types.ts InputEvent.

type InputEventResult

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

InputEventResult is the sealed union of handler responses for the "input" extension event. Mirrors upstream `types.ts InputEventResult`:

export type InputEventResult =
    | { action: "continue" }
    | { action: "transform"; text: string; images?: ImageContent[] }
    | { action: "handled" };

The interface is package-sealed via the unexported `isInputEventResult` marker method: only the three variants in this package can satisfy it. Custom MarshalJSON/UnmarshalJSON in marshalling.go preserves upstream's `{"action": "..."}` discriminator wire shape.

Authors return one of:

upstream: types.ts:750

func UnmarshalInputEventResult

func UnmarshalInputEventResult(data []byte) (InputEventResult, error)

UnmarshalInputEventResult parses upstream wire shape into the matching sealed-interface variant. Returns an error on unknown action discriminators so silent drift cannot enter the system.

type InputEventResultContinue

type InputEventResultContinue struct{}

InputEventResultContinue: upstream `{ action: "continue" }`.

type InputEventResultHandled

type InputEventResultHandled struct{}

InputEventResultHandled: upstream `{ action: "handled" }`. Tells the host the extension fully handled the input; the agent does NOT run for this turn.

type InputEventResultTransform

type InputEventResultTransform struct {
	Text   string         `json:"text"`
	Images []ImageContent `json:"images,omitempty"`
}

InputEventResultTransform: upstream `{ action: "transform"; text: string; images?: ImageContent[] }`. Replaces the user input before it reaches the agent.

type InputSource

type InputSource = string

InputSource mirrors upstream "interactive" | "rpc" | "extension".

const (
	InputSourceUser      InputSource = "interactive"
	InputSourceRPC       InputSource = "rpc"
	InputSourceExtension InputSource = "extension"
)

type KeyID

type KeyID = string

KeyID identifies a keyboard shortcut. Mirrors @mariozechner/pi-tui KeyId, which is a string (e.g. "ctrl+shift+l", "alt+enter").

type KeybindingsManager

type KeybindingsManager = *tui.TUIKeybindingsManager

KeybindingsManager mirrors core/keybindings.KeybindingsManager.

type LiveRemoteEditor

type LiveRemoteEditor interface {
	RenderFrame(width int) []string
}

LiveRemoteEditor is a RemoteEditor that runs in the host's process and renders on demand: the host shows what RenderFrame returns at the width of each render instead of the last frame the editor pushed.

type LoginDefinition

type LoginDefinition struct {
	Brand       []string          `json:"brand"`
	Hero        []string          `json:"hero"`
	Mascot      []string          `json:"mascot"`
	Palette     map[string]string `json:"palette"`
	Name        string            `json:"name"`
	Description string            `json:"description"`
	Tagline     string            `json:"tagline"`
}

LoginDefinition describes one login using Pig's fixed native template. Grid cells are printable ASCII palette symbols; '.' is transparent.

type LoginDefinitionError

type LoginDefinitionError struct {
	Field   string
	Message string
}

LoginDefinitionError identifies the invalid field in a login definition.

func (*LoginDefinitionError) Error

func (e *LoginDefinitionError) Error() string

type LsToolDetails

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

LsToolDetails mirrors upstream ls.ts:23, including fractional requested limits.

type LsToolInput

type LsToolInput struct {
	Path  *string  `json:"path,omitempty"`
	Limit *float64 `json:"limit,omitempty"`
	// Extra holds members the schema does not declare; upstream's input is a plain object that keeps them.
	Extra map[string]json.RawMessage `json:"-"`
}

LsToolInput is upstream's LsToolInput (ls.ts lsSchema).

func (LsToolInput) MarshalJSON

func (in LsToolInput) MarshalJSON() ([]byte, error)

func (*LsToolInput) UnmarshalJSON

func (in *LsToolInput) UnmarshalJSON(data []byte) error

type LsToolResultEvent

type LsToolResultEvent struct {
	ToolResultEventBase
	ToolName string         `json:"toolName"` // "ls"
	Details  *LsToolDetails `json:"details,omitempty"`
}

LsToolResultEvent: upstream types.ts LsToolResultEvent.

func (LsToolResultEvent) MarshalJSON

func (e LsToolResultEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the event in Pi's member order; see [marshalToolResultEvent].

type MarkdownMessageType

type MarkdownMessageType = markdowntransform.MarkdownMessageType

MarkdownMessageType identifies the transcript message being transformed for display. It is markdowntransform.MarkdownMessageType, shared with the tui message components.

type MarkdownTransformContext

type MarkdownTransformContext = markdowntransform.MarkdownTransformContext

MarkdownTransformContext mirrors upstream MarkdownTransformContext. It is markdowntransform.MarkdownTransformContext.

type MarkdownTransformer

type MarkdownTransformer = markdowntransform.MarkdownTransformer

MarkdownTransformer performs a synchronous display-only Markdown rewrite. It is markdowntransform.MarkdownTransformer.

type McpAuthConfig

type McpAuthConfig struct {
	Provider string `json:"provider"`
}

McpAuthConfig sends the token of a pi provider (`/login <provider>`) as the bearer token instead of using OAuth.

type McpExposure

type McpExposure string

McpExposure selects how the model reaches the tools of an MCP server.

  • codemode: tools are callable from codemode scripts, but not declared to the model and not listed in the codemode description, which lists only the server's namespace. Scripts find them with searchTools(). "codemode-deferred" is accepted as an alias.
  • deferred: not declared to the model until the tool_search tool loads them; the model then calls them directly. Does not need codemode.
  • direct: tools are declared to the model like any other tool (and callable from codemode).
  • hidden: tools are registered but unreachable.
const (
	McpExposureCodemode McpExposure = "codemode"
	McpExposureDeferred McpExposure = "deferred"
	McpExposureDirect   McpExposure = "direct"
	McpExposureHidden   McpExposure = "hidden"
)

The exposures of upstream's McpExposure union.

func GetMcpToolExposure

func GetMcpToolExposure(config McpServerConfig, toolName string) McpExposure

GetMcpToolExposure is the exposure of one tool of a server: its `toolExposure` entry, else the server's `exposure`.

type McpOAuthConfig

type McpOAuthConfig struct {
	// ClientID is a pre-registered client id. Without it, a client is registered
	// with the authorization server.
	ClientID string `json:"clientId,omitempty"`
	// ClientSecret may reference environment variables (`${NAME}`) or commands (`!cmd`).
	ClientSecret string `json:"clientSecret,omitempty"`
	// CallbackPort is the port of the loopback callback server, for clients
	// registered with a fixed redirect URI. Without CallbackURL, the redirect URI
	// is `http://127.0.0.1:<port>/callback`.
	CallbackPort *int `json:"callbackPort,omitempty"`
	// CallbackURL is the redirect URI registered for ClientID, for example
	// `http://localhost:8080/oauth/callback`. It must be an `http` URI on
	// `localhost`, `127.0.0.1`, or `[::1]`. Without a port, the callback server
	// listens on CallbackPort or a free port, which is added to the URI (RFC 8252).
	CallbackURL string `json:"callbackUrl,omitempty"`
	// Scope lists the scopes to request, separated by spaces. Default: the
	// scopes the server advertises.
	Scope string `json:"scope,omitempty"`
	// ClientName is the `client_name` sent with dynamic client registration,
	// for servers that only accept known clients. Default: the app name.
	ClientName string `json:"clientName,omitempty"`
	// ClientRegistration is how pi identifies itself without ClientID. `dcr`
	// (default): dynamic client registration. `cimd`: pi's Client ID Metadata
	// Document on pi.dev, for authorization servers that allow pi by that URL.
	// The server must support it for public clients, and the callback must use
	// the default path `/callback`.
	ClientRegistration string `json:"clientRegistration,omitempty"`
	// AuthServerMetadataURL is an authorization server metadata document
	// (RFC 8414 or OpenID Connect discovery) to use instead of discovery
	// through the server, for servers that advertise a wrong authorization
	// server or none. The document is trusted as configured. It must use
	// https, except on loopback hosts.
	AuthServerMetadataURL string `json:"authServerMetadataUrl,omitempty"`
}

McpOAuthConfig is OAuth client settings for servers that do not support dynamic client registration.

func (*McpOAuthConfig) UnmarshalJSON

func (c *McpOAuthConfig) UnmarshalJSON(data []byte) error

UnmarshalJSON reads `callbackPort` as a JavaScript number, so `8080.0` and `8e3` are the integers validation accepts.

type McpServerConfig

type McpServerConfig struct {
	// Type is "stdio" or "http"; "streamable-http" is accepted for HTTP servers.
	Type string `json:"type,omitempty"`
	// Exposure defaults to codemode.
	Exposure McpExposure `json:"exposure,omitempty"`
	// Description is what the server offers, in a sentence. The `mcp_servers`
	// system prompt section lists the server with it, tool search ranks the
	// server's tools by it, and codemode's `describeNamespace()` returns it.
	Description string `json:"description,omitempty"`
	// ToolExposure overrides Exposure for single tools. Keys are tool names as
	// the server offers them, or patterns where `*` matches any characters. An
	// exact name wins over patterns; among patterns the first match in the
	// object wins. hidden removes tools, so `"exposure": "hidden"` with overrides
	// for a few tools exposes only those.
	ToolExposure *OrderedExposures `json:"toolExposure,omitempty"`
	// Enabled set to false keeps the entry without connecting. Default: true.
	Enabled *bool `json:"enabled,omitempty"`
	// Timeout is the per-request timeout in seconds. Progress notifications from
	// the server reset it. Default: 60.
	Timeout *float64 `json:"timeout,omitempty"`

	// Stdio servers.
	Command string   `json:"command,omitempty"`
	Args    []string `json:"args,omitempty"`
	// Env values may reference environment variables (`${NAME}`) or commands (`!cmd`).
	Env *OrderedStrings `json:"env,omitempty"`
	// Cwd is relative to the session working directory.
	Cwd string `json:"cwd,omitempty"`

	// HTTP servers.
	URL string `json:"url,omitempty"`
	// Headers values may reference environment variables (`${NAME}`) or commands (`!cmd`).
	Headers *OrderedStrings `json:"headers,omitempty"`
	OAuth   *McpOAuthConfig `json:"oauth,omitempty"`
	// Auth sends the token of a pi provider instead of using OAuth. Not allowed
	// in project `mcp.json` files, and requires https except on loopback hosts.
	Auth *McpAuthConfig `json:"auth,omitempty"`
}

McpServerConfig is one server entry of the `mcpServers` shape. It is either a stdio server (Command set) or a streamable HTTP server (URL set): upstream's McpStdioServerConfig | McpHttpServerConfig union.

func ValidateMcpServerConfig

func ValidateMcpServerConfig(name string, value json.RawMessage) (McpServerConfig, string)

ValidateMcpServerConfig validates one entry of the `mcpServers` shape. It returns the config, or the message upstream's validation returns as a string.

func (McpServerConfig) IsHTTP

func (c McpServerConfig) IsHTTP() bool

IsHTTP reports whether the entry is a streamable HTTP server: upstream's `"url" in config` check.

type McpServerRegistry

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

McpServerRegistry holds the servers registered by the extensions of one runtime. It is safe for concurrent use; the change listener and the change observers run after the registry's lock is released.

func NewMcpServerRegistry

func NewMcpServerRegistry() *McpServerRegistry

NewMcpServerRegistry returns an empty registry.

func (*McpServerRegistry) Get

Get returns a registered server.

func (*McpServerRegistry) List

List returns copies of the registered servers, in registration order.

func (*McpServerRegistry) ObserveChange

func (r *McpServerRegistry) ObserveChange(observe func()) func()

ObserveChange registers observe to run after every change to the registry, after the change listener. Upstream's registry has the one listener the runner owns (runner.ts:465-467), and `pi.getMcpServers()` reads the registry live (loader.ts:495-497); an owner that hands a copy of the list to a runtime that has no `mcp_servers_change` handler reports each change through this. observe runs on the goroutine that changed the registry, after it released its lock, and must return at once. The returned function removes it and can be called repeatedly.

func (*McpServerRegistry) Register

func (r *McpServerRegistry) Register(server RegisteredMcpServer)

Register adds or replaces a server. The caller checks ownership. A replaced server keeps its position, as a JavaScript Map does.

func (*McpServerRegistry) SetChangeListener

func (r *McpServerRegistry) SetChangeListener(listener func())

SetChangeListener sets the function called after every change. The runner sets it when it binds, to emit `mcp_servers_change`.

func (*McpServerRegistry) Unregister

func (r *McpServerRegistry) Unregister(name, extensionPath string)

Unregister removes a server registered by extensionPath. Servers of other extensions are left alone.

type McpServersChangeEvent

type McpServersChangeEvent struct {
	Type string `json:"type"`
	// Servers is every registered server after the change.
	Servers []RegisteredMcpServer `json:"servers"`
}

McpServersChangeEvent: upstream types.ts McpServersChangeEvent. Fired when an extension registers or unregisters an MCP server after the extensions are bound (see API.RegisterMcpServer). Servers registered while extensions load are read with API.GetMcpServers on session_start. Handling this event marks an extension as the one that connects registered servers.

upstream: types.ts:699-709

type MessageEndEvent

type MessageEndEvent struct {
	Type    string       `json:"type"`
	Message AgentMessage `json:"message"`
}

MessageEndEvent: upstream types.ts MessageEndEvent.

type MessageEndEventResult

type MessageEndEventResult struct {
	// Message replaces the finalized message. Replacement must preserve role.
	Message *AgentMessage `json:"message,omitempty"`
}

MessageEndEventResult mirrors upstream message_end handler result.

type MessageRenderOptions

type MessageRenderOptions struct {
	Expanded bool `json:"expanded"`
	// OutputPad is the horizontal padding configured by the outputPad setting.
	OutputPad int `json:"outputPad"`
}

MessageRenderOptions is passed to a MessageRenderer.

type MessageRenderer

type MessageRenderer = func(
	message CustomMessage,
	options MessageRenderOptions,
	theme Theme,
) Component

MessageRenderer mirrors upstream MessageRenderer<T>. Renders a custom session message into a TUI Component, or returns nil to fall back to the default renderer.

The Go signature drops the TS generic parameter T: the message's data is carried on CustomMessage (Content and Details are `any`) and the renderer type-asserts as needed. This avoids the compilation explosion of N generic instantiations across the host package and matches how subprocess extensions see this surface (untyped JSON over the wire).

type MessageStartEvent

type MessageStartEvent struct {
	Type    string       `json:"type"`
	Message AgentMessage `json:"message"`
}

MessageStartEvent: upstream types.ts MessageStartEvent.

type MessageUpdateEvent

type MessageUpdateEvent struct {
	Type                  string                `json:"type"`
	Message               AgentMessage          `json:"message"`
	AssistantMessageEvent AssistantMessageEvent `json:"assistantMessageEvent"`
}

MessageUpdateEvent: upstream types.ts MessageUpdateEvent.

type Model

type Model = *ai.Model

Model mirrors @earendil-works/pi-ai Model<Api>.

type ModelRegistry

type ModelRegistry interface {
	// Refresh reloads models.json and provider catalogs; a caller awaits it before synchronous reads (model-registry.ts:56).
	Refresh(ctx context.Context, options ai.ModelsRefreshOptions) ai.ModelsRefreshResult
	// GetError is the current model configuration diagnostic, or "" (model-registry.ts:60).
	GetError() string
	// GetAll is every known chat model (model-registry.ts:64).
	GetAll() []*ai.Model
	// GetAvailable is the chat models whose provider has configured auth (model-registry.ts:68).
	GetAvailable() []*ai.Model
	// Find is the chat model with this provider and ID, or nil (model-registry.ts:72).
	Find(provider, modelID string) *ai.Model
	// FindOfType is the model of a non-chat type, or nil (model-registry.ts:77).
	FindOfType(modelType ai.ModelType, provider, modelID string) ai.AnyModel
	// HasConfiguredAuth reports whether the model's provider has configured auth (model-registry.ts:85).
	HasConfiguredAuth(model *ai.Model) bool
	// GetAPIKeyAndHeaders resolves the model's request credentials; it never fails, reporting a failure in the result (model-registry.ts:89).
	GetAPIKeyAndHeaders(ctx context.Context, model *ai.Model) ResolvedRequestAuth
	// GetProviderAuthStatus is how the provider is authenticated (model-registry.ts:120).
	GetProviderAuthStatus(provider string) ai.AuthStatus
	// GetProvider is the composed provider, or nil (model-registry.ts:124).
	GetProvider(provider string) *ai.ModelsProvider
	// Stream streams through the configured provider with request-time authentication (model-registry.ts:129).
	Stream(ctx context.Context, model *ai.Model, request ai.Context, options ai.StreamOptions) *ai.AssistantMessageEventStream
	// StreamSimple streams with provider-neutral options and request-time authentication (model-registry.ts:138).
	StreamSimple(ctx context.Context, model *ai.Model, request ai.Context, options ai.StreamOptions) *ai.AssistantMessageEventStream
	// Complete is Stream's final message (model-registry.ts:142).
	Complete(ctx context.Context, model *ai.Model, request ai.Context, options ai.StreamOptions) *ai.AssistantMessage
	// GetModelsOfType is every known model of a type, optionally for one provider (model-registry.ts:151).
	GetModelsOfType(modelType ai.ModelType, provider ...string) []ai.AnyModel
	// GetAvailableOfType is the models of a type whose provider has working credentials (model-registry.ts:156).
	GetAvailableOfType(ctx context.Context, modelType ai.ModelType, provider ...string) ([]ai.AnyModel, error)
	// GetModelOfType is the model of a type with this provider and ID, or nil (model-registry.ts:164).
	GetModelOfType(modelType ai.ModelType, provider, modelID string) ai.AnyModel
	// Classify classifies structured state with request-time authentication; it never fails (model-registry.ts:173).
	Classify(ctx context.Context, model *ai.ClassifierModel, request ai.ClassifierContext, options ...ai.ModelsClassifierOptions) ai.ClassifierResult
	// GenerateImages generates images with request-time authentication; it never fails (model-registry.ts:182).
	GenerateImages(ctx context.Context, model *ai.ImageModel, request ai.ImagesContext, options ...ai.ModelsImagesOptions) ai.AssistantImages
	// GetProviderDisplayName is the provider's name, or its ID when it has none (model-registry.ts:190).
	GetProviderDisplayName(provider string) string
	// GetProviderAuth resolves the provider's authentication (model-registry.ts:194).
	GetProviderAuth(ctx context.Context, provider string) (*ai.AuthResult, error)
	// GetAPIKeyForProvider is the provider's API key, or nil when authentication is absent or fails (model-registry.ts:198).
	GetAPIKeyForProvider(ctx context.Context, provider string) *string
	// IsUsingOAuth reports whether the model's provider authenticates with OAuth (model-registry.ts:206).
	IsUsingOAuth(model *ai.Model) bool
	// RegisterProvider registers a provider by name (model-registry.ts:211 registerProvider(providerName, config)).
	RegisterProvider(name string, config ProviderConfigInput) error
	// RegisterProviderObject registers a Provider (model-registry.ts:210 registerProvider(provider)).
	RegisterProviderObject(provider *ai.ModelsProvider) error
	// UnregisterProvider removes a registered provider (model-registry.ts:221).
	UnregisterProvider(name string)
	// RegisterVirtualModel registers a virtual model (model-registry.ts:225).
	RegisterVirtualModel(definition VirtualModelDefinition) error
	// UnregisterVirtualModel removes a virtual model (model-registry.ts:229).
	UnregisterVirtualModel(provider, id string)
	// GetRegisteredProviderConfig is the configuration a provider was registered with by name, or nil (model-registry.ts:233).
	GetRegisteredProviderConfig(name string) *ProviderConfigInput
	// GetRegisteredNativeProvider is the Provider registered under the name, or nil (model-registry.ts:237).
	GetRegisteredNativeProvider(name string) *ai.ModelsProvider
	// GetRegisteredProviderIDs lists the registered providers (model-registry.ts:241).
	GetRegisteredProviderIDs() []string
}

ModelRegistry is the synchronous model-registry facade an extension reaches through ctx.modelRegistry (model-registry.ts:48). It has every public member of Pi's ModelRegistry; the Session's registry implements it. Pi's asynchronous members block until their result is ready and take the request's context. Pi's registerProvider overloads are RegisterProvider (name and ProviderConfigInput) and RegisterProviderObject (a Provider).

type ModelRoute

type ModelRoute struct {
	Model         *ai.Model
	ThinkingLevel ai.ModelThinkingLevel
	// State is the new router state, stored on the session branch unless it is the request's own state. Return the request's state or nil to keep the current state. Must be JSON. Ignored for `direct` requests.
	State json.RawMessage
}

ModelRoute is the physical model and thinking level for one request.

upstream: virtual-models.ts:75-85 (ModelRoute)

type ModelRouteFailed

type ModelRouteFailed struct {
	Model         *ai.Model
	ThinkingLevel ai.ModelThinkingLevel
	Message       ai.AssistantMessage
}

ModelRouteFailed is the failed request of a `retry`, which the request's messages no longer contain. Message carries its stop reason and error message.

type ModelRouteFunc

type ModelRouteFunc = func(ctx context.Context, request ModelRouteRequest) (ModelRoute, error)

ModelRouteFunc picks the physical model, which must have credentials, and thinking level for one request. ctx carries the request's cancellation and, for an extension's virtual model, the extension Context (FromContext).

upstream: virtual-models.ts:100 (VirtualModelDefinition.route), types.ts:1866 (ExtensionVirtualModel.route)

type ModelRoutePrevious

type ModelRoutePrevious struct {
	Model         *ai.Model
	ThinkingLevel ai.ModelThinkingLevel
}

ModelRoutePrevious is the physical model and thinking level of the latest successful response in a request's messages.

type ModelRouteReason

type ModelRouteReason string

ModelRouteReason says why a request is being routed.

  • user: first request after a message the user wrote (prompt, steering, or follow-up)
  • continuation: any other request in the agent loop, e.g. after tool results or extension messages
  • retry: automatic retry after a failed request, including after compaction for a context overflow
  • direct: a request outside the agent loop, e.g. a compaction summary or an extension call

upstream: virtual-models.ts:53 (ModelRouteReason)

const (
	ModelRouteReasonUser         ModelRouteReason = "user"
	ModelRouteReasonContinuation ModelRouteReason = "continuation"
	ModelRouteReasonRetry        ModelRouteReason = "retry"
	ModelRouteReasonDirect       ModelRouteReason = "direct"
)

The reasons of upstream's ModelRouteReason union.

type ModelRouteRequest

type ModelRouteRequest struct {
	// Model is the selected virtual model.
	Model *ai.Model
	// ThinkingLevel is the selected thinking level. Its meaning is up to the router.
	ThinkingLevel ai.ModelThinkingLevel
	Reason        ModelRouteReason
	// Previous is the physical model and thinking level of the latest successful response in Messages.
	Previous *ModelRoutePrevious
	// Failed is the failed request of a retry. Absent when the router itself failed.
	Failed *ModelRouteFailed
	// State is the router state last returned on this session branch. Absent before the first state and for `direct` requests.
	State json.RawMessage
	// Messages is the conversation for this request, including system messages.
	Messages []ai.Message
}

ModelRouteRequest is what a router sees for one request.

Go mechanic (not a divergence): upstream's `signal` is the context.Context passed to Route, and the TState of `state` is a JSON value (an absent state is nil).

upstream: virtual-models.ts:55-72 (ModelRouteRequest)

type ModelSelectEvent

type ModelSelectEvent struct {
	Type          string            `json:"type"`
	Model         Model             `json:"model"`
	PreviousModel Model             `json:"previousModel,omitempty"`
	Source        ModelSelectSource `json:"source"`
}

ModelSelectEvent: upstream types.ts ModelSelectEvent.

type ModelSelectSource

type ModelSelectSource = string

ModelSelectSource mirrors upstream "set" | "cycle" | "restore".

const (
	ModelSelectSourceUser    ModelSelectSource = "set"
	ModelSelectSourceCycle   ModelSelectSource = "cycle"
	ModelSelectSourceRestore ModelSelectSource = "restore"
)

type ModelStreamRequest

type ModelStreamRequest struct {
	API              bool
	Fetch            *http.Client
	OnPayload        func(any, *ai.Model) (any, error)
	OnResponse       func(context.Context, ai.ProviderResponse, *ai.Model) error
	TransformHeaders func(context.Context, ai.ProviderHeaders) (ai.ProviderHeaders, error)
}

ModelStreamRequest carries a resolved API-leaf request and connection-owned callbacks. API leaves use the caller's model/auth, not the parent catalog.

func ModelStreamRequestFromContext

func ModelStreamRequestFromContext(ctx context.Context) ModelStreamRequest

ModelStreamRequestFromContext returns the transport contract for this operation.

type ModelValue

type ModelValue struct{ Model ai.AnyModel }

ModelValue is a model inside a larger JSON value: it encodes as the model's ModelObject (null for a nil model), and that encoding fails with ModelObject's error.

func (ModelValue) MarshalJSON

func (v ModelValue) MarshalJSON() ([]byte, error)

MarshalJSON encodes the model's ModelObject.

type NamedInlineExtension

type NamedInlineExtension struct {
	// Name is shown as `<inline:name>` in the startup Extensions list and errors. With Builtin, the extension is named `builtin:name` in errors and diagnostics.
	Name    string
	Factory ExtensionFactory
	// Hidden omits the extension from the startup Extensions list.
	Hidden bool
	// Replaceable leaves the extension out when another extension registers a tool, command or flag with a name it registers during loading, instead
	// of reporting a conflict. The factory still runs, so it should only register tools, commands, flags and event handlers.
	Replaceable bool
	// Builtin supplies the code of the `builtin:<name>` extension resource instead of loading as an inline extension: it loads by default, `pig config`
	// lists it, `-builtin:<name>` in the `extensions` setting and --no-extensions disable it, and `-e builtin:<name>` loads it explicitly. It is hidden
	// from the startup Extensions list and loads after project trust is resolved, so it cannot handle `project_trust`.
	Builtin bool
}

NamedInlineExtension is the object member of types.ts:2008 `InlineExtension`.

type NativeProvider

type NativeProvider struct {
	// IsCurrent guards publication when host registrations overlap across connections.
	IsCurrent func() bool
	ID        string
	Name      string
	BaseURL   string
	// Headers is Pi's Provider.headers: the provider's declared header names and values. A null value is a header the provider removes.
	// upstream: packages/ai/src/models.ts:155 (Provider.headers), read by packages/coding-agent/src/core/bug-report.ts:119
	Headers ai.ProviderHeaders
	Models  []ProviderModelConfig
	// Auth is Pi's Provider.auth: the API-key and OAuth methods the provider supports. Registration reads it for the provisional configured auth type.
	// upstream: packages/ai/src/models.ts:164 (Provider.auth), packages/coding-agent/src/core/model-runtime.ts:885-897
	Auth      ai.ProviderAuth
	CheckAuth func(context.Context, *ai.Credential) (*ai.AuthCheck, error)
	// GetModels lists the provider's current chat models, as the provider object reports them now; Models is the list it declared at registration. A nil GetModels leaves the registered list as the current one.
	// upstream: pi-ai Provider.getModels
	GetModels func(context.Context) ([]*ai.Model, error)
	// GetAllModels lists the models of every type and FilterAllModels filters them by credential; nil when the provider object has no such member.
	// upstream: pi-ai Provider.getAllModels, Provider.filterAllModels
	GetAllModels             func(context.Context) ([]ai.AnyModel, error)
	FilterAllModels          func(context.Context, []ai.AnyModel, *ai.Credential) ([]ai.AnyModel, error)
	FilterModels             func(context.Context, []*ai.Model, *ai.Credential) ([]*ai.Model, error)
	ResolveAuth              func(context.Context, *ai.Credential, ai.AuthResolutionOverrides) (*ai.AuthResult, *ai.Credential, error)
	ResolveRefreshCredential func(context.Context, *ai.Credential) (*ai.Credential, *ai.Credential, error)
	RefreshModels            func(ai.RefreshModelsContext) error
	Stream                   func(context.Context, *ai.Model, ai.TranscriptContext, ai.StreamOptions) (*ai.AssistantMessageEventStream, error)
	// StreamSimple is the provider's simple stream method; a provider with only Stream serves simple requests through it.
	// upstream: pi-ai Provider.streamSimple
	StreamSimple func(context.Context, *ai.Model, ai.TranscriptContext, ai.StreamOptions) (*ai.AssistantMessageEventStream, error)
	// FetchDeferred and CancelDeferred are the provider object's deferred-response operations; nil when it has none.
	// upstream: pi-ai Provider.fetchDeferred, Provider.cancelDeferred
	FetchDeferred  func(context.Context, *ai.Model, ai.DeferredHandle, ai.DeferredFetchOptions) (*ai.AssistantMessageEventStream, error)
	CancelDeferred func(context.Context, *ai.Model, ai.DeferredHandle, ai.DeferredCancelOptions) error
	// GenerateImages and Classify are the provider object's image and classifier operations; nil when it has none.
	// upstream: pi-ai Provider.generateImages, Provider.classify
	GenerateImages func(context.Context, *ai.ImageModel, ai.ImagesContext, ai.ImagesOptions) (ai.AssistantImages, error)
	Classify       func(context.Context, *ai.ClassifierModel, ai.ClassifierContext, ai.ClassifierOptions) (ai.ClassifierResult, error)
}

NativeProvider is a session-owned carrier for Pi's native Provider callbacks. Metadata is immutable; refresh publishes replacement model snapshots. The host owns credentials and persistence, and every callback receives its operation context.

func NativeProviderOf

func NativeProviderOf(provider *ai.ModelsProvider) *NativeProvider

NativeProviderOf is the registration carrier of a provider object a compiled-in extension built: every member the object has is the carrier's member of the same name, so the registry sees the object as it would see a subprocess extension's provider. upstream: packages/coding-agent/src/core/extensions/types.ts registerProvider(name, provider: Provider)

func (*NativeProvider) ProviderObject

func (p *NativeProvider) ProviderObject() *ai.ModelsProvider

ProviderObject is the Provider object a carrier made by NativeProviderOf was built from, assembled again from the carrier's members. A registry registers a compiled-in extension's provider as that object: it has no host callbacks, only the object's own auth, model and stream members. upstream: packages/coding-agent/src/core/model-runtime.ts registerNativeProvider(provider: Provider)

type NavigateTreeOptions struct {
	Summarize           bool   `json:"summarize,omitempty"`
	CustomInstructions  string `json:"customInstructions,omitempty"`
	ReplaceInstructions bool   `json:"replaceInstructions,omitempty"`
	Label               string `json:"label,omitempty"`
}

NavigateTreeOptions mirrors upstream's navigateTree options.

upstream: types.ts:347-351

type NewSessionOptions

type NewSessionOptions struct {
	ParentSession string                              `json:"parentSession,omitempty"`
	Setup         func(SessionManager) error          `json:"-"`
	WithSession   func(*ReplacedSessionContext) error `json:"-"`
}

NewSessionOptions mirrors upstream's newSession parameter object.

upstream: types.ts:334-338 (ExtensionCommandContext.newSession options)

type OAuthCredentials

type OAuthCredentials = ai.OAuthCredentials

OAuthCredentials mirrors @earendil-works/pi-ai OAuthCredentials.

type OAuthLoginCallbacks

type OAuthLoginCallbacks = ai.OAuthLoginCallbacks

OAuthLoginCallbacks mirrors @earendil-works/pi-ai OAuthLoginCallbacks.

type OrderedExposures

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

OrderedExposures is a map of tool names or patterns to exposures that keeps its JSON key order: among patterns the first match wins.

func NewOrderedExposures

func NewOrderedExposures(pairs ...string) *OrderedExposures

NewOrderedExposures builds the map from alternating patterns and exposures.

func (*OrderedExposures) Get

func (e *OrderedExposures) Get(key string) (McpExposure, bool)

Get returns the exposure of a key.

func (*OrderedExposures) Keys

func (e *OrderedExposures) Keys() []string

Keys returns the patterns in order.

func (OrderedExposures) MarshalJSON

func (e OrderedExposures) MarshalJSON() ([]byte, error)

MarshalJSON writes the keys in order.

func (*OrderedExposures) UnmarshalJSON

func (e *OrderedExposures) UnmarshalJSON(data []byte) error

UnmarshalJSON reads an object; validation of the values is ValidateMcpServerConfig's.

type OrderedStrings

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

OrderedStrings is a string map that keeps its JSON key order, as a JavaScript object does.

func NewOrderedStrings

func NewOrderedStrings(pairs ...string) *OrderedStrings

NewOrderedStrings builds the map from alternating keys and values.

func (*OrderedStrings) Get

func (s *OrderedStrings) Get(key string) (string, bool)

Get returns the value of key.

func (*OrderedStrings) Keys

func (s *OrderedStrings) Keys() []string

Keys returns the keys in order.

func (OrderedStrings) MarshalJSON

func (s OrderedStrings) MarshalJSON() ([]byte, error)

MarshalJSON writes the keys in order.

func (*OrderedStrings) UnmarshalJSON

func (s *OrderedStrings) UnmarshalJSON(data []byte) error

UnmarshalJSON reads an object of strings.

type OverlayHandle

type OverlayHandle = any

OverlayHandle mirrors @earendil-works/pi-tui OverlayHandle.

type OverlayLayout

type OverlayLayout struct {
	Width        *OverlaySizeValue   `json:"width,omitempty"`
	MinWidth     *int                `json:"minWidth,omitempty"`
	MaxHeight    *OverlaySizeValue   `json:"maxHeight,omitempty"`
	Anchor       string              `json:"anchor,omitempty"`
	OffsetX      int                 `json:"offsetX,omitempty"`
	OffsetY      int                 `json:"offsetY,omitempty"`
	Row          *OverlaySizeValue   `json:"row,omitempty"`
	Col          *OverlaySizeValue   `json:"col,omitempty"`
	Margin       *OverlayMarginValue `json:"margin,omitempty"`
	NonCapturing bool                `json:"nonCapturing,omitempty"`
}

OverlayLayout is the serialisable subset of upstream pi-tui OverlayOptions: every field except the visible callback.

type OverlayMarginValue

type OverlayMarginValue struct {
	All                      *int
	Top, Right, Bottom, Left int
}

OverlayMarginValue is upstream `OverlayMargin | number`.

func (OverlayMarginValue) MarshalJSON

func (m OverlayMarginValue) MarshalJSON() ([]byte, error)

func (*OverlayMarginValue) UnmarshalJSON

func (m *OverlayMarginValue) UnmarshalJSON(data []byte) error

type OverlayOptions

type OverlayOptions = any

OverlayOptions mirrors @earendil-works/pi-tui OverlayOptions.

type OverlayOptionsFunc

type OverlayOptionsFunc func() tui.OverlayOptions

OverlayOptionsFunc is overlayOptions given as a function, called each time the overlay is shown.

type OverlayOptionsSource

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

OverlayOptionsSource is `OverlayOptions | (() => OverlayOptions)`, the overlayOptions member of CustomOptions: the options themselves or a function that returns them when the overlay is shown.

type OverlayOptionsValue

type OverlayOptionsValue struct{ Options tui.OverlayOptions }

OverlayOptionsValue is overlayOptions given as an object.

type OverlaySizeValue

type OverlaySizeValue struct {
	Value   float64
	Percent bool
	Invalid bool
}

OverlaySizeValue is upstream SizeValue: a cell count or an "N%" string. A string that is not a percentage is kept with Invalid set, matching upstream parseSizeValue returning undefined.

func (OverlaySizeValue) MarshalJSON

func (v OverlaySizeValue) MarshalJSON() ([]byte, error)

func (*OverlaySizeValue) UnmarshalJSON

func (v *OverlaySizeValue) UnmarshalJSON(data []byte) error

type PendingNativeProviderRegistration

type PendingNativeProviderRegistration struct {
	Provider      *ai.ModelsProvider
	ExtensionPath string
	// contains filtered or unexported fields
}

PendingNativeProviderRegistration retains a native provider and its owning extension until the registry is bound. Provider is Pi's Provider object: the one a compiled-in extension registered, or the object assembled from the carrier of a subprocess extension's provider. upstream: runner.ts:481-497 (pendingNativeProviderRegistrations: { provider: Provider; extensionPath: string }[])

type PendingProviderRegistration

type PendingProviderRegistration struct {
	Name          string
	Config        ProviderConfig
	ExtensionPath string
}

PendingProviderRegistration retains the configuration and its owning extension until the registry is bound.

type PendingVirtualModelRegistration

type PendingVirtualModelRegistration struct {
	Definition    VirtualModelDefinition
	ExtensionPath string
}

PendingVirtualModelRegistration retains a virtual model and its owning extension until the runner binds.

upstream: types.ts:2097 (pendingVirtualModelRegistrations)

type PlaceholderOmitter

type PlaceholderOmitter interface {
	InputWithoutPlaceholder(ctx context.Context, title string, opts ExtensionUIDialogOptions) (string, error)
}

PlaceholderOmitter is implemented by a UIContext that tells an input dialog opened without a placeholder from one opened with an empty placeholder. Pi's input(title, placeholder?, opts?) leaves `placeholder` undefined when the extension passes none, and RPC mode omits the member then but writes `placeholder: ""` for an empty string (rpc-mode.ts input). InputWithoutPlaceholder is the first form. The extension host calls it when an extension sends no placeholder, and falls back to Input with an empty placeholder for a UIContext that does not implement it.

type PowerShellToolDetails

type PowerShellToolDetails = BashToolDetails

PowerShellToolDetails is the bash details shape (upstream powershell.ts).

type PowerShellToolInput

type PowerShellToolInput = BashToolInput

PowerShellToolInput is the bash input shape (upstream powershell.ts).

type PowerShellToolResultEvent

type PowerShellToolResultEvent struct {
	ToolResultEventBase
	ToolName string                 `json:"toolName"` // "powershell"
	Details  *PowerShellToolDetails `json:"details,omitempty"`
}

PowerShellToolResultEvent: upstream types.ts PowerShellToolResultEvent.

func (PowerShellToolResultEvent) MarshalJSON

func (e PowerShellToolResultEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the event in Pi's member order; see [marshalToolResultEvent].

type PrefillOmitter

type PrefillOmitter interface {
	EditorWithoutPrefill(ctx context.Context, title string) (string, error)
}

PrefillOmitter is PlaceholderOmitter for editor(title, prefill?) (rpc-mode.ts editor): EditorWithoutPrefill opens the editor dialog with no prefill, and the extension host falls back to Editor with an empty prefill for a UIContext that does not implement it.

type ProjectTrustContext

type ProjectTrustContext struct {
	// Cwd is the project folder being decided.
	Cwd string
	// Mode is the run mode: "tui" for interactive, otherwise "print", "json" or "rpc".
	Mode ExtensionMode
	// HasUI reports whether the UI can prompt.
	HasUI bool
	UI    ProjectTrustUI
}

ProjectTrustContext is the context a project_trust handler receives before any runtime exists (types.ts:693).

type ProjectTrustEvent

type ProjectTrustEvent struct {
	Type string `json:"type"` // "project_trust"
	Cwd  string `json:"cwd"`
}

ProjectTrustEvent: upstream types.ts ProjectTrustEvent. Fired before project-local inputs load so a global/CLI extension can decide trust.

type ProjectTrustEventDecision

type ProjectTrustEventDecision string

ProjectTrustEventDecision is an extension's trust verdict for a project. Values: "yes" | "no" | "undecided". Mirrors upstream ProjectTrustEventDecision.

const (
	ProjectTrustYes       ProjectTrustEventDecision = "yes"
	ProjectTrustNo        ProjectTrustEventDecision = "no"
	ProjectTrustUndecided ProjectTrustEventDecision = "undecided"
)

type ProjectTrustEventResult

type ProjectTrustEventResult struct {
	Trusted  ProjectTrustEventDecision `json:"trusted"`
	Remember *bool                     `json:"remember,omitempty"`
}

ProjectTrustEventResult: upstream types.ts ProjectTrustEventResult. The first handler returning yes/no wins; undecided falls through.

type ProjectTrustHandler

type ProjectTrustHandler func(ctx context.Context, evt ProjectTrustEvent, trust ProjectTrustContext) (ProjectTrustEventResult, error)

ProjectTrustHandler decides trust for a project folder (types.ts:698). The first handler that returns "yes" or "no" wins; "undecided" falls through to the next handler.

type ProjectTrustUI

type ProjectTrustUI interface {
	Select(ctx context.Context, title string, options []string, opts ExtensionUIDialogOptions) (string, error)
	Confirm(ctx context.Context, title, message string, opts ExtensionUIDialogOptions) (bool, error)
	Input(ctx context.Context, title, placeholder string, opts ExtensionUIDialogOptions) (string, error)
	Notify(message, kind string)
}

ProjectTrustUI is the Pick<ExtensionUIContext, "select" | "confirm" | "input" | "notify"> a project_trust handler may use. Every UIContext satisfies it.

type ProjectedSessionEntry

type ProjectedSessionEntry struct {
	SourceEntry any            `json:"sourceEntry"`
	Messages    []AgentMessage `json:"messages"`
}

ProjectedSessionEntry is one boundary preview entry and its model-visible messages.

type ProviderActions

type ProviderActions struct {
	RegisterProvider   func(name string, config ProviderConfig) error
	UnregisterProvider func(name string)
	// RegisterNativeProvider applies a native provider registration of Pi's Provider object; the call's context carries the registering
	// call's initiation. A carrier registered by a subprocess extension reaches it as the object assembled from the carrier.
	// upstream: runner.ts:410-418, 481-490 (providerActions.registerNativeProvider(provider: Provider))
	RegisterNativeProvider func(ctx context.Context, provider *ai.ModelsProvider) error
	// RegisterNativeProviderCarrier is RegisterNativeProvider for the registration carrier, which keeps each member's context.Context and
	// error; a registry that serves subprocess extensions binds it. When both are set, the carrier form applies.
	RegisterNativeProviderCarrier func(ctx context.Context, provider *NativeProvider) error
	// RegisterVirtualModel and UnregisterVirtualModel apply virtual-model registrations; the model registry's own ones apply when unset.
	// upstream: runner.ts:413-417 (providerActions.registerVirtualModel, unregisterVirtualModel)
	RegisterVirtualModel   func(definition VirtualModelDefinition) error
	UnregisterVirtualModel func(provider, id string)
}

ProviderActions supplies synchronous provider registration callbacks. Registration errors are reported per queued entry during binding and returned directly for post-bind calls. upstream: packages/coding-agent/src/core/extensions/runner.ts:bindCore

type ProviderConfig

type ProviderConfig struct {
	Name         string               `json:"name,omitempty"`
	BaseURL      string               `json:"baseUrl,omitempty"`
	APIKey       string               `json:"apiKey,omitempty"`
	API          ai.API               `json:"api,omitempty"`
	StreamSimple ProviderStreamSimple `json:"-"`
	// RefreshModels refreshes this provider's model list; the returned models replace the extension-provided models. A
	// callback publishes a persisted catalog through context.Publish. Ports ProviderConfig.refreshModels
	// (core/extensions/types.ts:1930).
	RefreshModels func(context RefreshModelsContext) ([]ProviderModelConfig, error) `json:"-"`
	// Images are the image-generation implementations keyed by image API.
	// upstream: types.ts:1896 (ProviderConfig.images)
	Images map[ai.ImageAPI]*ai.ProviderImages `json:"-"`
	// Classifiers are the classifier implementations keyed by classifier API.
	// upstream: types.ts:1898 (ProviderConfig.classifiers)
	Classifiers map[ai.ClassifierAPI]*ai.ProviderClassifier `json:"-"`
	Headers     map[string]string                           `json:"headers,omitempty"`

	AuthHeader bool                  `json:"authHeader,omitempty"`
	Models     []ProviderModelConfig `json:"models,omitempty"`
	OAuth      *ProviderOAuth        `json:"oauth,omitempty"`
	// Insecure skips TLS certificate verification for this provider's
	// endpoint. Opt-in only, for self-signed/internal-CA on-prem gateways.
	// pig additive (D36): additive optional field; no upstream per-provider TLS-skip.
	Insecure bool `json:"insecure,omitempty"`
	// contains filtered or unexported fields
}

ProviderConfig is the registration payload for API.RegisterProvider. Mirrors upstream's ProviderConfig 1:1.

Field semantics (from upstream JSDoc):

  • If Models is provided: replaces all existing models for this provider.
  • If only BaseURL is provided: overrides the URL for existing models.
  • If OAuth is provided: registers OAuth provider for /login support.
  • If StreamSimple is provided: registers a custom API stream handler.

func (ProviderConfig) MarshalJSON

func (config ProviderConfig) MarshalJSON() ([]byte, error)

func (*ProviderConfig) UnmarshalJSON

func (config *ProviderConfig) UnmarshalJSON(data []byte) error

type ProviderConfigInput

type ProviderConfigInput struct {
	Name         string
	BaseURL      string
	APIKey       string
	API          ai.API
	StreamSimple ai.ModelsStreamFunction
	Headers      map[string]string
	AuthHeader   *bool
	OAuth        *ExtensionOAuthConfig
	// Models are chat, image and classifier model definitions; a model without a type is a chat model.
	Models []ai.AnyModel
	// Images and Classifiers are the implementations of the image and classifier models Models declares.
	Images        ai.ProviderImageAPIMap
	Classifiers   ai.ProviderClassifierMap
	RefreshModels func(ai.RefreshModelsContext) ([]ai.AnyModel, error)
	// Insecure skips TLS certificate verification for this provider's endpoint.
	// pig additive (D36): carries ProviderConfig.Insecure through a registration composed in the native collection.
	Insecure bool
}

ProviderConfigInput is the core registration input of ModelRegistry.RegisterProvider (provider-composer.ts:91); Models nil preserves the base catalog and an empty slice replaces it.

type ProviderHeaders

type ProviderHeaders = map[string]*string

ProviderHeaders mirrors upstream pi-ai ProviderHeaders (`Record<string, string | null>`): a nil value signals "delete this header".

type ProviderModelConfig

type ProviderModelConfig struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Type is "chat", "image" or "classifier". Empty is "chat".
	// upstream: types.ts:1953-1976 (type)
	Type ai.ModelType `json:"type,omitempty"`
	// API is a chat API, or for an image or classifier entry the image or classifier API id.
	API ai.API `json:"api,omitempty"`
	// Output is the output types of an image entry: it always includes "image"; "text" means the model can also return text blocks.
	// upstream: types.ts:1969 (ProviderImageModelConfig.output)
	Output           []string            `json:"output,omitempty"`
	BaseURL          string              `json:"baseUrl,omitempty"`
	Reasoning        bool                `json:"reasoning"`
	ThinkingLevelMap ai.ThinkingLevelMap `json:"thinkingLevelMap,omitempty"`
	Input            []string            `json:"input"`
	// InputLimits is upstream's provider input limits and cache-safe image
	// preprocessing metadata.
	InputLimits *ai.ModelInputLimits `json:"inputLimits,omitempty"`
	Cost        ProviderModelCost    `json:"cost"`
	// PromptCache is upstream's best-effort prompt cache lifetime in seconds
	// per retention tier.
	PromptCache    ai.ModelPromptCache `json:"promptCache,omitempty"`
	SamplingParams map[string]any      `json:"samplingParams,omitempty"`
	// SamplingParamsByThinkingLevel overrides SamplingParams for the effective Pi thinking level of a chat entry.
	// upstream: packages/coding-agent/src/core/provider-composer.ts:72 (ProviderChatModelConfig.samplingParamsByThinkingLevel), carried by extensionModelFromDefinition's spread.
	SamplingParamsByThinkingLevel ai.SamplingParamsByThinkingLevel `json:"samplingParamsByThinkingLevel,omitempty"`
	ContextWindow                 int                              `json:"contextWindow"`
	MaxTokens                     int                              `json:"maxTokens"`
	Headers                       map[string]string                `json:"headers,omitempty"`

	Compat any `json:"compat,omitempty"`
	// contains filtered or unexported fields
}

ProviderModelConfig mirrors upstream ProviderModelConfig, the union of ProviderChatModelConfig, ProviderImageModelConfig and ProviderClassifierModelConfig (types.ts:1929-1991).

Go mechanic (not a divergence): one struct carries the discriminator and the fields of all three variants, so an entry round-trips through the extension wire and the registries unchanged. Type omitted is normalized to "chat". A chat entry uses ID, Name, API, BaseURL, Reasoning, ThinkingLevelMap, Input, InputLimits, Cost, PromptCache, SamplingParams, SamplingParamsByThinkingLevel, ContextWindow, MaxTokens, Headers and Compat. An image entry uses ID, Name, API (an image API), BaseURL, Input, InputLimits, Cost, Headers and Output. A classifier entry uses ID, Name, API (a classifier API), BaseURL, Input, InputLimits, Cost, Headers and ContextWindow. A field outside its variant is not marshalled.

func (ProviderModelConfig) Definition

func (config ProviderModelConfig) Definition() (json.RawMessage, error)

Definition is the entry as the registering extension wrote it: the JSON it was decoded from, every member in the extension's order, or the entry's encoding when it was built in Go. Pi spreads that object into the model it registers (provider-composer.ts extensionModelFromDefinition), so it fixes the members of the model object extensions read back and their order.

func (ProviderModelConfig) MarshalJSON

func (config ProviderModelConfig) MarshalJSON() ([]byte, error)

func (*ProviderModelConfig) UnmarshalJSON

func (config *ProviderModelConfig) UnmarshalJSON(data []byte) error

type ProviderModelCost

type ProviderModelCost struct {
	Input      float64       `json:"input"`
	Output     float64       `json:"output"`
	CacheRead  float64       `json:"cacheRead"`
	CacheWrite float64       `json:"cacheWrite"`
	Tiers      []ai.CostTier `json:"tiers,omitzero"`
}

ProviderModelCost mirrors upstream ProviderModelConfig.cost.

type ProviderOAuth

type ProviderOAuth struct {
	Name string `json:"name"`
	// IsSubscription marks access through this OAuth method as subscription-backed.
	IsSubscription bool `json:"isSubscription,omitempty"`
	// UsesCallbackServer is retained for source compatibility; canonical auth flows ignore it (types.ts:1937-1938).
	UsesCallbackServer bool                                                          `json:"usesCallbackServer,omitempty"`
	Login              func(callbacks OAuthLoginCallbacks) (OAuthCredentials, error) `json:"-"`
	// RefreshToken refreshes expired credentials; ctx is the refresh's AbortSignal (types.ts:1944 refreshToken(credentials, signal)).
	RefreshToken func(ctx context.Context, creds OAuthCredentials) (OAuthCredentials, error) `json:"-"`
	GetAPIKey    func(creds OAuthCredentials) string                                         `json:"-"`
	ModifyModels func(models []Model, creds OAuthCredentials) []Model                        `json:"-"`
}

ProviderOAuth mirrors upstream ProviderConfig.oauth.

type ProviderStreamEvent

type ProviderStreamEvent struct {
	// Data comes first because sdk.ts:402-408 builds the event as { data, type, provider, api, model }, which is the order an extension iterating or stringifying it sees.
	Data     any    `json:"data"`
	Type     string `json:"type"`
	Provider string `json:"provider"`
	API      string `json:"api"`
	Model    string `json:"model"`
}

ProviderStreamEvent: upstream types.ts ProviderStreamEvent. Fired for a parsed provider stream event before it is normalized. Data is adapter-owned and read-only.

upstream: types.ts:884-890

type ProviderStreamSimple

type ProviderStreamSimple = func(model Model, ctx AIContext, opts SimpleStreamOptions) AssistantMessageEventStream

ProviderStreamSimple mirrors upstream's optional streamSimple callback. The callback's model, request context, options, and event stream remain opaque at this dynamic extension boundary.

type ReadToolDetails

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

ReadToolDetails mirrors upstream read.ts:28. Attached only when output was truncated (or the first line exceeded the byte limit).

type ReadToolInput

type ReadToolInput struct {
	Path   string   `json:"path"`
	Offset *float64 `json:"offset,omitempty"`
	Limit  *float64 `json:"limit,omitempty"`
	// Extra holds members the schema does not declare; upstream's input is a plain object that keeps them.
	Extra map[string]json.RawMessage `json:"-"`
}

ReadToolInput is upstream's ReadToolInput (read.ts readSchema).

func (ReadToolInput) MarshalJSON

func (in ReadToolInput) MarshalJSON() ([]byte, error)

func (*ReadToolInput) UnmarshalJSON

func (in *ReadToolInput) UnmarshalJSON(data []byte) error

type ReadToolResultEvent

type ReadToolResultEvent struct {
	ToolResultEventBase
	ToolName string           `json:"toolName"` // "read"
	Details  *ReadToolDetails `json:"details,omitempty"`
}

ReadToolResultEvent: upstream types.ts ReadToolResultEvent.

func (ReadToolResultEvent) MarshalJSON

func (e ReadToolResultEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the event in Pi's member order; see [marshalToolResultEvent].

type ReadonlyFooterDataProvider

type ReadonlyFooterDataProvider interface {
	// GetGitBranch is the current git branch, empty outside a repository or on a detached HEAD without a branch name.
	GetGitBranch() string
	// GetExtensionStatuses are the statuses extensions set with setStatus, by key.
	GetExtensionStatuses() map[string]string
	// GetAvailableProviderCount is the number of providers with usable credentials.
	GetAvailableProviderCount() int
	// OnBranchChange subscribes to branch changes and returns the unsubscribe function.
	OnBranchChange(callback func()) func()
}

ReadonlyFooterDataProvider is the footer data an extension's footer reads (footer-data-provider.ts:385 Pick<FooterDataProvider, "getGitBranch" | "getExtensionStatuses" | "getAvailableProviderCount" | "onBranchChange">).

type ReadonlySessionManager

type ReadonlySessionManager interface {
	GetCwd() string
	GetSessionDir() string
	GetSessionId() string
	GetSessionFile() *string
	GetLeafID() *string
	GetLeafEntry() (SessionEntry, bool)
	GetEntry(id string) (SessionEntry, bool)
	GetLabel(id string) (string, bool)
	GetBranch(fromID ...string) []SessionEntry
	BuildContextEntries() []SessionEntry
	BuildSessionProjection() SessionProjection
	GetHeader() SessionHeader
	GetEntries() []SessionEntry
	GetTree() []*SessionTreeNode
	GetSessionName() string
}

ReadonlySessionManager is the read-only view of the session log that ctx.sessionManager exposes to extensions (session-manager.ts:245 ReadonlySessionManager, a Pick of SessionManager). Optional TypeScript results (`string | undefined`, `SessionEntry | undefined`) are a second bool or a nil pointer, as in the host's session log.

type RefreshModelsContext

type RefreshModelsContext = ai.RefreshModelsContext

RefreshModelsContext is the context a RefreshModels callback receives: the credential and stored catalog, whether the network may be used, the cancellation signal and Publish for persisting a refreshed catalog.

type RegisteredCommand

type RegisteredCommand struct {
	Name                   string                  `json:"name"`
	SourceInfo             SourceInfo              `json:"sourceInfo"`
	Description            string                  `json:"description,omitempty"`
	GetArgumentCompletions ArgumentCompletionsFunc `json:"-"`
	Handler                CommandHandler          `json:"-"`
}

RegisteredCommand mirrors upstream RegisteredCommand. The host's view of a command after registration.

type RegisteredMcpServer

type RegisteredMcpServer struct {
	Name   string          `json:"name"`
	Config McpServerConfig `json:"config"`
	// Declared is the config as the extension wrote it with its exposure aliases resolved, JSON.stringify(JSON.parse(text)): every member, known or not, in the order written, the way a JavaScript object holds them. Extensions read it back through getMcpServers, so the wire carries it in place of Config, which holds the members the host uses. Empty for a server registered with a typed Config alone.
	// upstream: mcp-servers.ts:151-166,192-222 (validateMcpServerConfig returns the alias-resolved copy of the object it was given), 283 (list copies it with structuredClone)
	Declared json.RawMessage `json:"-"`
	// ExtensionPath is the path of the extension that registered the server.
	ExtensionPath string `json:"extensionPath"`
}

RegisteredMcpServer is a server an extension registered with `pi.registerMcpServer()`.

func (RegisteredMcpServer) MarshalJSON

func (s RegisteredMcpServer) MarshalJSON() ([]byte, error)

MarshalJSON writes the server as getMcpServers returns it: name, config, extensionPath, with the config as declared.

type RegisteredTool

type RegisteredTool struct {
	Definition ToolDefinition `json:"definition"`
	SourceInfo SourceInfo     `json:"sourceInfo"`
	// Source is PiG's per-tool source attribution (D23): the tool's declared source, or the registering extension's name. It is not part of upstream's RegisteredTool and is empty for tools no extension registered.
	Source string `json:"-"`
	// Revision identifies this registration: a live registry stamps every registration, including one that replaces a name, with a value no other registration of the process has, so a consumer that derived something from a definition can tell that the definition is the one it saw. Zero is a registration no live registry stamped, which identifies nothing.
	Revision uint64 `json:"-"`
}

RegisteredTool mirrors upstream RegisteredTool: the host's bookkeeping after a tool is registered.

type RemoteEditor

type RemoteEditor interface {
	// Input delivers one keystroke to the editor's handleInput.
	Input(data string)
	// SetText, InsertTextAtCursor and AddToHistory call the editor's
	// methods of the same name, as Pi's host calls them on this.editor.
	SetText(text string)
	InsertTextAtCursor(text string)
	AddToHistory(text string)
	// Mouse delivers a left click on the editor rows to the editor's
	// handleMouse, as Pi's fullscreen renderer does.
	Mouse(event RemoteMouseEvent)
	// Configure applies host editor state to the editor: Pi copies the
	// default editor's text, padding and autocomplete size when it installs
	// the editor, and the TUI sets its focus.
	Configure(config RemoteEditorConfig)
	// EmbedWorkingStatus reports whether this editor wants status in its border.
	EmbedWorkingStatus() bool
	// Bind attaches the host that receives the editor's frames and
	// callbacks. Events that arrive before Bind are delivered on binding.
	Bind(host RemoteEditorHost)
	// Close detaches the editor from the host.
	Close()
}

RemoteEditor is an editor an extension installed with ctx.ui.setEditorComponent, running in the extension's process. Pi puts the factory's editor (typically a CustomEditor subclass) in place of its own: every keystroke goes to that editor's handleInput, its render output is the editor on screen, and Pi wires the editor's callbacks to its own handlers. The host does the same across the process boundary: it hands the editor every keystroke and every text change it makes, shows the editor's frames, and receives the editor's callbacks through the bound RemoteEditorHost.

UIContext.SetEditorComponent receives a RemoteEditor; nil restores the host's own editor.

func RemoteEditorOf

func RemoteEditorOf(component tui.EditorComponent) (RemoteEditor, bool)

RemoteEditorOf is the editor in an extension's process that component stands for, when RemoteEditorFactory built it.

type RemoteEditorAction

type RemoteEditorAction struct {
	Action   string `json:"action"`
	Text     string `json:"text"`
	Expanded string `json:"expanded"`
	Local    bool   `json:"local"`
}

RemoteEditorAction snapshots the editor at the app-action boundary. Local means the component already applied the synchronous editor mutations; the host must not replay them into that component.

type RemoteEditorBaseHost

type RemoteEditorBaseHost interface {
	EditorBase(ctx context.Context, op string, args json.RawMessage) (json.RawMessage, error)
}

RemoteEditorBaseHost is implemented by the RemoteEditorHost bound to a DelegatedRemoteEditor. EditorBase runs one of the base editor's operations on the host's owner loop and returns its JSON result: handleInput, handleMouse, render, getText, getExpandedText, getLines, getCursor, setText, insertTextAtCursor, addToHistory, setPaddingX, getPaddingX, setAutocompleteMaxVisible, getAutocompleteMaxVisible, isShowingAutocomplete, borderColor, getDisableSubmit, setDisableSubmit, getFocused, setFocused, setAutocompleteProvider, onSubmit and onChange. An unknown operation is an error.

handleInput takes the app actions the component handles itself (its onEscape, onCtrlD, onPasteImage and actionHandlers) as "hooks": when the key is one of them the host answers {"hook": <action>} without running the action, and the component runs its handler, in the order Pi's CustomEditor.handleInput gives them.

type RemoteEditorComponent

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

RemoteEditorComponent is the tui.EditorComponent RemoteEditorFactory builds.

func (*RemoteEditorComponent) Editor

func (c *RemoteEditorComponent) Editor() RemoteEditor

Editor is the editor in the extension's process.

func (*RemoteEditorComponent) HandleInput

func (c *RemoteEditorComponent) HandleInput(data string)

HandleInput delivers a keystroke to the editor.

func (*RemoteEditorComponent) Invalidate

func (*RemoteEditorComponent) Invalidate()

Invalidate is a no-op: the process redraws on its own.

func (*RemoteEditorComponent) Render

func (*RemoteEditorComponent) Render(int) []string

Render is empty: the process draws the editor and the host shows its frames.

func (*RemoteEditorComponent) SetOnChange

func (*RemoteEditorComponent) SetOnChange(func(string))

func (*RemoteEditorComponent) SetOnSubmit

func (*RemoteEditorComponent) SetOnSubmit(func(string))

SetOnSubmit and SetOnChange are no-ops: the host binds its callbacks through RemoteEditor.Bind.

func (*RemoteEditorComponent) SetText

func (c *RemoteEditorComponent) SetText(text string)

SetText replaces the editor's text.

func (*RemoteEditorComponent) Text

func (c *RemoteEditorComponent) Text() string

Text is the text the host last set; the editor's typing reaches the host through RemoteEditorHost.EditorChanged.

type RemoteEditorConfig

type RemoteEditorConfig struct {
	PaddingX               int  `json:"paddingX"`
	AutocompleteMaxVisible int  `json:"autocompleteMaxVisible"`
	Focused                bool `json:"focused"`
	// ThinkingLevel is the session's thinking level, whose border color Pi
	// gives the editor outside bash mode.
	ThinkingLevel string `json:"thinkingLevel"`
	// ShowHardwareCursor is the TUI's hardware-cursor setting, which the
	// editor's tui.getShowHardwareCursor() reports.
	ShowHardwareCursor bool `json:"showHardwareCursor"`
	// Shortcuts are the key ids of the extension shortcuts Pi's
	// onExtensionShortcut runs from inside the editor.
	Shortcuts        []string `json:"shortcuts"`
	Streaming        bool     `json:"streaming"`
	Compacting       bool     `json:"compacting"`
	BashRunning      bool     `json:"bashRunning"`
	InterruptHandled bool     `json:"interruptHandled"`
	// WorkingStatus is the current border status; nil clears it.
	WorkingStatus *RemoteEditorStatus `json:"workingStatus"`
}

RemoteEditorConfig is the host editor state an RemoteEditor mirrors.

type RemoteEditorHost

type RemoteEditorHost interface {
	// EditorFrame is the editor's render(width) output for the terminal
	// width. WantsKeyRelease is the editor's wantsKeyRelease flag.
	EditorFrame(lines []string, width int, wantsKeyRelease bool)
	// EditorChanged is the editor's onChange: its text and, for the host's
	// getEditorText, the text with paste markers expanded.
	EditorChanged(text, expanded string)
	// EditorSubmit is the editor's onSubmit. done runs once the host has
	// handled the submission, which settles the promise onSubmit returns.
	EditorSubmit(text string, done func())
	// EditorAction runs Pi's handler for an app action the editor
	// dispatched: app.interrupt (onEscape), app.exit (onCtrlD),
	// app.clipboard.pasteImage (onPasteImage), or an actionHandlers entry.
	EditorAction(action RemoteEditorAction)
	// EditorInputDone releases input backpressure after the key's callbacks have reached the host.
	EditorInputDone()
	// EditorShortcut runs the extension shortcut the editor's
	// onExtensionShortcut matched for data.
	EditorShortcut(data string)
	// TerminalWrite writes raw output to the terminal (tui.terminal.write).
	TerminalWrite(data string)
	// SetShowHardwareCursor is tui.setShowHardwareCursor.
	SetShowHardwareCursor(enabled bool)
	// EditorClosed reports that the extension's editor is gone (its process
	// ended); the host restores its own editor.
	EditorClosed()
}

RemoteEditorHost receives an RemoteEditor's output. The bridge calls it off the host's UI loop, in the order the extension produced the events.

type RemoteEditorInvalidator

type RemoteEditorInvalidator interface {
	Invalidate()
}

RemoteEditorInvalidator is a RemoteEditor whose component hears the TUI's invalidate(), which Pi sends every component it holds when the theme changes, so a component that caches styled rows drops them.

type RemoteEditorStatus

type RemoteEditorStatus struct {
	Kind              string   `json:"kind"`
	Message           string   `json:"message"`
	Frames            []string `json:"frames"`
	Frame             int      `json:"frame"`
	SpinnerColor      string   `json:"spinnerColor"`
	MessageColor      string   `json:"messageColor"`
	IndicatorVerbatim bool     `json:"indicatorVerbatim"`
}

RemoteEditorStatus is a border-status snapshot. pig divergence (D94): the host advances the animation and sends snapshots; Pi's editor-side indicator runs its own timer.

type RemoteMouseEvent

type RemoteMouseEvent struct {
	Type       string `json:"type"`
	Button     string `json:"button"`
	X          int    `json:"x"`
	Y          int    `json:"y"`
	ScreenX    int    `json:"screenX"`
	ScreenY    int    `json:"screenY"`
	Width      int    `json:"width"`
	Height     int    `json:"height"`
	Shift      bool   `json:"shift"`
	Alt        bool   `json:"alt"`
	Ctrl       bool   `json:"ctrl"`
	WheelDelta int    `json:"wheelDelta,omitempty"`
	ClickCount int    `json:"clickCount,omitempty"`
}

RemoteMouseEvent is pi-tui's TuiMouseEvent as it crosses to an extension: one cell-based pointer event, zero-based, with X and Y relative to the receiving component's first rendered cell.

type RemoteOverlayBounds

type RemoteOverlayBounds struct {
	Row    int `json:"row"`
	Col    int `json:"col"`
	Width  int `json:"width"`
	Height int `json:"height"`
}

RemoteOverlayBounds is the last rendered terminal-relative rectangle.

type RemoteOverlayFocusHost

type RemoteOverlayFocusHost interface {
	// OnFocus reports a change of the component's focus after it was mounted. Called from the goroutine that delivers its input,
	// in order with it.
	OnFocus(focused bool)
}

RemoteOverlayFocusHost is an optional RemoteOverlayHost that publishes the component's TUI focus to the remote producer: Pi's TUI.setFocus sets the focused flag of the component that gains focus and clears it on the one that loses it (tui.ts:602-665), so a custom component that another opens over learns it lost focus, and learns it has it again when that one closes.

pig-specific: Pi's component is in-process; a remote component learns its focus through this callback.

type RemoteOverlayFocusTarget

type RemoteOverlayFocusTarget struct {
	Overlay any
	Editor  bool
}

RemoteOverlayFocusTarget is an explicit OverlayHandle.unfocus target resolved by the host. The zero value is Pi's null target. Overlay is another mounted overlay of the same extension, as the host registered it; Editor selects the main editor component.

type RemoteOverlayHandle

type RemoteOverlayHandle interface {
	// UpdateLines replaces the overlay's cached lines and triggers
	// a TUI render. Safe to call from any goroutine.
	UpdateLines(lines []string)
	// Close signals that the overlay is finished and unblocks the
	// originating [UIContext.RunRemoteOverlay] call with the given
	// result value. Safe to call from any goroutine.
	Close(result any)
}

RemoteOverlayHandle is returned to the caller of UIContext.RunRemoteOverlay so it can push rendered lines into the overlay and close it when the remote producer signals completion.

pig-specific: no upstream equivalent.

type RemoteOverlayHost

type RemoteOverlayHost interface {
	// OnInput is invoked for every input chunk (a single key event
	// after [tui.ReadInput] segmentation) while the overlay is
	// open. Called from the input-reading goroutine.
	OnInput(data string)
}

RemoteOverlayHost is the callback surface the bridge provides so the overlay can forward user input back to the remote producer.

pig-specific: no upstream equivalent.

type RemoteOverlayMouseHost

type RemoteOverlayMouseHost interface {
	// OnMouse hands an event, local to the component's first cell, to the
	// components of the overlay's view, as Pi's would take it, and then,
	// when they leave it and the extension's component takes the mouse, to
	// the extension. The extension's answer cannot arrive in time, so a
	// component that takes the mouse handles every event inside its
	// bounds. Called on the owner loop.
	OnMouse(event RemoteMouseEvent) ViewMouseResult
}

RemoteOverlayMouseHost is a RemoteOverlayHost whose component may take the mouse in fullscreen mode, as an upstream component with handleMouse does.

pig-specific: no upstream equivalent; Pi calls handleMouse in-process.

type RemoteOverlayOptions

type RemoteOverlayOptions struct {
	// Title is the overlay's titlebar text. Empty hides the bar.
	Title string `json:"title,omitempty"`
	// WidthFraction is the fraction of terminal width the overlay
	// should occupy. Zero falls back to the overlay default.
	WidthFraction float64 `json:"widthFraction,omitempty"`
	// HeightFraction is the fraction of terminal height the
	// overlay should occupy. Zero falls back to the overlay default.
	HeightFraction float64 `json:"heightFraction,omitempty"`
	// Overlay opens a floating viewport overlay over the whole screen
	// instead of replacing the inline editor slot. Mirrors upstream
	// ui.custom()'s `overlay: true`. When false the component replaces
	// the editor slot.
	Overlay bool `json:"overlay,omitempty"`
	// Layout carries upstream ui.custom()'s overlayOptions (the pi-tui
	// OverlayOptions fields that can cross a process boundary). When set, or
	// when no legacy Title/fractions are given, an overlay is mounted
	// component-framed with exactly upstream's showOverlay geometry.
	Layout *OverlayLayout `json:"overlayOptions,omitempty"`
}

RemoteOverlayOptions controls how a remote (subprocess-backed) overlay is positioned and sized when the host opens it.

Upstream's `ui.custom()` takes an `overlay` boolean plus an `OverlayOptions` value. The OverlayOptions reference TUI primitives that cannot cross a process boundary, so the subprocess bridge ports the overlay flag and the size/position fields into this serialisable struct.

type RemoteOverlayState

type RemoteOverlayState struct {
	Hidden  bool                 `json:"hidden"`
	Focused bool                 `json:"focused"`
	Visible bool                 `json:"visible"`
	Bounds  *RemoteOverlayBounds `json:"bounds,omitempty"`
	// FocusOwner is the component that holds TUI focus after the control, so the bridge can tell the extension which of its
	// overlays has focus: Pi's setFocus clears the focused flag of every other component (tui.ts:602-665).
	FocusOwner any `json:"-"`
}

RemoteOverlayState is the host's mounted-overlay state at a control/input boundary.

type RemoteTUI

type RemoteTUI interface {
	// ShowRemoteOverlay is TUI.showOverlay for a remote component: it mounts a raw overlay with no ui.custom call behind it and
	// returns once the overlay is on the stack. The handle takes the component's frames and applies OverlayHandle controls
	// (Control); a "hide" control ends the overlay. Close ends it too, removing its entry if it is still on the stack. ended is
	// closed once the overlay ended and stopped reading input. ok is false when the UI has no TUI.
	ShowRemoteOverlay(opts RemoteOverlayOptions, host RemoteOverlayHost) (handle RemoteOverlayHandle, ended <-chan struct{}, ok bool)
	// HideTopOverlay is TUI.hideOverlay: it pops the topmost overlay, whichever component it shows, and returns the component
	// that holds focus afterwards.
	HideTopOverlay(ctx context.Context) (focused any, err error)
	// SetRemoteFocus is TUI.setFocus with target and returns the component that holds focus afterwards.
	SetRemoteFocus(ctx context.Context, target RemoteOverlayFocusTarget) (focused any, err error)
}

RemoteTUI is an optional UIContext that drives the TUI a remote component factory receives. Pi hands showExtensionCustom's factory the TUI itself (interactive-mode.ts:3008), and the factory or its components may call its showOverlay, hideOverlay and setFocus (tui.ts:598-842); a subprocess factory makes those calls across the process boundary.

pig-specific: Pi's factory holds the TUI in process.

type RemoteTerminalInputHandler

type RemoteTerminalInputHandler = func(ctx context.Context, data string) TerminalInputResult

RemoteTerminalInputHandler asks a terminal-input listener that runs in another process for its verdict on one chunk. It blocks until the verdict arrives, the connection fails, or ctx ends. A failure returns the zero result, which leaves the input unchanged.

pig additive (D19): upstream's TerminalInputHandler answers synchronously in process. A subprocess listener's answer crosses a socket, so the host calls this off its input loop.

type ReplacedSessionContext

type ReplacedSessionContext struct {
	*CommandContext
	// contains filtered or unexported fields
}

ReplacedSessionContext is the fresh command-capable context supplied after Session replacement and host rebinding. Its message methods await the Session operation rather than launching extension-owned background work.

func NewReplacedSessionContext

func NewReplacedSessionContext(command *CommandContext, sendMessage func(CustomMessageRef, *SendMessageOptions) error, sendUserMessage func(any, *ReplacedSessionSendUserMessageOptions) error) *ReplacedSessionContext

NewReplacedSessionContext binds the replacement Session's direct, awaited message operations to its command context.

func (*ReplacedSessionContext) SendMessage

func (c *ReplacedSessionContext) SendMessage(message CustomMessageRef, options *SendMessageOptions) error

SendMessage awaits custom-message persistence and any triggered turn.

func (*ReplacedSessionContext) SendUserMessage

func (c *ReplacedSessionContext) SendUserMessage(content any, options *ReplacedSessionSendUserMessageOptions) error

SendUserMessage awaits input handling and the selected prompt or queue operation.

type ReplacedSessionSendUserMessageOptions

type ReplacedSessionSendUserMessageOptions = SendUserMessageOptions

ReplacedSessionSendUserMessageOptions controls the awaited user-message operation on a replacement context. Template and command expansion default to false.

type ResolvedCommand

type ResolvedCommand struct {
	RegisteredCommand
	InvocationName string `json:"invocationName"`
}

ResolvedCommand mirrors upstream ResolvedCommand: RegisteredCommand plus the name under which it was actually invoked (which can differ from Name when the command exposes aliases).

type ResolvedRequestAuth

type ResolvedRequestAuth struct {
	OK      bool               `json:"ok"`
	APIKey  *string            `json:"apiKey,omitempty"`
	Headers ai.ProviderHeaders `json:"headers,omitzero"`
	BaseURL string             `json:"baseUrl,omitempty"`
	Env     map[string]string  `json:"env,omitzero"`
	Error   string             `json:"error,omitempty"`
}

ResolvedRequestAuth is the result of ModelRegistry.GetAPIKeyAndHeaders (model-registry.ts:33): OK with the request credentials, or not OK with Error.

type ResourceCollision

type ResourceCollision struct {
	ResourceType string `json:"resourceType"`
	Name         string `json:"name"`
	WinnerPath   string `json:"winnerPath"`
	LoserPath    string `json:"loserPath"`
	WinnerSource string `json:"winnerSource,omitempty"`
	LoserSource  string `json:"loserSource,omitempty"`
}

ResourceCollision describes two resources that claim the same name: the winner is kept and the loser is skipped. ResourceType is "extension", "skill", "prompt" or "theme"; WinnerSource and LoserSource are package sources such as "npm:foo" or "local".

upstream: core/diagnostics.ts:1-8 (export interface ResourceCollision)

type ResourceDiagnostic

type ResourceDiagnostic struct {
	// Type is one of "warning", "error", "collision". Mirrors the
	// upstream literal union. Not enforced by the Go type system -
	// callers are expected to use the constants below.
	Type string `json:"type"`

	// Message is the human-readable diagnostic text. Format matches
	// upstream verbatim where the diagnostic is user-visible (e.g.
	// shortcut/command collision strings) so no fidelity drift in
	// diagnostic UIs.
	Message string `json:"message"`

	// Path is the extension's resolvedPath for attribution. Optional;
	// upstream uses `path?: string`.
	Path string `json:"path,omitempty"`

	// Collision carries structured details when Type == "collision".
	// upstream: ResourceCollision in core/diagnostics.ts.
	Collision *ResourceCollision `json:"collision,omitempty"`
}

ResourceDiagnostic is a warning, error or collision reported while the runner and the resource loader resolve extensions, skills, prompts and themes.

upstream: core/diagnostics.ts:10-15 (export interface ResourceDiagnostic)

type ResourcesDiscoverAggregateResult

type ResourcesDiscoverAggregateResult struct {
	SkillPaths  []AttributedResourcePath `json:"skillPaths"`
	PromptPaths []AttributedResourcePath `json:"promptPaths"`
	ThemePaths  []AttributedResourcePath `json:"themePaths"`
}

ResourcesDiscoverAggregateResult is the combined output of all resources_discover handlers, with each path attributed to its source extension.

upstream: anonymous return type at runner.ts:944-948

type ResourcesDiscoverEvent

type ResourcesDiscoverEvent struct {
	Type   string `json:"type"`
	Cwd    string `json:"cwd"`
	Reason string `json:"reason"` // "startup" | "reload"
}

ResourcesDiscoverEvent: upstream types.ts ResourcesDiscoverEvent. Fired after session_start to allow extensions to provide additional resource paths.

type ResourcesDiscoverResult

type ResourcesDiscoverResult struct {
	SkillPaths  []string `json:"skillPaths,omitempty"`
	PromptPaths []string `json:"promptPaths,omitempty"`
	ThemePaths  []string `json:"themePaths,omitempty"`
}

ResourcesDiscoverResult: upstream types.ts ResourcesDiscoverResult.

type ScopedModel

type ScopedModel struct {
	Model         *ai.Model
	ThinkingLevel agent.ThinkingLevel
}

Ports packages/coding-agent/src/core/model-resolver.ts. ScopedModel is a resolved member of the session's model scope. An absent thinking level supplies no per-scope override when cycling.

type SendMessageOptions

type SendMessageOptions struct {
	TriggerTurn *bool     `json:"triggerTurn,omitempty"`
	DeliverAs   DeliverAs `json:"deliverAs,omitempty"`
}

SendMessageOptions mirrors the inline options object on sendMessage.

upstream: types.ts:1161–1162

type SendMessagePayload

type SendMessagePayload struct {
	CustomType string `json:"customType"`
	// Content preserves upstream CustomMessage content across the dynamic
	// extension boundary.
	Content any  `json:"content,omitempty"`
	Display bool `json:"display"`
	Details any  `json:"details,omitempty"`
}

SendMessagePayload mirrors the inline `Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">` parameter on upstream's sendMessage.

upstream: types.ts:1159–1163

func (*SendMessagePayload) UnmarshalJSON

func (p *SendMessagePayload) UnmarshalJSON(data []byte) error

UnmarshalJSON keeps the member order of the `details` object the extension wrote.

type SendUserMessageHandler

type SendUserMessageHandler func(content any, options *SendUserMessageOptions) error

SendUserMessageHandler injects a user message into the agent loop. content is upstream's `string | (TextContent | ImageContent)[]` union; current in-process callers use strings, while unsupported content shapes should fail at the host boundary.

upstream: types.ts:1525-1528 Go returns error so hosts can surface invalid content/delivery modes loudly instead of dropping extension calls on the floor.

type SendUserMessageOptions

type SendUserMessageOptions struct {
	DeliverAs             DeliverAs `json:"deliverAs,omitempty"`
	ExpandPromptTemplates *bool     `json:"expandPromptTemplates,omitempty"`
}

SendUserMessageOptions mirrors the inline options object on sendUserMessage. Note upstream restricts DeliverAs to {steer, followUp}; the type is shared, but DeliverAsNextTurn is invalid here and the host rejects it at runtime.

upstream: types.ts:1170–1171

type SessionBeforeCompactEvent

type SessionBeforeCompactEvent struct {
	Type               string                `json:"type"`
	Preparation        CompactionPreparation `json:"preparation"`
	BranchEntries      []SessionEntry        `json:"branchEntries"`
	CustomInstructions string                `json:"customInstructions,omitempty"`
	// reason/willRetry adopted upstream in 0.80.3.
	Reason    string          `json:"reason"`
	WillRetry bool            `json:"willRetry"`
	Signal    context.Context `json:"-"`
}

SessionBeforeCompactEvent: upstream types.ts SessionBeforeCompactEvent.

Signal carries the upstream AbortSignal through Go's context.Context.

type SessionBeforeCompactResult

type SessionBeforeCompactResult struct {
	Cancel bool `json:"cancel,omitempty"`
	// Compaction is the extension-supplied CompactionResult (types.ts:1472); a subprocess extension's raw JSON result reaches the host undecoded.
	Compaction *CompactionResult `json:"compaction,omitempty"`
}

SessionBeforeCompactResult: upstream types.ts SessionBeforeCompactResult.

type SessionBeforeForkEvent

type SessionBeforeForkEvent struct {
	Type     string `json:"type"`
	EntryID  string `json:"entryId"`
	Position string `json:"position"` // "before" | "at"
}

SessionBeforeForkEvent: upstream types.ts SessionBeforeForkEvent.

type SessionBeforeForkResult

type SessionBeforeForkResult struct {
	Cancel                  bool `json:"cancel,omitempty"`
	SkipConversationRestore bool `json:"skipConversationRestore,omitempty"`
}

SessionBeforeForkResult: upstream types.ts SessionBeforeForkResult.

type SessionBeforeSwitchEvent

type SessionBeforeSwitchEvent struct {
	Type              string `json:"type"`
	Reason            string `json:"reason"` // "new" | "resume"
	TargetSessionFile string `json:"targetSessionFile,omitempty"`
}

SessionBeforeSwitchEvent: upstream types.ts SessionBeforeSwitchEvent.

type SessionBeforeSwitchResult

type SessionBeforeSwitchResult struct {
	Cancel bool `json:"cancel,omitempty"`
}

SessionBeforeSwitchResult: upstream types.ts SessionBeforeSwitchResult.

type SessionBeforeTreeEvent

type SessionBeforeTreeEvent struct {
	Type        string          `json:"type"`
	Preparation TreePreparation `json:"preparation"`
	Signal      context.Context `json:"-"`
}

SessionBeforeTreeEvent: upstream types.ts SessionBeforeTreeEvent.

Signal carries the upstream AbortSignal through Go's context.Context.

type SessionBeforeTreeResult

type SessionBeforeTreeResult struct {
	Cancel              bool                            `json:"cancel,omitempty"`
	Summary             *SessionBeforeTreeResultSummary `json:"summary,omitempty"`
	CustomInstructions  *string                         `json:"customInstructions,omitempty"`
	ReplaceInstructions *bool                           `json:"replaceInstructions,omitempty"`
	Label               *string                         `json:"label,omitempty"`
}

SessionBeforeTreeResult: upstream types.ts SessionBeforeTreeResult. A nil pointer is a field the handler left undefined, so the navigation keeps its own value; an explicit false or empty string overrides it.

type SessionBeforeTreeResultSummary

type SessionBeforeTreeResultSummary struct {
	Summary string `json:"summary"`
	Details any    `json:"details,omitempty"`
	// Usage is the pi-ai Usage of the extension's summarization call.
	Usage *ai.Usage `json:"usage,omitempty"`
}

SessionBeforeTreeResultSummary mirrors the inline `summary` object on upstream's SessionBeforeTreeResult.

func (*SessionBeforeTreeResultSummary) UnmarshalJSON

func (s *SessionBeforeTreeResultSummary) UnmarshalJSON(data []byte) error

UnmarshalJSON keeps the member order of the `details` object the extension wrote.

type SessionBoundaryDraft

type SessionBoundaryDraft struct {
	Type             SessionBoundaryDraftType `json:"type"`
	CustomType       string                   `json:"customType,omitempty"`
	Data             any                      `json:"data,omitempty"`
	Content          any                      `json:"content,omitempty"`
	Display          bool                     `json:"display,omitempty"`
	Details          any                      `json:"details,omitempty"`
	TargetID         string                   `json:"targetId,omitempty"`
	Replacement      json.RawMessage          `json:"replacement,omitempty"`
	Summary          string                   `json:"summary,omitempty"`
	FirstKeptEntryID *string                  `json:"firstKeptEntryId,omitempty"`
	Usage            *ai.Usage                `json:"usage,omitempty"`
}

SessionBoundaryDraft is the wire representation of upstream's closed SessionBoundaryDraft union. Fields apply according to Type.

func (SessionBoundaryDraft) MarshalJSON

func (d SessionBoundaryDraft) MarshalJSON() ([]byte, error)

MarshalJSON preserves each upstream union member's required fields, including null firstKeptEntryId and replacement values.

func (*SessionBoundaryDraft) UnmarshalJSON

func (d *SessionBoundaryDraft) UnmarshalJSON(data []byte) error

UnmarshalJSON keeps the member order of the `data` and `details` objects the extension wrote.

type SessionBoundaryDraftType

type SessionBoundaryDraftType string

SessionBoundaryDraftType is the discriminator of the SessionBoundaryDraft union: the type of each upstream member.

const (
	// SessionBoundaryDraftCustom is upstream CustomEntryDraft.
	SessionBoundaryDraftCustom SessionBoundaryDraftType = "custom"
	// SessionBoundaryDraftCustomMessage is upstream CustomMessageEntryDraft.
	SessionBoundaryDraftCustomMessage SessionBoundaryDraftType = "custom_message"
	// SessionBoundaryDraftContextEdit is upstream ContextEditEntryDraft.
	SessionBoundaryDraftContextEdit SessionBoundaryDraftType = "context_edit"
	// SessionBoundaryDraftCompaction is upstream CompactionEntryDraft.
	SessionBoundaryDraftCompaction SessionBoundaryDraftType = "compaction"
)

type SessionCompactEvent

type SessionCompactEvent struct {
	Type            string          `json:"type"`
	CompactionEntry CompactionEntry `json:"compactionEntry"`
	FromExtension   bool            `json:"fromExtension"`
	// reason/willRetry adopted upstream in 0.80.3.
	Reason    string `json:"reason"`
	WillRetry bool   `json:"willRetry"`
}

SessionCompactEvent: upstream types.ts SessionCompactEvent.

type SessionCompactFailedEvent

type SessionCompactFailedEvent struct {
	Type string `json:"type"`
	// Reason is what triggered the compaction: "manual" (/compact),
	// "threshold" (the context threshold), or "overflow" (context overflow
	// recovery).
	Reason string `json:"reason"`
	// ErrorMessage is the error text when compaction failed for a
	// non-abort reason.
	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: upstream types.ts SessionCompactFailedEvent. Fired after context compaction fails or is aborted.

type SessionContext

type SessionContext = sessionentry.SessionContext

SessionContext is the model-visible messages and settings on a branch (session-manager.ts SessionContext).

type SessionEntry

type SessionEntry = sessionentry.SessionEntry

SessionEntry mirrors core/session-manager SessionEntry.

type SessionEvent

type SessionEvent interface {
	ExtensionEvent
	// contains filtered or unexported methods
}

SessionEvent is the union of the session lifecycle events (types.ts:848 SessionEvent): a member of ExtensionEvent that carries a session_* type.

type SessionHeader

type SessionHeader = sessionentry.SessionHeader

SessionHeader is the session log's header line (session-manager.ts SessionHeader).

type SessionInfoChangedEvent

type SessionInfoChangedEvent struct {
	Type string `json:"type"`
	Name string `json:"name,omitempty"`
}

SessionInfoChangedEvent: upstream types.ts SessionInfoChangedEvent (adopted upstream in 0.80.3).

type SessionManager

type SessionManager interface {
	ReadonlySessionManager
	SetSessionFile(sessionFile string) error
	NewSession(options *SessionManagerNewSessionOptions) (string, error)
	IsPersisted() bool
	UsesDefaultSessionDir() bool
	AppendMessage(message SessionMessage) (string, error)
	AppendThinkingLevelChange(thinkingLevel string) (string, error)
	AppendModelChange(provider, modelID string) (string, error)
	AppendUsage(kind, provider, model string, usage ai.Usage, note string) (UsageEntry, error)
	AppendCompaction(summary, firstKeptEntryID string, tokensBefore int, details any, fromHook bool, usage *ai.Usage) (string, error)
	AppendCustomEntry(customType string, data any) (string, error)
	AppendSessionInfo(name string) (string, error)
	AppendCustomMessageEntry(customType string, content any, display bool, details any) (string, error)
	AppendContextEdit(targetID string, replacement *ContextEditReplacement) (string, error)
	GetChildren(parentID string) []SessionEntry
	AppendLabelChange(targetID string, label *string) (string, error)
	BuildSessionContext() SessionContext
	GetEntryCount() int
	Branch(branchFromID string) error
	ResetLeaf()
	BranchWithSummary(parentID *string, summary string, details any, fromHook bool, usage *ai.Usage) (string, error)
	CreateBranchedSession(leafID string) (string, error)
}

type SessionManagerNewSessionOptions

type SessionManagerNewSessionOptions = sessionentry.NewSessionOptions

SessionManagerNewSessionOptions are the options of SessionManager.NewSession (session-manager.ts:52 NewSessionOptions); NewSessionOptions is the parameter object of the command context's newSession.

type SessionMessage

type SessionMessage interface {
	MessageRole() string
}

SessionManager is the session log an extension's newSession setup callback receives (session-manager.ts:987 SessionManager): the read-only view plus every operation that changes the log. A TypeScript `string | undefined` or `void` result that can fail is an error as in the host's session log. SessionMessage is the union session-manager.ts appendMessage takes (Message | CustomMessage | BashExecutionMessage): an agent.AgentMessage, a CustomMessage or a BashExecutionMessage. MessageRole is the role of the message the entry stores.

type SessionProjection

type SessionProjection = sessionentry.SessionProjection

SessionProjection is the compaction-aware model context of one branch (session-manager.ts SessionProjection).

type SessionShutdownEvent

type SessionShutdownEvent struct {
	Type              string `json:"type"`
	Reason            string `json:"reason"` // "quit" | "reload" | "new" | "resume" | "fork"
	TargetSessionFile string `json:"targetSessionFile,omitempty"`
}

SessionShutdownEvent: upstream types.ts SessionShutdownEvent.

type SessionStartEvent

type SessionStartEvent struct {
	Type                string `json:"type"`
	Reason              string `json:"reason"` // "startup" | "reload" | "new" | "resume" | "fork"
	PreviousSessionFile string `json:"previousSessionFile,omitempty"`
}

SessionStartEvent: upstream types.ts SessionStartEvent.

type SessionTreeEvent

type SessionTreeEvent struct {
	Type          string              `json:"type"`
	NewLeafID     *string             `json:"newLeafId"`
	OldLeafID     *string             `json:"oldLeafId"`
	SummaryEntry  *BranchSummaryEntry `json:"summaryEntry,omitempty"`
	FromExtension bool                `json:"fromExtension,omitempty"`
}

SessionTreeEvent: upstream types.ts SessionTreeEvent.

NewLeafID and OldLeafID are upstream `string | null` (NOT optional). The difference between "null" and "absent" matters for wire-format round-trip through session JSONL: upstream always emits the keys, with `null` when no leaf. We use *string so json.Marshal emits null on nil and so the distinction survives a marshal/unmarshal cycle.

type SessionTreeNode

type SessionTreeNode = sessionentry.SessionTreeNode

SessionTreeNode is one node of the session tree (session-manager.ts SessionTreeNode).

type SetThemeResult

type SetThemeResult struct {
	Success bool   `json:"success"`
	Error   string `json:"error,omitempty"`
}

SetThemeResult mirrors the inline return type of `ExtensionUIContext.setTheme` (types.ts:262: `{ success, error? }`). Promoted to a named type because the inline TS object literal needs a Go-level identifier; field shape matches verbatim.

type Settings

type Settings = map[string]any

Settings is the effective settings object API.GetSettings returns: the JSON object of the global and project settings merged, with overrides. It is a copy, so a change to it does not change the settings.

Go mechanic (not a divergence): the settings manager lives in a package that imports this one, so the extension boundary carries the object as decoded JSON, the way the subprocess wire does.

upstream: .upstream/v0.99.1/packages/coding-agent/src/core/settings-manager.ts (Settings)

type ShortcutHandler

type ShortcutHandler = func(ctx context.Context) error

ShortcutHandler is invoked when a registered shortcut fires. Mirrors upstream `ExtensionAPI.registerShortcut.handler` signature.

ShortcutHandler receives cancellation and per-extension values through the Go context. Use FromContext to access the extension context.

type ShortcutOptions

type ShortcutOptions struct {
	Description string          `json:"description,omitempty"`
	Handler     ShortcutHandler `json:"-"`
}

ShortcutOptions is the registration payload for API.RegisterShortcut.

type SimpleStreamOptions

type SimpleStreamOptions = ai.StreamOptions

SimpleStreamOptions mirrors @earendil-works/pi-ai SimpleStreamOptions.

type SlashCommandInfo

type SlashCommandInfo struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	// Source is "extension", "prompt" or "skill".
	Source     string     `json:"source"`
	SourceInfo SourceInfo `json:"sourceInfo"`
}

SlashCommandInfo mirrors core/slash-commands.SlashCommandInfo, one entry of getCommands: an extension command, prompt template or skill.

type SourceInfo

type SourceInfo = source.SourceInfo

SourceInfo mirrors core/source-info.SourceInfo: where a resource, tool or command came from. It is the shared coding/source type, so the TUI's Theme can carry it (theme.ts Theme.sourceInfo) without importing this package.

type SpriteDefinition

type SpriteDefinition struct {
	ID      string            `json:"id"`
	Name    string            `json:"name"`
	Tagline string            `json:"tagline"`
	Mascot  []string          `json:"mascot"`
	Palette map[string]string `json:"palette"`
}

SpriteDefinition is one sprite: its stable ID, the name and tagline /sprite lists, its pig (LoginMascotWidth by LoginMascotHeight), which the startup header draws in Pi's logo slot and /sprite preview beside the wordmark, and the palette that colors it. Grid cells are printable ASCII palette symbols; '.' is transparent.

type SpriteDefinitionError

type SpriteDefinitionError struct {
	Field   string
	Message string
}

SpriteDefinitionError identifies the invalid field in a sprite definition.

func (*SpriteDefinitionError) Error

func (e *SpriteDefinitionError) Error() string

type SpriteRegistrar

type SpriteRegistrar interface {
	RegisterSprite(owner string, definition ValidatedSpriteDefinition) error
	UnregisterSprites(owner string)
}

SpriteRegistrar is a UI that keeps extension sprites: the interactive mode adds them to /sprite. owner names the extension; a sprite's ID is unique across owners, and an owner registering an ID again replaces its sprite.

type StackError

type StackError interface {
	error
	ErrorStack() string
}

StackError is an error that carries the stack of the failure it reports, such as a JavaScript error's `stack` or a recovered Go panic's stack.

type StatusClearer

type StatusClearer interface {
	ClearStatus(key string)
}

StatusClearer is implemented by a UIContext that tells an absent status from an empty one. Pi's setStatus(key, text: string | undefined) writes the text it is given and treats `undefined` as the removal of the entry (footer-data-provider.ts setExtensionStatus); RPC mode writes `statusText` for any string, the empty one included, and omits it for `undefined` (rpc-mode.ts setStatus). ClearStatus is the `undefined` form. The extension host calls it when an extension sends no text, and falls back to SetStatus(key, "") for a UIContext that does not implement it. It is a separate interface so existing UIContext implementations keep compiling.

type SwitchSessionOptions

type SwitchSessionOptions struct {
	WithSession func(*ReplacedSessionContext) error `json:"-"`
}

SwitchSessionOptions mirrors upstream's switchSession options.

upstream: types.ts:354-356

type SystemPrompt

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

SystemPrompt is BeforeAgentStartEvent.SystemPrompt, Pi's event.systemPrompt getter (runner.ts:1426-1433 renderCurrentSystemPrompt). The host builds one for each before_agent_start emission.

func NewSystemPrompt

func NewSystemPrompt(render func() (string, error)) *SystemPrompt

NewSystemPrompt returns the getter that reads render.

func (*SystemPrompt) Get

func (p *SystemPrompt) Get() (string, error)

Get returns the prompt the run's shared options render now. An invalid custom section is an error, as Pi's builder throws. A nil SystemPrompt is the empty prompt.

func (*SystemPrompt) MarshalJSON

func (p *SystemPrompt) MarshalJSON() ([]byte, error)

MarshalJSON encodes the prompt the options render now, as JSON.stringify reads Pi's getter.

type SystemPromptContextFile

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

SystemPromptContextFile mirrors the upstream anonymous `{ path: string; content: string }` element of contextFiles.

upstream: packages/coding-agent/src/core/system-prompt.ts:22

type SystemPromptSkill

type SystemPromptSkill struct {
	Name                   string     `json:"name"`
	Description            string     `json:"description"`
	FilePath               string     `json:"filePath"`
	BaseDir                string     `json:"baseDir"`
	SourceInfo             SourceInfo `json:"sourceInfo,omitzero"`
	DisableModelInvocation bool       `json:"disableModelInvocation"`
}

SystemPromptSkill mirrors the upstream `Skill` interface fields that extensions can rely on. Extensions inspect skill metadata; the physical SkillFrontmatter is not exposed.

upstream: packages/coding-agent/src/core/skills.ts:74-82 Skill

type TUI

type TUI = tui.TUI

TUI mirrors @earendil-works/pi-tui TUI.

type TerminalBeller

type TerminalBeller interface {
	Bell()
}

TerminalBeller is a UI with a terminal to ring: Bell writes BEL between frames. A UI without one (print, JSON and RPC modes) does not implement it, and the call does nothing.

type TerminalInputHandler

type TerminalInputHandler = func(data string) TerminalInputResult

TerminalInputHandler mirrors upstream `TerminalInputHandler` (types.ts:120): raw terminal byte handler for interactive mode. Returns a result indicating whether to consume the input.

type TerminalInputResult

type TerminalInputResult struct {
	Consume bool    // true → swallow the keystroke, don't process further
	Data    *string // replacement data (nil = no replacement)
}

TerminalInputResult is the return value from a TerminalInputHandler. Mirrors upstream `{ consume?: boolean; data?: string }`. A nil Data leaves the input unchanged; a non-nil Data replaces it for later listeners and for normal handling, and an empty replacement drops it.

type TextContent

type TextContent = any

TextContent mirrors @earendil-works/pi-ai TextContent.

type Theme

type Theme = any

Theme mirrors core/modes/interactive/theme.Theme.

type ThemeInstance

type ThemeInstance struct{ Theme *tui.Theme }

ThemeInstance selects a theme object, which has no name to look up and nothing to watch.

type ThemeMeta

type ThemeMeta struct {
	Name string `json:"name"`
	Path string `json:"path,omitempty"`
}

ThemeMeta mirrors the inline return-element type of `ExtensionUIContext.getAllThemes` (types.ts:257 - `{ name, path | undefined }[]`). Named for the same reason as SetThemeResult.

type ThemeName

type ThemeName string

ThemeName selects a theme by name.

type ThemeSelection

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

ThemeSelection is `string | Theme`, the argument of setTheme: a theme by name or a theme object.

type ThinkingLevel

type ThinkingLevel = agent.ThinkingLevel

ThinkingLevel mirrors @earendil-works/pi-agent-core ThinkingLevel.

type ThinkingLevelSelectEvent

type ThinkingLevelSelectEvent struct {
	Type          string                `json:"type"`
	Level         ai.ModelThinkingLevel `json:"level"`
	PreviousLevel ai.ModelThinkingLevel `json:"previousLevel"`
}

ThinkingLevelSelectEvent: upstream types.ts ThinkingLevelSelectEvent.

type ToolActions

type ToolActions struct {
	// ExecuteTool backs [ToolContext.ExecuteTool]. ctx is the options' Signal, or the calling tool's context; options.Signal is nil. Without it, nested calls fail with an error outcome.
	// upstream: types.ts:2162
	ExecuteTool func(ctx context.Context, callerID, name string, args json.RawMessage, options ExecuteToolOptions) (AgentToolCallOutcome, error)
	// GetCallableTools backs [ToolContext.Tools]. Without it, the list is empty.
	// upstream: types.ts:2169
	GetCallableTools func() []AgentTool
	// AppendEntry backs [ToolContext.AppendEntry]: append the entry to the session's log and report it as an `entry_appended` event. Go returns the error the log reports, where upstream throws it.
	// upstream: agent-session.ts:3321-3327 (ExtensionActions.appendEntry, types.ts:1687)
	AppendEntry func(customType string, data any) error
}

ToolActions is the host-side injection that backs ToolContext. Mirrors the executeTool and getCallableTools members of upstream ExtensionContextActions.

upstream: types.ts:2161-2169 (ExtensionContextActions.executeTool, getCallableTools)

type ToolAnnotations

type ToolAnnotations struct {
	ReadOnlyHint    *bool `json:"readOnlyHint,omitempty"`
	DestructiveHint *bool `json:"destructiveHint,omitempty"`
	IdempotentHint  *bool `json:"idempotentHint,omitempty"`
	OpenWorldHint   *bool `json:"openWorldHint,omitempty"`
}

ToolAnnotations mirrors upstream ToolAnnotations: hints about what a tool does, with the meaning of MCP tool annotations. They come from the tool's author and are not verified.

upstream: types.ts:515 (ToolAnnotations)

type ToolCallEvent

type ToolCallEvent interface {
	ExtensionEvent
	// contains filtered or unexported methods
}

ToolCallEvent is the event a tool_call handler receives. Pi's `ToolCallEvent` union (types.ts:810) has one member per built-in tool plus CustomToolCallEvent; the variants differ only in the compile-time type of `input`, and Pi's runtime emits the same object shape for every tool. The Session emits CustomToolCallEvent for every tool, so it is the one Go representation: a handler reads `ToolName` and the `Input` map. Package-sealed through the unexported `isToolCallEvent` marker.

upstream: types.ts:810

type ToolCallEventBase

type ToolCallEventBase struct {
	Type string `json:"type"`
	// ToolCallID is the call's id. For calls another tool made (with
	// ParentToolCallID set), pi assigns `<parent id>/<n>`; such ids never appear
	// as tool calls or tool results in the transcript, only in the parent
	// result's `nestedCalls` record.
	ToolCallID string `json:"toolCallId"`
	// ParentToolCallID is set when another tool (for example a codemode script)
	// issued this call. upstream: parentToolCallId?: string
	ParentToolCallID string `json:"parentToolCallId,omitempty"`
	// WireInput points at the call's input as JSON in the member order the model wrote it, edited as JavaScript edits an object: a retained member keeps its place and a new member follows. A Go map has no order, so [CustomToolCallEvent.Input] carries the values and this carries the order. The Session seeds it from the call's arguments, and a subprocess extension's reply replaces the bytes it points at, so every copy of the event shares the edit. Nil when Input is the only source.
	WireInput *json.RawMessage `json:"-"`
}

ToolCallEventBase mirrors upstream's internal ToolCallEventBase. Embedded in each per-tool variant so all variants share the discriminator and toolCallId fields.

Go embeds the common fields so reflection sees the same promoted shape.

type ToolCallEventResult

type ToolCallEventResult struct {
	Block  bool   `json:"block,omitempty"`
	Reason string `json:"reason,omitempty"`
	// Terminate hints that the agent should stop after the current tool batch
	// when this call is blocked. Early termination only happens when every
	// finalized tool result in the batch sets it.
	Terminate bool `json:"terminate,omitempty"`
}

ToolCallEventResult: upstream types.ts ToolCallEventResult.

type ToolContext

type ToolContext struct {
	*Context
	// contains filtered or unexported fields
}

ToolContext is the context passed to tool Execute in a session: the extension Context plus ToolContext.ExecuteTool for running other tools through the same validation, hooks, and permission checks as model-issued calls. Retrieve it with ToolContextFromContext.

A tool that no runner wrapped, such as a built-in tool run in a plain Agent or called directly, gets no ToolContext.

upstream: types.ts:383-395 (ExtensionToolContext)

func NewToolContext

func NewToolContext(base *Context, toolCallID string, signal context.Context, actions ToolActions) *ToolContext

NewToolContext builds the context of the tool call toolCallID. signal is the default cancellation of nested calls. Hosts call it; tool authors never do.

upstream: runner.ts:952-985 (createToolContext)

func ToolContextFromContext

func ToolContextFromContext(ctx context.Context) *ToolContext

ToolContextFromContext returns the ToolContext a host attached to a tool call, or nil when the tool runs outside a runner.

func (*ToolContext) AppendEntry

func (c *ToolContext) AppendEntry(customType string, data any) error

AppendEntry appends a custom entry to the session for state persistence (it is not sent to the LLM) and reports it as an `entry_appended` event. It is `pi.appendEntry()`, for a declarative Go tool that has no `pi` to close over: upstream's codemode passes `(customType, data) => pi.appendEntry(customType, data)` into its tool definition. Without a bound action the call fails with ErrRuntimeNotInitialized.

upstream: loader.ts:376-379 (appendEntry: assertActive, then runtime.appendEntry), loader.ts:157-159, 171 (notInitialized), agent-session.ts:3321-3327, codemode/index.ts:35

func (*ToolContext) ExecuteTool

func (c *ToolContext) ExecuteTool(name string, args any, options *ExecuteToolOptions) (AgentToolCallOutcome, error)

ExecuteTool runs another tool. The call gets the id `<calling id>/<n>`, and the `tool_call`, `tool_result`, and `tool_execution_*` events carry `parentToolCallId`. It does not appear in the transcript; a bounded record of it is kept as `nestedCalls` on the calling tool's result message.

It never fails for tool failures: unknown tools, validation errors, blocked calls, and thrown errors come back as an outcome with IsError set. The error is non-nil only for a stale context or unencodable arguments. The call is cancelled with options.Signal, which defaults to the calling tool's context.

upstream: types.ts:386-394 (executeTool), runner.ts:966-983

func (*ToolContext) Tools

func (c *ToolContext) Tools() ([]AgentTool, error)

Tools returns the tools ToolContext.ExecuteTool can call. Without a GetCallableTools action the list is empty.

upstream: types.ts:385 (ExtensionToolContext.tools), runner.ts:955-964, 379

type ToolDefinition

type ToolDefinition struct {
	Name                string                   `json:"name"`
	Label               string                   `json:"label"`
	Description         string                   `json:"description"`
	PromptSnippet       string                   `json:"promptSnippet,omitempty"`
	PromptGuidelines    []string                 `json:"promptGuidelines,omitempty"`
	Parameters          json.RawMessage          `json:"parameters"`
	ConstrainedSampling json.RawMessage          `json:"constrainedSampling,omitempty"`
	RenderShell         ToolRenderShell          `json:"renderShell,omitempty"`
	PrepareArguments    ToolPrepareArgumentsFunc `json:"-"`
	ExecutionMode       ToolExecutionMode        `json:"executionMode,omitempty"`
	Execute             ToolExecuteFunc          `json:"-"`
	RenderCall          ToolRenderCallFunc       `json:"-"`
	RenderResult        ToolRenderResultFunc     `json:"-"`
	// DefaultActive is whether registering the tool activates it. Default: true
	// for direct and model-only tools; other exposures are never activated on
	// registration. A tool with DefaultActive false is activated by naming it in
	// `--tools` or the `defaultTools` setting, or with SetActiveTools.
	// upstream: types.ts:600 (defaultActive)
	DefaultActive *bool `json:"defaultActive,omitempty"`
	// PrepareLoadout adjusts how the loadout is presented to the model while
	// this tool is active. Called whenever the active tools change. Tools that
	// orchestrate other tools use it, for example to list the callable tools in
	// their own description.
	// upstream: types.ts:607 (prepareLoadout)
	PrepareLoadout ToolPrepareLoadoutFunc `json:"-"`
	// ReserveCallOrder reserves this call's place among the calls the tool's requests must follow in call order. The host
	// calls it synchronously, in call order, before any call of a parallel batch or a codemode script runs, and puts the
	// result on the call's context (CallOrderFromContext). A nil result reserves nothing. Pi's calls run their
	// synchronous prefix in call order, which Go goroutines do not give; this restores it for tools whose request order is
	// observable, such as MCP tool calls to one server.
	ReserveCallOrder func(params json.RawMessage) *CallOrder `json:"-"`
	// MayTakeFileMutationQueue is set for a tool whose code runs in an extension that can register in the host's file mutation queue (withFileMutationQueue),
	// so the dispatcher holds the edit and write calls that follow it in a parallel batch behind the end of its synchronous prefix (agent.MayTakeFileMutationQueue).
	MayTakeFileMutationQueue bool `json:"-"`
	// ReachesTools is for tools that reach other tools (such as codemode, which calls them, and tool_search, which loads
	// them): which tools a call with the given input may reach. Extensions that register tools late, such as MCP servers
	// that are still connecting, use it from their tool_call handler to finish registering those tools before the call runs.
	// upstream: types.ts:621 (reachesTools)
	ReachesTools ToolReachesToolsFunc `json:"-"`
	// BuiltInRenderers names the built-in tool whose renderers draw the card
	// halves this definition does not render itself. A subprocess extension
	// sets it for a tool built from Pi's create<Tool>ToolDefinition, whose
	// renderers are that built-in tool's (D73).
	BuiltInRenderers string `json:"-"`
	// ValidationParameters is the host-only representation of non-enumerable TypeBox metadata.
	ValidationParameters json.RawMessage `json:"-"`
	// OutputSchema is the schema of the structured result. upstream: types.ts:585
	OutputSchema json.RawMessage `json:"outputSchema,omitempty"`
	// Exposure is how the model reaches the tool. Default: direct. upstream: types.ts:590
	Exposure ToolExposure `json:"exposure,omitempty"`
	// Namespace groups the tool with related tools. upstream: types.ts:593
	Namespace *ToolNamespace `json:"namespace,omitempty"`
	// Annotations are hints about what the tool does. upstream: types.ts:596
	Annotations *ToolAnnotations `json:"annotations,omitempty"`
}

ToolDefinition mirrors upstream ToolDefinition<TParams, TDetails, TState>.

pig Go mechanic (not a divergence): upstream is generic over TParams (TypeBox TSchema), TDetails, and TState. Go uses json.RawMessage for parameters and any for details/state because Go interface methods cannot have type parameters and the host registry is heterogeneous. The SDK ergonomics layer in `extensions/sdk/go/` provides typed wrappers without changing the wire format.

type ToolDetailsConverter

type ToolDetailsConverter interface {
	ToolResultDetails() any
}

ToolDetailsConverter is implemented by a built-in tool's internal result details to produce the upstream SDK wire shape for the `details` field of a tool_result event. pig keeps richer internal detail structs for the TUI renderer; this contract lets the extension emission boundary convert them to the lean upstream shapes without the generic runtime depending on the concrete tool package.

type ToolExecuteFunc

type ToolExecuteFunc = func(
	ctx context.Context,
	toolCallID string,
	params json.RawMessage,
	onUpdate AgentToolUpdateCallback,
) (AgentToolResult, error)

ToolExecuteFunc mirrors upstream ToolDefinition.execute.

Go carries the upstream abort signal and extension values through one context.Context. Use FromContext to access the extension context.

type ToolExecutionEndEvent

type ToolExecutionEndEvent struct {
	Type       string `json:"type"`
	ToolCallID string `json:"toolCallId"`
	ToolName   string `json:"toolName"`
	Result     any    `json:"result"`
	// WireResult is the value the event carries for Result on the extension wire, with its members in the order the tool wrote them: a map in Result sorts them. Nil when Result marshals as it is.
	WireResult any  `json:"-"`
	IsError    bool `json:"isError"`
	// DurationMs is the milliseconds execute() took, measured with a monotonic clock; absent when the tool did not run.
	// upstream: types.ts ToolExecutionEndEvent.durationMs
	DurationMs *int64 `json:"durationMs,omitempty"`
	// ParentToolCallID is set when another tool (for example a codemode script)
	// made this call. upstream: parentToolCallId?: string
	ParentToolCallID string `json:"parentToolCallId,omitempty"`
}

ToolExecutionEndEvent: upstream types.ts ToolExecutionEndEvent.

func (ToolExecutionEndEvent) MarshalJSON

func (e ToolExecutionEndEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the event with WireResult in place of Result, in Pi's member order.

type ToolExecutionMode

type ToolExecutionMode = string

ToolExecutionMode mirrors ToolExecutionMode ("sequential" | "parallel").

type ToolExecutionStartEvent

type ToolExecutionStartEvent struct {
	Type       string `json:"type"`
	ToolCallID string `json:"toolCallId"`
	ToolName   string `json:"toolName"`
	Args       any    `json:"args"`
	// WireArgs is the JSON the event carries for Args on the extension wire: the model's arguments in the order it wrote them, which the map in Args cannot keep. Nil when Args marshals as it is.
	WireArgs json.RawMessage `json:"-"`
	// ParentToolCallID is set when another tool (for example a codemode script)
	// made this call. upstream: parentToolCallId?: string
	ParentToolCallID string `json:"parentToolCallId,omitempty"`
}

ToolExecutionStartEvent: upstream types.ts ToolExecutionStartEvent.

func (ToolExecutionStartEvent) MarshalJSON

func (e ToolExecutionStartEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the event with WireArgs in place of Args, in Pi's member order.

type ToolExecutionUpdateEvent

type ToolExecutionUpdateEvent struct {
	Type       string `json:"type"`
	ToolCallID string `json:"toolCallId"`
	ToolName   string `json:"toolName"`
	Args       any    `json:"args"`
	// WireArgs is the JSON the event carries for Args on the extension wire; see [ToolExecutionStartEvent.WireArgs].
	WireArgs      json.RawMessage `json:"-"`
	PartialResult any             `json:"partialResult"`
	// WirePartialResult is the value the event carries for PartialResult on the extension wire, with its members in the order the tool wrote them. Nil when PartialResult marshals as it is.
	WirePartialResult any `json:"-"`
	// ParentToolCallID is set when another tool (for example a codemode script)
	// made this call. upstream: parentToolCallId?: string
	ParentToolCallID string `json:"parentToolCallId,omitempty"`
}

ToolExecutionUpdateEvent: upstream types.ts ToolExecutionUpdateEvent.

func (ToolExecutionUpdateEvent) MarshalJSON

func (e ToolExecutionUpdateEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the event with the wire values in place of Args and PartialResult, in Pi's member order.

type ToolExposure

type ToolExposure string

ToolExposure mirrors upstream ToolExposure: how the model reaches a tool. "Callable" means callable from other tools through `ctx.executeTool()`, as the codemode tool does.

  • direct: declared to the model while active, and callable while active.
  • model-only: declared to the model while active, never callable.
  • codemode: callable whenever registered. Not declared to the model unless explicitly activated. Codemode tools list it in their description.
  • deferred: like codemode, but codemode tools do not list it; tool search can find it.
  • hidden: registered but unreachable. Activating it has no effect.

`direct` and `model-only` tools are activated when they are registered; the others are not.

upstream: types.ts:509 (ToolExposure)

const (
	ToolExposureDirect    ToolExposure = "direct"
	ToolExposureModelOnly ToolExposure = "model-only"
	ToolExposureCodemode  ToolExposure = "codemode"
	ToolExposureDeferred  ToolExposure = "deferred"
	ToolExposureHidden    ToolExposure = "hidden"
)

The exposures of upstream's ToolExposure union.

type ToolFilter

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

ToolFilter is the `--tools` allowlist and `--exclude-tools` denylist of a Session. Entries are tool names or `*` patterns. A non-empty allowlist without `mcp__` entries keeps MCP tools registered for codemode and tool_search; only tool_search can declare them. An empty allowlist (`--no-tools`) removes them.

func NewToolFilter

func NewToolFilter(allowed, excluded map[string]struct{}) ToolFilter

NewToolFilter compiles an allowlist (nil: none) and a denylist (nil or empty: none).

Ports packages/coding-agent/src/core/agent-session.ts (the constructor's _allowedTools, _allowlistFiltersMcp and _excludedTools).

func (ToolFilter) Allows

func (f ToolFilter) Allows(name string) bool

Allows reports whether `--tools` and `--exclude-tools` keep the tool registered. MCP tools stay registered unless the allowlist filters them.

Ports packages/coding-agent/src/core/agent-session.ts (_isAllowedTool).

func (ToolFilter) HasAllowlist

func (f ToolFilter) HasAllowlist() bool

HasAllowlist reports whether `--tools` or `--no-tools` is in force.

func (ToolFilter) MayBeActive

func (f ToolFilter) MayBeActive(name string, exposure ToolExposure, toolSearchRegistered bool) bool

MayBeActive reports whether the tool may be active, which declares it to the model. MCP tools the allowlist keeps without matching them are only for codemode and tool_search: they may be declared only when tool_search can load them (non-`direct` exposure and tool_search registered). This also applies to tools restored from the transcript or set by extensions.

Ports packages/coding-agent/src/core/agent-session.ts (_isActivatable).

func (ToolFilter) Names

func (f ToolFilter) Names(name string) bool

Names reports whether the allowlist names or matches the tool. It is false without an allowlist.

type ToolInfo

type ToolInfo struct {
	Name             string          `json:"name"`
	Description      string          `json:"description"`
	Parameters       json.RawMessage `json:"parameters"`
	PromptGuidelines []string        `json:"promptGuidelines,omitempty"`
	SourceInfo       SourceInfo      `json:"sourceInfo"`
	// Source is PiG's per-tool source attribution (D23): "builtin", the registering extension's name, or the tool's declared source. It is not part of upstream's ToolInfo.
	Source string `json:"-"`
	// Exposure, Namespace, and Annotations mirror upstream ToolInfo. upstream: types.ts:2063
	Exposure    ToolExposure     `json:"exposure,omitempty"`
	Namespace   *ToolNamespace   `json:"namespace,omitempty"`
	Annotations *ToolAnnotations `json:"annotations,omitempty"`
	// ReachesTools is the tool's reachesTools, nil for a tool that reaches no others. upstream: types.ts:2107 (ToolInfo)
	ReachesTools ToolReachesToolsFunc `json:"-"`
}

ToolInfo mirrors upstream ToolInfo: the read-only view returned by API.GetAllTools.

type ToolLoadout

type ToolLoadout struct {
	// Declared are the tools declared to the model (the active tools), in order, with their original descriptions.
	Declared []AgentTool
	// Callable are the tools callable through [ToolContext.ExecuteTool].
	Callable []AgentTool
	// Registered is every registered tool.
	Registered   []AgentTool
	GetExposure  func(name string) ToolExposure
	GetNamespace func(name string) *ToolNamespace
	// GetPromptGuidelines is a tool's `promptGuidelines`, normalized as the system prompt has them. Hidden declarations leave
	// them out of the system prompt.
	GetPromptGuidelines func(name string) []string
}

ToolLoadout is the tools of a session as ToolDefinition.PrepareLoadout sees them.

Go mechanic (not a divergence): upstream's getExposure and getNamespace methods are function-valued fields, so a test double is a struct literal.

upstream: types.ts:541-551 (ToolLoadout)

type ToolLoadoutChanges

type ToolLoadoutChanges struct {
	// Descriptions are the model-facing descriptions of declared tools, by tool name.
	Descriptions map[string]string `json:"descriptions,omitempty"`
	// HiddenDeclarations names declared tools whose declarations requests leave out. They stay active and callable, and the transcript still declares them, so the active set survives `/tree` and resume.
	HiddenDeclarations []string `json:"hiddenDeclarations,omitempty"`
}

ToolLoadoutChanges are the changes ToolDefinition.PrepareLoadout makes to what the model sees.

upstream: types.ts:554-563 (ToolLoadoutChanges)

type ToolNamespace

type ToolNamespace struct {
	Name string `json:"name"`
	// Aliases are other names that refer to the namespace where tools look it up by name (codemode's describeNamespace()
	// and the namespace option of searchTools()), for example `docs` for `mcp__docs`. A nil slice is an absent member;
	// an explicit empty one encodes as [], as upstream returns the authored namespace object (agent-session.ts:1505).
	Aliases []string `json:"aliases,omitzero"`
	// Description is a short summary shown once with the group in model-facing tool listings.
	Description string `json:"description,omitempty"`
	// Instructions is longer usage guidance, such as MCP server instructions. It is not part of tool listings; tools
	// that describe the namespace on request (codemode's describeNamespace()) return it.
	Instructions string `json:"instructions,omitempty"`
}

ToolNamespace mirrors upstream ToolNamespace: a group of related tools, such as the tools of one MCP server.

upstream: types.ts:527 (ToolNamespace)

type ToolPrepareArgumentsFunc

type ToolPrepareArgumentsFunc = func(args json.RawMessage) (json.RawMessage, error)

ToolPrepareArgumentsFunc mirrors upstream ToolDefinition.prepareArguments.

type ToolPrepareLoadoutFunc

type ToolPrepareLoadoutFunc = func(loadout ToolLoadout) *ToolLoadoutChanges

ToolPrepareLoadoutFunc mirrors upstream ToolDefinition.prepareLoadout. A nil result leaves the loadout as it is (upstream returns undefined). Upstream's hook is synchronous and reports a failure by throwing; a Go hook panics instead, and the session recovers the panic and reports it as a `prepare_loadout` extension error (agent-session.ts:1520-1533).

type ToolReach

type ToolReach struct {
	All   bool
	Words []string
}

ToolReach mirrors the result of upstream ToolDefinition.reachesTools, `"all" | readonly string[]`: every tool, or the words of the input that may name them, where a word refers to a tool or namespace whose name contains it, so words may over-match.

pig Go mechanic (not a divergence): a Go struct stands for the string-or-array union.

type ToolReachesToolsFunc

type ToolReachesToolsFunc = func(input json.RawMessage) ToolReach

ToolReachesToolsFunc mirrors upstream ToolDefinition.reachesTools: which tools a call with input (the call's arguments as the tool receives them) may reach.

type ToolRenderCallFunc

type ToolRenderCallFunc = func(
	args json.RawMessage,
	theme Theme,
	context ToolRenderContext,
) Component

ToolRenderCallFunc mirrors upstream ToolDefinition.renderCall.

type ToolRenderContext

type ToolRenderContext struct {
	Args             any       `json:"args"`
	ToolCallID       string    `json:"toolCallId"`
	Invalidate       func()    `json:"-"`
	LastComponent    Component `json:"-"`
	State            any       `json:"-"`
	Cwd              string    `json:"cwd"`
	ExecutionStarted bool      `json:"executionStarted"`
	ArgsComplete     bool      `json:"argsComplete"`
	IsPartial        bool      `json:"isPartial"`
	Expanded         bool      `json:"expanded"`
	ShowImages       bool      `json:"showImages"`
	IsError          bool      `json:"isError"`
	// OutputPad is the horizontal padding configured by the outputPad setting. Renderers with renderShell "self" apply it themselves.
	OutputPad int `json:"outputPad"`
	// DurationMs is the recorded execution time of a final result in milliseconds. Nil while the result is partial and for results
	// stored without one. upstream: types.ts:496 ToolRenderContext.durationMs
	DurationMs *int64 `json:"durationMs,omitempty"`
	// Card identifies the tool card being rendered. Go mechanic (not a
	// divergence): a renderer that runs in an extension process keeps State
	// and its last component there, so the host names the card they belong
	// to; upstream passes the card's objects themselves.
	Card string `json:"-"`
}

ToolRenderContext mirrors upstream ToolRenderContext<TState, TArgs>.

Go mechanic (not a divergence): upstream is generic over TState and TArgs; the Go version uses any for both because Go function-type struct fields cannot have type parameters. SDK helpers in `extensions/sdk/go/` provide typed wrappers without changing the wire format.

type ToolRenderResultFunc

type ToolRenderResultFunc = func(
	result AgentToolResult,
	options ToolRenderResultOptions,
	theme Theme,
	context ToolRenderContext,
) Component

ToolRenderResultFunc mirrors upstream ToolDefinition.renderResult.

type ToolRenderResultOptions

type ToolRenderResultOptions struct {
	Expanded  bool `json:"expanded"`
	IsPartial bool `json:"isPartial"`
}

ToolRenderResultOptions mirrors upstream ToolRenderResultOptions.

type ToolRenderShell

type ToolRenderShell string

ToolRenderShell controls whether the standard tool-execution chrome wraps the tool's renderers, or the tool draws its own framing. Mirrors upstream "default" | "self".

const (
	ToolRenderShellDefault ToolRenderShell = "default"
	ToolRenderShellSelf    ToolRenderShell = "self"
)

type ToolRendererResolver

type ToolRendererResolver = func(toolName string, next func() *ToolRenderers) *ToolRenderers

ToolRendererResolver chooses how calls to a tool are drawn, including tools that are not registered. next returns the renderers the remaining resolvers, then the registered tool, would use. A nil result means none. upstream: types.ts ToolRendererResolver

type ToolRenderers

type ToolRenderers struct {
	RenderShell  ToolRenderShell
	RenderCall   ToolRenderCallFunc
	RenderResult ToolRenderResultFunc
}

ToolRenderers is how calls to a tool are drawn: the renderShell, renderCall, and renderResult of a ToolDefinition. upstream: types.ts ToolRenderers

type ToolResultEvent

type ToolResultEvent interface {
	ExtensionEvent
	// contains filtered or unexported methods
}

ToolResultEvent is the sealed union of per-tool ToolResultEvent variants. Mirrors upstream's `export type ToolResultEvent = | BashToolResultEvent | PowerShellToolResultEvent | ... | CustomToolResultEvent` (types.ts:869).

Package-sealed via the unexported `isToolResultEvent` marker method. Custom UnmarshalJSON in marshalling.go dispatches by `toolName`.

upstream: types.ts:869

func UnmarshalToolResultEvent

func UnmarshalToolResultEvent(data []byte) (ToolResultEvent, error)

UnmarshalToolResultEvent dispatches by `toolName`. Tool names that match no built-in variant fall through to CustomToolResultEvent, as Pi treats any other tool as a custom tool.

type ToolResultEventBase

type ToolResultEventBase struct {
	Type string `json:"type"`
	// ToolCallID is the call's id; `<parent id>/<n>` for nested calls, see [ToolCallEventBase].
	ToolCallID string `json:"toolCallId"`
	// ParentToolCallID is set when another tool (for example a codemode script)
	// issued this call. upstream: parentToolCallId?: string
	ParentToolCallID string         `json:"parentToolCallId,omitempty"`
	Input            map[string]any `json:"input"`
	// WireInput is the tool call's arguments as the model wrote them, which a subprocess extension receives as `input` in that member order; a map in Input sorts them. Empty when Input is the only source.
	WireInput json.RawMessage `json:"-"`
	Content   []any           `json:"content"` // (TextContent | ImageContent)[]
	// StructuredContent is the machine-readable result of a tool that declares an
	// outputSchema. Handlers that redact Content should also replace this;
	// replacing Content alone drops it. upstream: structuredContent?: JsonValue
	StructuredContent json.RawMessage `json:"structuredContent,omitempty"`
	IsError           bool            `json:"isError"`
	// Usage is the usage of the tool execution itself, if available
	// (upstream `usage?: Usage`).
	Usage any `json:"usage,omitempty"`
}

ToolResultEventBase mirrors upstream's internal ToolResultEventBase.

type ToolResultEventResult

type ToolResultEventResult struct {
	Content []any `json:"content,omitempty"` // (TextContent | ImageContent)[]
	Details any   `json:"details,omitempty"`
	// StructuredContent replaces the result's structured content. upstream: structuredContent?: JsonValue
	StructuredContent json.RawMessage `json:"structuredContent,omitempty"`
	// IsError is nil when the handler leaves the error flag unchanged, as
	// upstream's optional `isError?: boolean` is undefined.
	IsError *bool `json:"isError,omitempty"`
	// Usage replaces the tool's own usage in the session usage totals; nil keeps it.
	// upstream: ToolResultEventResult.usage?: Usage
	Usage *ai.Usage `json:"usage,omitempty"`
}

ToolResultEventResult: upstream types.ts ToolResultEventResult. Omitted fields stay as they are, except that replacing Content without returning StructuredContent drops the structured content, because it may no longer match. Return it along with Content to keep it.

func (*ToolResultEventResult) UnmarshalJSON

func (r *ToolResultEventResult) UnmarshalJSON(data []byte) error

UnmarshalJSON keeps the member order of the `details` object the handler wrote.

type ToolResultMessage

type ToolResultMessage = agent.ToolResultMessage

ToolResultMessage mirrors @earendil-works/pi-ai ToolResultMessage.

type TreePreparation

type TreePreparation struct {
	TargetID           string         `json:"targetId"`
	OldLeafID          *string        `json:"oldLeafId"`
	CommonAncestorID   *string        `json:"commonAncestorId"`
	EntriesToSummarize []SessionEntry `json:"entriesToSummarize"`
	UserWantsSummary   bool           `json:"userWantsSummary"`
	// CustomInstructions are the custom summarization instructions.
	CustomInstructions string `json:"customInstructions,omitempty"`
	// ReplaceInstructions makes CustomInstructions replace the default prompt instead of being appended.
	ReplaceInstructions bool `json:"replaceInstructions,omitempty"`
	// Label is the label to attach to the branch summary entry.
	Label string `json:"label,omitempty"`
}

TreePreparation is types.ts TreePreparation: what a session_before_tree handler receives about the navigation. EntriesToSummarize holds the SessionEntry values the navigation abandons.

type TruncationResult

type TruncationResult struct {
	Content               string `json:"content"`
	Truncated             bool   `json:"truncated"`
	TruncatedBy           string `json:"truncatedBy"` // "lines" | "bytes"
	TotalLines            int    `json:"totalLines"`
	TotalBytes            int    `json:"totalBytes"`
	OutputLines           int    `json:"outputLines"`
	OutputBytes           int    `json:"outputBytes"`
	LastLinePartial       bool   `json:"lastLinePartial"`
	FirstLineExceedsLimit bool   `json:"firstLineExceedsLimit"`
	MaxLines              int    `json:"maxLines"`
	MaxBytes              int    `json:"maxBytes"`
}

TruncationResult is the upstream TruncationResult wire shape (truncate.ts:15). It is attached as the `truncation` field of read/bash/grep/find/ls tool result details when output was truncated. All fields are present in a real truncation object (it is only attached when truncation occurred).

type TurnEndEvent

type TurnEndEvent struct {
	*BoundaryState
	Type               string              `json:"type"`
	TurnIndex          int                 `json:"turnIndex"`
	Message            AgentMessage        `json:"message"`
	ToolResults        []ToolResultMessage `json:"toolResults"`
	MessageEntryID     string              `json:"messageEntryId"`
	ToolResultEntryIds []string            `json:"toolResultEntryIds"`
}

TurnEndEvent carries the completed turn and the actionable boundary proposal and preview (upstream types.ts TurnEndEvent).

func (TurnEndEvent) MarshalJSON

func (e TurnEndEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the members in the order the event object has in Pi: the turn's base event, then the boundary's entries, continue and context (extensions/runner.ts emitBoundary spreads the base event before them).

type TurnEndEventResult

type TurnEndEventResult = BoundaryResult

TurnEndEventResult mirrors upstream's BoundaryResult alias for turn_end handlers.

type TurnStartEvent

type TurnStartEvent struct {
	Type      string `json:"type"`
	TurnIndex int    `json:"turnIndex"`
	Timestamp int64  `json:"timestamp"`
}

TurnStartEvent: upstream types.ts TurnStartEvent.

type UIContext

type UIContext interface {
	// Show a selector and return the user's choice.
	// upstream: types.ts:124
	Select(ctx context.Context, title string, options []string, opts ExtensionUIDialogOptions) (string, error)

	// Show a confirmation dialog.
	// upstream: types.ts:127
	Confirm(ctx context.Context, title, message string, opts ExtensionUIDialogOptions) (bool, error)

	// Show a text input dialog.
	// upstream: types.ts:130
	Input(ctx context.Context, title, placeholder string, opts ExtensionUIDialogOptions) (string, error)

	// Show a notification to the user. Type is one of
	// "info" | "warning" | "error".
	// upstream: types.ts:133
	Notify(message, kind string)

	// OnTerminalInput registers a raw-terminal-input handler
	// (interactive mode only). Returns an unsubscribe function.
	// upstream: types.ts:136
	OnTerminalInput(handler TerminalInputHandler) (unsubscribe func())

	// SetStatus sets status text in the footer/status bar. Empty text clears the entry, except in RPC mode, which writes it: Pi writes the text as given
	// there and `undefined` removes the entry, so a UIContext that implements [StatusClearer] receives the `undefined` form as ClearStatus.
	// upstream: types.ts:139
	SetStatus(key, text string)

	// SetWorkingMessage sets the working/loading message shown during streaming. A UIContext that implements [WorkingMessageClearer] shows an empty
	// message as an empty label, as Pi's `message ?? defaultWorkingMessage` does (interactive-mode.ts:2641-2646); one that does not treats
	// an empty message as the default, as before.
	// upstream: types.ts:142
	SetWorkingMessage(message string)

	// SetWorkingVisible toggles whether the working/loading indicator is shown.
	// upstream: interactive-mode.ts oauth/rpc extension contexts
	SetWorkingVisible(visible bool)

	// SetWorkingIndicator configures the interactive working
	// indicator. Nil opts restores the default animated spinner.
	// upstream: types.ts:153
	SetWorkingIndicator(opts WorkingIndicatorOptions)

	// SetHiddenThinkingLabel sets the label shown for hidden
	// thinking blocks. Empty label restores the default.
	// upstream: types.ts:156
	SetHiddenThinkingLabel(label string)

	// SetWidget sets a widget of text lines to display above or below the editor; nil lines remove it. opts describes placement.
	//
	// upstream: types.ts:188 (the string[] overload of setWidget; the component-factory overload, types.ts:189, is SetWidgetFactory).
	SetWidget(key string, content []string, opts *ExtensionWidgetOptions)

	// SetWidgetFactory sets a widget built by factory to display above or below the editor; a nil factory removes it. It is setWidget's
	// component-factory overload (types.ts:189), which Go names apart because a Go method cannot be overloaded.
	// upstream: types.ts:189
	SetWidgetFactory(key string, factory WidgetFactory, opts *ExtensionWidgetOptions)

	// SetFooter installs a custom footer factory. Nil restores the
	// built-in footer.
	// upstream: types.ts:172
	SetFooter(factory FooterFactory)

	// SetHeader installs a custom header factory. Nil restores the
	// built-in header.
	// upstream: types.ts:181
	SetHeader(factory HeaderFactory)

	// pig additive (D60): SetLogin validates and installs Pig's native login
	// definition in the shared header slot. Upstream Pi exposes only
	// SetHeader because its in-process extensions can supply component factories.
	SetLogin(definition LoginDefinition) error

	// SetTitle sets the terminal window/tab title.
	// upstream: types.ts:184
	SetTitle(title string)

	// Custom shows a custom component with keyboard focus and
	// returns the user's result via the `done` callback.
	//
	// upstream: types.ts:187: the generic `<T>` is erased to `any` because Go
	// interface methods cannot be generic (an ordinary TS→Go mechanic, not a
	// divergence). Authors typed-assert at the call site or use the SDK helpers.
	//
	// An extension in the host process passes a [CustomFactory] and, optionally,
	// [CustomOptions]; the call blocks until the factory's done callback returns
	// the result.
	Custom(ctx context.Context, factory CustomFactory, opts *CustomOptions) (any, error)

	// PasteToEditor pastes text into the editor, triggering paste
	// handling (collapse for large content).
	// upstream: types.ts:204
	PasteToEditor(text string)

	// SetEditorText sets the text in the core input editor.
	// upstream: types.ts:207
	SetEditorText(text string)

	// GetEditorText returns the current text from the core input
	// editor.
	// upstream: types.ts:210
	GetEditorText() string

	// Editor shows a multi-line editor for text editing. Returns
	// the entered text or empty + context.Canceled when cancelled.
	// upstream: types.ts:213
	Editor(ctx context.Context, title, prefill string) (string, error)

	// AddAutocompleteProvider stacks additional autocomplete
	// behavior on top of the built-in provider.
	// upstream: types.ts:216
	AddAutocompleteProvider(factory AutocompleteProviderFactory) error

	// SetEditorComponent installs the editor factory's component in place of the default editor, as Pi's setCustomEditorComponent does
	// (it calls the factory with the TUI, the editor theme and the keybindings). Nil restores the default editor.
	// upstream: types.ts:278
	SetEditorComponent(factory EditorFactory)

	// GetEditorComponent returns the factory the last SetEditorComponent installed, nil when the default editor is active.
	// upstream: types.ts:281 (interactive-mode.ts:2664 `getEditorComponent: () => this.editorComponentFactory`)
	GetEditorComponent() EditorFactory

	// Theme returns the current theme for styling.
	//
	// upstream: types.ts:254 (`readonly theme: Theme`). Mapped to a
	// getter method because Go interfaces cannot expose readonly
	// fields.
	Theme() Theme

	// GetAllThemes returns metadata for all available themes.
	// upstream: types.ts:257
	GetAllThemes() []ThemeMeta

	// GetTheme loads a theme by name without switching to it.
	// Returns nil + error if not found.
	// upstream: types.ts:260
	GetTheme(name string) (Theme, error)

	// SetTheme switches the current theme. theme is either a name
	// (string) or a Theme value; the result reports success +
	// optional error message.
	// upstream: types.ts:262
	SetTheme(theme ThemeSelection) SetThemeResult

	// GetToolsExpanded returns the current tool-output expansion
	// state.
	// upstream: types.ts:265
	GetToolsExpanded() bool

	// SetToolsExpanded sets the tool-output expansion state.
	// upstream: types.ts:268
	SetToolsExpanded(expanded bool)

	// RunRemoteOverlay opens an interactive overlay whose contents
	// are produced by a remote (subprocess) extension. The overlay
	// renders the cached lines pushed via the returned handle and
	// forwards user input chunks back to host.OnInput. Blocks until
	// the handle's Close is called and returns the result value the
	// remote producer supplied. Returns (nil, false) when the
	// overlay cannot be opened (e.g. no TUI bound, like in print or
	// RPC modes).
	//
	// pig-specific: no upstream equivalent. Upstream's Custom()
	// can't cross a subprocess boundary because its factory captures
	// in-process TUI references; this is the deserialised companion.
	RunRemoteOverlay(opts RemoteOverlayOptions, host RemoteOverlayHost, onHandle func(RemoteOverlayHandle)) (any, bool)

	// OnRemoteTerminalInput registers the raw-terminal-input listener of
	// the subprocess extension named extensionName. It takes its place in
	// registration order as OnTerminalInput does, but the host never calls
	// handler on its input loop: it asks off the loop and applies the
	// verdict in input order. Returns an unsubscribe function.
	//
	// pig additive (D19): upstream listeners run in process and answer
	// synchronously; a subprocess listener's verdict crosses a socket.
	OnRemoteTerminalInput(extensionName string, handler RemoteTerminalInputHandler) (unsubscribe func())
}

UIContext is the per-mode UI surface for extensions.

**Upstream alias:** mirrors `ExtensionUIContext` (types.ts:120-269). Each mode (interactive, RPC, print) provides its own implementation; extensions interact with whichever the host bound at runtime.

**Default:** when the host binds nothing, `Context.UI()` returns the package-level NoopUIContext (a value, not a constructor - matches upstream's module-level `noOpUIContext` constant at runner.ts:188).

**Method shape conventions (pig):**

  • Methods that upstream returns `Promise<T | undefined>` from map to `(T, error)` in Go. The error half carries cancellation and routes upstream "undefined" through the typed zero value (empty string, false). Callers distinguish "user cancelled" from "ok with default value" by inspecting `errors.Is(err, context.Canceled)`.
  • Methods that upstream returns `Promise<void>` from map to `error`-returning Go methods so cancellation propagates.
  • Methods that upstream returns synchronously stay synchronous in Go (Notify, SetStatus, etc.).
  • Method names are upstream camelCase → Go PascalCase. The `setX` family becomes `SetX`. The readonly property `theme` becomes a `Theme()` getter (Go has no readonly fields on interfaces).

**Sync-compat:** every divergence from a 1:1 method shape is a silent sync-debt risk. Method order in this interface mirrors upstream types.ts order verbatim so `git diff` against the next upstream sync is mechanical.

upstream: types.ts:120-269 (ExtensionUIContext)

var NoopUIContext UIContext = &noopUIContext{}

NoopUIContext is the package-level no-op singleton. Hosts that have no UI (print and JSON modes) wire `ContextActions.UI = NoopUIContext`; equivalently, leaving `ContextActions.UI` nil produces the same behavior because Context.UI falls back to this value.

**Identity contract:** the value is intentionally a singleton (one shared `*noopUIContext`) so `Context.HasUI()` can implement upstream's identity check (runner.ts:361: `this.uiContext !== noOpUIContext`) by pointer comparison.

upstream: runner.ts:188 (`const noOpUIContext: ExtensionUIContext = ...`)

type UIPromptEndEvent

type UIPromptEndEvent struct {
	Type   string       `json:"type"`   // "ui_prompt_end"
	Reason string       `json:"reason"` // "ui_prompt"
	Kind   UIPromptKind `json:"kind"`
	Title  string       `json:"title,omitempty"`
}

UIPromptEndEvent: upstream types.ts UIPromptEndEvent. Fired when Pi is no longer waiting on a blocking user-facing extension UI prompt. Kind and Title repeat the outermost prompt's start event.

type UIPromptKind

type UIPromptKind string

UIPromptKind mirrors upstream types.ts UIPromptKind: "select" | "confirm" | "input" | "editor" | "custom".

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"`   // "ui_prompt_start"
	Reason string       `json:"reason"` // "ui_prompt"
	Kind   UIPromptKind `json:"kind"`
	Title  string       `json:"title,omitempty"`
}

UIPromptStartEvent: upstream types.ts UIPromptStartEvent. Fired when Pi starts waiting on a blocking user-facing extension UI prompt. Title is omitted when the prompt has none (upstream `...(title ? { title } : {})`).

type UsageEntry

type UsageEntry = sessionentry.UsageEntry

UsageEntry is model-attributed usage that does not enter model context (session-manager.ts UsageEntry).

type UserBashEvent

type UserBashEvent struct {
	Type               string `json:"type"`
	Command            string `json:"command"`
	ExcludeFromContext bool   `json:"excludeFromContext"`
	Cwd                string `json:"cwd"`
}

UserBashEvent: upstream types.ts UserBashEvent.

type UserBashEventResult

type UserBashEventResult struct {
	Operations BashOperations `json:"operations,omitempty"`
	Result     BashResult     `json:"result,omitempty"`
}

UserBashEventResult: upstream types.ts UserBashEventResult.

type ValidatedLoginDefinition

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

ValidatedLoginDefinition is an immutable, renderer-ready login definition.

func DecodeLoginDefinitionJSON

func DecodeLoginDefinitionJSON(data []byte) (ValidatedLoginDefinition, error)

DecodeLoginDefinitionJSON strictly decodes and validates the current login wire shape. Duplicate and unknown object fields are rejected.

func ValidateLoginDefinition

func ValidateLoginDefinition(definition LoginDefinition) (ValidatedLoginDefinition, error)

ValidateLoginDefinition validates and defensively copies a login definition.

func (ValidatedLoginDefinition) Brand

func (d ValidatedLoginDefinition) Brand() []string

func (ValidatedLoginDefinition) Color

func (d ValidatedLoginDefinition) Color(symbol byte) (color.RGBA, bool)

func (ValidatedLoginDefinition) Description

func (d ValidatedLoginDefinition) Description() string

func (ValidatedLoginDefinition) Hero

func (d ValidatedLoginDefinition) Hero() []string

func (ValidatedLoginDefinition) Mascot

func (d ValidatedLoginDefinition) Mascot() []string

func (ValidatedLoginDefinition) Name

func (ValidatedLoginDefinition) Tagline

func (d ValidatedLoginDefinition) Tagline() string

type ValidatedSpriteDefinition

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

ValidatedSpriteDefinition is an immutable, renderer-ready sprite definition.

func DecodeSpriteDefinitionJSON

func DecodeSpriteDefinitionJSON(data []byte) (ValidatedSpriteDefinition, error)

DecodeSpriteDefinitionJSON strictly decodes and validates the sprite wire shape. Duplicate and unknown object fields are rejected.

func ValidateSpriteDefinition

func ValidateSpriteDefinition(definition SpriteDefinition) (ValidatedSpriteDefinition, error)

ValidateSpriteDefinition validates and defensively copies a sprite definition. The grids, palette and text follow the login definition's rules (ValidateLoginDefinition); the name has the login name's width and the tagline the login tagline's.

func (ValidatedSpriteDefinition) ID

func (ValidatedSpriteDefinition) Mascot

func (d ValidatedSpriteDefinition) Mascot() []string

func (ValidatedSpriteDefinition) Name

func (ValidatedSpriteDefinition) Palette

func (d ValidatedSpriteDefinition) Palette() map[byte]color.RGBA

Palette returns a copy of the sprite's colors by symbol.

func (ValidatedSpriteDefinition) Tagline

func (d ValidatedSpriteDefinition) Tagline() string

type ViewMouseResult

type ViewMouseResult struct {
	Handled, Capture, Focus bool
	// Render is the component's explicit render request, or nil for the
	// default of the event's type.
	Render *bool
}

ViewMouseResult is pi-tui's TuiMouseEventResult for an event the components of a view took: Handled is false when none did.

type ViewSurface

type ViewSurface interface {
	// Render returns the lines at width. It performs no I/O.
	Render(width int) []string
	// Invalidate drops cached lines, as a theme change requires.
	Invalidate()
	// HandleViewInput gives a key to the view's focused list when that list
	// binds it, and reports whether it did. A key it does not take goes to
	// the extension.
	HandleViewInput(data string) bool
	// FrontendView returns the structure of Render(width), or nil when the
	// surface has none (a Node view that did not reproduce its lines).
	FrontendView(width int) *frontend.View
}

ViewSurface is an extension surface whose lines the host draws from a view of Pi's tui components (D107): an authoritative view the host renders, or lines a Node runtime rendered together with the view that describes them. The terminal always draws Render; FrontendView only adds structure for a D91 frontend.

pig additive (D107): Pi passes components in-process.

type ViewTarget

type ViewTarget interface {
	UpdateViewAt(view ViewSurface, width int)
}

ViewTarget is implemented by a RemoteOverlayHandle that can draw a ViewSurface. The bridge calls UpdateViewAt for each accepted frame and for each change the surface makes on its own (a key its list took, a loader frame), with the terminal width the frame was laid out for (0 for any width).

type VirtualModelDefinition

type VirtualModelDefinition struct {
	// Provider is the provider the virtual model is listed under. May be a provider with physical models.
	Provider string
	// ID must not be the id of a physical model of Provider.
	ID   string
	Name string
	// ThinkingLevels are the thinking levels offered for selection. Defaults to `["off"]`.
	ThinkingLevels []ai.ModelThinkingLevel
	// ContextWindow and MaxTokens are the limits shown before the first response. Afterwards, the limits of the physical model that answered apply. Unset limits are unknown (0).
	ContextWindow int
	MaxTokens     int
	// Input are the input types accepted for selection. Defaults to text and images; routed models without image support get placeholders.
	Input []string
	Route ModelRouteFunc
}

VirtualModelDefinition is a selectable catalog entry that routes each request to a physical model.

upstream: virtual-models.ts:87-101 (VirtualModelDefinition)

type VirtualModelStateData

type VirtualModelStateData struct {
	Provider string          `json:"provider"`
	ModelID  string          `json:"modelId"`
	State    json.RawMessage `json:"state"`
}

VirtualModelStateData is the data of a `pi.virtual-model-state` custom entry. State is the router's JSON state.

upstream: virtual-models.ts:35-39 (VirtualModelStateData)

type WidgetFactory

type WidgetFactory func(host tui.TUI, theme *tui.Theme) DisposableComponent

WidgetFactory builds an extension's widget component (types.ts:189 setWidget's second overload: `(tui: TUI, theme: Theme) => Component & { dispose?(): void }`). Its Dispose runs when the widget is replaced, removed or cleared.

type WidgetPlacement

type WidgetPlacement string

WidgetPlacement is where an extension widget renders. Mirrors upstream WidgetPlacement (core/extensions/types.ts:122).

const (
	WidgetPlacementAboveEditor WidgetPlacement = "aboveEditor"
	WidgetPlacementBelowEditor WidgetPlacement = "belowEditor"
)

type WidthLines

type WidthLines struct {
	Lines []string
	Width int
}

WidthLines is a component frame rendered outside the host (by a subprocess extension) together with the terminal width it was rendered at, so the host never paints a frame rendered for another width. Width 0 means unknown.

func (WidthLines) Dispose

func (WidthLines) Dispose()

Dispose is a no-op: a frame holds nothing to release.

func (WidthLines) Invalidate

func (WidthLines) Invalidate()

Invalidate is a no-op: a frame is static until the extension sends another.

func (WidthLines) Render

func (w WidthLines) Render(int) []string

Render and Invalidate make a frame a component: it renders the lines the extension rendered, whatever the width it is asked for, because the extension process rendered them at Width.

type WireMembers

type WireMembers interface {
	WireMembers() (names []string, values []any)
}

WireMembers is a wire value that encodes as a JSON object. It names the members in the order the object writes them and holds each value, so the host can compare one such value with the one it sent before without encoding it again. Its MarshalJSON writes the same object.

type WorkingIndicatorOptions

type WorkingIndicatorOptions struct {
	// Frames are the animation frames; a pointer to an empty slice hides the indicator, nil keeps the default frames.
	Frames *[]string `json:"frames,omitempty"`
	// IntervalMs is the frame interval in milliseconds, nil for the default.
	IntervalMs *float64 `json:"intervalMs,omitempty"`
}

WorkingIndicatorOptions mirrors upstream WorkingIndicatorOptions.

type WorkingMessageClearer

type WorkingMessageClearer interface {
	ClearWorkingMessage()
}

WorkingMessageClearer is implemented by a UIContext that tells an absent working message from an empty one. Pi's setWorkingMessage(message?: string) shows `message ?? defaultWorkingMessage`: no argument restores the default label and an empty string is a message. ClearWorkingMessage is the no-argument form; the extension host calls it when an extension sends no message, and falls back to SetWorkingMessage("") for a UIContext that does not implement it. It is a separate interface so existing UIContext implementations keep compiling.

type WriteToolInput

type WriteToolInput struct {
	Path    string `json:"path"`
	Content string `json:"content"`
	// Extra holds members the schema does not declare; upstream's input is a plain object that keeps them.
	Extra map[string]json.RawMessage `json:"-"`
}

WriteToolInput is upstream's WriteToolInput (write.ts writeSchema).

func (WriteToolInput) MarshalJSON

func (in WriteToolInput) MarshalJSON() ([]byte, error)

func (*WriteToolInput) UnmarshalJSON

func (in *WriteToolInput) UnmarshalJSON(data []byte) error

type WriteToolResultEvent

type WriteToolResultEvent struct {
	ToolResultEventBase
	ToolName string `json:"toolName"` // "write"
	Details  any    `json:"details,omitempty"`
}

WriteToolResultEvent: upstream types.ts WriteToolResultEvent.

func (WriteToolResultEvent) MarshalJSON

func (e WriteToolResultEvent) MarshalJSON() ([]byte, error)

MarshalJSON writes the event in Pi's member order; see [marshalToolResultEvent].

Directories

Path Synopsis
Package builtin is the registry of upstream's built-in extensions that PiG implements natively: the `builtin:<name>` extension paths of codemode and tool-search (docs/specs/builtin-codemode-tool-search.md).
Package builtin is the registry of upstream's built-in extensions that PiG implements natively: the `builtin:<name>` extension paths of codemode and tool-search (docs/specs/builtin-codemode-tool-search.md).
codemode
Package codemode is the built-in `codemode` extension: the tool that lets the model write JavaScript that calls other tools.
Package codemode is the built-in `codemode` extension: the tool that lets the model write JavaScript that calls other tools.
toolsearch
Package toolsearch is the built-in `tool_search` extension: tool discovery with a BM25 ranker over tool metadata, shared by `searchTools()` in codemode scripts and the optional `tool_search` tool.
Package toolsearch is the built-in `tool_search` extension: tool discovery with a BM25 ranker over tool metadata, shared by `searchTools()` in codemode scripts and the optional `tool_search` tool.
Package extensiontest provides test doubles for the extension.API surface.
Package extensiontest provides test doubles for the extension.API surface.
Package factoryload runs the compiled-in extension factories of a binary: Go code that the source of the binary's own main package passes to it by value (docs/specs/extension-factory-trust.md).
Package factoryload runs the compiled-in extension factories of a binary: Go code that the source of the binary's own main package passes to it by value (docs/specs/extension-factory-trust.md).
host
cellpack
Package cellpack is the Piglet-Binary-side counterpart to the host's prebuilt-cell seam (runtimecell.PrebuiltResolver).
Package cellpack is the Piglet-Binary-side counterpart to the host's prebuilt-cell seam (runtimecell.PrebuiltResolver).
fusepack
Package fusepack holds Go extensions fused into a Piglet Binary.
Package fusepack holds Go extensions fused into a Piglet Binary.
inproc
Package inproc implements the in-process Go dispatch runner for extensions.
Package inproc implements the in-process Go dispatch runner for extensions.
runtimecell
Package runtimecell builds and resolves packed extension runtime cells.
Package runtimecell builds and resolves packed extension runtime cells.
subprocess
Package subprocess implements pig's out-of-process extension transport: extensions communicate over a local stream socket with length-prefixed JSON framing.
Package subprocess implements pig's out-of-process extension transport: extensions communicate over a local stream socket with length-prefixed JSON framing.
subprocess/internal/noderuntimegen command
Command noderuntimegen packages the Node runtime and its content identity reproducibly.
Command noderuntimegen packages the Node runtime and its content identity reproducibly.
subprocess/internal/noderuntimepack
Package noderuntimepack stores the embedded Node runtime as a few solid zstd blocks.
Package noderuntimepack stores the embedded Node runtime as a few solid zstd blocks.
subprocess/internal/noderuntimepeers
Package noderuntimepeers generates the host peer packages of the Node runtime archive: package.json and entry modules under runtime-node/harness/node_modules.
Package noderuntimepeers generates the host peer packages of the Node runtime archive: package.json and entry modules under runtime-node/harness/node_modules.
tsruntime
Package tsruntime selects the runtime that runs PiG's TypeScript and JavaScript extension host.
Package tsruntime selects the runtime that runs PiG's TypeScript and JavaScript extension host.
Package installresolver is Pig's product-neutral seam for contributed package-source behavior.
Package installresolver is Pig's product-neutral seam for contributed package-source behavior.
Package markdowntransform holds the display-only Markdown transformer contract and its chain.
Package markdowntransform holds the display-only Markdown transformer contract and its chain.
Package pigsdk stages Pig's extension SDKs (Go, Python, and Rust) into the config root so out-of-tree extension builds and packed runtime cells can use the API that matches the running binary.
Package pigsdk stages Pig's extension SDKs (Go, Python, and Rust) into the config root so out-of-tree extension builds and packed runtime cells can use the API that matches the running binary.
Package source resolves an authorized extension path into one conventional factory or exact isolated standalone definition.
Package source resolves an authorized extension path into one conventional factory or exact isolated standalone definition.

Jump to

Keyboard shortcuts

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