subprocess

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: MIT Imports: 44 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
	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"
)

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

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.

Types

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. Build retains the background-context compatibility 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
}

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 extension configs into runtime cells. Today explicit factory-style Go, Rust, Python, and Node SDK extensions are packable. Everything else remains an isolated subprocess. Quarantined packed cell keys are fissioned back to isolated cells.

A pack group only ever spans a *contiguous* run of the same packGroupKey in configured order (CNEO-001). Upstream loader.ts activates each extension strictly in path order (loader.ts:613-627): pig only starts a later cell's process once every earlier cell has committed (stageCellsInOrder), so activation order across cells matches configured order exactly when, and only when, a cell's Order is the index of the earliest configured extension that ends up in it *and no other cell sits between that extension and the next one configured*. Grouping by key alone (ignoring what sits between two same-key extensions) breaks that: [NodeA, GoB(isolated), NodeC] would otherwise pack NodeA+NodeC into one cell ordered at NodeA's index, activating NodeC (in the same process, same install loop) before GoB even though NodeC was configured after GoB. This splits at every interleaving boundary instead, giving up packing NodeA with NodeC in that case (they land in two separate Node cells, so two Node processes) in exchange for exact activation order: the common case, a run of same-language extensions actually configured together, still packs into one cell/process exactly as before. pig additive (D20): packed runtime cells are Pig's downstream-only subprocess process-sharing optimizer; each extension still speaks the current subprocess wire.

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 type-stripping 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
}

CommandDecl declares a slash command the extension provides.

type CommandInfo

type CommandInfo struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

CommandInfo is a simplified command metadata struct.

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) 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 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"`
}

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 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) 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

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.

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

FlagDefault returns the default value for a registered extension flag. 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) 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) 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) SetProviderCallbacks

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

SetProviderCallbacks registers callbacks for extension-declared providers.

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 gracefully shuts down all managed extensions.

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
	AppendEntry func(customType string, data any) 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()

	// 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

	// 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)

	// 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 MessageRendererDecl

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

MessageRendererDecl declares a custom message renderer.

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.

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 struct {
	Refresh   string `json:"refresh"`
	Access    string `json:"access"`
	Expires   int64  `json:"expires"`
	ProjectID string `json:"projectId,omitempty"`
}

OAuthCredentialsWire is the wire shape of OAuth credentials. Matches ai.OAuthCredentials so the host can marshal that type directly; the SDK mirrors these tags.

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 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 {
	Name   string          `json:"name"`
	Config json.RawMessage `json:"config"`
}

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 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. This NEVER blocks on I/O: guaranteed <1μs. Satisfies the tui.Component interface.

Returns a defensive copy so callers cannot corrupt the cache.

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"`

	// 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 RemoteOverlayInputPayload

type RemoteOverlayInputPayload struct {
	Key  string `json:"key"`
	Data string `json:"data"`
}

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"`
	// 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 RenderResult

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

RenderResult is the structured result from a renderer execution.

type RequestPayload

type RequestPayload struct {
	Method     string          `json:"method"` // "tool_call", "event", "command", "shortcut", "render_message", "render_entry"
	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
}

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
	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. 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, 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 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,omitempty"`
	SessionFile string `json:"sessionFile,omitempty"`
	LeafID      string `json:"leafId,omitempty"`
	// 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"`
}

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,omitempty"`
	AllTools            []string                   `json:"allTools,omitempty"`
	Commands            []string                   `json:"commands,omitempty"`
	ThinkingLevel       string                     `json:"thinkingLevel,omitempty"`
	Model               map[string]any             `json:"model,omitempty"`
	Session             *SessionStatePayload       `json:"session,omitempty"`
	IsIdle              bool                       `json:"isIdle"`
	ProjectTrusted      bool                       `json:"projectTrusted"`
	HasPendingMessages  bool                       `json:"hasPendingMessages"`
	ContextUsage        *extensionContextUsageDTO  `json:"contextUsage,omitempty"`
	SystemPrompt        string                     `json:"systemPrompt,omitempty"`
	SystemPromptOptions json.RawMessage            `json:"systemPromptOptions,omitempty"`
	Flags               map[string]json.RawMessage `json:"flags,omitempty"`
	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,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.

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 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"
	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
}

ToolDecl declares a tool the extension provides.

type ToolInfo

type ToolInfo struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Source      string `json:"source,omitempty"`
}

ToolInfo is a simplified tool metadata struct for getActiveTools/getAllTools.

type ToolResult

type ToolResult struct {
	Content string            `json:"-"`
	Images  []ai.ImageContent `json:"-"`
	Details json.RawMessage   `json:"details,omitempty"`
	IsError bool              `json:"is_error,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 is the structured result from a tool execution, carried inside ResponsePayload.Result. Content is a string or upstream's block array of {type:"text",text} and {type:"image",data,mimeType}. Text blocks join with newlines, unchanged; image blocks become Images in order.

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) 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 by updating the cached lines.

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) 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) 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 OR func() []map[string]string
  • "getCommands": func() []CommandInfo OR func() []map[string]string
  • "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) error
  • "setLabel": func(string, string) error
  • "setActiveTools": func([]string)
  • "refreshTools": func()
  • "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) 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) 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. It reads through whatever HostCallbacks are registered; missing callbacks contribute zero values.

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.

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"`           // Pre-rendered lines (may contain ANSI)
	Width int      `json:"width,omitempty"` // Width the lines were rendered at (0 = unknown)
}

WidgetPushPayload carries rendered widget lines from extension to host.

Jump to

Keyboard shortcuts

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