subprocess

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: MIT Imports: 52 Imported by: 0

Documentation

Overview

Package subprocess implements pig's out-of-process extension transport: extensions communicate over a local stream socket with length-prefixed JSON framing. The socket is AF_UNIX, except that a Node extension on Windows gets a named pipe, because Node's net module cannot reach AF_UNIX there. The extension finds its address in PIG_EXT_SOCKET; framing and handshake are the same on both.

Architecture

The subprocess host spawns extension binaries, connects via those sockets, translates subprocess registrations into extension.Extension structs, and feeds them to the existing [inproc.Runner]. This is additive: it sits ABOVE the in-process runner, not beside it. The inproc runner remains the dispatch engine; the subprocess layer is a transport adapter.

┌─────────────────────────────────────────────────────────┐
│             inproc.Runner (dispatch engine)              │
│   Consumes []extension.Extension: doesn't care how     │
│   they were created (compiled-in vs subprocess)          │
└─────────────────────┬───────────────────────────────────┘
                      │ feeds []extension.Extension
┌─────────────────────┴───────────────────────────────────┐
│             subprocess.Host (this package)               │
│   Spawns binaries, manages sockets, translates          │
│   register messages → extension.Extension structs       │
└─────────────────────────────────────────────────────────┘

Wire Protocol

Messages are length-prefixed JSON: 4 bytes big-endian uint32 length followed by that many bytes of UTF-8 JSON. Message types:

  • register (ext→host): declares tools, commands, shortcuts, event handlers
  • ready (host→ext): acknowledges registration, sends context (cwd, theme)
  • notify (bidirectional): fire-and-forget (no response expected)
  • request (host→ext): expects a response (tool_call, event dispatch)
  • response (ext→host): reply to a request
  • call (ext→host): extension calls host method (ui.notify, sendMessage, etc.)
  • call_result (host→ext): reply to a call
  • shutdown (host→ext): graceful shutdown signal

pig-specific: no upstream equivalent

This entire package is pig-specific. Upstream pi uses TypeScript extensions loaded via jiti in-process. The subprocess protocol exists to support compiled extensions in Go, Rust, or any language that can speak Unix socket + JSON.

Index

Constants

View Source
const (
	// Extension → host.
	NotifyEditorInstall   = "ui.editor.install"
	NotifyEditorClear     = "ui.editor.clear"
	NotifyEditorRender    = "ui.editor.render"
	NotifyEditorChange    = "ui.editor.change"
	NotifyEditorSubmit    = "ui.editor.submit"
	NotifyEditorAction    = "ui.editor.action"
	NotifyEditorInputDone = "ui.editor.inputDone"
	NotifyEditorShortcut  = "ui.editor.shortcut"
	NotifyTerminalWrite   = "ui.terminal.write"
	NotifyHardwareCursor  = "ui.setShowHardwareCursor"

	// Host → extension.
	NotifyEditorInput        = "ui.editor.input"
	NotifyEditorMouse        = "ui.editor.mouse"
	NotifyEditorSetText      = "ui.editor.setText"
	NotifyEditorInsertText   = "ui.editor.insertText"
	NotifyEditorAddToHistory = "ui.editor.addToHistory"
	NotifyEditorConfigure    = "ui.editor.configure"
	NotifyEditorSubmitted    = "ui.editor.submitted"
	NotifyEditorClosed       = "ui.editor.closed"
)

Wire of an extension editor component (ctx.ui.setEditorComponent): Pi's factory runs in the extension process and the editor it returns stays there. Every message is a notify, so the connection's frame order is the order the host and the editor see each other's events. Autocomplete uses the shared provider bridge.

View Source
const (
	// Extension → Host
	MsgRegister     = "register"      // Initial handshake: declare capabilities
	MsgResponse     = "response"      // Reply to a host request
	MsgCall         = "call"          // Extension calls a host method (ui.notify, sendMessage, etc.)
	MsgWidgetPush   = "widget_push"   // Push rendered widget lines to host cache
	MsgPong         = "pong"          // Dispatcher heartbeat reply
	MsgRequestState = "request_state" // Request lifecycle/activity update

	// Host → Extension
	MsgReady      = "ready"       // Acknowledge registration, send context
	MsgRequest    = "request"     // Tool call or event dispatch (expects response)
	MsgNotify     = "notify"      // Fire-and-forget notification (no response)
	MsgCancel     = "cancel"      // Cancel an in-flight request by ID
	MsgCallResult = "call_result" // Reply to an extension call
	MsgShutdown   = "shutdown"    // Graceful shutdown signal
	MsgPing       = "ping"        // Dispatcher heartbeat request
)

Message types for the wire protocol.

View Source
const (
	MethodOAuthLogin             = "oauth_login"              // Args: none.                Result: OAuthCredentialsWire.
	MethodOAuthRefresh           = "oauth_refresh"            // Args: OAuthCredentialsWire. Result: OAuthCredentialsWire.
	MethodOAuthGetAPIKey         = "oauth_get_api_key"        // Args: OAuthCredentialsWire. Result: OAuthAPIKeyResult.
	MethodOAuthCredentialStatus  = "oauth_credential_status"  // Args: none.                Result: OAuthCredentialStatusResult.
	MethodOAuthStoreCredentials  = "oauth_store_credentials"  // Args: OAuthCredentialsWire. Result: OAuthStoreResult.
	MethodOAuthDeleteCredentials = "oauth_delete_credentials" // Args: none.                Result: OAuthDeleteResult.
)

OAuth bridge request methods (host→ext), carried in RequestPayload.Method.

View Source
const (
	CallOAuthOnAuth            = "oauth.cb.onAuth"            // Args: OAuthAuthInfoWire.       No result.
	CallOAuthOnDeviceCode      = "oauth.cb.onDeviceCode"      // Args: OAuthDeviceCodeInfoWire. No result.
	CallOAuthOnProgress        = "oauth.cb.onProgress"        // Args: OAuthProgressWire.       No result.
	CallOAuthOnPrompt          = "oauth.cb.onPrompt"          // Args: OAuthPromptWire.         Result: OAuthInputResult.
	CallOAuthOnSelect          = "oauth.cb.onSelect"          // Args: OAuthSelectPromptWire.   Result: OAuthInputResult.
	CallOAuthOnManualCodeInput = "oauth.cb.onManualCodeInput" // Args: none.                    Result: OAuthInputResult.
)

OAuth login-callback methods (ext→host), carried in CallPayload.Method. Issued by the extension while its login flow is in flight to drive the host UI.

View Source
const (
	CallUICustom = "ui.custom"
	// pig additive (D60): typed native login crosses the subprocess boundary.
	CallUISetLogin       = "ui.setLogin"
	NotifyUICustomInput  = "ui.custom.input"
	NotifyUICustomRender = "ui.custom.render"
	NotifyUICustomClose  = "ui.custom.close"
	NotifyUICustomOpened = "ui.custom.opened"
	CallUICustomControl  = "ui.custom.control"
)

Focused custom UI uses three current-wire message classes. Input is an ordered, non-idempotent event; render is a replaceable snapshot; open and close/error are exactly-once barriers that delimit one key generation.

View Source
const CallProviderCallback = "provider.callback"
View Source
const CallProviderObject = "provider.object"
View Source
const CallProviderPublish = "provider.publish"
View Source
const CallRegisterTool = "registerTool"

CallRegisterTool carries one ToolDecl after the initial registration. The host validates and replaces the definition, refreshes the Session registry, and replies with allTools and activeTools before the SDK returns.

View Source
const MaxFrameSize = 128 * 1024 * 1024

MaxFrameSize bounds a single length-prefixed wire frame. The 4-byte length prefix is a uint32, so the hard ceiling is ~4 GB; this cap guards against unbounded allocation from a corrupt/oversized length while still allowing the large payloads legitimate extensions request: notably getBranch on a long session, whose full branch history can run to tens of MB (an earlier 16 MB cap silently disabled context-info on big sessions). Upstream pi's Node IPC has no comparable hard cap. Must stay in sync with the Go/Rust/Python SDK MaxFrameSize constants.

View Source
const MethodModelStreamCallback = "model_stream_callback"
View Source
const MethodProviderCall = "provider_call"
View Source
const MethodProviderObjectCallback = "provider_object_callback"
View Source
const MethodProviderStream = "provider_stream"
View Source
const MethodProviderSync = "provider_sync"
View Source
const NotifyLoadFailed = "load_failed"

NotifyLoadFailed (ext→host) takes the place of the register handshake when an extension's module or factory throws: the Node runtime reports its loader's error, as Pi's loader words it, and closes. Args is a FactoryLoadError.

View Source
const NotifyProviderStreamEvent = "provider_stream_event"

NotifyProviderStreamEvent carries ordered assistant events before the final request response.

View Source
const NotifyToolRenderInvalidate = "tool_render_invalidate"

NotifyToolRenderInvalidate (ext→host) is a renderer's context.invalidate(): the host runs the card's renderers again and repaints. Args is a ToolRenderCardPayload.

View Source
const NotifyToolRenderRelease = "tool_render_release"

NotifyToolRenderRelease (host→ext) reports that a tool card no longer exists, so the extension drops the card's renderer state and components. Args is a ToolRenderCardPayload.

View Source
const NotifyToolUpdate = "tool_update"

NotifyToolUpdate (ext→host) carries a tool's partial result while its tool_call request runs, as upstream's onUpdate(partialResult) does. The host delivers it to the running tool in frame order, before the final response.

View Source
const RequestCommandArgumentCompletions = "command_argument_completions"

RequestCommandArgumentCompletions (host→ext) runs a command's getArgumentCompletions for the editor's autocomplete. Tool names the command and Args is the argument prefix as a JSON string; the response is the items as a JSON array, or null for none.

View Source
const RequestMarkdownTransform = "markdown_transform"

RequestMarkdownTransform runs an extension's registered display rewrite. A null answer keeps the input, as Pi does for a throwing or non-string transformer.

View Source
const RequestProviderStream = "provider_stream_simple"

RequestProviderStream invokes a legacy streamSimple callback. Native Provider objects retain their provider_stream method/params carrier.

View Source
const RequestRenderTool = "render_tool"

RequestRenderTool (host→ext) runs a tool's renderCall or renderResult for one tool card and renders the component it returns, as upstream ToolExecutionComponent.updateDisplay and render do. Args is a RenderToolPayload; the response is a RenderResult, and an error response means the renderer threw, so the card draws upstream's fallback.

Variables

This section is empty.

Functions

func CurrentCacheEntries

func CurrentCacheEntries(configs []ExtConfig, cacheRoot string) (map[string]struct{}, []error)

CurrentCacheEntries resolves the cache entries selected by the same source hashes and cell planner used during startup. It performs no build and returns only complete entries that already exist.

func CurrentNodePackedCellEntry

func CurrentNodePackedCellEntry(cacheRoot, cellKey string, exts []nodeExtension) (string, bool, error)

CurrentNodePackedCellEntry reports the cache entry the given members would resolve to, without building anything. It mirrors runtimecell.CurrentGoPackedCellEntry for the Node cell's GC accounting.

func FormatCrashNotice

func FormatCrashNotice(name string, delay time.Duration, disabled bool, reason string) string

FormatCrashNotice renders the operator-facing text for an extension crash event. Both crash surfaces (the stderr handler in non-interactive mode and the TUI transcript notice) use it so their wording cannot drift.

func ListenExtension

func ListenExtension(sockPath string, _ bool) (net.Listener, string, error)

ListenExtension listens for one extension process on the AF_UNIX socket at sockPath and returns the address the process finds in PIG_EXT_SOCKET. The second argument, whether the process runs under Node, matters only on Windows.

func SetFusedResolver

func SetFusedResolver(r FusedResolver)

SetFusedResolver installs the process-wide fused-extension resolver. Called once at startup by a Piglet Binary's generated registration; nil (the default) disables fusion. Not safe for concurrent use with LoadAll.

func StagedSDKFingerprint

func StagedSDKFingerprint(sdkDir, buildType string) (string, error)

StagedSDKFingerprint hashes the source files that define one staged SDK.

func WithTerminalInputState

func WithTerminalInputState(ctx context.Context, editorText string, toolsExpanded bool) context.Context

WithTerminalInputState captures the UI values on the owner loop before a remote input listener runs. The request worker serializes this snapshot without reading mutable editor state or traversing Session history.

Types

type BeforeAgentStartResponsePayload

type BeforeAgentStartResponsePayload struct {
	Sections      ai.OrderedSections `json:"_pigPromptSections"`
	SelectedTools json.RawMessage    `json:"_pigPromptSelectedTools"`
	Result        json.RawMessage    `json:"_pigPromptResult"`
}

BeforeAgentStartResponsePayload carries per-run mutations even when a handler fails. SelectedTools retains the untyped value until the handler chain ends: non-string entries cannot name registered tools, and null rejects prompt admission. Result carries the handler's ordinary message/systemPrompt result.

type BoundaryEventResultPayload

type BoundaryEventResultPayload struct {
	Entries  *json.RawMessage `json:"entries,omitempty"`
	Continue *bool            `json:"continue,omitempty"`
}

BoundaryEventResultPayload is the current-wire result for turn_end and agent_before_settle. Entries is the complete replacement proposal; pointers preserve an omitted field from an explicit empty list or false continuation.

type BuildResult

type BuildResult struct {
	BinaryPath string // path to the built (or cached) binary
	Cached     bool   // true if cache hit: no rebuild needed
	Hash       string // source content hash used for the cache key
	Language   string // detected build type (go | rust | node)
}

BuildResult holds the outcome of an auto-build.

type Builder

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

Builder handles automatic compilation and caching of source-based extensions. It detects the build system (Go or Rust) from the source directory and uses content-hash caching so unchanged sources produce instant startup.

Cache layout: ~/.pig/cache/ext/<name>-<hash>[.exe]

func NewBuilder

func NewBuilder(cacheDir string) *Builder

NewBuilder creates a builder with the given cache directory. Typically <config-root>/cache/ext/.

func NewBuilderWithConfigRoot

func NewBuilderWithConfigRoot(cacheDir, configRoot string) *Builder

NewBuilderWithConfigRoot creates a builder pinned to the same writable config root as the running Pig process. Product assembly should prefer this form so an overridden HOME/XDG root cannot diverge from extension builds.

func (*Builder) Build

func (b *Builder) Build(name, srcDir string) (*BuildResult, error)

Build compiles the extension source at srcDir if needed. Returns the path to the binary (cached or freshly built).

Detection:

  • go.mod present → Go extension (go build)
  • Cargo.toml present → Rust extension (cargo build --release)
  • package.json / *.ts / *.js → Node/TypeScript extension (launcher script)

The binary is cached at <cacheDir>/<name>-<hash>. If the hash matches an existing cached binary, no build occurs (instant startup).

func (*Builder) BuildContext

func (b *Builder) BuildContext(ctx context.Context, name, srcDir string) (*BuildResult, error)

BuildContext builds an extension and cancels compiler subprocesses when ctx ends. Independent sources may build concurrently; PublishArtifact deduplicates each content identity and publishes it atomically. Build retains the background-context entry point.

func (*Builder) CurrentCacheEntry

func (b *Builder) CurrentCacheEntry(name, srcDir string) (string, bool, error)

CurrentCacheEntry returns the valid source-build cache entry selected by the same source and staged-SDK hash as BuildContext, without building it.

func (*Builder) SetStagedSDKVerifier

func (b *Builder) SetStagedSDKVerifier(fn func(stagedDir, buildType string) error)

SetStagedSDKVerifier installs the staged-SDK freshness check. Without one the builder only requires the directory to exist.

type CallPayload

type CallPayload struct {
	Method          string          `json:"method"` // e.g. "ui.notify", "ui.setStatus", "sendMessage"
	Args            json.RawMessage `json:"args,omitempty"`
	ParentRequestID string          `json:"parent_request_id,omitempty"`
}

CallPayload is an extension calling a host method.

type CallResultPayload

type CallResultPayload struct {
	Result json.RawMessage `json:"result,omitempty"`
	Error  *ErrorInfo      `json:"error,omitempty"`
}

CallResultPayload is the host's reply to an extension call.

type CancelPayload

type CancelPayload struct {
	RequestID string `json:"request_id,omitempty"`
	Reason    string `json:"reason,omitempty"`
}

CancelPayload asks the extension SDK to cancel an in-flight request.

type CellSpec

type CellSpec struct {
	Key        string
	Hash       string
	Strategy   CellStrategy
	Runtime    string
	Language   string
	SDK        string
	Isolation  string
	Order      int
	Extensions []ExtConfig
	// Group names the plan group whose factories share one runtime process; a Node cell re-invokes its factories in the process that already ran the group.
	Group string
}

CellSpec is the runtime planner output consumed by reload/startup code. It is intentionally host-level rather than command-level so validation, reload, and future install flows can share one grouping contract.

func PlanCells

func PlanCells(configs []ExtConfig, quarantined map[string]string) []CellSpec

PlanCells groups compatible factories. Native packed factories form contiguous runs because their runners execute all factories together. Node members share one process across intervening native cells; host admission runs each Node factory in configured order. pig additive (D20): process sharing preserves one registration per extension.

func (CellSpec) GoExtensions

func (c CellSpec) GoExtensions() ([]runtimecell.GoExtension, error)

func (CellSpec) NodeExtensions

func (c CellSpec) NodeExtensions() ([]nodeExtension, error)

NodeExtensions resolves each member's entrypoint the same way an isolated Node extension does (resolveNodeEntrypoint), preserving the cell's plan order.

func (CellSpec) PythonExtensions

func (c CellSpec) PythonExtensions() ([]runtimecell.PythonExtension, error)

func (CellSpec) RustExtensions

func (c CellSpec) RustExtensions() ([]runtimecell.RustExtension, error)

type CellStrategy

type CellStrategy string

CellStrategy describes how a group of extension configs should be started.

const (
	CellStrategyIsolated     CellStrategy = "isolated"
	CellStrategyPackedGo     CellStrategy = "packed-go"
	CellStrategyPackedRust   CellStrategy = "packed-rust"
	CellStrategyPackedPython CellStrategy = "packed-python"
	// CellStrategyPackedNode hosts every packable TS/JS extension in one Node
	// process, the way upstream pi loads all its extensions in one process
	// (N8). Unlike the other packed strategies this needs no compiled runner:
	// the jiti loader reads each member's source fresh at start.
	CellStrategyPackedNode CellStrategy = "packed-node"
)

type CommandDecl

type CommandDecl struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Args        string `json:"args,omitempty"` // Argument hint shown in /help
	// ArgumentCompletions reports that the command defines upstream
	// getArgumentCompletions. The host asks for them with
	// RequestCommandArgumentCompletions.
	ArgumentCompletions bool `json:"argument_completions,omitempty"`
}

CommandDecl declares a slash command the extension provides.

type CommandInfo

type CommandInfo struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	// Source is "extension", "prompt" or "skill".
	Source     string               `json:"source"`
	SourceInfo extension.SourceInfo `json:"sourceInfo"`
}

CommandInfo is one entry of getCommands on the wire. Mirrors upstream SlashCommandInfo (slash-commands.ts): an extension command, prompt template or skill, with its source kind and sourceInfo.

type Conn

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

Conn manages one extension socket with reader, writer, and heartbeat goroutines. Only the reader reads the socket, and only the writer writes it. pig-specific: no upstream equivalent.

func NewConn

func NewConn(name string, c net.Conn) *Conn

NewConn wraps a connected socket into a managed connection. Call Conn.Start to begin read/write goroutines.

func (*Conn) Close

func (c *Conn) Close(reason string) error

Close gracefully shuts down the connection. Sends a shutdown message if possible, then closes the socket.

func (*Conn) Done

func (c *Conn) Done() <-chan struct{}

Done returns a channel that closes when all connection goroutines have exited.

func (*Conn) Incoming

func (c *Conn) Incoming() <-chan *Envelope

Incoming returns the channel of non-response messages from the extension. The host reads from this to handle calls, widget pushes, etc.

func (*Conn) Name

func (c *Conn) Name() string

Name returns the extension name this connection serves.

func (*Conn) RecentOversizedFrame

func (c *Conn) RecentOversizedFrame() (uint64, bool)

RecentOversizedFrame reports the size of the most recent frame the host wrote to this extension above the legacy frame cap, if it was written within frameSkewWindow. The host uses it to explain a disconnect that a binary built against an older SDK (receive cap below the host's) causes.

func (*Conn) Request

func (c *Conn) Request(ctx context.Context, env *Envelope) (*Envelope, error)

Request sends a message and waits for the correlated response. Blocks until the response arrives or the context expires.

func (*Conn) Retire

func (c *Conn) Retire(reason string) error

Retire asks the peer to end its side and waits for it to close after tearing down, then closes. A retiring peer that shares its process with a live successor generation must finish its teardown, such as leaving the shared event bus, before the successor is visible as the only generation. The peer closing ends the read loop. The wait is outstanding work, so the heartbeat fails a peer that stops answering, and a peer that answers keeps its teardown running, as Pi awaits session_shutdown handlers without a deadline (agent-session.ts:3291-3314).

func (*Conn) Send

func (c *Conn) Send(env *Envelope) error

Send queues a message without waiting for the socket write. A full queue waits for the writer rather than dropping the frame: a lost call result or notification would leave the extension waiting forever. The wait ends when the peer drains the queue or the connection fails, which the heartbeat guarantees for a peer that stops reading.

func (*Conn) Start

func (c *Conn) Start(ctx context.Context)

Start launches the reader and writer goroutines. The provided context controls their lifetime. Cancellation stops all three goroutines.

type DirectEntryAppend

type DirectEntryAppend struct {
	ID        string `json:"id"`
	Timestamp string `json:"timestamp"`
}

DirectEntryAppend is a custom entry ctx.sessionManager.appendCustomEntry appended in the extension process: upstream's SessionManager returns the entry's id synchronously, so the extension generates the id and timestamp and the host writes the entry with them.

type EditorPayload

type EditorPayload struct {
	Key             string   `json:"key"`
	Data            string   `json:"data,omitempty"`
	Text            string   `json:"text,omitempty"`
	Expanded        string   `json:"expanded,omitempty"`
	Lines           []string `json:"lines,omitempty"`
	Width           int      `json:"width,omitempty"`
	Seq             uint64   `json:"seq,omitempty"`
	WantsKeyRelease bool     `json:"wantsKeyRelease,omitempty"`
	ID              uint64   `json:"id,omitempty"`
	Action          string   `json:"action,omitempty"`
	Local           bool     `json:"local,omitempty"`
	Enabled         bool     `json:"enabled,omitempty"`
}

EditorPayload is the argument of the editor notifies; each carries the fields its method uses.

type EmbeddedCell

type EmbeddedCell struct {
	Language   string
	Key        string
	Strategy   string
	BinaryPath string
	Extensions []EmbeddedExtension
}

EmbeddedCell is a source-free packed cell extracted from a Piglet Binary binary. It is intentionally independent of the coding/extension/host/cellpack package so the generic subprocess host does not depend on Piglet Binary build orchestration.

type EmbeddedExtension

type EmbeddedExtension struct {
	Name string
	Hash string
}

type EntryRendererDecl

type EntryRendererDecl struct {
	CustomType string `json:"custom_type"`
}

EntryRendererDecl declares a custom session-entry renderer.

type Envelope

type Envelope struct {
	Type string `json:"type"`

	// Common fields
	ID string `json:"id,omitempty"` // Correlation ID for request/response pairs

	// Register (ext→host)
	Register *RegisterPayload `json:"register,omitempty"`

	// Ready (host→ext)
	Ready *ReadyPayload `json:"ready,omitempty"`

	// Request (host→ext)
	Request *RequestPayload `json:"request,omitempty"`

	// Response (ext→host)
	Response *ResponsePayload `json:"response,omitempty"`

	// Notify (bidirectional)
	Notify *NotifyPayload `json:"notify,omitempty"`

	// Call (ext→host)
	Call *CallPayload `json:"call,omitempty"`

	// CallResult (host→ext)
	CallResult *CallResultPayload `json:"call_result,omitempty"`

	// WidgetPush (ext→host)
	WidgetPush *WidgetPushPayload `json:"widget_push,omitempty"`

	// Cancel (host→ext)
	Cancel *CancelPayload `json:"cancel,omitempty"`

	// Shutdown (host→ext)
	Shutdown *ShutdownPayload `json:"shutdown,omitempty"`

	// Heartbeat and request lifecycle.
	Ping         *PingPayload         `json:"ping,omitempty"`
	Pong         *PongPayload         `json:"pong,omitempty"`
	RequestState *RequestStatePayload `json:"request_state,omitempty"`
}

Envelope is the top-level wire message. Every message on the socket is an Envelope serialized as length-prefixed JSON. The Type field determines which payload fields are populated. pig additive (D19): Pig's language SDKs use this one current subprocess wire because upstream Pi loads only in-process TypeScript extensions.

type ErrorInfo

type ErrorInfo struct {
	Code    string `json:"code,omitempty"`
	Message string `json:"message"`
	// Stack is the thrown error's own stack when the extension runtime has
	// one (a JavaScript `err.stack`). Hosts report it as upstream reports
	// `ExtensionError.stack`.
	Stack string `json:"stack,omitempty"`
}

ErrorInfo carries structured error information.

func (*ErrorInfo) ToError

func (e *ErrorInfo) ToError() error

type ExtConfig

type ExtConfig struct {

	// Name is the extension's identifier (must match the name in register).
	Name string

	// Path is the path to the extension binary. Resolved relative to
	// the extension directory (~/.pig/extensions/) if not absolute.
	// Mutually exclusive with Source.
	Path string

	// Source is the path to the extension source directory (Go module or
	// Rust crate). When set, the host auto-builds before spawning and
	// caches the binary by content hash. Mutually exclusive with Path.
	Source string

	// SourceInfo is the Pi-compatible provenance stamped onto this loaded
	// extension and every command it registers.
	SourceInfo extension.SourceInfo

	// Enabled controls whether the extension is loaded. Default: true.
	Enabled bool

	// SupervisorConfig overrides crash recovery settings. Zero value uses defaults.
	SupervisorConfig SupervisorConfig

	// Runtime metadata is derived from the conventional source form. These
	// fields drive runtime-cell planning and are not authored configuration.
	RuntimeKind        string
	RuntimeLanguage    string
	SDKName            string
	Isolation          string
	EntrypointKind     string
	ModulePath         string
	Package            string
	Factory            string
	ContentHash        string
	GoWorkspaceModules []string
	// contains filtered or unexported fields
}

ExtConfig describes a subprocess extension to load.

func ResolveExtConfig

func ResolveExtConfig(path string) (ExtConfig, *extsource.Definition, error)

ResolveExtConfig resolves one authorized path into one conventional factory or exact isolated standalone runtime configuration.

func ResolveExtConfigWithIdentity

func ResolveExtConfigWithIdentity(path, expectedName string) (ExtConfig, *extsource.Definition, error)

ResolveExtConfigWithIdentity binds runtime registration to an identity owned by the selecting Package or Piglet. Empty expectedName derives from the exact selected path.

func ResolveExtConfigWithResolver

func ResolveExtConfigWithResolver(path, expectedName string, resolve extsource.ResolveFunc) (ExtConfig, *extsource.Definition, error)

ResolveExtConfigWithResolver maps the Definition returned by resolve into a runtime configuration. Startup passes its bounded resolver snapshot so Package validation, trust loading, and final loading consume one scan.

func UnresolvedExtConfig

func UnresolvedExtConfig(path string, err error) ExtConfig

UnresolvedExtConfig returns a config for an extension path whose source did not resolve. It stays enabled, so every consumer that selects enabled extensions sees the attempt, but the host never plans or starts it: LoadAll returns err as an ExtensionLoadError and Reload records it in ReloadReport.Issues, as upstream loadExtensions records a failed extension beside the ones it loaded.

func (ExtConfig) ResolveError

func (c ExtConfig) ResolveError() error

ResolveError returns the source resolution failure of an UnresolvedExtConfig, or nil.

func (ExtConfig) SelectedAs

func (c ExtConfig) SelectedAs(path string) ExtConfig

SelectedAs returns c reporting path as its configured extension path in load errors and reload issues. Discovery uses it when an entry file such as <dir>/index.js selects its directory, since upstream names the entry file.

type ExtensionLoadError

type ExtensionLoadError struct {
	Name string
	Path string
	Err  error
	// contains filtered or unexported fields
}

ExtensionLoadError is one extension that failed to load. Path is the configured extension path.

func (*ExtensionLoadError) Error

func (e *ExtensionLoadError) Error() string

func (*ExtensionLoadError) Unwrap

func (e *ExtensionLoadError) Unwrap() error

type ExtensionUnresponsiveError

type ExtensionUnresponsiveError struct {
	Extension string
	RequestID string
	Operation string
}

ExtensionUnresponsiveError reports a missed dispatcher heartbeat.

func (*ExtensionUnresponsiveError) Error

type FacetBridge

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

FacetBridge owns a selected Node facet driver through the ordinary extension Host. It never restarts a loaded generation after a process failure or retargets its captured connection to a replacement.

func OpenFacetBridge

func OpenFacetBridge(ctx context.Context, options FacetBridgeOptions) (_ *FacetBridge, err error)

OpenFacetBridge loads a private host-derived factory through the existing Node launcher, socket, registration, heartbeat and cancellation machinery. The context controls startup; the returned loaded-generation connection remains alive until Close so cancelled callers cannot preempt facet teardown. Individual calls retain their own contexts. Closing the bridge joins that same Host before removing its materialized launcher.

func (*FacetBridge) Call

func (bridge *FacetBridge) Call(ctx context.Context, args json.RawMessage) (json.RawMessage, error)

Call awaits an operation owned by the selected facet driver. Args is a private driver payload inside the existing request envelope; absent and null results remain distinguishable to its codec.

func (*FacetBridge) CallSync

func (bridge *FacetBridge) CallSync(ctx context.Context, args json.RawMessage) (json.RawMessage, error)

CallSync invokes only a synchronous driver callback through the existing restricted Node pump. Nested synchronous host calls use this callback's own pending request identity instead of the ambient blocked caller's lane. Callers run off the TUI input/render loop. The driver must not await a Promise in this dispatcher.

func (*FacetBridge) Close

func (bridge *FacetBridge) Close() error

Close joins the existing extension shutdown before releasing private files. Concurrent callers observe the same cleanup result.

type FacetBridgeOptions

type FacetBridgeOptions struct {
	Directory          string
	TemporaryDirectory string
	Module             string
	Call               func(context.Context, string, json.RawMessage) (json.RawMessage, error)
}

FacetBridgeOptions selects a private facet driver for one isolated Node extension connection. Module is a host-materialized module, not an authored extension manifest. Call receives the existing connection-parented call context, including its initiation marker; asynchronous delegates mark initiation only after their synchronous prefix has applied.

type FactoryLoadError

type FactoryLoadError struct {
	Message string `json:"error"`
	Stack   string `json:"stack,omitempty"`
}

FactoryLoadError is an extension's own report that it failed to load. Message is Pi's loader error ("Failed to load extension: <message>", or the missing-factory message); Stack is the thrown error's stack.

func (*FactoryLoadError) Error

func (e *FactoryLoadError) Error() string

func (*FactoryLoadError) ErrorStack

func (e *FactoryLoadError) ErrorStack() string

type FlagDecl

type FlagDecl struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	Type        string          `json:"type"` // "boolean" | "string"
	Default     json.RawMessage `json:"default,omitempty"`
}

FlagDecl declares a CLI flag the extension consumes.

type FooterDataPayload

type FooterDataPayload struct {
	GitBranch              string            `json:"gitBranch,omitempty"`
	ExtensionStatuses      map[string]string `json:"extensionStatuses,omitempty"`
	AvailableProviderCount int               `json:"availableProviderCount"`
}

FooterDataPayload carries the data behind upstream's ReadonlyFooterDataProvider (footer-data-provider.ts:387), the third argument handed to a ui.setFooter factory.

type FrameTooLargeError

type FrameTooLargeError struct {
	Size int
	Max  int
}

FrameTooLargeError reports that a marshaled envelope exceeds MaxFrameSize and was therefore not sent. Every SDK reader rejects a frame above MaxFrameSize, so writing one would silently kill even a current-SDK extension; callers that can degrade gracefully (e.g. a call result) should send a small error frame instead.

func (*FrameTooLargeError) Error

func (e *FrameTooLargeError) Error() string

type FusedResolver

type FusedResolver interface {
	// FusedServe returns the in-process serve func for cfg if this Piglet Binary
	// compiled that extension in, and false otherwise.
	FusedServe(cfg ExtConfig) (serve func(net.Conn) error, ok bool)
}

FusedResolver maps an extension config to an in-process serve func compiled into the binary. A forged Piglet Binary (fused Piglet Binary) installs one whose serve funcs are each fused extension's factory().RunWithConn; the resolver is nil in stock pig, so LoadAll routes every extension through the subprocess cell path unchanged (D31).

type HandlerDecl

type HandlerDecl struct {
	Event     string `json:"event"`      // e.g. "tool_call", "session_start"
	CanBlock  bool   `json:"can_block"`  // Whether the handler can block/mutate
	HandlerID int    `json:"handler_id"` // Positive registration identity.
}

HandlerDecl declares which events the extension wants to receive.

type HandlerStalledError

type HandlerStalledError struct {
	Extension        string
	Operation        string
	HeartbeatHealthy bool
}

HandlerStalledError reports a request-inactivity lease expiration.

func (*HandlerStalledError) Error

func (e *HandlerStalledError) Error() string

type Host

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

Host manages all subprocess extensions. It spawns binaries, manages connections, handles the register handshake, and produces extension.Extension structs suitable for feeding to [inproc.Runner].

pig-specific: no upstream equivalent.

func NewHost

func NewHost(cwd string) *Host

NewHost creates an extension host using the process environment's Pig config root. Product assembly should prefer NewHostWithConfigRoot.

func NewHostWithConfigRoot

func NewHostWithConfigRoot(cwd, configRoot string) *Host

NewHostWithConfigRoot creates an extension host pinned to configRoot. The socketDir is where Unix sockets are created (for example $XDG_RUNTIME_DIR/pig/ or $TMPDIR/pig-<uid>/).

func (*Host) BroadcastStateUpdate

func (h *Host) BroadcastStateUpdate()

BroadcastStateUpdate sends a "state_update" notify to every connected subprocess extension with a freshly-snapshotted StatePayload. Call this after host-side transitions that mutate the synchronous getter surface (active tools, thinking level, idle state, system prompt, context usage, flag values, etc.) so extension caches stay accurate.

Safe to call when no extensions are loaded or no UIBridge is wired - in that case it is a no-op.

func (*Host) Builder

func (h *Host) Builder() *Builder

Builder exposes the extension builder so the owner can install policy that core cannot reach, such as the staged-SDK freshness check whose reference data lives outside core.

func (*Host) EndInput

func (h *Host) EndInput()

EndInput tells hosted runtimes that no further terminal or RPC input can arrive. This does not cancel requests or synthesize responses.

func (*Host) ExtensionCount

func (h *Host) ExtensionCount() int

ExtensionCount returns the number of loaded subprocess extensions.

func (*Host) Extensions

func (h *Host) Extensions() []extension.Extension

Extensions returns all successfully registered extension structs.

func (*Host) FlagDefault

func (h *Host) FlagDefault(extName, flagName string) any

FlagDefault returns the first committed default for a flag registered by the named extension.

func (*Host) FlushCommands

func (h *Host) FlushCommands()

FlushCommands is the stdout-flush checkpoint of an RPC shutdown. Pi's flush follows stdin's end within microtasks and one tick, so a runtime with no microtask continuation has nothing that can still settle: its command still running counts as suspended. A Node runtime reports its own commands as their windows close. A command that settles first responds normally. It does not cancel requests or synthesize responses.

func (*Host) Invalidate

func (h *Host) Invalidate(message string)

Invalidate makes the Host reject every later extension→host call with message, as Pi's ExtensionRunner.invalidate makes a captured pi or ctx throw (runner.ts:679-690). A call that already started keeps its result, so the replacement command that triggered the teardown still returns. The first message wins.

func (*Host) IsShuttingDown

func (h *Host) IsShuttingDown() bool

IsShuttingDown returns true after Shutdown has been called.

func (*Host) LastReloadReport

func (h *Host) LastReloadReport() *ReloadReport

LastReloadReport returns a copy of the latest reload report.

func (*Host) Load

func (h *Host) Load(ctx context.Context, cfg ExtConfig) (*extension.Extension, error)

Load spawns and registers a subprocess extension. Blocks until the register handshake completes or the context expires. The extension runs in its own process outside the cell plan, so a later Reload claims that process only when the extension's plan is isolated too.

func (*Host) LoadAll

func (h *Host) LoadAll(ctx context.Context, configs []ExtConfig) ([]extension.Extension, []error)

LoadAll loads multiple extensions using the cell planner, which packs compatible factory-mode extensions into shared processes (D20). This is the cell-planned equivalent of calling Load() per-extension and should be used for initial startup to get the same packing behavior as /reload. Non-fatal errors are collected and returned alongside successfully loaded extensions.

func (*Host) LoadEmbeddedCells

func (h *Host) LoadEmbeddedCells(ctx context.Context, cells []EmbeddedCell) ([]extension.Extension, []error)

LoadEmbeddedCells starts cells already embedded in a Piglet Binary binary. It does not touch source directories or invoke language toolchains.

func (*Host) LoadErrors

func (h *Host) LoadErrors() []string

LoadErrors returns the formatted errors from the most recent LoadAll, for surfacing startup extension load/build/register failures in-session. Safe for concurrent UI use.

func (*Host) LoadFinalExtensionSet

func (h *Host) LoadFinalExtensionSet(ctx context.Context, configs, preloaded []ExtConfig) ([]extension.Extension, []error)

LoadFinalExtensionSet keeps extensions initialized for project_trust and loads only paths not attempted in that phase. Failed preloads are not retried. Mirrors resource-loader.ts loadFinalExtensionSet; the caller supplies both resolved config sets because a failed load has no managed extension.

func (*Host) LoadGoPackedCell

func (h *Host) LoadGoPackedCell(ctx context.Context, cell *runtimecell.GoPackedCell) ([]extension.Extension, error)

LoadGoPackedCell starts a generated Go packed-cell runner and registers all extensions contained in the cell as one atomic unit. The runner is still a subprocess; packing only reduces process/artifact count. If any contained extension fails to connect/register, all staged connections/processes are stopped and previously loaded extensions remain active.

func (*Host) LoadInProcess

func (h *Host) LoadInProcess(ctx context.Context, cfg ExtConfig, serve func(net.Conn) error) (*extension.Extension, error)

LoadInProcess loads an extension whose factory runs inside the host process, served over an in-memory pipe with no subprocess and no runtime build. A fused Piglet Binary supplies serve as factory().RunWithConn. Registration, handshake, and lifecycle are otherwise identical to Load. pig additive (D31): fused in-process extension runtime.

func (*Host) LoadNodePackedCell

func (h *Host) LoadNodePackedCell(ctx context.Context, cell *nodePackedCell) ([]extension.Extension, error)

LoadNodePackedCell starts a generated Node packed-cell runner and registers every contained extension atomically. It mirrors LoadGoPackedCell: each extension keeps its own socket and its own register handshake.

func (*Host) LoadPythonPackedCell

func (h *Host) LoadPythonPackedCell(ctx context.Context, cell *runtimecell.PythonPackedCell) ([]extension.Extension, error)

LoadPythonPackedCell starts a generated Python packed-cell runner and registers every contained extension atomically. It mirrors the Go/Rust paths and keeps the current subprocess wire with one socket/register handshake per extension.

func (*Host) LoadRustPackedCell

func (h *Host) LoadRustPackedCell(ctx context.Context, cell *runtimecell.RustPackedCell) ([]extension.Extension, error)

LoadRustPackedCell starts a generated Rust packed-cell runner and registers every contained extension atomically. It mirrors LoadGoPackedCell. Each extension keeps one socket and one register handshake on the current wire.

func (*Host) NotifyHeight

func (h *Host) NotifyHeight(height int)

NotifyHeight broadcasts a height_change notification to every connected extension, but only when the value has actually changed. Call this from the TUI's resize handler alongside NotifyWidth, so extensions that render height-dependent content (chain graphs, dashboards) can reflow.

func (*Host) NotifyWidth

func (h *Host) NotifyWidth(width int)

NotifyWidth broadcasts a width_change notification to every connected extension, but only when the value has actually changed. Call this from the TUI's resize handler.

func (*Host) OAuthProviderNames

func (h *Host) OAuthProviderNames(extName string) []string

OAuthProviderNames returns runtime-registered OAuth provider IDs owned by an extension.

func (*Host) ProviderNames

func (h *Host) ProviderNames(extName string) []string

ProviderNames returns provider names registered by a loaded extension.

func (*Host) QuarantinedCells

func (h *Host) QuarantinedCells() map[string]string

QuarantinedCells returns a snapshot of packed runtime cells disabled after a crash.

func (*Host) Reload

func (h *Host) Reload(ctx context.Context) ([]extension.Extension, error)

Reload re-reads extension config, starts a fresh replacement for every enabled extension beside the currently running ones (unchanged extensions reuse their cached build artifact but, like upstream's re-invoked factories, never their running instance), validates their handshakes, then swaps the new set into the registry. Like upstream reload, an extension that fails to resolve, build, start, or register is not loaded: its previous runtime is stopped, its failure is recorded in ReloadReport.Issues, and every other extension loads. Only a config loader failure fails the reload.

func (*Host) Retain

func (h *Host) Retain()

Retain parks this Host's live extension processes in its RuntimeRetention, so Shutdown ends the Host's own connections and leaves the processes running for the replacement Host to claim. It is a no-op for a Host without a shared RuntimeRetention, and parks nothing once a successor Host has loaded. Call it before Shutdown, after session_shutdown has been delivered. It returns once every process has taken the hold, so the generations Shutdown retires next are not the last thing keeping a process open.

func (*Host) Runtime

func (h *Host) Runtime() *extension.ExtensionRuntime

Runtime returns the shared provider registration state for a Runner created from this Host's loaded extensions.

func (*Host) SetCallHandler

func (h *Host) SetCallHandler(fn func(extName string, call *CallPayload) (*CallResultPayload, error))

SetCallHandler registers the callback for extension→host calls (ui.notify, sendMessage, etc.). Must be called before Host.Load.

func (*Host) SetCommandSuspendHandler

func (h *Host) SetCommandSuspendHandler(fn func(suspended int))

SetCommandSuspendHandler installs the process-owner callback that receives how many in-flight extension commands are suspended: a Node command whose runtime reported its event-loop window closed unresponded, or a command of another runtime that was running at the checkpoint. The callback runs on host goroutines, must not block, and must not resume or cancel the command.

func (*Host) SetConfigLoader

func (h *Host) SetConfigLoader(fn func() ([]ExtConfig, error))

SetConfigLoader overrides the config source used by Reload.

func (*Host) SetCrashHandler

func (h *Host) SetCrashHandler(fn func(name string, delay time.Duration, disabled bool, reason string))

SetCrashHandler registers a callback for extension crash events.

func (*Host) SetHeightFunc

func (h *Host) SetHeightFunc(fn func() int)

SetHeightFunc registers the current terminal height. pig additive (D52): expose height to extension SDKs.

func (*Host) SetMode

func (h *Host) SetMode(mode string)

SetMode sets the run mode (tui|rpc|json|print) sent to extensions in the ReadyPayload and read back as ctx.mode. Call before Load. An empty mode is sent as omitted; SDKs default it to "print" to match upstream (runner.ts:229).

func (*Host) SetNativeProviderCallback

func (h *Host) SetNativeProviderCallback(register func(context.Context, *extension.NativeProvider) error)

SetNativeProviderCallback binds connection-owned native provider registrations.

func (*Host) SetProviderCallbacks

func (h *Host) SetProviderCallbacks(register func(name string, config extension.ProviderConfig) error, unregister func(name string)) []*extension.ExtensionError

SetProviderCallbacks binds the registry, drains pending registrations and returns their owning-path diagnostics. Configure callbacks before dispatching handlers. A Runner can instead bind Runtime through BindCore to deliver these diagnostics to its error listeners.

func (*Host) SetRuntimeDrainHandler

func (h *Host) SetRuntimeDrainHandler(fn func())

SetRuntimeDrainHandler installs the process-owner callback for a Node event-loop drain after input end. A drain is not handler completion; the callback must not resume pending extension work.

func (*Host) SetRuntimeRetention

func (h *Host) SetRuntimeRetention(r *RuntimeRetention)

SetRuntimeRetention shares r with the Hosts that succeed this one in a Session runtime, so a replacement Session's extensions re-invoke their factories in the processes this Host started. Configure it before loading extensions.

func (*Host) SetStartupTrace

func (h *Host) SetStartupTrace(mark func(string))

SetStartupTrace registers startup checkpoint instrumentation. Labels are stable and contain only the extension identity and lifecycle phase.

func (*Host) SetUIBridge

func (h *Host) SetUIBridge(bridge *UIBridge)

SetUIBridge attaches a UI bridge for handling widget pushes and UI method calls. Must be called before Host.Load.

func (*Host) SetWidthFunc

func (h *Host) SetWidthFunc(fn func() int)

SetWidthFunc registers a callback that returns the current terminal width. The host uses this to populate the ready payload with the real terminal width (instead of a hardcoded default) and to broadcast width_change notifications to all connected extensions.

func (*Host) Shutdown

func (h *Host) Shutdown(reason string)

Shutdown detaches all extension consumers before removing providers, then stops and reaps every managed process. Session owners emit and await session_shutdown before calling it.

func (*Host) TerminateProcesses

func (h *Host) TerminateProcesses()

TerminateProcesses kills hosted processes without running extension callbacks or waiting for their handlers. It is only for a host process that is about to exit; ordinary owners use Shutdown to release all resources.

type HostCallbacks

type HostCallbacks struct {
	// SendMessage injects a custom message into the conversation.
	// upstream: types.ts:1448: SendMessageHandler
	SendMessage func(msg extension.CustomMessageRef, opts SendMessageOptions) error

	// SendUserMessage injects a user message into the conversation.
	// upstream: types.ts:1449: SendUserMessageHandler
	SendUserMessage func(content any, opts SendUserMessageOptions) error

	// AppendEntry appends a custom session entry.
	// upstream: types.ts:1450: AppendEntryHandler
	// direct is non-nil for ctx.sessionManager.appendCustomEntry, which
	// writes the log only and has already returned the entry's id; nil is
	// pi.appendEntry, which also emits entry_appended.
	AppendEntry func(customType string, data any, direct *DirectEntryAppend) error

	// Exec runs a local command and returns stdout/stderr/exit status.
	// ExecContext is preferred by production hosts: the call context carries
	// the ordered-initiation mark that ExecCommand reports after process start.
	// Exec remains for direct adapters that cannot report an earlier initiation;
	// those adapters release the call lane when they return.
	// upstream: types.ts:1190
	Exec        func(command string, args []string, opts *extension.ExecOptions) (extension.ExecResult, error)
	ExecContext func(context.Context, string, []string, *extension.ExecOptions) (extension.ExecResult, error)

	// GetSessionName returns the current session name.
	// upstream: types.ts:1452
	GetSessionName func() string

	// GetSessionID returns the current session id.
	// upstream: session-manager.ts session.id getter
	GetSessionID func() string

	// GetSessionFile returns the current session file path.
	// upstream: session-manager.ts getSessionFile()
	GetSessionFile func() string

	// GetLeafID returns the current branch leaf entry id.
	// upstream: session-manager.ts getLeafId()
	GetLeafID func() string

	// GetFlag returns the value of a registered CLI flag for an extension.
	// upstream: types.ts:1145
	GetFlag func(extName, name string) any

	// SetSessionName sets the session name.
	// upstream: types.ts:1451
	SetSessionName func(name string) error

	// SetLabel sets a label on a session entry; an empty label clears it.
	// Its error fails the extension's call, as upstream appendLabelChange
	// throws.
	// upstream: types.ts:1453
	SetLabel func(entryID, label string) error

	// GetActiveTools returns the currently active tool names.
	// upstream: types.ts:1454
	GetActiveTools func() []string

	// GetAllTools returns metadata about all available tools.
	// upstream: types.ts:1455
	GetAllTools func() []ToolInfo

	// SetActiveTools sets the active tool list.
	// upstream: types.ts:1456
	SetActiveTools func(names []string)

	// RefreshTools reloads tool definitions.
	// upstream: types.ts:1457
	RefreshTools func() error

	// GetCommands returns available slash commands.
	// upstream: types.ts:1458
	GetCommands func() []CommandInfo

	// SetModel changes the active model.
	// upstream: types.ts:1459
	SetModel func(context.Context, string) (bool, error)

	// GetThinkingLevel returns the current thinking level.
	// upstream: types.ts:1460
	GetThinkingLevel func() string

	// SetThinkingLevel sets the thinking level.
	// upstream: types.ts:1461
	SetThinkingLevel func(level string)

	// GetContextUsage returns context window utilization data.
	// upstream: runner.ts:614-617
	GetContextUsage func() *extension.ContextUsage

	// GetSystemPrompt returns the current system prompt text.
	// upstream: runner.ts:620 (getSystemPrompt getter on ExtensionContext)
	GetSystemPrompt func() string

	// GetSystemPromptOptions returns the base inputs pi currently uses to
	// build the system prompt. Backs ctx.getSystemPromptOptions().
	// upstream: runner.ts:653 (createCommandContext getSystemPromptOptions)
	GetSystemPromptOptions func() extension.BuildSystemPromptOptions

	// GetModelInfo returns structured metadata for the active model.
	// upstream: runner.ts:609 (model getter on ExtensionContext)
	GetModelInfo func() map[string]any

	// GetScopedModels returns the Session's resolved model scope in selection order.
	GetScopedModels func() []extension.ScopedModel

	// GetModel resolves metadata by provider and model ID through the Session-owned runtime registry.
	GetModel  func(providerID, modelID string) map[string]any
	GetModels func() []map[string]any

	// GetBranch returns the conversation history as raw session entries. The
	// entries are already JSON on disk, so they are passed through rather than
	// decoded into maps and re-encoded on every push.
	// upstream: sessionManager.getBranch(): returns SessionEntry[]
	GetBranch func() []json.RawMessage

	// GetEntries returns all session entries in append order.
	// upstream: sessionManager.getEntries()
	GetEntries func() []json.RawMessage

	// GetEntriesPage returns a bounded page at or after cursor, the cursor after
	// that page, whether more entries remain, and the current branch leaf.
	GetEntriesPage func(cursor, maxBytes int) ([]json.RawMessage, int, bool, string)

	// GetModelAuth resolves request auth for a model lookup.
	// upstream: modelRegistry.getApiKeyAndHeaders(model)
	GetModelAuth func(context.Context, string, string) map[string]any

	// Complete performs a one-shot LLM completion.
	// upstream: @mariozechner/pi-ai complete()
	Complete func(context.Context, map[string]any, map[string]any, map[string]any) (map[string]any, error)

	// StreamModel starts a model operation through the Session-owned runtime.
	StreamModel func(context.Context, map[string]any, map[string]any) (*ai.AssistantMessageEventStream, error)

	// GetModelRegistryState returns the state behind upstream ModelRegistry's
	// synchronous reads: the catalog, the available models, each provider's
	// display name, auth status and OAuth use, and the registry error.
	// upstream: model-registry.ts getAll, getAvailable, hasConfiguredAuth,
	// getProviderAuthStatus, getProvider, getProviderDisplayName,
	// isUsingOAuth, getError.
	GetModelRegistryState func() map[string]any

	// GetProviderAuth resolves request auth for a provider, or nil when it has
	// none. upstream: model-registry.ts getProviderAuth(provider)
	GetProviderAuth func(ctx context.Context, provider string) (map[string]any, error)

	// RefreshModelRegistry reloads models.json and refreshes the provider
	// catalogs. allowNetwork nil means the runtime default; providers nil
	// means every provider. upstream: model-registry.ts refresh(options)
	RefreshModelRegistry func(ctx context.Context, allowNetwork *bool, providers []string, force *bool) (map[string]any, error)

	// SessionRead answers a ReadonlySessionManager read computed from the
	// host's session: the header facts (method "info"), and for the Go, Rust
	// and Python SDKs the reads their session mirror cannot answer.
	// upstream: session-manager.ts ReadonlySessionManager
	SessionRead func(method string, args json.RawMessage) (any, error)

	// IsIdle returns whether the agent is currently idle (not streaming).
	// upstream: types.ts:307
	IsIdle func() bool

	// IsProjectTrusted returns whether the current project is trusted.
	// upstream: types.ts:332
	IsProjectTrusted func() bool

	// Footer data behind upstream's ReadonlyFooterDataProvider.
	GetGitBranch              func() string
	GetExtensionStatuses      func() map[string]string
	GetAvailableProviderCount func() int

	// Abort cancels the current agent operation.
	// upstream: types.ts:311
	Abort func()

	// HasPendingMessages returns whether there are queued messages waiting.
	// upstream: types.ts:313
	HasPendingMessages func() bool

	// Shutdown triggers a graceful shutdown and exit.
	// upstream: types.ts:315
	Shutdown func()

	// Compact triggers compaction without awaiting completion.
	// upstream: types.ts:319
	Compact func(context.Context, *extension.CompactOptions)

	// WaitForIdle blocks until the agent finishes streaming.
	// upstream: types.ts:331 (ExtensionCommandContext)
	WaitForIdle func(context.Context) error

	// NewSession starts a new session.
	// upstream: types.ts:333
	NewSession func(context.Context, *extension.NewSessionOptions) (extension.CancelledResult, error)

	// Fork creates a new branch from an entry.
	// upstream: types.ts:340
	Fork func(context.Context, string, *extension.ForkOptions) (extension.CancelledResult, error)

	// NavigateTree moves to a different point in the session tree.
	// upstream: types.ts:346
	NavigateTree func(context.Context, string, *extension.NavigateTreeOptions) (extension.CancelledResult, error)

	// SwitchSession switches to a different session file.
	// upstream: types.ts:352
	SwitchSession func(context.Context, string, *extension.SwitchSessionOptions) (extension.CancelledResult, error)

	// Reload reloads extensions, skills, prompts, themes.
	// upstream: types.ts:358
	Reload func(context.Context) error
}

HostCallbacks provides the agent-loop callbacks that extensions can invoke. These map to upstream ExtensionActions (types.ts:1447-1462).

All fields are optional (nil = no-op). They are set after the agent session is created, which happens after extensions load. Promise-shaped callbacks receive the call context and invoke extension.CallInitiated after their synchronous prefix has applied; they may then block until completion.

type LoadError

type LoadError struct {
	Extension string
	Phase     string
	Code      string
	StderrLog string
	// Hint is optional operator-facing remediation guidance (e.g. rebuild a
	// stale standalone binary). It is advisory and appended to Error().
	Hint string
	Err  error
}

managedExt tracks a single subprocess extension's lifecycle. LoadError is a structured extension load/startup failure. Validation and diagnostics use Phase/Code to tell users exactly where startup failed.

func (*LoadError) Error

func (e *LoadError) Error() string

func (*LoadError) Unwrap

func (e *LoadError) Unwrap() error

type MarkdownTransformPayload

type MarkdownTransformPayload struct {
	Markdown string                             `json:"markdown"`
	Context  extension.MarkdownTransformContext `json:"context"`
}

MarkdownTransformPayload is the RequestMarkdownTransform argument.

type MessageRendererDecl

type MessageRendererDecl struct {
	CustomType string `json:"custom_type"`
}

MessageRendererDecl declares a custom message renderer.

type ModelStreamCall

type ModelStreamCall struct {
	StreamID         string          `json:"streamId"`
	Simple           bool            `json:"simple,omitempty"`
	APIRequest       bool            `json:"apiRequest,omitempty"`
	Fetch            bool            `json:"fetch,omitempty"`
	OnPayload        bool            `json:"onPayload,omitempty"`
	OnResponse       bool            `json:"onResponse,omitempty"`
	TransformHeaders bool            `json:"transformHeaders,omitempty"`
	Model            map[string]any  `json:"model"`
	Request          json.RawMessage `json:"request"`
}

ModelStreamCall invokes a registry stream or an already-resolved API leaf. Callback capabilities remain scoped to StreamID and the originating connection.

type ModelStreamCallback

type ModelStreamCallback struct {
	StreamID string `json:"streamId"`
	Callback string `json:"callback"`
	Value    any    `json:"value"`
}

ModelStreamCallback invokes one advertised callback before its provider boundary proceeds.

type NativeProviderDeclaration

type NativeProviderDeclaration struct {
	ID      string                          `json:"id"`
	Key     string                          `json:"key"`
	Handle  string                          `json:"handle,omitempty"`
	Headers *map[string]string              `json:"headers,omitempty"`
	Auth    *ProviderObjectAuthDeclaration  `json:"auth,omitempty"`
	Methods []string                        `json:"methods,omitempty"`
	Name    string                          `json:"name"`
	BaseURL *string                         `json:"baseUrl,omitempty"`
	Models  []extension.ProviderModelConfig `json:"models"`
	OAuth   *ProviderOAuthConfig            `json:"oauth,omitempty"`
}

NativeProviderDeclaration describes callback ownership, never executable code. Key identifies the owner's callback object; Handle identifies its host-owned reference lifetime. Methods lists the callable public members. Provider calls carry caller callbacks as request-scoped handles, and stream creation is acknowledged before ordered events.

type NotifyPayload

type NotifyPayload struct {
	Method string          `json:"method"` // e.g. "width_change", "widget_invalidate"
	Args   json.RawMessage `json:"args,omitempty"`
}

NotifyPayload carries a fire-and-forget notification. The host-only runtime_input_end notification removes stdin as a Node keepalive. runtime_drained reports a still-pending quit handler whose event loop drained. runtime_quit_yield reports a post-disposal boundary that suspended beyond its immediately fulfilled continuations. Command suspension travels as request_state. None completes an extension request.

type OAuthAPIKeyResult

type OAuthAPIKeyResult struct {
	APIKey string `json:"apiKey"`
}

OAuthAPIKeyResult is the reply to MethodOAuthGetAPIKey.

type OAuthAuthInfoWire

type OAuthAuthInfoWire struct {
	URL          string `json:"url"`
	Instructions string `json:"instructions,omitempty"`
}

OAuthAuthInfoWire, OAuthDeviceCodeInfoWire, OAuthProgressWire, OAuthPromptWire, OAuthSelectPromptWire, and OAuthSelectOptionWire carry the login-callback payloads. The host converts to/from the untagged ai callback types.

type OAuthCredentialStatusResult

type OAuthCredentialStatusResult struct {
	Present  bool   `json:"present"`
	AuthType string `json:"authType,omitempty"`
	Source   string `json:"source,omitempty"`
}

OAuthCredentialStatusResult is the reply to MethodOAuthCredentialStatus.

type OAuthCredentialsWire

type OAuthCredentialsWire = ai.OAuthCredentials

OAuthCredentialsWire is the wire shape of OAuth credentials: Pi's complete token object, including provider-owned keys and the exact JavaScript expires value.

type OAuthDeleteResult

type OAuthDeleteResult struct {
	Deleted bool `json:"deleted"`
}

OAuthDeleteResult is the reply to MethodOAuthDeleteCredentials.

type OAuthDeviceCodeInfoWire

type OAuthDeviceCodeInfoWire struct {
	UserCode         string  `json:"userCode"`
	VerificationURI  string  `json:"verificationUri"`
	IntervalSeconds  float64 `json:"intervalSeconds,omitempty"`
	ExpiresInSeconds float64 `json:"expiresInSeconds,omitempty"`
}

type OAuthInputResult

type OAuthInputResult struct {
	Value  string `json:"value"`
	Cancel bool   `json:"cancel,omitempty"`
}

OAuthInputResult is the reply to a value-returning login callback. Cancel is true when the user dismissed the prompt.

type OAuthProgressWire

type OAuthProgressWire struct {
	Message string `json:"message"`
}

type OAuthPromptWire

type OAuthPromptWire struct {
	Message     string `json:"message"`
	Placeholder string `json:"placeholder,omitempty"`
	AllowEmpty  bool   `json:"allowEmpty,omitempty"`
}

type OAuthSelectOptionWire

type OAuthSelectOptionWire struct {
	ID    string `json:"id"`
	Label string `json:"label"`
}

type OAuthSelectPromptWire

type OAuthSelectPromptWire struct {
	Message string                  `json:"message"`
	Options []OAuthSelectOptionWire `json:"options"`
}

type OAuthSignalReleaseArgs

type OAuthSignalReleaseArgs struct {
	RequestID string `json:"request_id"`
}

OAuthSignalReleaseArgs is the Args of notifyOAuthSignalRelease.

type OAuthStoreResult

type OAuthStoreResult struct {
	Path string `json:"path"`
}

OAuthStoreResult is the reply to MethodOAuthStoreCredentials.

type PingPayload

type PingPayload struct {
	Nonce string `json:"nonce"`
}

PingPayload and PongPayload correlate one dispatcher liveness probe.

type PongPayload

type PongPayload struct {
	Nonce string `json:"nonce"`
}

type ProviderDecl

type ProviderDecl struct {
	StreamSimple bool                       `json:"stream_simple,omitempty"`
	Name         string                     `json:"name"`
	Config       json.RawMessage            `json:"config"`
	Native       *NativeProviderDeclaration `json:"native,omitempty"`
}

ProviderDecl registers or overrides a model provider.

type ProviderOAuthConfig

type ProviderOAuthConfig struct {
	Name               string `json:"name"`
	IsSubscription     bool   `json:"isSubscription,omitempty"`
	HasLogin           bool   `json:"has_login"`
	HasRefresh         bool   `json:"has_refresh"`
	HasGetAPIKey       bool   `json:"has_get_api_key"`
	HasModifyModels    bool   `json:"has_modify_models,omitempty"`
	HasCredentialStore bool   `json:"has_credential_store,omitempty"`
}

ProviderOAuthConfig is the "oauth" sub-object inside a ProviderDecl.Config. It carries declarative fields and capability flags only, never functions.

type ProviderObjectAuthDeclaration

type ProviderObjectAuthDeclaration struct {
	APIKey *ProviderObjectAuthMethodDeclaration `json:"apiKey,omitempty"`
	OAuth  *ProviderObjectAuthMethodDeclaration `json:"oauth,omitempty"`
}

type ProviderObjectAuthMethodDeclaration

type ProviderObjectAuthMethodDeclaration struct {
	Name           string  `json:"name"`
	IsSubscription *bool   `json:"isSubscription,omitempty"`
	LoginLabel     *string `json:"loginLabel,omitempty"`
}

type ProviderObjectCall

type ProviderObjectCall struct {
	Handle     string          `json:"handle"`
	Method     string          `json:"method"`
	Params     json.RawMessage `json:"params"`
	StreamID   string          `json:"streamId,omitempty"`
	CallbackID string          `json:"callbackId,omitempty"`
}

type PushProxy

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

PushProxy implements the Component interface (Render + Invalidate) backed by a cached []string that the extension pushes asynchronously. Render() NEVER touches the socket: it reads from the cache in O(1). Width-change events flow back to the extension via a notification so it can re-render.

Performance contract: Render() returns in <1μs (slice copy from cache). All socket I/O happens on the connection's read goroutine.

pig-specific: no upstream equivalent.

func NewPushProxy

func NewPushProxy(invalidate func(), onWidthChange func(width int)) *PushProxy

NewPushProxy creates a proxy component. The invalidate callback should trigger a TUI render cycle. The onWidthChange callback should notify the extension of the new terminal width.

func (*PushProxy) Clear

func (p *PushProxy) Clear()

Clear removes all cached lines.

func (*PushProxy) Invalidate

func (p *PushProxy) Invalidate()

Invalidate marks the component for re-render. Called by the TUI framework. For PushProxy this is a no-op: re-renders are triggered by UpdateLines.

func (*PushProxy) Lines

func (p *PushProxy) Lines() []string

Lines returns the current cached lines (for testing/inspection).

func (*PushProxy) Render

func (p *PushProxy) Render(width int) []string

Render returns the cached lines, or lays a string list widget out at width. It never blocks on I/O. Satisfies the tui.Component interface.

Returns a defensive copy so callers cannot corrupt the cache.

func (*PushProxy) UpdateContent

func (p *PushProxy) UpdateContent(content []string)

UpdateContent replaces the widget with a string list that the host lays out at the width it renders. Pi wraps the first ten entries in Text(line, 1, 0) and adds a muted "... (widget truncated)" Text for a longer list (interactive-mode.ts:2321-2336); the theme is read when the widget is set, as Pi reads it there.

func (*PushProxy) UpdateLines

func (p *PushProxy) UpdateLines(lines []string)

UpdateLines replaces the cached lines and triggers a TUI re-render. Called from the connection's read goroutine when a widget_push arrives. Thread-safe: can be called from any goroutine.

func (*PushProxy) UpdateLinesAt

func (p *PushProxy) UpdateLinesAt(lines []string, width int)

UpdateLinesAt replaces the cached lines with a frame rendered at width (0 when the extension did not report it) and triggers a TUI re-render.

type ReadyPayload

type ReadyPayload struct {
	SessionName string           `json:"session_name,omitempty"` // Current session name
	Cwd         string           `json:"cwd"`                    // Working directory
	Mode        string           `json:"mode,omitempty"`         // Run mode: tui|rpc|json|print (ctx.mode)
	Width       int              `json:"width"`                  // Terminal width
	Height      int              `json:"height,omitempty"`       // Terminal height (0 if unavailable)
	Model       string           `json:"model,omitempty"`        // Active model name
	Models      []map[string]any `json:"models,omitempty"`       // Complete registry snapshot for synchronous Node lookup
	Theme       json.RawMessage  `json:"theme,omitempty"`        // Current theme data
	State       *StatePayload    `json:"state,omitempty"`        // Initial extension-host state snapshot
}

ReadyPayload is sent after successful registration.

type RegisterPayload

type RegisterPayload struct {
	Name    string `json:"name"`
	Version string `json:"version,omitempty"`

	Tools            []ToolDecl            `json:"tools,omitempty"`
	Commands         []CommandDecl         `json:"commands,omitempty"`
	Shortcuts        []ShortcutDecl        `json:"shortcuts,omitempty"`
	Handlers         []HandlerDecl         `json:"handlers,omitempty"`
	Widgets          []WidgetDecl          `json:"widgets,omitempty"`
	Flags            []FlagDecl            `json:"flags,omitempty"`
	Providers        []ProviderDecl        `json:"providers,omitempty"`
	MessageRenderers []MessageRendererDecl `json:"message_renderers,omitempty"`
	EntryRenderers   []EntryRendererDecl   `json:"entry_renderers,omitempty"`
	// MarkdownTransformer reports that the extension registered a Markdown
	// transformer. The host runs it with RequestMarkdownTransform.
	MarkdownTransformer bool `json:"markdown_transformer,omitempty"`

	// WantsSessionLog subscribes this extension to session-log replication from
	// the handshake, before the ready state is built, so the log is present on
	// the first read. Runtimes whose session readers can block on the host
	// subscribe on first use instead and leave this false; a runtime that
	// exposes those readers synchronously over asynchronous IPC has no such
	// moment and declares it here.
	WantsSessionLog bool `json:"wants_session_log,omitempty"`
	// contains filtered or unexported fields
}

RegisterPayload declares an extension's capabilities at startup.

func (*RegisterPayload) UnmarshalJSON

func (p *RegisterPayload) UnmarshalJSON(data []byte) error

type ReloadCellReport

type ReloadCellReport struct {
	Key           string        // planner cell key
	Strategy      CellStrategy  // isolated, packed-go, packed-rust, packed-python
	Language      string        // runtime language ("go", "rust", "python", "")
	Extensions    []string      // member extension names (planner order)
	Hash          string        // packed cell artifact hash, empty for isolated
	BinaryPath    string        // resolved artifact path
	Cached        bool          // true if packed artifact was reused from cache
	BuildDuration time.Duration // cold-build duration; zero on cache hit / no build
	Replaced      bool          // true if cell replaced an existing one
	Quarantined   bool          // true if planner refused to pack due to quarantine
	Reason        string        // short human reason ("factory shared-ok", "isolated source", ...)
}

ReloadCellReport records one extension placement decision.

type ReloadReport

type ReloadReport struct {
	StartedAt time.Time
	Duration  time.Duration
	Cells     []ReloadCellReport
	Removed   []string
	Error     string
	// Issues lists, as "<path>: Failed to load extension: <error>", the
	// extensions that failed to resolve, build, start, or register. They do
	// not fail the reload.
	Issues []string
}

pig additive (D21): ReloadReport exposes subprocess placement diagnostics. ReloadReport records the latest Reload operation.

type RemoteOverlayClosePayload

type RemoteOverlayClosePayload struct {
	Key    string          `json:"key"`
	Result json.RawMessage `json:"result,omitempty"`
	Error  string          `json:"error,omitempty"`
}

type RemoteOverlayControlPayload

type RemoteOverlayControlPayload struct {
	Key    string                      `json:"key"`
	Action string                      `json:"action"`
	Hidden bool                        `json:"hidden,omitempty"`
	Target *RemoteOverlayTargetPayload `json:"target,omitempty"`
}

type RemoteOverlayInputPayload

type RemoteOverlayInputPayload struct {
	Key   string                        `json:"key"`
	Data  string                        `json:"data"`
	State *extension.RemoteOverlayState `json:"state,omitempty"`
}

type RemoteOverlayOpenPayload

type RemoteOverlayOpenPayload struct {
	Key            string  `json:"key"`
	Title          string  `json:"title,omitempty"`
	WidthFraction  float64 `json:"widthFraction,omitempty"`
	HeightFraction float64 `json:"heightFraction,omitempty"`
	Overlay        bool    `json:"overlay,omitempty"`
	HasHandle      bool    `json:"hasHandle,omitempty"`
	// OverlayOptions is upstream ui.custom()'s serialisable overlayOptions.
	OverlayOptions *extension.OverlayLayout `json:"overlayOptions,omitempty"`
}

type RemoteOverlayRenderPayload

type RemoteOverlayRenderPayload struct {
	Key   string   `json:"key"`
	Lines []string `json:"lines"`
	// Width is the terminal width the frame was laid out for (stale-frame
	// key), not the overlay render width.
	Width int    `json:"width,omitempty"`
	Seq   uint64 `json:"seq,omitempty"`
}

type RemoteOverlayTargetPayload

type RemoteOverlayTargetPayload struct {
	Kind string `json:"kind"`
	Key  string `json:"key,omitempty"`
}

RemoteOverlayTargetPayload names an explicit unfocus target: "null", "editor", or "overlay" with the key of another mounted overlay of the same extension.

type RenderResult

type RenderResult struct {
	Lines []string `json:"lines,omitempty"`
}

RenderResult is the structured result from a renderer execution.

type RenderToolContent

type RenderToolContent struct {
	Type          string `json:"type"`
	Text          string `json:"text,omitempty"`
	TextSignature string `json:"textSignature,omitempty"`
	Data          string `json:"data,omitempty"`
	MimeType      string `json:"mimeType,omitempty"`
}

RenderToolContent is one text or image block of a RenderToolResult.

func (RenderToolContent) MarshalJSON

func (block RenderToolContent) MarshalJSON() ([]byte, error)

MarshalJSON retains required empty text and image fields on the renderer wire.

type RenderToolContext

type RenderToolContext struct {
	ToolCallID       string `json:"toolCallId"`
	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"`
}

RenderToolContext carries the serializable fields of upstream ToolRenderContext. The extension supplies args, state, lastComponent and invalidate from the card.

type RenderToolPayload

type RenderToolPayload struct {
	Card     string                             `json:"card"`
	Phase    string                             `json:"phase"` // "call" | "result"
	Rerender bool                               `json:"rerender"`
	Args     json.RawMessage                    `json:"args"`
	Result   *RenderToolResult                  `json:"result,omitempty"`
	Options  *extension.ToolRenderResultOptions `json:"options,omitempty"`
	Context  RenderToolContext                  `json:"context"`
	Width    int                                `json:"width"`
}

RenderToolPayload is the RequestRenderTool argument. Card identifies the tool card; upstream keeps one renderer state per card, shared by both renderers, and one last component per renderer. Rerender runs the renderer again; without it the extension renders the card's last component at Width, as a resize does upstream, and runs the renderer only when it has none.

type RenderToolResult

type RenderToolResult struct {
	Content []RenderToolContent `json:"content"`
	Details json.RawMessage     `json:"details,omitempty"`
}

RenderToolResult is the result renderResult receives: upstream's {content, details}.

type RequestPayload

type RequestPayload struct {
	Method     string          `json:"method"` // "tool_call", "event", "command", "shortcut", "render_message", "render_entry", "render_tool"
	Tool       string          `json:"tool,omitempty"`
	Event      string          `json:"event,omitempty"`
	HandlerID  int             `json:"handler_id,omitempty"`
	ToolCallID string          `json:"tool_call_id,omitempty"` // For tool_call: unique ID
	Args       json.RawMessage `json:"args,omitempty"`         // Tool args or event payload
	// SignalTimeoutMS, on oauth_refresh, asks a runtime whose refresh callback receives an AbortSignal to compose AbortSignal.timeout(SignalTimeoutMS) into it, as Pi's resolveStoredOAuth does (auth/resolve.ts:149-153). Absent, the signal follows only the caller (models.ts:474).
	SignalTimeoutMS *float64 `json:"signal_timeout_ms,omitempty"`
}

RequestPayload carries a host request that expects a response.

type RequestStatePayload

type RequestStatePayload struct {
	RequestID string `json:"request_id"`
	State     string `json:"state"`            // started | progress | blocked | completed | suspended
	Reason    string `json:"reason,omitempty"` // user | host_call | external_io
}

RequestStatePayload reports activity for one host-owned request. A blocked state means the handler has entered an awaited operation; completed means its body returned. The Node runtime reports suspended when an extension command's, or a quit session_shutdown handler's, event-loop window closed with the request unresponded. Either admits the next unawaited UI prompt event. Started alone reports dispatch and does not establish handler-body invocation order.

type ResponsePayload

type ResponsePayload struct {
	Result json.RawMessage `json:"result,omitempty"` // Tool result, event result, etc.
	Error  *ErrorInfo      `json:"error,omitempty"`  // Non-nil on failure
}

ResponsePayload is the extension's reply to a request. For agent_before_settle and turn_end, Result carries {_pigBoundaryEntries, _pigBoundaryResult}: the mutated input draft list and the explicit handler result. Mutations also accompany Error; the host applies them before surfacing the error and ignores the explicit result.

type RuntimeRetention

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

RuntimeRetention keeps extension processes alive across the Hosts of one Session runtime. Pi re-invokes extension factories inside the process that already holds their modules, on /reload and on every Session replacement, so module state and globals persist. A Host claims a retained process from its RuntimeRetention when a cell it starts matches one, and admits the new factory generation to it instead of spawning another process.

func NewRuntimeRetention

func NewRuntimeRetention() *RuntimeRetention

NewRuntimeRetention returns an empty retention for the Hosts of one Session runtime.

func (*RuntimeRetention) Close

func (r *RuntimeRetention) Close()

Close kills every parked process no Host claimed. Call it when the Session runtime that owns the retention ends.

type SendMessageOptions

type SendMessageOptions struct {
	TriggerTurn *bool  `json:"triggerTurn,omitempty"`
	DeliverAs   string `json:"deliverAs,omitempty"` // "steer" | "followUp" | "nextTurn"
}

SendMessageOptions mirrors upstream options for sendMessage. Both fields are optional upstream and their defaults depend on session state, so an omitted field stays unset: TriggerTurn is nil and DeliverAs is empty.

type SendUserMessageOptions

type SendUserMessageOptions struct {
	DeliverAs string `json:"deliverAs,omitempty"` // "steer" | "followUp"
}

SendUserMessageOptions mirrors upstream options for sendUserMessage.

type SessionStatePayload

type SessionStatePayload struct {
	SessionID   string `json:"sessionId,omitempty"`
	SessionName string `json:"sessionName"`
	SessionFile string `json:"sessionFile"`
	LeafID      string `json:"leafId"`
	// EntriesAppended carries only the next bounded page after this extension's
	// cursor. EntryCount is the cursor after applying the page. When
	// EntriesRemaining is true, the host sends another ordered state update.
	EntriesAppended  []json.RawMessage `json:"entriesAppended,omitempty"`
	EntryCount       int               `json:"entryCount"`
	EntriesRemaining bool              `json:"entriesRemaining,omitempty"`
	// Info carries the session manager facts the log does not hold: the
	// header, cwd, session directory, and whether the session persists
	// (upstream getHeader, getCwd, getSessionDir, isPersisted,
	// usesDefaultSessionDir).
	Info json.RawMessage `json:"info,omitempty"`
}

SessionStatePayload mirrors the synchronous sessionManager getters exposed to TS extensions (session id/name/file, current leaf, branch, full entry list). Branch/Entries carry raw session-entry objects serialized from the host session file.

type ShortcutDecl

type ShortcutDecl struct {
	Key         string `json:"key"` // e.g. "ctrl+shift+i"
	Description string `json:"description"`
}

ShortcutDecl declares a keyboard shortcut the extension binds.

type ShutdownPayload

type ShutdownPayload struct {
	Reason string `json:"reason,omitempty"` // "quit", "reload", "disable"
}

ShutdownPayload signals the extension to exit gracefully.

type StatePayload

type StatePayload struct {
	ActiveTools         []string                   `json:"activeTools"`
	AllTools            []ToolInfo                 `json:"allTools"`
	Commands            []CommandInfo              `json:"commands"`
	ThinkingLevel       string                     `json:"thinkingLevel"`
	Model               map[string]any             `json:"model"`
	ScopedModels        []scopedModelSnapshot      `json:"scopedModels"`
	Session             *SessionStatePayload       `json:"session,omitempty"`
	IsIdle              bool                       `json:"isIdle"`
	ProjectTrusted      bool                       `json:"projectTrusted"`
	HasPendingMessages  bool                       `json:"hasPendingMessages"`
	ContextUsage        *extensionContextUsageDTO  `json:"contextUsage"`
	SystemPrompt        string                     `json:"systemPrompt"`
	SystemPromptOptions json.RawMessage            `json:"systemPromptOptions,omitempty"`
	Flags               map[string]json.RawMessage `json:"flags"`
	HasUI               bool                       `json:"hasUI"`
	FooterData          *FooterDataPayload         `json:"footerData,omitempty"`
	// Always serialized: an emptied editor must clear the replicated value
	// rather than leave the previous text in place.
	EditorText    string         `json:"editorText"`
	ToolsExpanded bool           `json:"toolsExpanded"`
	AllThemes     []themeMetaDTO `json:"allThemes"`
	// TerminalCapabilities is the host terminal's resolved capabilities
	// (detection plus settings overrides). The Node runtime seeds pi-tui's
	// capability cache with it, so Pi's Markdown renders links as the host
	// terminal supports them.
	TerminalCapabilities *TerminalCapabilitiesPayload `json:"terminalCapabilities,omitempty"`
	// Theme is the host's active theme as extensions see it (ctx.ui.theme):
	// its name, foreground and background escape sequences by token, and
	// whether chalk styles draw. The Node runtime's theme helpers
	// (getSelectListTheme, highlightCode, keyHint, ...) color with it.
	Theme any `json:"theme,omitempty"`
	// Keybindings is Pi's keybinding table as the host resolved it: every
	// tui.* and app.* definition with the user's keybindings.json overrides.
	// The Node runtime installs it as pi-tui's keybindings manager, the one
	// Pi hands editor and custom-component factories and sets globally.
	Keybindings any `json:"keybindings,omitempty"`
}

StatePayload is the host's view of state visible to extensions through the upstream-faithful synchronous getters (pi.getActiveTools(), pi.getThinkingLevel(), ctx.isIdle(), ctx.getContextUsage(), etc.). It is sent with ReadyPayload at startup and re-sent via "state_update" notifies whenever the host knows it has changed. State fields carry explicit empty/null values so a snapshot clears prior values; session log pages remain incremental.

type Supervisor

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

Supervisor monitors extension process crashes and implements exponential backoff with a circuit breaker. After too many crashes in a window, the extension is disabled until manually re-enabled via /reload.

pig-specific: no upstream equivalent.

func NewSupervisor

func NewSupervisor(cfg SupervisorConfig) *Supervisor

NewSupervisor creates a crash supervisor with the given config.

func (*Supervisor) DisableReason

func (s *Supervisor) DisableReason() string

DisableReason returns the circuit breaker message, or empty if not disabled.

func (*Supervisor) IsDisabled

func (s *Supervisor) IsDisabled() bool

IsDisabled returns whether the circuit breaker has tripped.

func (*Supervisor) RecordCrash

func (s *Supervisor) RecordCrash() (time.Duration, error)

RecordCrash records a crash and returns the restart delay, or an error if the circuit breaker has tripped.

func (*Supervisor) RecordSuccess

func (s *Supervisor) RecordSuccess()

RecordSuccess resets the consecutive crash counter (process started and registered successfully).

func (*Supervisor) Reset

func (s *Supervisor) Reset()

Reset clears all crash history and re-enables the extension. Used by /reload.

type SupervisorConfig

type SupervisorConfig struct {
	MaxCrashes    int           // Default: 5
	CrashWindow   time.Duration // Default: 60s
	InitialDelay  time.Duration // Default: 2s
	MaxDelay      time.Duration // Default: 30s
	BackoffFactor float64       // Default: 2.0
}

SupervisorConfig configures crash recovery behavior.

func DefaultSupervisorConfig

func DefaultSupervisorConfig() SupervisorConfig

DefaultSupervisorConfig returns production defaults. pig divergence (D56): crash-restart window and backoff supervise the subprocess boundary; every restart and disable is reported through onCrash.

type TerminalCapabilitiesPayload

type TerminalCapabilitiesPayload struct {
	Images     string `json:"images,omitempty"` // "kitty", "iterm2", or empty for none
	TrueColor  bool   `json:"trueColor"`
	Hyperlinks bool   `json:"hyperlinks"`
}

TerminalCapabilitiesPayload mirrors pi-tui's TerminalCapabilities.

type TerminalInputArgs

type TerminalInputArgs struct {
	Data          string `json:"data"`
	EditorText    string `json:"editorText"`
	ToolsExpanded bool   `json:"toolsExpanded"`
}

TerminalInputArgs carries an ordered input and the UI values visible before its listener runs. Data and EditorText preserve UTF-16 units using WTF-8 in Go and surrogate escapes in JSON. Runtimes with synchronous local UI getters refresh those values before invoking the listener; host-query SDKs read the same live UI through their existing calls.

type ToolDecl

type ToolDecl struct {
	Name                string            `json:"name"`
	Label               string            `json:"label,omitempty"`
	Description         string            `json:"description"`
	Parameters          json.RawMessage   `json:"parameters"`                     // JSON Schema
	ConstrainedSampling json.RawMessage   `json:"constrained_sampling,omitempty"` // false | ConstrainedSamplingConfig (ai.ConstrainedSamplingConfig JSON); false/null/absent all disable
	ExecutionMode       string            `json:"execution_mode,omitempty"`       // "sequential" | "parallel"
	PromptSnippet       string            `json:"prompt_snippet,omitempty"`
	PromptGuidelines    []string          `json:"prompt_guidelines,omitempty"`
	Annotations         map[string]string `json:"annotations,omitempty"`
	Source              string            `json:"source,omitempty"` // pig additive (D23): per-tool source override; default: extension name
	// RenderShell is upstream ToolDefinition.renderShell: "self" when the
	// tool's renderers draw their own framing, else empty for "default".
	RenderShell string `json:"render_shell,omitempty"`
	// RendersCall and RendersResult report that the tool defines renderCall
	// and renderResult. The host asks for them with RequestRenderTool.
	RendersCall   bool `json:"renders_call,omitempty"`
	RendersResult bool `json:"renders_result,omitempty"`
	// BuiltInRenderers names the built-in tool whose host renderers draw the
	// halves the tool does not render itself: the Node runtime sets it for a
	// definition from Pi's create<Tool>ToolDefinition (D73).
	BuiltInRenderers string `json:"builtin_renderers,omitempty"`
	// ValidationParameters preserves non-enumerable TypeBox kinds separately from provider parameters.
	ValidationParameters json.RawMessage `json:"validation_parameters,omitempty"`
}

ToolDecl declares a tool the extension provides.

type ToolInfo

type ToolInfo struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Parameters  json.RawMessage `json:"parameters"`
	// PromptGuidelines is omitted when the definition has none, as upstream
	// copies an undefined definition.promptGuidelines.
	PromptGuidelines []string `json:"promptGuidelines,omitempty"`
	// SourceInfo is upstream's SourceInfo object: path, source, scope, origin
	// and an optional baseDir.
	SourceInfo extension.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, so the replicated state Node
	// extensions read omits it; the getAllTools host call keeps sending it
	// as "source" for SDKs released before sourceInfo existed.
	Source string `json:"-"`
}

ToolInfo is one entry of getAllTools on the wire. Mirrors upstream ToolInfo (types.ts): the tool definition's name, description, parameter schema and prompt guidelines, with the sourceInfo of whatever registered it.

type ToolRenderCardPayload

type ToolRenderCardPayload struct {
	Card string `json:"card"`
}

ToolRenderCardPayload names one tool card.

type ToolResult

type ToolResult struct {
	Content []ai.ToolResultMessageContent `json:"-"`
	Details json.RawMessage               `json:"details,omitempty"`
	IsError bool                          `json:"is_error,omitempty"`
	// Usage is upstream AgentToolResult.usage: the tool execution's own usage.
	Usage *ai.Usage `json:"usage,omitempty"`
	// Terminate mirrors upstream AgentToolResult.terminate: the agent stops
	// after the current tool batch when every result in it sets terminate.
	Terminate bool `json:"terminate,omitempty"`
	// Preview is an optional short summary shown when the tool result
	// is collapsed in the TUI. Extensions set this to provide a custom
	// collapsed view instead of the default tail-of-output preview.
	Preview string `json:"preview,omitempty"`
}

ToolResult retains the ordered text/image array returned by a subprocess tool. The SDK's text shorthand decodes as one text block, including an explicit empty string.

func (*ToolResult) UnmarshalJSON

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

type ToolUpdatePayload

type ToolUpdatePayload struct {
	RequestID string          `json:"request_id"`
	Result    json.RawMessage `json:"result"`
}

ToolUpdatePayload is the NotifyToolUpdate argument. Result has the shape of a ToolResult.

type TransportError

type TransportError struct {
	Extension string
	Operation string
	Err       error
}

TransportError reports a concrete socket read or write failure.

func (*TransportError) Error

func (e *TransportError) Error() string

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

type UIBridge

type UIBridge struct {

	// WatchSessionLog enrolls one extension in session-log replication and
	// returns the entries it has not seen. Set by the Host, which owns the
	// per-extension cursor and subscription flag.
	WatchSessionLog func(extName string, cursor int, complete bool) ([]json.RawMessage, int, bool, string)

	// OnStateChanged is called after a host-side change to the synchronous
	// getter surface that a subprocess extension cannot observe on its own,
	// such as an extension status set through ui.setStatus. Set by the Host
	// to its own BroadcastStateUpdate, which pushes a fresh state_update to
	// every connected extension. Mirrors upstream's setExtensionStatus,
	// which calls this.ui.requestRender() synchronously in the single
	// in-process runtime (interactive-mode.ts:2203); pig's footer factory
	// runs in a separate subprocess and only re-renders on a pushed
	// state_update, so the host must proactively push one.
	OnStateChanged func()
	// contains filtered or unexported fields
}

UIBridge translates extension→host call messages into real UI/action method invocations. It holds a reference to the host's extension.UIContext and HostCallbacks and manages PushProxy instances for widget components.

The bridge replaces the need for a narrow adapter interface: it directly calls the UIContext methods, which handle the "TUI not ready" case via the noop implementation (NoopUIContext returns sane zero values for every method).

pig-specific: no upstream equivalent.

func NewUIBridge

func NewUIBridge(invalidateTUI func()) *UIBridge

func (*UIBridge) AllWidgets

func (b *UIBridge) AllWidgets() map[string]*PushProxy

AllWidgets returns all widget proxies (for rendering).

func (*UIBridge) BindCommandActions

func (b *UIBridge) BindCommandActions(actions extension.CommandActions)

BindCommandActions binds the non-nil command-context actions to the host actions subprocess extensions call, as Runner.BindCommandActions does for in-process extensions. A nil action keeps the one already bound.

func (*UIBridge) ClearExtension

func (b *UIBridge) ClearExtension(extName string)

ClearExtension removes all widgets for a given extension (on crash/shutdown).

func (*UIBridge) ClearExtensionConn

func (b *UIBridge) ClearExtensionConn(extName string, owner *Conn)

func (*UIBridge) ForgetProviderRegistration

func (b *UIBridge) ForgetProviderRegistration(name string)

ForgetProviderRegistration drops a registered provider config. Upstream ModelRuntime.unregisterProvider.

func (*UIBridge) GetWidget

func (b *UIBridge) GetWidget(extName, key string) *PushProxy

GetWidget returns the PushProxy for a given extension:key pair, or nil.

func (*UIBridge) HandleCall

func (b *UIBridge) HandleCall(extName string, call *CallPayload) (*CallResultPayload, error)

HandleCall processes an extension→host call message and returns the result. This is the main dispatch point for ALL extension API methods:

  • UI methods: ui.notify, ui.setStatus, ui.select, ui.confirm, ui.input, ui.setWidget, ui.setWorkingIndicator, ui.setWorkingMessage, ui.setHiddenThinkingLabel, ui.setFooter, ui.setHeader, ui.setTitle, ui.custom, ui.pasteToEditor, ui.setEditorText, ui.getEditorText, ui.editor, ui.setEditorComponent, ui.addAutocompleteProvider, ui.onTerminalInput, ui.theme, ui.getAllThemes, ui.getTheme, ui.setTheme, ui.getToolsExpanded, ui.setToolsExpanded
  • Action methods: sendMessage, sendUserMessage, appendEntry, getSessionName, setSessionName, setLabel, getActiveTools, getAllTools, setActiveTools, refreshTools, getCommands, setModel, getThinkingLevel, setThinkingLevel

func (*UIBridge) HandleCallFrom

func (b *UIBridge) HandleCallFrom(extName string, owner *Conn, call *CallPayload) (*CallResultPayload, error)

func (*UIBridge) HandleNotify

func (b *UIBridge) HandleNotify(extName string, n *NotifyPayload)

HandleNotify routes a Node→Go fire-and-forget notification. Currently the only routed notifications are remote-overlay render/close events, but the surface is the natural extension point for future notification-only host APIs.

pig-specific: no upstream equivalent.

func (*UIBridge) HandleNotifyFrom

func (b *UIBridge) HandleNotifyFrom(extName string, owner *Conn, n *NotifyPayload)

func (*UIBridge) HandleWidgetPush

func (b *UIBridge) HandleWidgetPush(extName string, push *WidgetPushPayload)

HandleWidgetPush processes a widget_push message. A push with a width is a frame a component rendered at that width. A push without one is a string list widget (the Go, Rust and Python SDKs' setWidget(key, string[])), which the host lays out at its own width as Pi's setExtensionWidget does.

func (*UIBridge) Invalidate

func (b *UIBridge) Invalidate()

Invalidate requests a TUI render using the current host callback.

func (*UIBridge) ModelCatalog

func (b *UIBridge) ModelCatalog() []map[string]any

func (*UIBridge) ModelRegistryState

func (b *UIBridge) ModelRegistryState() map[string]any

ModelRegistryState is the registry snapshot an extension's synchronous ctx.modelRegistry reads answer from: the host's registry state (the catalog under "models", availability, provider auth and the registry error) and the provider configs extensions registered, in registration order. Upstream ModelRegistry reads the same state in process.

func (*UIBridge) PublishModelCatalog

func (b *UIBridge) PublishModelCatalog()

PublishModelCatalog sends the current registry snapshot to every connected extension. With no connection it builds nothing: a later connection receives its own snapshot from RegisterExtConn.

func (*UIBridge) RecordNativeProviderRegistration

func (b *UIBridge) RecordNativeProviderRegistration(name string, native NativeProviderDeclaration)

RecordNativeProviderRegistration publishes native ownership metadata.

func (*UIBridge) RecordProviderRegistration

func (b *UIBridge) RecordProviderRegistration(name string, config json.RawMessage)

RecordProviderRegistration records a provider config an extension registered. A re-registration merges its defined top-level values over the previous config and keeps the provider's place, as upstream ModelRuntime.registerProvider does with its extensionProviders map.

func (*UIBridge) RegisterExtConn

func (b *UIBridge) RegisterExtConn(extName string, conn *Conn)

RegisterExtConn associates an extension's socket connection with the bridge so input notifications generated by overlay surfaces can be forwarded back to the extension subprocess.

pig-specific: no upstream equivalent.

func (*UIBridge) SetActions

func (b *UIBridge) SetActions(actions *HostCallbacks)

SetActions sets the agent-loop callbacks. Thread-safe. Called after the agent session is fully initialized.

func (*UIBridge) SetHostAction

func (b *UIBridge) SetHostAction(key string, fn any)

SetHostAction sets a single host callback by name. Thread-safe. This allows the interactive mode to wire callbacks one-by-one without importing the HostCallbacks type (avoiding circular deps).

Accepted function signatures per key:

  • "getFlag": func(string, string) any
  • "getActiveTools": func() []string
  • "getAllTools": func() []ToolInfo
  • "getCommands": func() []CommandInfo
  • "getThinkingLevel": func() string
  • "setThinkingLevel": func(string)
  • "getContextUsage": func() *extension.ContextUsage
  • "getSystemPrompt": func() string
  • "getSessionName": func() string
  • "getSessionID": func() string
  • "getSessionFile": func() string
  • "getLeafID": func() string
  • "getEntries": func() []map[string]any
  • "exec": func(context.Context, string, []string, *extension.ExecOptions) (extension.ExecResult, error) OR func(string, []string, *extension.ExecOptions) (extension.ExecResult, error)
  • "sendMessage": func(extension.CustomMessageRef, SendMessageOptions) error
  • "sendUserMessage": func(any, SendUserMessageOptions) error
  • "appendEntry": func(string, any, *DirectEntryAppend) error
  • "setLabel": func(string, string) error
  • "setActiveTools": func([]string)
  • "refreshTools": func() error
  • "setModel": func(context.Context, string) (bool, error)
  • "isIdle": func() bool
  • "abort": func()
  • "hasPendingMessages": func() bool
  • "shutdown": func()
  • "compact": func(context.Context, *extension.CompactOptions)
  • "waitForIdle": func(context.Context) error
  • "reload": func(context.Context) error
  • "getModelAuth": func(context.Context, string, string) map[string]any
  • "complete": func(context.Context, map[string]any, map[string]any, map[string]any) (map[string]any, error)
  • "setSessionName": func(string)

func (*UIBridge) SetInvalidate

func (b *UIBridge) SetInvalidate(fn func())

SetInvalidate replaces the TUI invalidation callback. Thread-safe. Called by InteractiveMode after TUI creation to wire live rendering.

pig-specific: no upstream equivalent.

func (*UIBridge) SetKeybindingsFunc

func (b *UIBridge) SetKeybindingsFunc(fn func() any)

SetKeybindingsFunc registers the source of the host's resolved keybinding table, which every state snapshot carries.

func (*UIBridge) SetModelCatalog

func (b *UIBridge) SetModelCatalog(getModels func() []map[string]any, encodeModels func() (json.RawMessage, error))

SetModelCatalog installs equivalent value and JSON projections atomically. Publication uses the encoder without changing the value getter or its notification boundary. Replacing the getter through SetHostAction or SetActions clears the encoder. pig additive (D19): subprocess snapshot encoding reuses the same current model data without changing the extension API.

func (*UIBridge) SetNotifyFunc

func (b *UIBridge) SetNotifyFunc(fn func(message, level string))

SetNotifyFunc sets the function used to render notifications in the chat area. Thread-safe. Called by InteractiveMode after TUI creation.

func (*UIBridge) SetTerminalCapabilitiesFunc

func (b *UIBridge) SetTerminalCapabilitiesFunc(fn func() TerminalCapabilitiesPayload)

SetTerminalCapabilitiesFunc registers the source of the host terminal's resolved capabilities, sent to extensions with every state snapshot.

func (*UIBridge) SetThemeFunc

func (b *UIBridge) SetThemeFunc(fn func() any)

SetThemeFunc registers the source of the host's active theme palette, which every state snapshot carries.

func (*UIBridge) SetUIContext

func (b *UIBridge) SetUIContext(ctx extension.UIContext)

SetUIContext upgrades the UI context from noop to the real TUI. Thread-safe. Called by InteractiveMode after TUI creation.

func (*UIBridge) SetUIPromptScope

func (b *UIBridge) SetUIPromptScope(scope UIPromptScope)

SetUIPromptScope binds the runner that reports subprocess prompts. The host rebinds it when a reload replaces the runner. nil stops reporting.

func (*UIBridge) SetWidgetRequestFunc

func (b *UIBridge) SetWidgetRequestFunc(fn func(extName, key string, lines []string, opts extension.ExtensionWidgetOptions))

SetWidgetRequestFunc installs a mode-specific serialized-widget observer.

func (*UIBridge) SetWidgetSyncFunc

func (b *UIBridge) SetWidgetSyncFunc(fn func(widgets map[string]*PushProxy))

SetWidgetSyncFunc sets a callback invoked whenever an extension widget is set or cleared. The callback receives all current widget proxies. The host uses this to sync PushProxy components into the TUI layout. PushProxy implements Render(int)[]string + Invalidate() which matches tui.Component via structural typing.

func (*UIBridge) SetWidth

func (b *UIBridge) SetWidth(width int)

func (*UIBridge) Snapshot

func (b *UIBridge) Snapshot(flagNames []string, cursor int, wantSessionLog bool) *StatePayload

Snapshot returns the current host-side state visible to the extension via upstream-faithful synchronous getters. Missing usage stays absent; unknown token and percentage counts stay null.

The result is suitable for the protocol's StatePayload: callers send it at handshake time (embedded in ReadyPayload) and on host-side state changes via "state_update" notifies. Snapshot builds the state pushed to one extension. cursor is how many session entries that extension already holds. wantSessionLog reports whether it has ever read the log; when false no entries are sent, because an extension that never inspects the session would otherwise hold a full copy of it in resident memory for nothing.

func (*UIBridge) SyncAutocomplete

func (b *UIBridge) SyncAutocomplete(ctx context.Context, provider *extension.AutocompleteProvider) error

SyncAutocomplete gives an installed subprocess editor the same provider as the default editor. It runs off the UI loop and awaits the editor's synchronous setter.

type UIPromptScope

type UIPromptScope interface {
	BeginUIPrompt(kind extension.UIPromptKind, title string) (end func())
}

UIPromptScope records blocking extension UI prompts for the runner that emits ui_prompt_start and ui_prompt_end. [inproc.Runner] implements it.

upstream: runner.ts withUIPrompt wraps every ctx.ui select/confirm/input/ editor/custom call. Subprocess calls reach the terminal through this bridge rather than the runner's UI surface, so the bridge opens the scope.

type WidgetDecl

type WidgetDecl struct {
	Key string `json:"key"` // Widget slot key
}

WidgetDecl declares a widget the extension will push updates for.

type WidgetPushPayload

type WidgetPushPayload struct {
	Key   string   `json:"key"`             // Widget slot key (matches WidgetDecl.Key)
	Lines []string `json:"lines"`           // Frame rows or string list entries (may contain ANSI)
	Width int      `json:"width,omitempty"` // Width the frame was rendered at (0 = a string list)
}

WidgetPushPayload carries widget lines from extension to host. With a width the lines are a frame a component rendered at that width; without one they are a string list the host lays out as Pi's setWidget(key, string[]) does.

Directories

Path Synopsis
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.

Jump to

Keyboard shortcuts

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