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.
Process environment ¶
The host starts every extension process with its own environment plus the entries below and runtime-specific ones (harness, Node runtime, Python path). An isolated process gets PIG_EXT_SOCKET, the address above, and PIG_EXT_NAME, the extension's name; a packed cell process gets one PIG_EXT_SOCKET_<NAME> per member instead (runtimecell.SocketEnvName). PIG_EXT_HOST_INFO (set by Host.SetHostInfo; absent when the host has none) is a JSON object {"agentDir", "configDirName", "version", "packageDir", "shell"}: Pi's getAgentDir(), CONFIG_DIR_NAME, VERSION, getPackageDir() and the default getShellConfig() as the host resolved them, which an SDK returns from before its factory runs because the ready message comes later. A Node extension answers getAgentDir() and CONFIG_DIR_NAME from its environment (shims/pig-config.mjs) and VERSION from the bundled Pi package (shims/pi-dist/pi-coding-agent/config.js).
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
- Variables
- func BuiltinToolDefinitionJSON(argsJSON []byte) ([]byte, error)
- func BuiltinToolExecute(ctx context.Context, argsJSON []byte, binDir string, peer BuiltinToolPeer) ([]byte, error)
- func BuiltinToolPrepareArgumentsJSON(argsJSON []byte) ([]byte, error)
- func CopyToClipboard(text string) error
- func CurrentCacheEntries(configs []ExtConfig, cacheRoot string) (map[string]struct{}, []error)
- func CurrentNodePackedCellEntry(cacheRoot, cellKey string, exts []nodeExtension) (string, bool, error)
- func DefaultStagedSDKVerifier(configRoot string) func(stagedDir, buildType string) error
- func EnableEditorViews()
- func EnableLisp()
- func EnableTuiAltScreens()
- func FormatCrashNotice(name string, delay time.Duration, disabled bool, reason string) string
- func GenerateUnifiedPatch(path, oldContent, newContent string, contextLines *int) string
- func GraphVirtualModelRoute(scope SessionGraphScope, callbackID string) extension.ModelRouteFunc
- func GroupLoadErrors(errs []error) []error
- func HighlightCodeLines(code, lang string, palette []byte) (lines []string, err error)
- func IsBuildFailureGroupMessage(message string) bool
- func ListenExtension(sockPath string, _ bool) (net.Listener, string, error)
- func LoadThemeJSON(name *string) ([]byte, error)
- func LocalExec(ctx context.Context, args BuiltinToolLocalExecArgs, binDir string, ...) (*int, error)
- func ParseDateMs(text string) (float64, bool)
- func ParseFrontmatterJSON(content string) (frontmatterJSON []byte, body string, err error)
- func RunsFused(cfg ExtConfig) bool
- func SetClipboardCopier(copy func(text string) error)
- func SetConversationRenderers(renderers ConversationRenderers)
- func SetDefaultStagedSDKVerifier(factory func(configRoot string) func(stagedDir, buildType string) error)
- func SetEarlyModelStream(...)
- func SetFusedResolver(r FusedResolver)
- func SetThemeLoader(load func(name *string) any)
- func SetTypeEngine(serve func(request []byte) []byte)
- func SetTypeScriptRuntimeSetting(id string)
- func SetViewLoaderAnimation(enabled bool)
- func StagedSDKFingerprint(sdkDir, buildType string) (string, error)
- func TypeScriptRuntimeRequest() tsruntime.Request
- func UnavailableNestedCall(callerID, name string) extension.AgentToolCallOutcome
- func WithTerminalInputState(ctx context.Context, editorText string, toolsExpanded bool) context.Context
- type BashOperationsRelease
- type BeforeAgentStartResponsePayload
- type BoundaryEventResultPayload
- type BuildFailureGroup
- type BuildResult
- type Builder
- func (b *Builder) Build(name, srcDir string) (*BuildResult, error)
- func (b *Builder) BuildContext(ctx context.Context, name, srcDir string) (*BuildResult, error)
- func (b *Builder) CurrentCacheEntry(name, srcDir string) (string, bool, error)
- func (b *Builder) SetStagedSDKVerifier(fn func(stagedDir, buildType string) error)
- func (b *Builder) WithGoListing(srcDir string, use func(GoListing) error) error
- type BuiltinToolCallback
- type BuiltinToolDefinitionArgs
- type BuiltinToolDefinitionResult
- type BuiltinToolExecData
- type BuiltinToolExecuteArgs
- type BuiltinToolLocalExecArgs
- type BuiltinToolLocalExecResult
- type BuiltinToolOptions
- type BuiltinToolPeer
- type BuiltinToolPrepareArgumentsArgs
- type CallPayload
- type CallResultPayload
- type CallableToolsResult
- type CancelPayload
- type CellSpec
- func (c CellSpec) GoExtensions() ([]runtimecell.GoExtension, error)
- func (c CellSpec) LispExtensions() ([]runtimecell.LispExtension, error)
- func (c CellSpec) NodeExtensions() ([]nodeExtension, error)
- func (c CellSpec) PythonExtensions() ([]runtimecell.PythonExtension, error)
- func (c CellSpec) RustExtensions() ([]runtimecell.RustExtension, error)
- type CellStrategy
- type ChildScopedModel
- type ChildSession
- type ChildSessionCreate
- type ChildSessionEmit
- type ChildSessionEmitResult
- type ChildSessionEvent
- type ChildSessionFactory
- type ChildSessionImage
- type ChildSessionInfo
- type ChildSessionManagerHandle
- type ChildSessionPrompt
- type ChildSessionPromptResult
- type ChildSessionQueue
- type ChildSessionRef
- type ChildSessionRequest
- type ChildSessionResources
- type ChildSessionStartEvent
- type ChildSessionState
- type CommandDecl
- type CommandInfo
- type Conn
- func (c *Conn) Close(reason string) error
- func (c *Conn) Done() <-chan struct{}
- func (c *Conn) Incoming() <-chan *Envelope
- func (c *Conn) Name() string
- func (c *Conn) RecentOversizedFrame() (uint64, bool)
- func (c *Conn) Request(ctx context.Context, env *Envelope) (*Envelope, error)
- func (c *Conn) Retire(reason string) error
- func (c *Conn) Send(env *Envelope) error
- func (c *Conn) Start(ctx context.Context)
- type ConversationRenderers
- type ConvertToPngArgs
- type CopyToClipboardArgs
- type DirectEntryAppend
- type EditorPayload
- type EmbeddedCell
- type EmbeddedExtension
- type EntryRendererDecl
- type Envelope
- type ErrorInfo
- type EventBusRetention
- type EventStream
- type ExecArgs
- type ExecCancel
- type ExecuteToolArgs
- type ExecuteToolCancel
- type ExecuteToolOutcome
- type ExecuteToolUpdate
- type ExtConfig
- func DisambiguateIdentities(configs []ExtConfig) []ExtConfig
- func ResolveExtConfig(path string) (ExtConfig, *extsource.Definition, error)
- func ResolveExtConfigWithIdentity(path, expectedName string) (ExtConfig, *extsource.Definition, error)
- func ResolveExtConfigWithResolver(path, expectedName string, resolve extsource.ResolveFunc) (ExtConfig, *extsource.Definition, error)
- func UnresolvedExtConfig(path string, err error) ExtConfig
- type ExtensionLoadError
- type ExtensionUnresponsiveError
- type FacetBridge
- type FacetBridgeOptions
- type FactoryLoadError
- type FileMutationEnterArgs
- type FileMutationEnterResult
- type FileMutationExitArgs
- type FlagDecl
- type FooterDataPayload
- type FrameTooLargeError
- type FusedResolver
- type GenerateDiffStringArgs
- type GenerateDiffStringResult
- type GenerateUnifiedPatchArgs
- type GenerateUnifiedPatchResult
- type GoListing
- type HandlerDecl
- type HandlerStalledError
- type HandlerYieldedPayload
- type HighlightCodeArgs
- type HighlightCodeResult
- type Host
- func (h *Host) BroadcastStateUpdate()
- func (h *Host) Builder() *Builder
- func (h *Host) EndInput()
- func (h *Host) EventBusRetention() EventBusRetention
- func (h *Host) ExtensionCount() int
- func (h *Host) Extensions() []extension.Extension
- func (h *Host) FlagDefault(extName, flagName string) any
- func (h *Host) FlushCommands()
- func (h *Host) Invalidate(message string)
- func (h *Host) IsShuttingDown() bool
- func (h *Host) LastReloadReport() *ReloadReport
- func (h *Host) Load(ctx context.Context, cfg ExtConfig) (*extension.Extension, error)
- func (h *Host) LoadAll(ctx context.Context, configs []ExtConfig) ([]extension.Extension, []error)
- func (h *Host) LoadEmbeddedCells(ctx context.Context, cells []EmbeddedCell) ([]extension.Extension, []error)
- func (h *Host) LoadErrors() []string
- func (h *Host) LoadFinalExtensionSet(ctx context.Context, configs, preloaded []ExtConfig) ([]extension.Extension, []error)
- func (h *Host) LoadGoPackedCell(ctx context.Context, cell *runtimecell.GoPackedCell) ([]extension.Extension, error)
- func (h *Host) LoadInProcess(ctx context.Context, cfg ExtConfig, serve func(net.Conn) error) (*extension.Extension, error)
- func (h *Host) LoadLispPackedCell(ctx context.Context, cell *runtimecell.LispPackedCell) ([]extension.Extension, error)
- func (h *Host) LoadNodePackedCell(ctx context.Context, cell *nodePackedCell) ([]extension.Extension, error)
- func (h *Host) LoadPythonPackedCell(ctx context.Context, cell *runtimecell.PythonPackedCell) ([]extension.Extension, error)
- func (h *Host) LoadRustPackedCell(ctx context.Context, cell *runtimecell.RustPackedCell) ([]extension.Extension, error)
- func (h *Host) NotifyHeight(height int)
- func (h *Host) NotifyWidth(width int)
- func (h *Host) OAuthProviderNames(extName string) []string
- func (h *Host) ProviderNames(extName string) []string
- func (h *Host) QuarantinedCells() map[string]string
- func (h *Host) Reload(ctx context.Context) ([]extension.Extension, error)
- func (h *Host) Retain()
- func (h *Host) Runtime() *extension.ExtensionRuntime
- func (h *Host) SessionGraphObjectOf(conn *Conn, handle string) (SessionGraphObject, bool)
- func (h *Host) SetBackgroundCallGate(gate func() <-chan struct{})
- func (h *Host) SetCallHandler(fn func(extName string, call *CallPayload) (*CallResultPayload, error))
- func (h *Host) SetCommandSuspendHandler(fn func(suspended int))
- func (h *Host) SetCommandWindowHandler(fn func(suspended int))
- func (h *Host) SetConfigLoader(fn func() ([]ExtConfig, error))
- func (h *Host) SetCrashHandler(fn func(name string, delay time.Duration, disabled bool, reason string))
- func (h *Host) SetHeightFunc(fn func() int)
- func (h *Host) SetHostInfo(info HostInfo)
- func (h *Host) SetInboundObserver(fn func(extName string, env *Envelope))
- func (h *Host) SetMode(mode string)
- func (h *Host) SetNativeProviderCallback(register func(context.Context, *extension.NativeProvider) error) []*extension.ExtensionError
- func (h *Host) SetOutboundObserver(fn func(extName string, frame []byte))
- func (h *Host) SetProviderCallbacks(register func(name string, config extension.ProviderConfig) error, ...) []*extension.ExtensionError
- func (h *Host) SetReplacementHost(resolve func() *Host)
- func (h *Host) SetRuntimeDrainHandler(fn func())
- func (h *Host) SetRuntimeRetention(r *RuntimeRetention)
- func (h *Host) SetSessionGraph(backend SessionGraphBackend)
- func (h *Host) SetSettleTailHandler(fn func(suspended int))
- func (h *Host) SetStartupTrace(mark func(string))
- func (h *Host) SetTimerTurns(turns *jsloop.Turns)
- func (h *Host) SetToolRenderersResolvedFunc(fn func(toolName string))
- func (h *Host) SetUIBridge(bridge *UIBridge)
- func (h *Host) SetWidthFunc(fn func() int)
- func (h *Host) Shutdown(reason string)
- func (h *Host) TerminateProcesses()
- func (h *Host) TypeScriptRuntimeSelections() map[string]tsruntime.Selection
- func (h *Host) UseRuntime(runtime *extension.ExtensionRuntime)
- type HostCallbacks
- type HostInfo
- type ImageResult
- type InvalidateArgs
- type LoadError
- type LoadThemeArgs
- type LoadThemeResult
- type LoopTurnArgs
- type MarkdownTransformPayload
- type McpServerDecl
- type McpServerRef
- type McpServersResult
- type MessageRendererDecl
- type ModelStreamCall
- type ModelStreamCallback
- type NativeProviderDeclaration
- type NotifyPayload
- type OAuthAPIKeyResult
- type OAuthAuthInfoWire
- type OAuthCredentialStatusResult
- type OAuthCredentialsWire
- type OAuthDeleteResult
- type OAuthDeviceCodeInfoWire
- type OAuthInputResult
- type OAuthProgressWire
- type OAuthPromptWire
- type OAuthSelectOptionWire
- type OAuthSelectPromptWire
- type OAuthSignalReleaseArgs
- type OAuthStoreResult
- type OwnThinkingRunsPayload
- type ParseDateArgs
- type ParseDateResult
- type ParseFrontmatterArgs
- type ParseFrontmatterResult
- type PingPayload
- type PongPayload
- type ProviderDecl
- type ProviderOAuthConfig
- type ProviderObjectAuthDeclaration
- type ProviderObjectAuthMethodDeclaration
- type ProviderObjectCall
- type PushProxy
- func (p *PushProxy) Clear()
- func (p *PushProxy) FrontendView(width int) *frontend.View
- func (p *PushProxy) Invalidate()
- func (p *PushProxy) IsFrame() bool
- func (p *PushProxy) Lines() []string
- func (p *PushProxy) Render(width int) []string
- func (p *PushProxy) UpdateContent(content []string)
- func (p *PushProxy) UpdateLines(lines []string)
- func (p *PushProxy) UpdateLinesAt(lines []string, width int)
- func (p *PushProxy) UpdateView(view *viewSurface, linesWidth int)
- func (p *PushProxy) WidgetLayout() (placement string, order uint64)
- type ReadyPayload
- type RegisterPayload
- type ReloadCellReport
- type ReloadReport
- type RemoteOverlayClosePayload
- type RemoteOverlayControlPayload
- type RemoteOverlayFocusPayload
- type RemoteOverlayFocusResult
- type RemoteOverlayInputPayload
- type RemoteOverlayMousePayload
- type RemoteOverlayOpenPayload
- type RemoteOverlayRenderPayload
- type RemoteOverlayShowPayload
- type RemoteOverlayTargetPayload
- type RenderResult
- type RenderToolContent
- type RenderToolContext
- type RenderToolPayload
- type RenderToolResult
- type RequestPayload
- type RequestStatePayload
- type ResizeImageArgs
- type ResolveToolRenderersPayload
- type ResolvedToolRenderers
- type ResponsePayload
- type RuntimeRetention
- type SendMessageOptions
- type SendUserMessageOptions
- type SessionGraphBackend
- type SessionGraphCall
- type SessionGraphCallbackArgs
- type SessionGraphHandle
- type SessionGraphNew
- type SessionGraphObject
- type SessionGraphReleaser
- type SessionGraphScope
- type SessionGraphStreamer
- type SessionStatePayload
- type SetupArgs
- type ShellInfo
- type ShortcutDecl
- type ShutdownPayload
- type StatePayload
- type Supervisor
- type SupervisorConfig
- type TerminalCapabilitiesPayload
- type TerminalInputArgs
- type TimerDeferAckArgs
- type TimerDeferArgs
- type ToolCallResponsePayload
- type ToolDecl
- type ToolInfo
- type ToolInfoReachesTools
- type ToolLoadoutPayload
- type ToolReachesToolsArgs
- type ToolRenderCardPayload
- type ToolRenderersDecl
- type ToolRenderersPayload
- type ToolResult
- type ToolUpdatePayload
- type TransportError
- type TypeEngineArgs
- type UIBridge
- func (b *UIBridge) AllWidgets() map[string]*PushProxy
- func (b *UIBridge) BatchModelCatalogPublication() func()
- func (b *UIBridge) BindCommandActions(actions extension.CommandActions)
- func (b *UIBridge) ClearExtension(extName string)
- func (b *UIBridge) ClearExtensionConn(extName string, owner *Conn)
- func (b *UIBridge) ForgetProviderRegistration(name string)
- func (b *UIBridge) GetWidget(extName, key string) *PushProxy
- func (b *UIBridge) HandleCall(extName string, call *CallPayload) (*CallResultPayload, error)
- func (b *UIBridge) HandleCallFrom(extName string, owner *Conn, call *CallPayload) (*CallResultPayload, error)
- func (b *UIBridge) HandleNotify(extName string, n *NotifyPayload)
- func (b *UIBridge) HandleNotifyFrom(extName string, owner *Conn, n *NotifyPayload)
- func (b *UIBridge) HandleWidgetPush(extName string, conn *Conn, push *WidgetPushPayload)
- func (b *UIBridge) HostStateChanged()
- func (b *UIBridge) Invalidate()
- func (b *UIBridge) ModelCatalog() []json.RawMessage
- func (b *UIBridge) ModelRegistryState() map[string]any
- func (b *UIBridge) PublishModelCatalog()
- func (b *UIBridge) RecordNativeProviderRegistration(name string, native NativeProviderDeclaration)
- func (b *UIBridge) RecordProviderRegistration(name string, config json.RawMessage) (withdraw func())
- func (b *UIBridge) RegisterExtConn(extName string, conn *Conn, wantsModelRegistry bool)
- func (b *UIBridge) RemoveWidget(key string)
- func (b *UIBridge) RunSignal() context.Context
- func (b *UIBridge) RunSignalChanged()
- func (b *UIBridge) SetActions(actions *HostCallbacks)
- func (b *UIBridge) SetFrontend(on bool)
- func (b *UIBridge) SetHostAction(key string, fn any)
- func (b *UIBridge) SetInvalidate(fn func())
- func (b *UIBridge) SetKeybindingsFunc(fn func() any)
- func (b *UIBridge) SetModelCatalog(getModels func() []json.RawMessage, ...)
- func (b *UIBridge) SetNotifyFunc(fn func(message, level string))
- func (b *UIBridge) SetTerminalCapabilitiesFunc(fn func() TerminalCapabilitiesPayload)
- func (b *UIBridge) SetThemeFunc(fn func() any)
- func (b *UIBridge) SetUIContext(ctx extension.UIContext)
- func (b *UIBridge) SetUIPromptScope(scope UIPromptScope)
- func (b *UIBridge) SetWidgetClearFunc(fn func(key string))
- func (b *UIBridge) SetWidgetRequestFunc(...)
- func (b *UIBridge) SetWidgetSyncFunc(fn func(widgets map[string]*PushProxy))
- func (b *UIBridge) SetWidth(width int)
- func (b *UIBridge) Snapshot(flagNames []string, cursor int, wantSessionLog bool) *StatePayload
- func (b *UIBridge) StopFrontendPushes()
- func (b *UIBridge) SyncAutocomplete(ctx context.Context, provider *extension.AutocompleteProvider) error
- type UICancelDialog
- type UIPromptScope
- type UserBashExecArgs
- type UserBashExecData
- type UserBashExecResult
- type ViewAssistantMessage
- type ViewAutocomplete
- type ViewBashComplete
- type ViewContentBlock
- type ViewCursor
- type ViewEventExtras
- type ViewEventPayload
- type ViewEvictedPayload
- type ViewImageData
- type ViewImageRef
- type ViewItem
- type ViewList
- type ViewListItem
- type ViewLoaderIndicator
- type ViewMouseRegion
- type ViewNode
- type ViewPayload
- type ViewProgress
- type ViewSelectLayout
- type ViewSkill
- type ViewSlashCommand
- type ViewStackEntry
- type ViewTextStyle
- type ViewToolResult
- type ViewWidgetFields
- type VirtualModelDecl
- type VirtualModelRef
- type VirtualModelRouteArgs
- type VirtualModelRouteFailed
- type VirtualModelRoutePrevious
- type VirtualModelRouteRequest
- type VirtualModelRouteResult
- type WidgetPushPayload
- type WithSessionArgs
Constants ¶
const ( // Extension → host. NotifyEditorInstall = "ui.editor.install" NotifyEditorOptions = "ui.editor.options" 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" NotifyEditorInvalidate = "ui.editor.invalidate" 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.
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.
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.
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, or a provider object's manual_code AuthPrompt. 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.
const ( LoadPhaseImport = "import" LoadPhaseFactory = "factory" )
Load phases of a FactoryLoadError.
const ( CallUICustom = "ui.custom" // pig additive (D60): typed native login crosses the subprocess boundary. CallUISetLogin = "ui.setLogin" // CallUIBell rings the terminal bell of the interactive terminal; it does nothing without one. CallUIBell = "ui.bell" // pig divergence (D2): an extension's sprite joins /sprite. CallUIRegisterSprite = "ui.registerSprite" NotifyUICustomInput = "ui.custom.input" NotifyUICustomRender = "ui.custom.render" NotifyUICustomClose = "ui.custom.close" NotifyUICustomOpened = "ui.custom.opened" CallUICustomControl = "ui.custom.control" // NotifyUICustomMouse (host→ext) hands a fullscreen // mouse event to a ui.custom component that takes the mouse, as Pi's // renderer calls its handleMouse. NotifyUICustomMouse = "ui.custom.mouse" // NotifyUICustomFocus (host→ext) reports that a mounted ui.custom component lost or regained TUI focus, in order with its input: // another custom component, dialog or overlay opened over it, or the one over it closed. The extension sets the component's // focused flag and the handle's isFocused as Pi's TUI.setFocus does, and renders again. NotifyUICustomFocus = "ui.custom.focus" // CallUICustomShowOverlay, CallUICustomHideOverlay and CallUICustomSetFocus (ext→host, synchronous) are Pi's TUI.showOverlay, // hideOverlay and setFocus (tui.ts:598-842) on the tui a ui.custom factory receives. showOverlay mounts a raw overlay for a // component of the extension under its own key, with no ui.custom call behind it: its frames, input, focus and controls use // the ui.custom messages with that key, and its handle's hide (ui.custom.control) ends it. CallUICustomShowOverlay = "ui.custom.showOverlay" CallUICustomHideOverlay = "ui.custom.hideOverlay" CallUICustomSetFocus = "ui.custom.setFocus" // CallTuiAlt (ext→host) drives a TuiAltScreen the extension constructed (pi-tui's alternate-screen host) and RequestTuiAltCallback // (host→ext request) asks the extension for what it owns: its Terminal, its components and its listeners. A tui.alt call the extension makes while // it serves a callback names that request as its parent (CallPayload.ParentRequestID): when the host's frame goroutine sent the callback (a // component's render, an overlay's visible callback, a style callback, a terminal write, an invalidate or focus it triggered), that goroutine runs // the call at once, while it holds the frame lock, as Pi's render calls the screen. From such a callback the calls render, renderNow, start, stop, // copyActiveSelectionToClipboard, queryTerminalColors and input fail (D208). CallTuiAlt = "tui.alt" RequestTuiAltCallback = "tui.alt.cb" )
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.
const ( // NotifyUIViewEvent (host→ext) reports a callback of an interactive view // node (select-list, settings-list) of a ui.custom frame, in firing // order after every ui.custom.input sent before it. NotifyUIViewEvent = "ui.view.event" // NotifyUIViewEvicted (host→ext) reports image refs whose bytes the // host dropped; the next frame that references one sends its data again. NotifyUIViewEvicted = "ui.view.evicted" )
pig additive (D107): the extension component kit. A view describes an extension surface as Pi's tui components. With lines absent it is authoritative: the host renders it with its tui ports. With lines present (Node) it annotates them and survives only when rendering it reproduces them byte for byte. See docs/plan/extension-component-kit.md.
const ( ViewKindContainer = "container" ViewKindBox = "box" ViewKindText = "text" ViewKindTruncatedText = "truncated-text" ViewKindMarkdown = "markdown" ViewKindSpacer = "spacer" ViewKindDynamicBorder = "dynamic-border" ViewKindSelectList = "select-list" ViewKindSettingsList = "settings-list" ViewKindImage = "image" ViewKindLoader = "loader" ViewKindHStack = "hstack" ViewKindVStack = "vstack" ViewKindLines = "lines" // The conversation kinds mirror the coding-agent components Pi exports // to extensions (UserMessageComponent, AssistantMessageComponent, // ToolExecutionComponent, BashExecutionComponent and renderDiff in a // Text). ViewKindUserMessage = "user-message" ViewKindAssistantMessage = "assistant-message" ViewKindToolExecution = "tool-execution" ViewKindBashExecution = "bash-execution" ViewKindDiff = "diff" )
View node kinds. Each mirrors the upstream pi-tui (or coding-agent DynamicBorder) component of the same name; ViewKindLines is an opaque range of rows a custom render(width) drew.
const ( // ViewToolDefinitionBuiltin is the built-in tool's definition when the // tool name has one, and a definition without renderers otherwise: the // card the main transcript draws for a tool without its own renderers. ViewToolDefinitionBuiltin = "builtin" // ViewToolDefinitionEmpty is a definition without renderers ({}). ViewToolDefinitionEmpty = "empty" )
Tool definitions of a tool-execution node: the renderers a closure-free tool definition names.
const ( ViewEventSelect = "select" ViewEventCancel = "cancel" ViewEventSelectionChange = "selectionChange" ViewEventChange = "change" )
View event types: the upstream callbacks of SelectList (onSelect, onCancel, onSelectionChange) and SettingsList (onChange, onCancel).
const ( // CallChildSessionCreate creates a session. Args is a ChildSessionCreate and the result a ChildSessionInfo. A closed connection refuses it with ChildSessionClosedMessage. CallChildSessionCreate = "childSession.create" // CallChildSessionPrompt runs AgentSession.prompt. Args is a ChildSessionPrompt and the result a ChildSessionPromptResult. It returns when the run has settled, as Pi's Promise does, and every event of the run has been sent before the result. CallChildSessionPrompt = "childSession.prompt" // CallChildSessionQueue runs AgentSession.steer or followUp. Args is a ChildSessionQueue. CallChildSessionQueue = "childSession.queue" // CallChildSessionAbort runs AgentSession.abort, which returns once the session is idle. Args is a ChildSessionRef. CallChildSessionAbort = "childSession.abort" // CallChildSessionDispose runs AgentSession.dispose. Args is a ChildSessionRef. A disposed session is gone: later calls on it fail with ChildSessionUnknownMessage, and no later event is sent. CallChildSessionDispose = "childSession.dispose" // CallChildSessionBindExtensions runs AgentSession.bindExtensions({}) for a session whose resources loaded extensions: they start headless (no UI) and receive session_start. Args is a ChildSessionRef. CallChildSessionBindExtensions = "childSession.bindExtensions" // CallChildSessionState reads the session's current state. Args is a ChildSessionRef and the result a ChildSessionState. CallChildSessionState = "childSession.state" // CallChildSessionMessages reads AgentSession.messages. Args is a ChildSessionRef and the result is the array of messages in Pi's shape. CallChildSessionMessages = "childSession.messages" )
Child session calls (ext→host). Args and results are the types named by each constant.
const ( // ChildSessionClosedMessage is Node's message for a connection that closed (independent-session-owner.mjs). ChildSessionClosedMessage = "Extension connection is closed" // ChildSessionClosedWhileCreatingMessage is Node's message for a connection that closed while a session was being created. ChildSessionClosedWhileCreatingMessage = "Extension connection closed while creating a Session" // ChildSessionUnknownMessage answers a call that names no live session of the connection. ChildSessionUnknownMessage = "Unknown or disposed child session" )
Messages the host answers with, which every SDK raises as the call's error.
const ( // CallChildSessionEmit runs `session.extensionRunner.emit(event)` when the session's extensions have a handler for the event's type (`hasHandlers(type)`, then `emit(event)`, as agent-session-runtime.ts does for session_before_switch, session_before_fork and, through emitSessionShutdownEvent, session_shutdown). Args is a ChildSessionEmit and the result a ChildSessionEmitResult. It returns when the handlers settled. CallChildSessionEmit = "childSession.emit" // CallChildSessionRefreshContext runs AgentSession.refreshContext: the session's finalized transcript is read again from its log, which an extension appended to through the session's SessionManager. Args is a ChildSessionRef. CallChildSessionRefreshContext = "childSession.refreshContext" // CallChildSessionSessionManager reads AgentSession.sessionManager: the result is a ChildSessionManagerHandle, the session graph handle of the log the session appends to. Every call returns a handle to the same log. CallChildSessionSessionManager = "childSession.sessionManager" )
The calls below give an extension that replaces sessions (Pi's AgentSessionRuntime) what Pi reads from the AgentSession it replaces. They are for the Go, Python and Rust SDKs; Node runs Pi's own AgentSession.
const ( // CallSessionGraphNew constructs an object. Args is a SessionGraphNew and the result a SessionGraphHandle. CallSessionGraphNew = "sessionGraph.new" // CallSessionGraphCall runs a method that returns synchronously in Pi. Args is a SessionGraphCall and the result the method's result in Pi's JSON shape. The call applies in the order the extension sent it, before the extension's next call. CallSessionGraphCall = "sessionGraph.call" // CallSessionGraphAsync runs a method that returns a Promise in Pi (SessionManager.list, SettingsManager.reload, ModelRuntime.completeSimple). Args and result are those of CallSessionGraphCall. The call starts in the order the extension sent it and completes on its own, so a later call never waits for it; cancelling the call aborts the method's AbortSignal. CallSessionGraphAsync = "sessionGraph.async" // CallSessionGraphRelease drops the host's reference to an object. Args is a SessionGraphHandle. A session that was created with the object keeps its own reference. CallSessionGraphRelease = "sessionGraph.release" )
Session graph calls (ext→host).
const ( SessionGraphSessionManager = "SessionManager" SessionGraphSettingsManager = "SettingsManager" SessionGraphModelRuntime = "ModelRuntime" SessionGraphResourceLoader = "DefaultResourceLoader" SessionGraphPackageManager = "DefaultPackageManager" SessionGraphProjectTrustStore = "ProjectTrustStore" // SessionGraphExtensionRuntime and SessionGraphExtensionRunner are Pi's createExtensionRuntime() result and ExtensionRunner (core/extensions/loader.ts, runner.ts). The runner runs over the extensions a DefaultResourceLoader of the same connection loaded, which stay in their own subprocesses. SessionGraphExtensionRuntime = "ExtensionRuntime" SessionGraphExtensionRunner = "ExtensionRunner" // SessionGraphAgentSessionServices names the two host steps of Pi's createAgentSessionServices (agent-session-services.ts): it builds no object, it only has static functions (SessionGraphServicesResolve, SessionGraphServicesApply). SessionGraphAgentSessionServices = "AgentSessionServices" )
Object kinds, named by Pi's classes.
const ( // SessionGraphServicesResolve answers `resolvePath(options.cwd)` and `options.agentDir ? resolvePath(options.agentDir) : getAgentDir()` (agent-session-services.ts:138-139). Args are [cwd, agentDir|null]; the result is {cwd, agentDir}. SessionGraphServicesResolve = "resolve" // SessionGraphServicesApply is the rest of createAgentSessionServices after resourceLoader.reload (agent-session-services.ts:157-193): the provider, native provider and virtual model registrations the loaded extensions queued apply to the model runtime, a local refresh follows, and the // command-line extension flag values are validated and stored. Args are [modelRuntimeHandle, settingsManagerHandle, resourceLoaderHandle, cwd, agentDir, flagValues] with flagValues a list of [name, true|string] pairs in command-line order; the result is the list of diagnostics ({type, message}). SessionGraphServicesApply = "apply" )
Static functions of SessionGraphAgentSessionServices. The extension builds the services' objects itself, as Pi's function does (ModelRuntime.create, SettingsManager.create, new DefaultResourceLoader, reload), and asks the host for the two steps that need the host's own state.
const ( ProviderOperationImages = "images" ProviderOperationClassifiers = "classifiers" )
The kinds of a provider operation.
const ( ViewKindScrollView = "scroll-view" ViewKindMouseRegion = "mouse-region" ViewKindInput = "input" ViewKindEditor = "editor" ViewKindCancellableLoader = "cancellable-loader" ViewKindBorderedLoader = "bordered-loader" ViewKindBranchSummary = "branch-summary" ViewKindCompactionSummary = "compaction-summary" ViewKindCustomMessage = "custom-message" ViewKindSkillInvocation = "skill-invocation" )
View node kinds of the pi-tui widgets and coding-agent messages the kit carries beyond the first set (D107, docs/plan/extension-component-kit.md §2.2). Each mirrors the upstream component of the same name; the host renders it with its Go port.
const ( ViewEventSubmit = "submit" ViewEventEscape = "escape" ViewEventAbort = "abort" ViewEventMouse = "mouse" )
View event types of the widget kinds: Input's and Editor's onSubmit, Input's onEscape, CancellableLoader's onAbort, the value an Input or an Editor holds after a key (onChange), and the mouse event a MouseRegion took.
const CallBuiltinToolDefinition = "builtinTool.definition"
CallBuiltinToolDefinition (ext→host) is the ToolDefinition that create<Tool>ToolDefinition(cwd, options) returns, without its `execute` and renderers. Args is a BuiltinToolDefinitionArgs and the result a BuiltinToolDefinitionResult. It reads no session state, so it may arrive before the register frame, from a factory that dialled lazily.
const CallBuiltinToolExecute = "builtinTool.execute"
CallBuiltinToolExecute (ext→host) runs `execute(toolCallId, params, signal, onUpdate, ctx)` of the definition create<Tool>ToolDefinition(cwd, options) returns. Args is a BuiltinToolExecuteArgs; the result is the AgentToolResult the tool resolved to, in Pi's shape. A tool that throws is an error reply carrying the thrown message, and a tool that returns `isError: true` is a result, as in Pi.
The call's ParentRequestID is the calling tool's request when the extension forwards its own signal (the request's cancellation is then the tool's signal), and empty when the extension passes another signal or none: the call is then detached and only CallExecuteToolCancel, naming ExecuteID, aborts it.
const CallBuiltinToolLocalExec = "builtinTool.localExec"
CallBuiltinToolLocalExec (ext→host) is `exec` of the BashOperations createLocalBashOperations(options) or createLocalPowerShellOperations() returns: the command runs through the host's shell tool implementation, its output reaches the extension in order as RequestBuiltinToolExecData requests before the reply, and the reply is Pi's `{ exitCode }`. Args is a BuiltinToolLocalExecArgs. A command Pi's exec rejects is an error reply with Pi's message ("aborted", "timeout:<seconds>", a missing working directory). CallExecuteToolCancel, naming ExecuteID, is the exec's AbortSignal.
const CallBuiltinToolPrepareArguments = "builtinTool.prepareArguments"
CallBuiltinToolPrepareArguments (ext→host) is `prepareArguments(args)` of the definition create<Tool>ToolDefinition(cwd, options) returns, for a tool whose BuiltinToolDefinitionResult.PreparesArguments is set (edit: prepareEditArguments, edit.ts:103). Args is a BuiltinToolPrepareArgumentsArgs and the result the prepared arguments as JSON. An override built from the definition carries the hook as `{ ...definition, execute }` does in Pi, and the host runs it (RequestPrepareArguments) before it validates the override's arguments; the extension answers by asking the host for the built-in's own.
const CallCheckMcpServer = "mcpServers.check"
CallCheckMcpServer (ext→host) validates a registration without making it: the config as an `mcpServers` entry and the ownership of the name, which upstream's registerMcpServer does when it is called and throws to the factory (loader.ts:456-468). Args is a McpServerDecl; the error is the throw's message. A Node factory may call it before its register frame, which commits what the factory registered.
const CallConvertToPng = "image.convertToPng"
CallConvertToPng (ext→host) is Pi's convertToPng (utils/image-convert.ts): a base64 image as base64 PNG, or null when it does not decode. The args are a ConvertToPngArgs and the result an ImageResult.
const CallCopyToClipboard = "clipboard.copy"
CallCopyToClipboard (ext→host) is Pi's copyToClipboard (utils/clipboard.ts): the host copies text with the same strategy its own copy commands use. The args are a CopyToClipboardArgs; the result is empty and a failed copy is the call's error.
const CallExecCancel = "exec.cancel"
CallExecCancel (ext→host) is the abort of options.signal for the exec call named by ExecCancel: the host terminates the child as core/exec.ts's abort listener does, and the call resolves with what the child wrote, killed set and code 0 (a child that the signal ended has none). The extension sends it after the call's own frame; a cancel for a call that already ended does nothing. A Node factory may send it before its register frame.
const CallExecuteTool = "executeTool"
CallExecuteTool (ext→host) runs another tool for the calling tool, as ctx.executeTool does. Args is an ExecuteToolArgs; the result is an ExecuteToolOutcome. It never fails for tool failures: they come back with IsError set. The call's ParentRequestID names the calling tool's request, whose cancellation cancels the nested call by default.
const CallExecuteToolCancel = "executeTool.cancel"
CallExecuteToolCancel (ext→host) cancels the nested call named by ExecuteToolCancel: the extension's own signal for the call aborted.
const CallFileMutationEnter = "fileMutation.enter"
CallFileMutationEnter (ext→host) is the registration and wait of Pi's withFileMutationQueue (core/tools/file-mutation-queue.ts), served by the one queue the host's edit and write tools use, so a mutation an extension process wraps in the queue is serialised with the built-in tools and with every other extension process, as in Pi's single process. The args are a FileMutationEnterArgs and the result a FileMutationEnterResult, sent once the path's earlier mutations have completed. The call takes its place in the queue when the host reads it (the call lane advances then, so calls made after it are not held up), and the reply is the extension's admission. A path that cannot be resolved fails the call, and the task does not run. The ticket stays held until CallFileMutationExit or until the connection closes (for the extensions of a packed Go, Rust or Python cell, which share one process and its tickets, until the last connection of the process closes: an extension that is replaced or stops while another one's task holds a turn does not release it, and the exit may arrive on any of the process's connections); an admitted ticket is never released by the call's own context, as Pi holds the file while the task runs. A detached call (no parent request), so it may arrive before the register frame.
const CallFileMutationExit = "fileMutation.exit"
CallFileMutationExit (ext→host) releases the ticket a CallFileMutationEnter returned, after the task finished (whatever its outcome). The args are a FileMutationExitArgs; the reply is empty. A ticket the connection (or its process) does not hold fails the call.
const CallGenerateDiffString = "diff.string"
CallGenerateDiffString (ext→host) is Pi's generateDiffString (core/tools/edit-diff.ts): the line-numbered display diff of two texts and the first changed line of the new one, from the host's byte-exact port. The args are a GenerateDiffStringArgs and the result a GenerateDiffStringResult. Like every pure helper it reads no session or extension state and may arrive before the register frame.
const CallGenerateUnifiedPatch = "diff.patch"
CallGenerateUnifiedPatch (ext→host) is Pi's generateUnifiedPatch (core/tools/edit-diff.ts): a standard unified patch of two texts, from the host's port of jsdiff's createTwoFilesPatch. The args are a GenerateUnifiedPatchArgs and the result a GenerateUnifiedPatchResult.
const CallGetCallableTools = "getCallableTools"
CallGetCallableTools (ext→host) lists the tools ctx.executeTool can call at the moment of the call (runner.ts:958-961). The result is a CallableToolsResult.
const CallGetMcpServers = "getMcpServers"
CallGetMcpServers (ext→host) reads the runtime registry, as getMcpServers does (loader.ts:475-478). The result is a McpServersResult. A Node factory may call it before its register frame.
const CallHighlightCode = "highlight.code"
CallHighlightCode (ext→host) is pi-coding-agent's highlightCode (theme.ts), which getMarkdownTheme().highlightCode is too: the lines of code highlighted for lang by the host's highlight.js port and drawn with a theme. The args are a HighlightCodeArgs and the result a HighlightCodeResult. It reads no session or extension state, so it may arrive before the register frame.
const CallLoadTheme = "theme.load"
CallLoadTheme (ext→host) is the theme initTheme(name) installs as pi-coding-agent's process-global theme: the registered theme of that name, or the system theme for an absent name or one no theme has, as initTheme falls back. The args are a LoadThemeArgs and the result a LoadThemeResult. It may arrive before the register frame.
const CallLoadingExec = "exec.loading"
CallLoadingExec (ext→host) runs a child for a Node factory's pi.exec before its register frame, and for a call a factory's callback made after the factory returned and before the runtime had its registered connection, which the runtime sends right after the register frame. Upstream's loader gives the factory an exec that spawns the child directly, in the loader's working directory, with no session bound (loader.ts:411-414), so the host runs core/exec.ts's execCommand in its own working directory. Args and result are those of "exec". Once the runtime has its registered connection, pi.exec calls "exec", which runs in the bound session.
const CallOwnThinkingRuns = "ownThinkingRuns"
CallOwnThinkingRuns (ext→host) declares or withdraws the extension's ownership of thinking runs after the register frame. The host updates the extension's own flag and answers with an empty result; calls of one connection apply in arrival order. pig additive (D214)
const CallParseDate = "date.parse"
CallParseDate (ext→host) is `Date.parse(text)` (V8's parser, legacy formats included), the time value `new Date(text).getTime()` reads. The args are a ParseDateArgs and the result a ParseDateResult. It may arrive before the register frame.
const CallParseFrontmatter = "frontmatter.parse"
CallParseFrontmatter (ext→host) is Pi's parseFrontmatter (utils/frontmatter.ts): the YAML header and trimmed body of a markdown document, parsed by the same parser the host uses for skills and prompt templates. The args are a ParseFrontmatterArgs and the result a ParseFrontmatterResult. It reads no session or extension state, so it may arrive before the register frame, from a factory that dialled lazily.
const CallProviderCallback = "provider.callback"
const CallProviderObject = "provider.object"
const CallRegisterDeclaration = "registerDeclaration"
CallRegisterDeclaration carries a RegisterPayload holding only commands, shortcuts, flags, message renderers and entry renderers registered after the initial registration. The host applies each to the live extension, replacing an earlier one with the same key, and replies with an empty result.
const CallRegisterMcpServer = "registerMcpServer"
CallRegisterMcpServer (ext→host) registers a server after load. Args is a McpServerDecl. The result is a McpServersResult; an invalid config or a name another extension registered is a call error, which the SDK raises to the extension as upstream's throw.
const CallRegisterTool = "registerTool"
CallRegisterTool carries one ToolDecl after the initial registration. The host validates and replaces the definition, refreshes the Session registry before replying, and replies with an empty result. The SDK reads the registry through getAllTools and getActiveTools, so the reply carries no catalog.
const CallRegisterVirtualModel = "registerVirtualModel"
CallRegisterVirtualModel (ext→host) registers a virtual model after load. Args is a VirtualModelDecl.
const CallResizeImage = "image.resize"
CallResizeImage (ext→host) is Pi's resizeImage (utils/image-resize.ts): an image fitted within the option limits and the encoded size limit, or null when it cannot be. The args are a ResizeImageArgs and the result an ImageResult.
const CallToolReachesTools = "tool.reachesTools"
CallToolReachesTools (ext→host) runs the reachesTools of a tool getAllTools lists (upstream ToolInfo.reachesTools, which an extension's tool_call handler calls with the call's input). getAllTools marks such a tool `"reachesTools": true`, since a function cannot cross the wire, and an SDK's ToolInfo turns the mark into a function that makes this call. Args is ToolReachesToolsArgs; the result is the string "all", or the array of words. A tool getAllTools no longer lists with the hook fails the call, and so does the hook's throw.
const CallTypeEngine = "type.engine"
CallTypeEngine (ext→host) is one member of TypeBox's `Type` namespace that computes a schema (Pick, Omit, Partial, KeyOf, Mapped, Conditional, Extends, Script, ...), run by the host's one port of TypeBox's type engine (internal/typebox/engine) so every SDK returns what Pi's `Type` returns. The args are a TypeEngineArgs: the member and its arguments in the engine's wire form (JSON, with an envelope for the hidden members a schema carries); the result is `{"value": <wire>}`, or `{"error": {"name", "message"}}` for what TypeBox throws. It reads no session or extension state, so it may arrive before the register frame (Type.X runs while the factory is loading).
const CallUICancelDialog = "ui.cancelDialog"
CallUICancelDialog (ext→host) dismisses the ui.select, ui.confirm or ui.input call that carried the same dialogId: the extension's options.signal aborted (rpc-mode.ts createDialogPromise). The dialog answers as a cancelled one, which the extension ignores because its own promise settled with the default when the signal aborted.
const CallUnregisterMcpServer = "unregisterMcpServer"
CallUnregisterMcpServer (ext→host) removes a server the extension registered. Args is McpServerRef; the result is a McpServersResult.
const CallUnregisterVirtualModel = "unregisterVirtualModel"
CallUnregisterVirtualModel (ext→host) removes a virtual model. Args is VirtualModelRef.
const CallYield = "yield"
CallYield (ext→host) is the explicit yield of a thread-based SDK (ctx.Yield, and ctx.Sleep before it waits): the handler of the request that made it stands where Pi's code writes `await`, so the hold a triggering send set (sync_run_hold.go) ends and later reads of isIdle are live. Args are empty, the result is empty. A runtime with an event loop needs no such call: it reports its first microtask checkpoint (NotifyHandlerYielded).
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.
const MethodModelStreamCallback = "model_stream_callback"
const MethodProviderCall = "provider_call"
const MethodProviderObjectCallback = "provider_object_callback"
const MethodProviderStream = "provider_stream"
const MethodProviderSync = "provider_sync"
const MethodToolCall = "tool_call"
MethodToolCall runs a registered tool's execute.
const NotifyBashOperationsRelease = "bash_operations_release"
NotifyBashOperationsRelease (host→ext) reports that the host dropped the BashOperations object a user_bash reply named, so the extension drops its table entry. Args is a BashOperationsRelease.
const NotifyChildSessionEvent = "childSession.event"
NotifyChildSessionEvent (host→ext) carries one AgentSession event to the listeners of a session. Args is a ChildSessionEvent. Events of a session are numbered from 1 in the order the session emitted them, and the notification of event n precedes every frame the host writes after the listener returned, so a prompt's result follows the notifications of its run.
const NotifyEventLoopTurned = "event_loop_turned"
NotifyEventLoopTurned (Node runtime→host) reports that the process took the turn RequestEventLoopTurn asked for. The host applies the calls the connection sent before it, as it does for a request_state report, before the turn counts as taken.
const NotifyHandlerYielded = "handler_yielded"
NotifyHandlerYielded (ext→host) tells the host that the code that sent a triggering message, a handler or a timer's or an I/O callback, awaited or returned control to the runtime's event loop. The send carried the token in its yield_token argument. A runtime with an event loop sends it from the first microtask checkpoint after the send, because the host cannot see an await, and only after the host answered the send; the host then answers isIdle from the Session again (sync_run_hold.go). A thread-based SDK does not send it: its handler yields in a call whose upstream API returns a Promise, or when it returns.
const NotifyInvalidate = "invalidate"
NotifyInvalidate (host→ext) carries the stale message after the host invalidated the extension's Session. A runtime that answers pi or ctx members locally throws InvalidateArgs.Message from them afterwards, as Pi's runner.invalidate makes them throw (runner.ts:679-690).
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.
const NotifyLoopTurnTaken = "loop_turn_taken"
NotifyLoopTurnTaken (Node runtime→host, then host→the turn's sender) reports that a forwarded NotifyLoopTurned was taken, with the LoopTurnArgs of the copy it answers. A runtime that was waiting for the host's next step takes the turn once the immediates and the timers due that it had queued before the turn have run; any other runtime takes it on arrival. When every connection the host forwarded the turn to took it or closed, the host sends NotifyLoopTurnTaken with the sender's own number to the sender, which then lets its handler resume; a turn with no recipient is taken at once. A request for the sender's process or its connection's close also ends that wait. The host sends it only to a Node runtime.
const NotifyLoopTurned = "loop_turned"
NotifyLoopTurned (Node runtime→host, then host→ext) tells the host that a handler yielded to its process's event loop, and the host tells every other Node process. Pi runs every extension on one event loop, so while one extension's handler awaits a timer, I/O or a child process, the callbacks another extension queued run, with a live ctx, before that handler resumes. In print and JSON mode a Node runtime sends it when a request's turn window closes with the request unanswered: after the handler's synchronous run and microtasks, once the short host calls Pi settles in microtasks have settled. The Conn read loop hands it to the host before it reads any later frame of the connection, such as that handler's response, and the host queues it on every connection of every other Node process, so each one reads it before anything the host sends after that response, such as invalidate. A Node runtime waiting for the host's next step after a prompt's last call or session_shutdown takes it as that step, and delivers the frames that follow it only after the immediates it had queued have run. Its LoopTurnArgs number the turn: the sender numbers its own, and the host numbers each turn it forwards. From the closing phase of the event-loop iteration that sent it, the sender's process stays in the turn until the host answers NotifyLoopTurnTaken, so a handler that awaits a timer or I/O resumes only after the other processes ran what Pi's loop runs first, however the OS schedules them. It changes no state; the Go, Rust and Python SDKs, which have no such wait, ignore it.
const NotifyProviderStreamEvent = "provider_stream_event"
NotifyProviderStreamEvent carries ordered assistant events before the final request response.
const NotifyReloadStarted = "reload_started"
NotifyReloadStarted (host→ext) tells a running generation that Host.Reload has begun, before the host writes the replacement generations' admissions to the process's control channel. In print and JSON mode a Node runtime that answered a prompt's last call or session_shutdown waits in place for the host's next step (Pi's print mode continues without an event-loop turn); this notification is that step for a reload, so the runtime returns to its event loop, which reads the admissions. It carries no arguments and changes no state. The host sends it only to a Node runtime: the Go, Rust and Python SDKs have no such wait.
const NotifyTimerDefer = "timer_defer"
NotifyTimerDefer (host→Node runtime) says whether the runtime must hold the timer and immediate callbacks it would run (D189): Pi runs the microtasks of a stdin command and its response before any timer, so a callback that fires while a command runs waits for the response, and the host cannot hold such a callback's calls because the runtime may wait for their answers. The args are TimerDeferArgs. The frame precedes every request the host sends for the command, so the runtime holds the callbacks before its handlers run.
const NotifyTimerDeferAck = "timer_defer_ack"
NotifyTimerDeferAck (Node runtime→host) says the runtime applied the NotifyTimerDefer frame numbered Seq: its timer and immediate callbacks follow the hold from here on, and every call it made before the ack is already on the wire ahead of it. The host arms a stdin command's hold and waits for this ack before it dispatches the command's first event, so no extension code of the command runs before the hold (Turns.Arm). The args are TimerDeferAckArgs.
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.
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.
const NotifyToolRenderers = "tool_renderers"
NotifyToolRenderers (ext→host) reports the extension's resolver count after a registration that followed loading. Args is a ToolRenderersPayload.
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.
const NotifyToolWindowSettled = "tool_window_settled"
NotifyToolWindowSettled (host→Node runtime) tells a runtime that reported a tool_call request's handler blocked on something that is not a host call (RequestStatePayload blocked, external_io) that the edit and write calls waiting for the request's start window registered in the file mutation queue. Pi registers them before the handler's next call, so the runtime holds that request's next fileMutation.enter until it arrives. Args carry {"request_id": ...}. The host sends it only to a runtime that sent the report.
const NotifyUIAutocompletePending = "ui.autocomplete.pending"
NotifyUIAutocompletePending (ext→host, args {"requestId"}) tells the host that the provider chain serving the autocomplete.suggest request with that id awaits real I/O. Pi's editor awaits the whole wrapper chain in the Promise jobs after the terminal read (editor.ts startAutocompleteRequest), so a chain that settles there has opened its menu before the next read, and the host holds that read for it. Only a runtime whose providers are async sends the notice: the Node runtime, at the end of its macrotask, when the chain is neither settled nor waiting on a ui.autocomplete.invoke it made. The Go, Rust, Python and Lisp SDKs call blocking providers, which settle when they return, as a synchronous Pi provider holds the loop until it returns. The notice is sent at most once per request and before the response; a request the host did not hold ignores it.
const RequestBuiltinToolCallback = "builtin_tool_callback"
RequestBuiltinToolCallback (host→ext) calls one of the callbacks of a running CallBuiltinToolExecute: Args is a BuiltinToolCallback and the response is the callback's result (JSON null for a callback that returns nothing). An error response is the callback's throw. The request is not cancelled with the tool's signal: the callback's own `signal` is the tool's.
const RequestBuiltinToolExecData = "builtin_tool_exec_data"
RequestBuiltinToolExecData (host→ext) delivers one chunk of the output of a CallBuiltinToolLocalExec, in order and before the call's reply. Args is a BuiltinToolExecData.
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.
const RequestEventLoopTurn = "event_loop_turn"
RequestEventLoopTurn (host→Node runtime) asks a Node process for one turn of its event loop after a tool the host ran outside it. Pi runs the tool on the extensions' event loop, so the immediates a tool_call handler queued, and the input a sendUserMessage among them started, run before tool_result (agent-session.ts:1968-2000). The runtime answers after one setImmediate, sending NotifyEventLoopTurned with the request's LoopTurnArgs first. The host sends it only to a Node runtime.
const RequestExecuteToolUpdate = "execute_tool_update"
RequestExecuteToolUpdate (host→ext) delivers one partial result of a nested call, in order and before the call's result, and the host waits for the answer. Args is an ExecuteToolUpdate. An error response is the callback's throw: the update raises no `tool_execution_update` event, the later updates are still sent, and the call rejects with the first error once the tool returned (nested-tool-calls.ts:219-231, agent-loop.ts:820-849). The request is not cancelled with the nested call: Pi's callback has no cancellation.
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.
const RequestPrepareArguments = "tool_prepare_arguments"
RequestPrepareArguments (host→ext) runs a tool's prepareArguments. RequestPayload.Tool names the tool and Args is the model's arguments; the response is the prepared arguments.
const RequestPrepareLoadout = "tool_prepare_loadout"
RequestPrepareLoadout (host→ext) runs a tool's prepareLoadout. RequestPayload.Tool names the tool and Args is a ToolLoadoutPayload; the response is an extension.ToolLoadoutChanges, or null for no changes.
const RequestProviderOperation = "provider_operation"
RequestProviderOperation runs an image or classifier implementation of a provider config in its owning extension. The request carries the provider in Tool and {kind, api, model, context, options} in Args; the response is the AssistantImages or ClassifierResult, and a callback failure is the request's error.
const RequestProviderStream = "provider_stream_simple"
RequestProviderStream invokes a legacy streamSimple callback. Native Provider objects retain their provider_stream method/params carrier.
const RequestReachesTools = "tool_reaches_tools"
RequestReachesTools (host→ext) runs a tool's reachesTools. RequestPayload.Tool names the tool and Args is the call's input; the response is the string "all", or an array of the words of the input that may name the tools the call reaches (upstream's `"all" | readonly string[]`).
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.
const RequestResolveToolRenderers = "resolve_tool_renderers"
RequestResolveToolRenderers (host→ext) runs the extension's tool renderer resolvers, in registration order, for one tool. Args is a ResolveToolRenderersPayload; the result is a ResolvedToolRenderers.
const RequestSessionGraphCallback = "sessionGraph.callback"
RequestSessionGraphCallback (host→ext) runs a function an extension passed in an option of a session graph object (DefaultResourceLoader's systemPromptOverride, skillsOverride and the like). Args is a SessionGraphCallbackArgs; the response carries the function's result in Pi's JSON shape, and its error is the function's thrown error. The host sends it while a call of the object (reload) waits, so the extension answers it on another thread of control than the one that made the call.
const RequestSetup = "setup"
RequestSetup (host→ext) runs the setup callback of a newSession call that named it under SetupArgs.Handle in its setup field (types.ts:411, agent-session-runtime.ts:254-257). The host sends it after the replacement Session is bound and before the withSession callback runs. Host calls whose parent is this request act on the replacement Session: sessionRead reads its SessionManager and sessionWrite appends to it (SessionManager.appendMessage, appendCustomEntry, appendCustomMessageEntry, appendSessionInfo, appendModelChange, appendThinkingLevelChange, appendLabelChange). The response settles the callback, and its error rejects the newSession call.
const RequestUserBashExec = "user_bash_exec"
RequestUserBashExec (host→ext) runs `operations.exec(command, cwd, { onData, signal, timeout, env })` of the object RequestPayload.Tool names. The extension streams each onData chunk as a NotifyToolUpdate whose result is a UserBashExecData, in order and before the response, and answers with a UserBashExecResult. The request's cancellation is the exec's signal. An error response is the exec's rejection.
const RequestVirtualModelRoute = "virtual_model_route"
RequestVirtualModelRoute (host→ext) routes one request. Args is a VirtualModelRouteArgs; the response is a VirtualModelRouteResult. A cancel for the request cancels the router's signal.
const RequestWithSession = "with_session"
RequestWithSession (host→ext) runs the withSession callback that a newSession, fork or switchSession call registered under WithSessionArgs.Handle. The call's args name that handle in their withSession field. The host sends it after the replacement Session is bound and before the call returns, as Pi's finishSessionReplacement awaits withSession (agent-session-runtime.ts:187-194). Host calls whose parent is this request act on the replacement Session; the response settles the callback, and its error rejects the call.
const SessionGraphClosedMessage = "Extension connection is closed"
SessionGraphClosedMessage answers a call on a connection that closed.
SessionGraphUnavailableMessage answers a call on a host that serves no session graph.
const SessionGraphUnknownMessage = "Unknown or released session graph object"
SessionGraphUnknownMessage answers a call that names no live object of the connection.
const ToolAbortGrace = 3 * time.Second
ToolAbortGrace is how long an aborted extension tool call waits for the tool to settle after its AbortSignal fires.
pig divergence (D111): Pi awaits an aborted tool indefinitely (agent-loop.ts:831-853); a subprocess call must not block the agent loop forever.
Variables ¶
var ErrToolAborted = errors.New("Operation aborted")
ErrToolAborted fails an aborted extension tool call that did not settle within ToolAbortGrace. Its text is Pi's abort tool result (agent-loop.ts:623).
Functions ¶
func BuiltinToolDefinitionJSON ¶
BuiltinToolDefinitionJSON is CallBuiltinToolDefinition over JSON: the reply for the arguments. The handler and the fused extensions' SDK hook share it.
func BuiltinToolExecute ¶
func BuiltinToolExecute(ctx context.Context, argsJSON []byte, binDir string, peer BuiltinToolPeer) ([]byte, error)
BuiltinToolExecute is `execute` of a built-in tool's definition for args (ExecuteID and Context are not used: a call with a context goes over its extension's connection): the tool the host runs for an extension. The connection handler serves an extension in another process with the same code, and a fused extension, which shares this process, calls it directly through [sdk.HostHelpers], so the call depends on no extension's connection. It returns the JSON of the tool's result, or the error the tool throws. The tool ends with ctx, as it does with args.Aborted.
func BuiltinToolPrepareArgumentsJSON ¶
BuiltinToolPrepareArgumentsJSON is CallBuiltinToolPrepareArguments over JSON: the built-in definition's prepareArguments applied to the arguments. The handler and the fused extensions' SDK hook share it.
func CopyToClipboard ¶
CopyToClipboard is Pi's copyToClipboard through the host's copy function. The CallCopyToClipboard handler and the fused extensions' SDK hook share it.
func CurrentCacheEntries ¶
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 DefaultStagedSDKVerifier ¶
DefaultStagedSDKVerifier is the registered check for the configuration root, or nil when no program registered one.
func EnableEditorViews ¶
func EnableEditorViews()
EnableEditorViews lets the view kit build `editor` nodes. The `pig` command calls it where it creates the extension host, so every mode serves editor views as before. An embedder that never draws an extension's editor leaves it out and does not link the terminal editor; one that serves views to its own terminal calls it once before the first view is built. It is safe to call more than once and from any goroutine.
func EnableLisp ¶
func EnableLisp()
EnableLisp lets the host build, find and start Lisp extensions. It is called from the init function of the lispcell package.
func EnableTuiAltScreens ¶
func EnableTuiAltScreens()
EnableTuiAltScreens lets an extension construct a TuiAltScreen (pi-tui's alternate-screen host). The `pig` command calls it where it creates the extension host, so every mode serves TuiAltScreens. An embedder that never draws one leaves it out and does not link the renderer; one that serves them to its own terminal calls it once before the first extension loads. It is safe to call more than once and from any goroutine.
func FormatCrashNotice ¶
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 GenerateUnifiedPatch ¶
GenerateUnifiedPatch is Pi's generateUnifiedPatch over the host's port; contextLines nil is Pi's default of 4.
func GraphVirtualModelRoute ¶
func GraphVirtualModelRoute(scope SessionGraphScope, callbackID string) extension.ModelRouteFunc
GraphVirtualModelRoute is the route function of a virtual model whose router is the function the extension named callbackID: it runs on the extension's connection through the scope, with Pi's ModelRouteRequest as JSON.
func GroupLoadErrors ¶
GroupLoadErrors replaces the load errors of extensions that failed to build for one root cause with one BuildFailureGroup each. Every other error, and a build failure no other extension shares, is returned unchanged and in place.
func HighlightCodeLines ¶
HighlightCodeLines is pi-coding-agent's highlightCode (getMarkdownTheme().highlightCode is the same function) over the host's highlight.js port. palette is the theme to draw with (see HighlightCodeArgs.Theme); empty draws with the host's active theme. The CallHighlightCode handler and the fused extensions' SDK hook share it.
func IsBuildFailureGroupMessage ¶
IsBuildFailureGroupMessage reports whether message is the text of a BuildFailureGroup, which starts with "<count> extensions failed to build: ": a failure to load each extension it names.
func ListenExtension ¶
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 LoadThemeJSON ¶
LoadThemeJSON is the palette of the theme initTheme(name) installs, encoded. The CallLoadTheme handler and the fused extensions' SDK hook share it.
func LocalExec ¶
func LocalExec(ctx context.Context, args BuiltinToolLocalExecArgs, binDir string, onData func([]byte) error) (*int, error)
LocalExec is `exec` of createLocalBashOperations / createLocalPowerShellOperations for args (ExecuteID is not used): the command the host runs for an extension. The connection handler serves an extension in another process with it, and a fused extension, which shares this process, calls it directly through [sdk.HostHelpers], so the command does not depend on any extension's connection, as Pi's exec depends on none. It returns Pi's `{ exitCode }` (nil for a command a signal ended), or the error Pi's exec rejects with. Output chunks reach onData in order before it returns, and a chunk is lent for the call. An onData error ends the command: nobody can read the rest, and the error is LocalExec's. ctx ends the command, as does args.Aborted.
func ParseDateMs ¶
ParseDateMs is `Date.parse(text)` through the host's port of V8's parser: the time value in milliseconds, false for NaN.
func ParseFrontmatterJSON ¶
ParseFrontmatterJSON is Pi's parseFrontmatter over the host's parser: the JSON of the parsed header (see ParseFrontmatterResult) and the body. A malformed header is the error parseFrontmatter throws. The CallParseFrontmatter handler and the fused extensions' SDK hook share it.
func RunsFused ¶
RunsFused reports whether the host serves cfg from the Piglet Binary's own code, in this process, as LoadAll and a reload do. Such an extension reads no source and builds nothing, so it needs no staged SDK. It is false in stock pig, which installs no resolver.
func SetClipboardCopier ¶
SetClipboardCopier installs the host's copy function (Pi's copyToClipboard); nil removes it. CopyToClipboard fails while none is installed.
func SetConversationRenderers ¶
func SetConversationRenderers(renderers ConversationRenderers)
SetConversationRenderers installs the coding agent's tool cards. Without them a view with a tool-execution node is invalid.
func SetDefaultStagedSDKVerifier ¶
func SetDefaultStagedSDKVerifier(factory func(configRoot string) func(stagedDir, buildType string) error)
SetDefaultStagedSDKVerifier registers the factory of the staged-SDK freshness check that hosts started by library entry points (coding.DiscoverAndLoadExtensions) install. Linking coding/extension/pigsdk, which embeds and stages the SDKs, registers it, so a program that imports the coding library without the SDKs does not link the SDK sources the check compares against.
func SetEarlyModelStream ¶
func SetEarlyModelStream(stream func(context.Context, map[string]any, map[string]any) (*ai.AssistantMessageEventStream, error))
SetEarlyModelStream installs the stream every Host without a UI bridge uses for load-time pi-ai calls. The coding package installs it once, as it is a model-request conversion that package owns.
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 SetThemeLoader ¶
SetThemeLoader installs the source of CallLoadTheme's palette.
func SetTypeEngine ¶
SetTypeEngine registers the engine that answers CallTypeEngine: serve takes the request and returns the reply (internal/typebox/engine.Serve). Linking coding/extension/pigsdk with at least one of the Go, Rust and Python SDKs, the three that call it, registers it, so a program that links the host without that package (the coding library, examples/headless) does not link the engine through it.
func SetTypeScriptRuntimeSetting ¶
func SetTypeScriptRuntimeSetting(id string)
SetTypeScriptRuntimeSetting registers the extensionsTypescriptRuntime setting for this process. PIG_TS_RUNTIME takes precedence.
func SetViewLoaderAnimation ¶
func SetViewLoaderAnimation(enabled bool)
SetViewLoaderAnimation turns the host-owned loader animation on or off for the views drawn after the call. A test freezes it to compare a loader's frames with Pi's byte for byte; the frames a view names stay as it named them.
func StagedSDKFingerprint ¶
StagedSDKFingerprint hashes the source files that define one staged SDK. The digest is memoized per directory (sdkSourceDigest), so the fingerprint a build records after compiling costs nothing once the build's cache key has read the SDK.
func TypeScriptRuntimeRequest ¶
TypeScriptRuntimeRequest is the runtime this process requests for its TypeScript extensions.
func UnavailableNestedCall ¶
func UnavailableNestedCall(callerID, name string) extension.AgentToolCallOutcome
UnavailableNestedCall is upstream's outcome when no executeTool action is bound: an error whose call id is `<caller>/0`. A mode that binds the action to a session it may not have yet answers with it too.
upstream: runner.ts:968-976
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 BashOperationsRelease ¶
type BashOperationsRelease struct {
Handle string `json:"handle"`
}
BashOperationsRelease is the NotifyBashOperationsRelease argument.
type BeforeAgentStartResponsePayload ¶
type BeforeAgentStartResponsePayload struct {
Sections ai.OrderedSections `json:"_pigPromptSections"`
SelectedTools json.RawMessage `json:"_pigPromptSelectedTools"`
Options json.RawMessage `json:"_pigPromptOptions"`
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. Options is the handler's whole options object; the host applies every field except sections and selectedTools from it. 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 BuildFailureGroup ¶
type BuildFailureGroup struct {
// Names are the failed extensions, in load order.
Names []string
// Failure is the first member's failure. Its Cause is shared by every member.
Failure *runtimecell.BuildFailure
}
BuildFailureGroup is several extensions whose builds failed for one root cause, reported as one error rather than once each. Thirteen extensions failing on a mismatched toolchain are one problem.
pig additive (D20): Pi loads extension source in process and never compiles.
func (*BuildFailureGroup) Error ¶
func (g *BuildFailureGroup) Error() string
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 ¶
NewBuilder creates a builder with the given cache directory. Typically <config-root>/cache/ext/.
func NewBuilderWithConfigRoot ¶
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 ¶
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 ¶
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 ¶
SetStagedSDKVerifier installs the staged-SDK freshness check. Without one the builder only requires the directory to exist.
func (*Builder) WithGoListing ¶
WithGoListing resolves srcDir as buildGo does, with the staged SDK when its go.mod needs one, and calls use. It compiles nothing and removes its temporary go.mod afterward.
pig additive (D109): pig extension upgrade reads the types of an extension the way its build does.
type BuiltinToolCallback ¶
type BuiltinToolCallback struct {
Handle string `json:"handle"`
Member string `json:"member"`
Args json.RawMessage `json:"args,omitempty"`
}
BuiltinToolCallback is the argument of RequestBuiltinToolCallback. Member is "spawnHook" or "operations.<member>" and Args the member's arguments as a JSON object: file paths and text as strings, binary content as base64 strings (the member's own table in the SDKs).
type BuiltinToolDefinitionArgs ¶
type BuiltinToolDefinitionArgs struct {
Name string `json:"name"`
Cwd string `json:"cwd"`
Options *BuiltinToolOptions `json:"options,omitempty"`
}
BuiltinToolDefinitionArgs are the arguments of CallBuiltinToolDefinition. Name is a built-in tool name: read, bash, powershell, edit, write, grep, find or ls.
type BuiltinToolDefinitionResult ¶
type BuiltinToolDefinitionResult struct {
Name string `json:"name"`
Label string `json:"label"`
Description string `json:"description"`
PromptSnippet string `json:"promptSnippet,omitempty"`
//portlint:allow emptydrop Pi's definition.promptGuidelines is undefined or a non-empty list for the built-in tools, and the SDKs read an absent list as undefined
PromptGuidelines []string `json:"promptGuidelines,omitempty"`
Parameters json.RawMessage `json:"parameters"`
OutputSchema json.RawMessage `json:"outputSchema,omitempty"`
ConstrainedSampling json.RawMessage `json:"constrainedSampling,omitempty"`
ExecutionMode string `json:"executionMode,omitempty"`
// RenderShell is "self" for a tool that draws its own framing (edit).
RenderShell string `json:"renderShell,omitempty"`
// PreparesArguments reports that the definition has a `prepareArguments` (edit); CallBuiltinToolPrepareArguments runs it.
PreparesArguments bool `json:"preparesArguments,omitempty"`
}
BuiltinToolDefinitionResult is the reply of CallBuiltinToolDefinition: the members of Pi's ToolDefinition for a built-in tool that are data. Absent members are Pi's undefined.
type BuiltinToolExecData ¶
BuiltinToolExecData is the argument of RequestBuiltinToolExecData: Data is the chunk, base64.
type BuiltinToolExecuteArgs ¶
type BuiltinToolExecuteArgs struct {
Name string `json:"name"`
Cwd string `json:"cwd"`
Options *BuiltinToolOptions `json:"options,omitempty"`
// ToolCallID is the `toolCallId` argument of execute.
ToolCallID string `json:"toolCallId"`
Params json.RawMessage `json:"params"`
// ExecuteID names this call for RequestExecuteToolUpdate and CallExecuteToolCancel. It is unique within the connection.
ExecuteID string `json:"executeId"`
// WantsUpdates reports an onUpdate callback: the host sends RequestExecuteToolUpdate for each partial result.
WantsUpdates bool `json:"wantsUpdates,omitempty"`
// Context reports that the extension passed its ExtensionContext as execute's fifth argument: the tool then reads the session's working directory,
// model and session identity from it, as `ctx?.cwd || cwd` and `ctx?.model` do. Without it the tool uses Cwd and has no session.
Context bool `json:"context,omitempty"`
// Callbacks names the extension's table of the callbacks Options announces, for RequestBuiltinToolCallback.
Callbacks string `json:"callbacks,omitempty"`
// Aborted reports that the signal the extension passed was aborted before the call: Pi's tool checks `signal.aborted` before it starts, so a cancel
// sent after the call could lose the race with a tool that finishes at once.
Aborted bool `json:"aborted,omitempty"`
}
BuiltinToolExecuteArgs are the arguments of CallBuiltinToolExecute.
type BuiltinToolLocalExecArgs ¶
type BuiltinToolLocalExecArgs struct {
Shell string `json:"shell"`
ShellPath string `json:"shellPath,omitempty"`
Command string `json:"command"`
Cwd string `json:"cwd"`
Timeout *float64 `json:"timeout,omitempty"`
Env *map[string]string `json:"env,omitempty"`
ExecuteID string `json:"executeId"`
// Aborted reports that the extension's signal was aborted before the call, as for BuiltinToolExecuteArgs.
Aborted bool `json:"aborted,omitempty"`
}
BuiltinToolLocalExecArgs are the arguments of CallBuiltinToolLocalExec. Shell is "bash" or "powershell". ShellPath is createLocalBashOperations' `shellPath`. Timeout is seconds; Env, when present even if empty, replaces the inherited environment.
type BuiltinToolLocalExecResult ¶
type BuiltinToolLocalExecResult struct {
ExitCode *int `json:"exitCode"`
}
BuiltinToolLocalExecResult is the reply of CallBuiltinToolLocalExec: Pi's `{ exitCode }`, null for a command that ended without an exit code.
type BuiltinToolOptions ¶
type BuiltinToolOptions struct {
// AutoResizeImages is ReadToolOptions.autoResizeImages.
AutoResizeImages *bool `json:"autoResizeImages,omitempty"`
// ResizeOptions is ReadToolOptions.resizeOptions.
ResizeOptions *ai.ModelImageResizeOptions `json:"resizeOptions,omitempty"`
// CommandPrefix is BashToolOptions.commandPrefix.
CommandPrefix string `json:"commandPrefix,omitempty"`
// ShellPath is BashToolOptions.shellPath.
ShellPath string `json:"shellPath,omitempty"`
// ExposeSessionEnvironment is BashToolOptions.exposeSessionEnvironment and PowerShellToolOptions.exposeSessionEnvironment.
ExposeSessionEnvironment *bool `json:"exposeSessionEnvironment,omitempty"`
// Operations names the members of the tool's `operations` object the extension supplied.
// An empty list is an operations object with no member, which the host tells from an absent one (newBuiltinTool).
Operations []string `json:"operations"`
// SpawnHook reports the extension supplied `spawnHook`.
SpawnHook bool `json:"spawnHook,omitempty"`
}
BuiltinToolOptions are the options of Pi's create<Tool>ToolDefinition that cross the wire. `operations` and `spawnHook` hold functions, which stay in the extension: Operations names the members the extension supplied and SpawnHook reports a hook, and BuiltinToolExecuteArgs.Callbacks names the extension's table of them. A member Operations does not name keeps the tool's local implementation, as an undefined member of a partial Pi object would not.
type BuiltinToolPeer ¶
type BuiltinToolPeer struct {
// Callback runs one function of the call's options under handle (builtin_tool_callback) and returns the JSON of its result, nil when it has none. An error
// is the callback's throw.
Callback func(ctx context.Context, handle, member string, args []byte) ([]byte, error)
// Update delivers the JSON of one partial result to the call's onUpdate (executeTool's update); an error is onUpdate's throw.
Update func(ctx context.Context, executeID string, result []byte) error
// Exec is operations.exec of the options' bash operations under handle (user_bash exec): it streams output to onData in order and returns Pi's
// `{ exitCode }`, or the error exec rejects with. The command ends with ctx.
Exec func(ctx context.Context, handle, command, cwd string, timeout *float64, env map[string]string, onData func([]byte)) (*int, error)
}
BuiltinToolPeer is the extension a fused extension's built-in tool call reaches back into, in this process: BuiltinToolExecute's counterpart of the connection an extension in another process answers on.
type BuiltinToolPrepareArgumentsArgs ¶
type BuiltinToolPrepareArgumentsArgs struct {
Name string `json:"name"`
Cwd string `json:"cwd"`
Options *BuiltinToolOptions `json:"options,omitempty"`
Args json.RawMessage `json:"args"`
}
BuiltinToolPrepareArgumentsArgs are the arguments of CallBuiltinToolPrepareArguments: the tool as BuiltinToolDefinitionArgs names it, and Args, the model's arguments as JSON.
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"`
// Timer marks a call made by deferred work: from a callback of a timer or an immediate (setTimeout, setInterval, setImmediate) or from work such a callback started, and in the Go, Python and Rust SDKs from a context whose request already returned. The host runs such a call when Pi's loop would run the callback: not while the agent's run chains microtasks (jsloop.Turns, D189).
Timer bool `json:"timer,omitempty"`
// Tick marks a Timer call that Pi runs right after the tool_execution_end of the tool that queued it: the call of a process.nextTick callback, or of deferred work that makes the call while a sibling tool call still runs, so Pi's loop is turning (a timer callback in the Node runtime, a call through a request's context after its handler returned in the Go, Python and Rust SDKs).
Tick bool `json:"tick,omitempty"`
// OriginToolCallID, with Tick, is the tool call whose handler queued the callback that made the call (a Node runtime knows it from the request the callback was queued in). The host runs the call after that call's tool_execution_end, whether the call reaches the host before or after the event: the runtime is another process, so the time between its answer and the callback's call decides nothing about Pi's order. Empty when no tool call queued the callback.
OriginToolCallID string `json:"origin_tool_call_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 CallableToolsResult ¶
CallableToolsResult is the reply of CallGetCallableTools.
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 ¶
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) LispExtensions ¶
func (c CellSpec) LispExtensions() ([]runtimecell.LispExtension, error)
LispExtensions lists the members of a packed-lisp cell.
func (CellSpec) NodeExtensions ¶
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" CellStrategyPackedLisp CellStrategy = "packed-lisp" // 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 ChildScopedModel ¶
type ChildScopedModel struct {
Model json.RawMessage `json:"model"`
ThinkingLevel string `json:"thinkingLevel,omitempty"`
}
ChildScopedModel is one entry of Pi's scopedModels option: a model object and an optional thinking level.
type ChildSession ¶
type ChildSession interface {
// Info is what the session shows right after creation.
Info() ChildSessionInfo
// Prompt is AgentSession.prompt. It returns once the run settled; a cancelled ctx aborts the run.
Prompt(ctx context.Context, prompt ChildSessionPrompt) error
// Queue is AgentSession.steer or followUp.
Queue(ctx context.Context, queue ChildSessionQueue) error
// Abort is AgentSession.abort: it aborts the run and returns once the session is idle.
Abort(ctx context.Context) error
// BindExtensions is AgentSession.bindExtensions({}).
BindExtensions(ctx context.Context) error
// EmitExtensionEvent is `hasHandlers(type)` then `extensionRunner.emit(event)` on the session's runner; event is one of the events the runner's generic emit takes. emitted is false, and nothing ran, when no handler is registered for the type.
EmitExtensionEvent(ctx context.Context, event json.RawMessage) (result json.RawMessage, emitted bool, err error)
// RefreshContext is AgentSession.refreshContext.
RefreshContext()
// SessionManagerObject is AgentSession.sessionManager as a session graph object over the log the session appends to.
SessionManagerObject() SessionGraphObject
// State is the session's current state.
State() ChildSessionState
// Messages is AgentSession.messages in Pi's JSON shape.
Messages() (json.RawMessage, error)
// Subscribe is AgentSession.subscribe; event is one AgentSessionEvent in Pi's JSON shape, valid only during the call.
Subscribe(listener func(event json.RawMessage)) (unsubscribe func())
// Dispose is AgentSession.dispose: it disconnects the session from its agent and drops the listeners. As in Pi, the session still answers a prompt afterwards (the agent runs; no listener sees it). It never fails.
Dispose()
// Close ends the run and releases the session and everything it started. The host calls it when the connection closes, or when a session whose creation was abandoned never became live.
Close()
}
ChildSession is a child agent session the host owns for one extension connection. It is the part of Pi's AgentSession an extension reaches over the wire; the process that builds sessions (the coding package's CreateAgentSession) implements it.
Prompt, Queue, Abort and BindExtensions are awaited as Pi's Promises are: each returns when its work settled, and ctx ends it early. Subscribe's listener runs synchronously with the session's emission, in order, as AgentSession.subscribe's does.
type ChildSessionCreate ¶
type ChildSessionCreate struct {
// ID is the extension's name for the session; unique within the connection.
ID string `json:"id"`
// Cwd is the working directory for project-local discovery. Absent is the session manager's cwd, which is the host's.
Cwd string `json:"cwd,omitempty"`
// AgentDir is the global config directory. Absent is the host's.
AgentDir string `json:"agentDir,omitempty"`
// Model is an object whose provider and id name a model, as Pi's option takes a Model. Absent selects Pi's default (settings, then the first available model).
Model json.RawMessage `json:"model,omitempty"`
// ThinkingLevel is the requested level, clamped to the model. Absent is Pi's default.
ThinkingLevel string `json:"thinkingLevel,omitempty"`
// Tools is the allowlist of tool names or `*` patterns, or a list of only `+name` and `-name` entries. Absent is Pi's undefined, an empty list is an allowlist of nothing.
Tools *[]string `json:"tools,omitempty"`
// ExcludeTools is the denylist applied after Tools.
//portlint:allow emptydrop PiG wire field read by the host as a list: an empty list and an absent one mean the same (nothing to exclude or add)
ExcludeTools []string `json:"excludeTools,omitempty"`
// NoTools is "all" or "builtin".
NoTools string `json:"noTools,omitempty"`
// CustomTools are tools the extension serves: the host asks it to run one with a tool_call request that names the session in RequestPayload.ChildSession, and the result becomes the session's tool result.
//portlint:allow emptydrop PiG wire field read by the host as a list: an empty list and an absent one mean the same (nothing to exclude or add)
CustomTools []ToolDecl `json:"customTools,omitempty"`
// Settings are in-memory settings, Pi's `SettingsManager.inMemory(settings)`: the session reads no settings file. Absent is `SettingsManager.create(cwd, agentDir)`, the settings files.
Settings json.RawMessage `json:"settings,omitempty"`
// InMemory is `SessionManager.inMemory(cwd)`: the session log is never written. Absent is `SessionManager.create(cwd)`.
InMemory bool `json:"inMemory,omitempty"`
// Resources selects what the session's resource loader loads: Pi's DefaultResourceLoader options.
Resources *ChildSessionResources `json:"resources,omitempty"`
// SessionManager, SettingsManager, ResourceLoader and ModelRuntime name session graph objects the extension built on this connection (CallSessionGraphNew): Pi's `sessionManager`, `settingsManager`, `resourceLoader` and `modelRuntime` options of createAgentSession. The session uses the very objects. Each replaces the option that builds its own (InMemory, Settings, Resources; the parent's model runtime), so naming both is an error.
SessionManager string `json:"sessionManager,omitempty"`
SettingsManager string `json:"settingsManager,omitempty"`
ResourceLoader string `json:"resourceLoader,omitempty"`
ModelRuntime string `json:"modelRuntime,omitempty"`
// ScopedModels is Pi's `scopedModels`: the models the session cycles through.
//portlint:allow emptydrop PiG wire field read by the host as a list: an empty list and an absent one mean the same (nothing to exclude or add)
ScopedModels []ChildScopedModel `json:"scopedModels,omitempty"`
// SessionStartEvent is Pi's `sessionStartEvent` option: the session_start event the session's extensions receive when they bind. Absent is Pi's default, `{type: "session_start", reason: "startup"}`.
SessionStartEvent *ChildSessionStartEvent `json:"sessionStartEvent,omitempty"`
}
ChildSessionCreate is the CallChildSessionCreate argument: the members of Pi's CreateAgentSessionOptions (core/sdk.ts:48-106) an extension can pass across a process boundary. A member that is absent is Pi's undefined.
The session shares the parent's model runtime (Pi's `modelRuntime: ctx.modelRegistry.runtime`), so every provider the parent's extensions registered is available to it. It never prompts or replaces the enclosing Session.
type ChildSessionEmit ¶
type ChildSessionEmit struct {
ID string `json:"id"`
Event json.RawMessage `json:"event"`
}
ChildSessionEmit is the CallChildSessionEmit argument. Event is one of the events the ExtensionRunner's generic emit takes, in Pi's JSON shape.
type ChildSessionEmitResult ¶
type ChildSessionEmitResult struct {
Emitted bool `json:"emitted"`
Result json.RawMessage `json:"result,omitempty"`
}
ChildSessionEmitResult is the CallChildSessionEmit result. Emitted is false when no extension has a handler for the event's type (nothing ran); Result is what emit answered, null when it answered nothing.
type ChildSessionEvent ¶
type ChildSessionEvent struct {
ID string `json:"id"`
Seq uint64 `json:"seq"`
Event json.RawMessage `json:"event,omitempty"`
// Stream numbers a message_update's payload in the session's sequence (EventStream): with Event it is a keyframe the extension keeps; without, it carries Ops that turn the payload numbered Base into the event, and the extension hands its listeners the full event either way. Seq is the event's number, so Base is the number of the previous message_update of the session. Absent, the event travels whole and leaves the extension's copy as it is.
Stream *EventStream `json:"stream,omitempty"`
}
ChildSessionEvent is the NotifyChildSessionEvent argument. Event is the AgentSessionEvent in Pi's JSON shape, the one print mode's JSON stream writes.
type ChildSessionFactory ¶
type ChildSessionFactory func(ctx context.Context, request ChildSessionRequest) (ChildSession, error)
ChildSessionFactory builds a child session. ctx ends the creation only: the session outlives it and ends with Dispose.
type ChildSessionImage ¶
type ChildSessionImage struct {
Type string `json:"type,omitempty"`
Data string `json:"data"`
MimeType string `json:"mimeType"`
}
ChildSessionImage is an image of a prompt.
type ChildSessionInfo ¶
type ChildSessionInfo struct {
// SessionID and SessionFile are the session's (`session.sessionId`, `session.sessionFile`); the file is absent for an in-memory session.
SessionID string `json:"sessionId"`
SessionFile string `json:"sessionFile,omitempty"`
// Model is the session's model as an extension model object, or null without one.
Model json.RawMessage `json:"model"`
// ThinkingLevel is the clamped level the session holds.
ThinkingLevel string `json:"thinkingLevel"`
// ActiveTools is `session.getActiveToolNames()`.
ActiveTools []string `json:"activeTools"`
// SystemPrompt is `session.systemPrompt`.
SystemPrompt string `json:"systemPrompt"`
// ModelFallbackMessage is CreateAgentSessionResult.modelFallbackMessage.
ModelFallbackMessage string `json:"modelFallbackMessage,omitempty"`
// ExtensionErrors are the errors of CreateAgentSessionResult.extensionsResult.errors, as "path: error".
//portlint:allow emptydrop PiG wire field every SDK reads as a list, an absent one as empty
ExtensionErrors []string `json:"extensionErrors,omitempty"`
}
ChildSessionInfo is the CallChildSessionCreate result: what Pi's createAgentSession returns and the session shows right after creating it.
type ChildSessionManagerHandle ¶
type ChildSessionManagerHandle struct {
Handle string `json:"handle"`
}
ChildSessionManagerHandle is the CallChildSessionSessionManager result.
type ChildSessionPrompt ¶
type ChildSessionPrompt struct {
ID string `json:"id"`
Text string `json:"text"`
//portlint:allow emptydrop PiG wire field: an empty image list and an absent one send the same prompt
Images []ChildSessionImage `json:"images,omitempty"`
// ExpandPromptTemplates is Pi's option; absent is true.
ExpandPromptTemplates *bool `json:"expandPromptTemplates,omitempty"`
// StreamingBehavior is "steer" or "followUp"; it is required to prompt a session that is running.
StreamingBehavior string `json:"streamingBehavior,omitempty"`
// Source is the input source ("interactive", "rpc" or "extension"); absent is Pi's "interactive".
Source string `json:"source,omitempty"`
}
ChildSessionPrompt is the CallChildSessionPrompt argument: AgentSession.prompt(text, options).
type ChildSessionPromptResult ¶
type ChildSessionPromptResult struct {
Events uint64 `json:"events"`
}
ChildSessionPromptResult is the CallChildSessionPrompt result. Events is the number of the session's last event when the run settled: the SDK resolves the prompt once its listeners have run through that event.
type ChildSessionQueue ¶
type ChildSessionQueue struct {
ID string `json:"id"`
Behavior string `json:"behavior"` // "steer" | "followUp"
Text string `json:"text"`
//portlint:allow emptydrop PiG wire field: an empty image list and an absent one send the same message
Images []ChildSessionImage `json:"images,omitempty"`
}
ChildSessionQueue is the CallChildSessionQueue argument: AgentSession.steer or followUp.
type ChildSessionRef ¶
type ChildSessionRef struct {
ID string `json:"id"`
}
ChildSessionRef names a session of the connection.
type ChildSessionRequest ¶
type ChildSessionRequest struct {
ChildSessionCreate
// ToolDefinitions are the extension's customTools, in order. Their Execute asks the extension that created the session.
ToolDefinitions []extension.ToolDefinition
// SessionManager, SettingsManager, ResourceLoader and ModelRuntime are the session graph objects the create call named (nil when it named none), resolved on the creating connection.
SessionManager, SettingsManager, ResourceLoader, ModelRuntime SessionGraphObject
}
ChildSessionRequest is a decoded CallChildSessionCreate: the wire arguments, and the definitions of CustomTools whose execute runs in the extension.
type ChildSessionResources ¶
type ChildSessionResources struct {
NoExtensions bool `json:"noExtensions,omitempty"`
NoSkills bool `json:"noSkills,omitempty"`
NoPromptTemplates bool `json:"noPromptTemplates,omitempty"`
NoThemes bool `json:"noThemes,omitempty"`
NoContextFiles bool `json:"noContextFiles,omitempty"`
// AdditionalExtensionPaths, AdditionalSkillPaths and AdditionalPromptTemplatePaths are loaded after the resolved resources.
//portlint:allow emptydrop PiG wire field read by the host as a list: an empty list and an absent one mean the same (nothing to exclude or add)
AdditionalExtensionPaths []string `json:"additionalExtensionPaths,omitempty"`
//portlint:allow emptydrop PiG wire field read by the host as a list: an empty list and an absent one mean the same (nothing to exclude or add)
AdditionalSkillPaths []string `json:"additionalSkillPaths,omitempty"`
//portlint:allow emptydrop PiG wire field read by the host as a list: an empty list and an absent one mean the same (nothing to exclude or add)
AdditionalPromptTemplatePaths []string `json:"additionalPromptTemplatePaths,omitempty"`
// ExtensionNames keeps only the extensions whose path contains one of the names, compared without case: Pi's `extensionsOverride`. Absent keeps all, an empty list none.
ExtensionNames *[]string `json:"extensionNames,omitempty"`
// SkillNames keeps only the skills named exactly by one of the names: Pi's `skillsOverride`. Absent keeps all, an empty list none.
SkillNames *[]string `json:"skillNames,omitempty"`
// SystemPrompt replaces SYSTEM.md discovery; AppendSystemPrompt replaces APPEND_SYSTEM.md discovery. Each is text or the path of a file holding it.
SystemPrompt *string `json:"systemPrompt,omitempty"`
AppendSystemPrompt *[]string `json:"appendSystemPrompt,omitempty"`
}
ChildSessionResources are the DefaultResourceLoader options of Pi (resource-loader.ts) that select resources.
type ChildSessionStartEvent ¶
type ChildSessionStartEvent struct {
// Reason is "startup", "reload", "new", "resume" or "fork".
Reason string `json:"reason"`
PreviousSessionFile string `json:"previousSessionFile,omitempty"`
}
ChildSessionStartEvent is Pi's SessionStartEvent (types.ts), the value of the sessionStartEvent option: the reason a session starts and, when it replaces another, that session's file.
type ChildSessionState ¶
type ChildSessionState struct {
SessionID string `json:"sessionId"`
SessionFile string `json:"sessionFile,omitempty"`
Model json.RawMessage `json:"model"`
IsStreaming bool `json:"isStreaming"`
IsIdle bool `json:"isIdle"`
ThinkingLevel string `json:"thinkingLevel"`
ActiveTools []string `json:"activeTools"`
SystemPrompt string `json:"systemPrompt"`
// PendingMessageCount is AgentSession.pendingMessageCount.
PendingMessageCount int `json:"pendingMessageCount"`
// LastAssistantText is getLastAssistantText(), absent when there is none.
LastAssistantText *string `json:"lastAssistantText,omitempty"`
}
ChildSessionState is the CallChildSessionState result.
type CommandDecl ¶
type CommandDecl struct {
Name string `json:"name"`
Description string `json:"description"`
// 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 ¶
NewConn wraps a connected socket into a managed connection. Call Conn.Start to begin read/write goroutines.
func (*Conn) Close ¶
Close gracefully shuts down the connection. Sends a shutdown message if possible, then closes the socket. It returns nil when the peer already ended the transport: the peer's own close ends the read loop, which closes the socket, so Close finds it closed or the shutdown frame has nowhere to go. Pi's RpcClient.stop likewise succeeds for a process that exited on its own (rpc-client.ts:145-168; the exit only rejects the pending requests, :107-112). A failure of the close itself, or a liveness failure, is still returned.
func (*Conn) Done ¶
func (c *Conn) Done() <-chan struct{}
Done returns a channel that closes when all connection goroutines have exited.
func (*Conn) Incoming ¶
Incoming returns the channel of non-response messages from the extension. The host reads from this to handle calls, widget pushes, etc.
func (*Conn) RecentOversizedFrame ¶
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 ¶
Request sends a message and waits for the correlated response. Blocks until the response arrives or the context expires.
func (*Conn) Retire ¶
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). Until the peer closes, the connection still sends the result of every call the peer makes, as Pi's in-process calls never go unanswered: a Node runtime blocked in a synchronous host call reads no shutdown frame until its result arrives (checkSendState).
func (*Conn) Send ¶
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.
type ConversationRenderers ¶
type ConversationRenderers struct {
// NewToolCard builds the tool card the main transcript draws for a
// tool-execution node's constructor arguments; toolDefinition is
// ViewToolDefinitionBuiltin or ViewToolDefinitionEmpty. requestRender
// is called, from any goroutine, after the card changed on its own.
// dispose cancels and joins the card's background work.
NewToolCard func(ctx context.Context, toolName, toolCallID, cwd string, args json.RawMessage, toolDefinition string, requestRender func()) (card *tui.ToolExecutionComponent, dispose func())
// ToolDiff is the diff a finished call's result carries, as the main
// transcript reports it to a frontend.
ToolDiff func(toolName string, arguments map[string]any, result any) *frontend.Diff
}
ConversationRenderers are the coding agent's parts of the conversation kinds, which the host cannot import.
type ConvertToPngArgs ¶
ConvertToPngArgs is the argument of CallConvertToPng: Pi's `(base64Data, mimeType)`.
type CopyToClipboardArgs ¶
type CopyToClipboardArgs struct {
Text string `json:"text"`
}
CopyToClipboardArgs is the argument of CallCopyToClipboard.
type DirectEntryAppend ¶
type DirectEntryAppend struct {
ID string `json:"id"`
Timestamp string `json:"timestamp"`
// Event marks pi.appendEntry, which the Node runtime also appends in its own process: the mode emits entry_appended for it as for a host-assigned pi.appendEntry (agent-session.ts:3406-3411). ctx.sessionManager.appendCustomEntry leaves it false and only writes the log.
Event bool `json:"event,omitempty"`
}
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,omitzero"`
Width int `json:"width,omitempty"`
Seq uint64 `json:"seq,omitempty"`
WantsKeyRelease bool `json:"wantsKeyRelease,omitempty"`
// CapturesViewportInput is the editor component's capturesViewportInput when the frame was drawn.
CapturesViewportInput bool `json:"capturesViewportInput,omitempty"`
EmbedWorkingStatus bool `json:"embedWorkingStatus,omitempty"`
// Delegated marks a component that subclasses the host's stock editor: its base calls arrive as ui.editor.base.
Delegated bool `json:"delegated,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. A Node cell is the exception to source-free: its BinaryPath is the directory holding its members' extracted sources.
type EmbeddedExtension ¶
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"`
// contains filtered or unexported fields
}
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.
type EventBusRetention ¶
type EventBusRetention struct {
// Channels, Listeners and Handlers describe the registry. Emissions counts routed emits whose realms have not settled, and Snapshots the dispatches in flight that still hold a listener.
Channels, Listeners, Handlers, Emissions, Snapshots int
// Realms, Leases, Holds and Expected describe the cross-process reference ledger.
Realms, Leases, Holds, Expected int
}
EventBusRetention counts the Host state the shared pi.events bus and the cross-process reference ledger retain. It is a product-neutral diagnostic of Stock mechanisms (D19): Pi's bus keeps one listener array per channel and nothing per emit (event-bus.ts:12-33), so a count that grows with the number of emits is a leak.
type EventStream ¶
type EventStream struct {
Seq uint64 `json:"seq"`
Base uint64 `json:"base,omitempty"`
Ops json.RawMessage `json:"ops,omitempty"`
Key string `json:"key,omitempty"`
Evict []string `json:"evict,omitempty"` //portlint:allow emptydrop a PiG-only frame field (D112 bounded cache); Pi has no such frame
}
EventStream numbers the payloads of one connection's message_update and tool_execution_update events and carries the operations that turn the previous one into the next. An operation is {"op":"set"|"append","path":[...],"value":...}: set writes the value at the path (an object key, or an array index no further than the array's length), append adds the string value to the string at the path. A path element is an object key or an array index; an empty path is the whole payload. Members keep the order the full payload would have: set creates a new key last.
A payload belongs to the sequence named by the event and Key: message_update has one sequence, and tool_execution_update has one for each toolCallId, which Key carries, so parallel tools that interleave their updates each send only what changed. Seq and Base number the payloads of one sequence. Evict names sequences of the same event whose payloads the runtime drops once it applied this frame: the host keeps a bounded number and releases the least recently updated, so a runtime's memory is bounded; the next frame of an evicted sequence is a keyframe.
type ExecArgs ¶
type ExecArgs struct {
Command string `json:"command"`
Args []string `json:"args"`
Options *extension.ExecOptions `json:"options,omitempty"`
// ExecID names this call for CallExecCancel. It is unique within the connection.
ExecID string `json:"execId,omitempty"`
// OwnSignal reports that the extension passed options.signal. The command then ends only when the signal aborts, the timeout fires or the connection closes: the call is not tied to a request, as Pi's exec has no signal but the one the caller passed (core/exec.ts).
OwnSignal bool `json:"ownSignal,omitempty"`
}
ExecArgs is the argument of "exec" and CallLoadingExec: upstream's pi.exec(command, args, options). The AbortSignal of options.signal cannot cross the socket: an extension that passed one sets OwnSignal and names the call by ExecID, and sends CallExecCancel when the signal aborts.
type ExecCancel ¶
type ExecCancel struct {
ExecID string `json:"execId"`
}
ExecCancel is the CallExecCancel argument.
type ExecuteToolArgs ¶
type ExecuteToolArgs struct {
// CallerID is the id of the calling tool call.
CallerID string `json:"callerId"`
Name string `json:"name"`
Args json.RawMessage `json:"args"`
// ExecuteID names this call for RequestExecuteToolUpdate and CallExecuteToolCancel. It is unique within the connection.
ExecuteID string `json:"executeId"`
// WantsUpdates reports an onUpdate callback: the host sends RequestExecuteToolUpdate for each partial result.
WantsUpdates bool `json:"wantsUpdates,omitempty"`
// OwnSignal reports that the extension passed options.signal: the nested tool runs with that signal instead of the calling tool's.
OwnSignal bool `json:"ownSignal,omitempty"`
}
ExecuteToolArgs is the CallExecuteTool argument.
type ExecuteToolCancel ¶
type ExecuteToolCancel struct {
ExecuteID string `json:"executeId"`
}
ExecuteToolCancel is the CallExecuteToolCancel argument.
type ExecuteToolOutcome ¶
type ExecuteToolOutcome struct {
ToolCall ai.ToolCall `json:"toolCall"`
Result json.RawMessage `json:"result"`
IsError bool `json:"isError"`
// DurationMs is the milliseconds execute() took, measured with a monotonic clock; absent when the tool did not run. upstream: agent/src/types.ts:454 AgentToolCallOutcome.durationMs
DurationMs *int64 `json:"durationMs,omitempty"`
}
ExecuteToolOutcome is upstream's AgentToolCallOutcome as JSON. Result is an AgentToolResult in Pi's shape (content, details, structuredContent, usage, terminate).
type ExecuteToolUpdate ¶
type ExecuteToolUpdate struct {
ExecuteID string `json:"executeId"`
Result json.RawMessage `json:"result"`
}
ExecuteToolUpdate is the RequestExecuteToolUpdate argument. Result is an AgentToolResult in Pi's shape.
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
// PackageRoot is the root of the package the extension was resolved from (package-manager.ts PathMetadata.packageRoot):
// a local directory or an installed npm or git package. It is empty for a project or user extension and for a local file
// source, which belongs to no package root.
PackageRoot string
// 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 DisambiguateIdentities ¶
DisambiguateIdentities gives each later copy of an extension identity from a different path its own host key ("ask:2", "ask:3", ...). Upstream identifies an extension by its path, so copies from two Packages both load; the host keys its registry by name, so the copies need distinct keys. LoadAll applies it to the configs it receives. A caller that loads configs one host at a time applies it to the whole set first, so every copy keeps its own key.
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 ¶
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 ¶
ResolveError returns the source resolution failure of an UnresolvedExtConfig, or nil.
func (ExtConfig) SelectedAs ¶
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 ¶
ExtensionUnresponsiveError reports a missed dispatcher heartbeat.
func (*ExtensionUnresponsiveError) Error ¶
func (e *ExtensionUnresponsiveError) Error() string
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"`
Phase string `json:"phase,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. Phase is LoadPhaseImport when the module failed before its factory was called and LoadPhaseFactory once the factory ran.
func (*FactoryLoadError) Error ¶
func (e *FactoryLoadError) Error() string
func (*FactoryLoadError) ErrorStack ¶
func (e *FactoryLoadError) ErrorStack() string
type FileMutationEnterArgs ¶
type FileMutationEnterArgs struct {
Path string `json:"path"`
}
FileMutationEnterArgs is the argument of CallFileMutationEnter. Path is absolute and lexically clean: the extension resolves it against its own working directory, as Pi's `resolve(filePath)` does; the host takes its real path as the queue key (a missing path or one below a regular file keys by itself).
type FileMutationEnterResult ¶
type FileMutationEnterResult struct {
Ticket string `json:"ticket"`
}
FileMutationEnterResult is the result of CallFileMutationEnter.
type FileMutationExitArgs ¶
type FileMutationExitArgs struct {
Ticket string `json:"ticket"`
}
FileMutationExitArgs is the argument of CallFileMutationExit.
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 {
}
FooterDataPayload carries the data behind upstream's ReadonlyFooterDataProvider (footer-data-provider.ts:387), the third argument handed to a ui.setFooter factory.
type FrameTooLargeError ¶
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 GenerateDiffStringArgs ¶
type GenerateDiffStringArgs struct {
OldContent string `json:"oldContent"`
NewContent string `json:"newContent"`
ContextLines *int `json:"contextLines,omitempty"`
}
GenerateDiffStringArgs is the argument of CallGenerateDiffString; ContextLines is Pi's optional third parameter (default 4).
type GenerateDiffStringResult ¶
type GenerateDiffStringResult struct {
Diff string `json:"diff"`
FirstChangedLine *int `json:"firstChangedLine"`
}
GenerateDiffStringResult is the result of CallGenerateDiffString: Pi's `{ diff, firstChangedLine }`, the line null when the texts do not differ.
func GenerateDiffString ¶
func GenerateDiffString(oldContent, newContent string, contextLines *int) GenerateDiffStringResult
GenerateDiffString is Pi's generateDiffString over the host's port; contextLines nil is Pi's default of 4.
type GenerateUnifiedPatchArgs ¶
type GenerateUnifiedPatchArgs struct {
Path string `json:"path"`
OldContent string `json:"oldContent"`
NewContent string `json:"newContent"`
ContextLines *int `json:"contextLines,omitempty"`
}
GenerateUnifiedPatchArgs is the argument of CallGenerateUnifiedPatch; ContextLines is Pi's optional fourth parameter (default 4).
type GenerateUnifiedPatchResult ¶
type GenerateUnifiedPatchResult struct {
Patch string `json:"patch"`
}
GenerateUnifiedPatchResult is the result of CallGenerateUnifiedPatch.
type GoListing ¶
GoListing is how to read the packages of a standalone Go source extension the way its build resolves them: the go command, the flags that select the staged SDK, and the environment.
type HandlerDecl ¶
type HandlerDecl struct {
Event string `json:"event"` // e.g. "tool_call", "session_start"
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
// Settled closes when the abandoned handler's late response arrives or the connection ends. Nil when the request had nothing left to settle.
Settled <-chan struct{}
}
HandlerStalledError reports a request-inactivity lease expiration.
func (*HandlerStalledError) Error ¶
func (e *HandlerStalledError) Error() string
type HandlerYieldedPayload ¶
type HandlerYieldedPayload struct {
Token string `json:"token"`
}
HandlerYieldedPayload is the NotifyHandlerYielded argument.
type HighlightCodeArgs ¶
type HighlightCodeArgs struct {
Code string `json:"code"`
Lang string `json:"lang,omitempty"`
Theme json.RawMessage `json:"theme,omitempty"`
}
HighlightCodeArgs is the argument of CallHighlightCode. Theme is the palette (the shape of ready.state.theme) of the theme to draw with: the one the extension installed with initTheme. An absent Theme draws with the host's active theme, which the extension's own global theme replicates.
type HighlightCodeResult ¶
type HighlightCodeResult struct {
Lines []string `json:"lines"`
}
HighlightCodeResult is the result of CallHighlightCode: Pi's array of highlighted lines.
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 ¶
NewHost creates an extension host using the process environment's Pig config root. Product assembly should prefer NewHostWithConfigRoot.
func NewHostWithConfigRoot ¶
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 (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 ¶
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 records that no further terminal or RPC input can arrive and tells each hosted Node runtime with runtime_input_end, which releases its command-suspension and loop-drain reports. The host applies stdin's end to other runtimes' commands itself (FlushCommands). This does not cancel requests or synthesize responses.
func (*Host) EventBusRetention ¶
func (h *Host) EventBusRetention() EventBusRetention
EventBusRetention reports the bus and reference-ledger state the Host retains now.
func (*Host) ExtensionCount ¶
ExtensionCount returns the number of loaded subprocess extensions.
func (*Host) Extensions ¶
Extensions returns all successfully registered extension structs.
func (*Host) FlagDefault ¶
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 settled or answered before the checkpoint responds normally. It does not cancel requests or synthesize responses.
func (*Host) Invalidate ¶
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.
Each connected extension process also receives the message in an invalidate notification, so a runtime that answers pi or ctx members locally throws it too. The notification precedes any with_session request on the connection.
func (*Host) IsShuttingDown ¶
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 ¶
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 ¶
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, except that a Node cell's members start from their extracted sources with the user's installed Node, exactly as Stock PiG starts the same extensions.
func (*Host) LoadErrors ¶
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) LoadLispPackedCell ¶
func (h *Host) LoadLispPackedCell(ctx context.Context, cell *runtimecell.LispPackedCell) ([]extension.Extension, error)
LoadLispPackedCell starts a generated Lisp runner image and registers every contained extension atomically. It mirrors the Python path and keeps the current subprocess wire with one socket and one register handshake per extension.
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 ¶
NotifyHeight sends a height_change notification to every connected extension that has not already seen this height. 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 ¶
NotifyWidth sends a width_change notification to every connected extension that has not already seen this width. Call this from the TUI's resize handler.
func (*Host) OAuthProviderNames ¶
OAuthProviderNames returns runtime-registered OAuth provider IDs owned by an extension.
func (*Host) ProviderNames ¶
ProviderNames returns provider names registered by a loaded extension.
func (*Host) QuarantinedCells ¶
QuarantinedCells returns a snapshot of packed runtime cells disabled after a crash.
func (*Host) Reload ¶
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) SessionGraphObjectOf ¶
func (h *Host) SessionGraphObjectOf(conn *Conn, handle string) (SessionGraphObject, bool)
SessionGraphObjectOf returns the live object handle names on conn, or false when the connection holds none. The caller holds nothing: a caller that keeps the object past its call takes a hold with the table's retain.
func (*Host) SetBackgroundCallGate ¶
func (h *Host) SetBackgroundCallGate(gate func() <-chan struct{})
SetBackgroundCallGate installs the embedder's hold on the UI calls that no request started. Pi runs a timer or I/O callback only when its event loop turns, so a toast an extension deferred with setTimeout(0) while the host runs one chain of awaited handlers (a replacement's session_start, then its command's response) reaches the output after the chain's end, whereas this runtime's timer fires while the host's next dispatch crosses the process boundary. gate returns nil when such a call may run now, or a channel that closes when it may. The gate runs on host goroutines and must not block.
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 ¶
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) SetCommandWindowHandler ¶
SetCommandWindowHandler installs the process-owner callback that receives how many in-flight extension commands Pi's process would have left unanswered when it reads stdin's end: those that count suspended, and those of a runtime with no microtask continuation that are still running (FlushCommands applies the same rule to the flights themselves later). A Node command is not counted until its runtime reports its window closed, which it does only after runtime_input_end. The callback runs on host goroutines, must not block, and must not resume or cancel the command.
func (*Host) SetConfigLoader ¶
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. The host reads it from its connection and recovery goroutines, so a later call (a reload binds the host again) replaces it atomically.
func (*Host) SetHeightFunc ¶
SetHeightFunc registers the current terminal height. The host calls fn while holding its lock, so fn must not call back into the Host. fn runs on host goroutines, so it must read the height without the owner loop; later calls replace it atomically. pig additive (D52): expose height to extension SDKs.
func (*Host) SetHostInfo ¶
SetHostInfo records the configuration facts every extension process starts with.
func (*Host) SetInboundObserver ¶
SetInboundObserver registers a diagnostic observer of every frame an extension sends, in wire order, for every load mode (isolated, packed, fused). It runs on the connection's read loop before the frame is routed, so it must not block and must neither modify nor retain env. Nil (the default) observes nothing at no cost. Must be called before Host.Load, Host.LoadInProcess or Host.Reload.
pig additive (D107): conformance uses it to read the component kit's image transport (docs/plan/extension-component-kit.md §7, §10).
func (*Host) SetMode ¶
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) []*extension.ExtensionError
SetNativeProviderCallback binds connection-owned native provider registrations to the registry, drains the ones queued while extensions loaded and returns their owning-path diagnostics. A registration made before this call is queued, as upstream queues it until bindCore.
func (*Host) SetOutboundObserver ¶
SetOutboundObserver registers a diagnostic observer of the JSON of every frame the host writes to an extension, in write order, for every load mode (isolated, packed, fused). It runs on the connection's write loop before the frame is written, so it must not block and must neither modify nor retain frame. Nil (the default) observes nothing at no cost. Must be called before Host.Load, Host.LoadInProcess or Host.Reload.
pig additive (D107): conformance uses it to prove that every frame is the encoder's json.Marshal of its envelope.
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) SetReplacementHost ¶
SetReplacementHost installs the resolver of the host that serves the Session replacing this host's Session. The factory that builds each Session's host installs it; without it, a replacement context serves only its awaited messages.
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) SetSessionGraph ¶
func (h *Host) SetSessionGraph(backend SessionGraphBackend)
SetSessionGraph binds the backend that serves the session graph. Without one the calls fail with SessionGraphUnavailableMessage.
func (*Host) SetSettleTailHandler ¶
pig additive (D19): Pi reads stdin while a settle-tail handler waits on a timer or I/O; only the host sees that wait in a runtime that is another process. SetSettleTailHandler installs the process-owner callback that receives how many in-flight agent_before_settle and agent_settled handlers wait on something during which Pi's event loop reads stdin: a Node handler whose window closed unresponded and, after EndInput, a still-running handler of a runtime with no microtask continuation. The callback runs on host goroutines and must not block.
func (*Host) SetStartupTrace ¶
SetStartupTrace registers startup checkpoint instrumentation. Labels are stable and contain only the extension identity and lifecycle phase.
func (*Host) SetTimerTurns ¶
SetTimerTurns gives the host the owner's model of Pi's event loop (D189). A host call that the runtime marks Timer runs when the loop would run the timer or immediate that made it: while the agent's run chains microtasks it waits (jsloop.Turns). Without it such a call runs on arrival.
func (*Host) SetToolRenderersResolvedFunc ¶
SetToolRenderersResolvedFunc sets the callback run when an extension process answers a tool renderer resolution, so the mode draws the tool's cards again with the answer. It runs on a host goroutine.
func (*Host) SetUIBridge ¶
SetUIBridge attaches a UI bridge for handling widget pushes and UI method calls. Must be called before Host.Load.
func (*Host) SetWidthFunc ¶
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. The host calls fn while holding its lock, so fn must not call back into the Host. fn runs on host goroutines, so it must read the width without the owner loop; later calls replace it atomically.
func (*Host) Shutdown ¶
Shutdown detaches all extension consumers before removing providers, then stops and reaps every managed process. When it returns, each extension it stopped has withdrawn its ownership of thinking runs and told the observers (D214). 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.
func (*Host) TypeScriptRuntimeSelections ¶
TypeScriptRuntimeSelections returns the runtime each TypeScript extension launch of this Host used, by extension or cell name.
func (*Host) UseRuntime ¶
func (h *Host) UseRuntime(runtime *extension.ExtensionRuntime)
UseRuntime makes the Host register its extensions' provider, MCP server and virtual model state in runtime, so one runtime serves the file extensions this Host loads and the in-process factory extensions that register against the same value (resource-loader.ts passes preTrustExtensions.runtime to loadExtensionPaths). Call it before the first load; a nil runtime keeps the Host's own.
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
// A non-nil direct carries the identity already allocated in the extension process. direct.Event distinguishes pi.appendEntry (true) from ctx.sessionManager.appendCustomEntry (false). A nil direct asks the host to allocate the identity and emit 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
// GetSettings returns the effective settings object: global and project settings merged, with overrides. Backs pi.getSettings().
// upstream: types.ts:2135 (GetSettingsHandler)
GetSettings func() extension.Settings
// GetSettingsJSON, when set, returns GetSettings() as JSON in the member order of Pi's settings object, and a state push uses it in
// GetSettings' place: the host encodes the settings once per change, so a push does not encode them again. The bridge does not change the bytes.
GetSettingsJSON func() json.RawMessage
// GetCallableTools returns the tools a nested call can run. Backs ctx.tools.
// upstream: types.ts:2169 (getCallableTools)
GetCallableTools func() []extension.AgentTool
// ExecuteTool runs a nested tool call for the tool call callerID. ctx carries the calling request's cancellation. Backs ctx.executeTool().
// upstream: types.ts:2162 (executeTool)
ExecuteTool func(ctx context.Context, callerID, name string, args json.RawMessage, options extension.ExecuteToolOptions) (extension.AgentToolCallOutcome, error)
// 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
// GetCommandsVersion numbers the states of the catalog GetCommands returns. A push re-encodes the catalog only when the number changes, so it must change whenever GetCommands can return something different, and never repeat. Nil means every push encodes it.
GetCommandsVersion func() uint64
// 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 the active model's object (extension.ModelObject), or nil without a model.
// upstream: runner.ts:609 (model getter on ExtensionContext)
GetModelInfo func() json.RawMessage
// GetModelKey returns the identity of the model GetModelInfo describes: the metadata is a pure function of an immutable model value, so a state push re-encodes it only when the key changes. Nil means every push encodes it.
GetModelKey func() any
// GetScopedModels returns the Session's resolved model scope in selection order.
GetScopedModels func() []extension.ScopedModel
// GetModel resolves a model object (extension.ModelObject) by provider and model ID through the Session-owned runtime registry; nil when none matches.
GetModel func(providerID, modelID string) json.RawMessage
GetModels func() []json.RawMessage
// GetBranch was the conversation history as raw session entries.
//
// Deprecated: no extension call reads it, and the host never calls it. Extensions read the branch through sessionRead (SessionManager.getBranch) or the state_update session mirror.
GetBranch func() []json.RawMessage
// GetEntries was every session entry in append order.
//
// Deprecated: no extension call reads it, and the host never calls it. Extensions read the entries through sessionRead (SessionManager.getEntries) or the state_update session mirror.
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)
// GetAvailableOfType lists the models of one type whose provider has working credentials; provider "" means every provider.
// upstream: model-registry.ts getAvailableOfType(type, provider?)
GetAvailableOfType func(ctx context.Context, modelType, provider string) ([]json.RawMessage, error)
// Classify classifies through the Session runtime with request-time auth. The request is the classifier context object and the result is a ClassifierResult object, both as JSON so the order of questions and answers survives; failures are results, never errors.
// upstream: model-registry.ts classify(model, context, options?)
Classify func(ctx context.Context, model map[string]any, request json.RawMessage, options map[string]any) (json.RawMessage, error)
// GenerateImages generates images through the Session runtime with request-time auth. The request is the images context object and the result is an AssistantImages object, both as JSON; failures are results, never errors.
// upstream: model-registry.ts generateImages(model, context, options?)
GenerateImages func(ctx context.Context, model map[string]any, request json.RawMessage, options map[string]any) (json.RawMessage, 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)
// CreateChildSession builds a child agent session for an extension: Pi's createAgentSession (core/sdk.ts). The session shares the model runtime of the Session the host serves, so providers the extensions registered are available to it. Nil refuses the call.
CreateChildSession ChildSessionFactory
// 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
// GetSignal returns the active run's cancellation, or nil while no run is active.
// upstream: types.ts:2158
GetSignal func() context.Context
// 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)
// 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 HostInfo ¶
type HostInfo struct {
AgentDir string
ConfigDirName string
Version string
// PackageDir is getPackageDir(): PI_PACKAGE_DIR when set, else the directory of the host executable (Pi's own answer for a compiled binary).
PackageDir string
// Shell resolves getShellConfig() with no custom shell path. It runs when an extension process starts, not when the host records it: finding a shell may start
// a process. A nil Shell sends none.
Shell func() *ShellInfo
}
HostInfo is the host's answer to Pi's getAgentDir(), CONFIG_DIR_NAME, VERSION, getPackageDir() and the default getShellConfig() (config.ts, utils/shell.ts). Every extension process receives it in PIG_EXT_HOST_INFO, so an SDK returns the host's own values instead of rederiving them from an environment it may not share.
type ImageResult ¶
type ImageResult struct {
Image *struct {
Data string `json:"data"`
MimeType string `json:"mimeType"`
OriginalWidth *int `json:"originalWidth,omitempty"`
OriginalHeight *int `json:"originalHeight,omitempty"`
Width *int `json:"width,omitempty"`
Height *int `json:"height,omitempty"`
WasResized *bool `json:"wasResized,omitempty"`
} `json:"image"`
}
ImageResult is the result of CallConvertToPng and CallResizeImage: the image, or null (Pi's null). A converted image has Data and MimeType only; a resized one also the sizes Pi's ResizedImage carries.
func ConvertToPng ¶
func ConvertToPng(data, mimeType string) *ImageResult
ConvertToPng is Pi's convertToPng over the host's image code: nil is Pi's null.
func ResizeImage ¶
func ResizeImage(args ResizeImageArgs) (*ImageResult, error)
ResizeImage is Pi's resizeImage over the host's image code: a nil Image is Pi's null.
type InvalidateArgs ¶
type InvalidateArgs struct {
Message string `json:"message"`
}
InvalidateArgs is the NotifyInvalidate argument.
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.
type LoadThemeArgs ¶
type LoadThemeArgs struct {
Name *string `json:"name"`
}
LoadThemeArgs is the argument of CallLoadTheme. A null Name is initTheme(undefined).
type LoadThemeResult ¶
type LoadThemeResult struct {
Theme json.RawMessage `json:"theme"`
}
LoadThemeResult is the result of CallLoadTheme: the theme's palette, in the shape of ready.state.theme.
type LoopTurnArgs ¶
type LoopTurnArgs struct {
Turn uint64 `json:"turn"`
}
LoopTurnArgs numbers one loop turn (NotifyLoopTurned, NotifyLoopTurnTaken, RequestEventLoopTurn, NotifyEventLoopTurned).
type MarkdownTransformPayload ¶
type MarkdownTransformPayload struct {
Markdown string `json:"markdown"`
Context extension.MarkdownTransformContext `json:"context"`
}
MarkdownTransformPayload is the RequestMarkdownTransform argument.
type McpServerDecl ¶
type McpServerDecl struct {
Name string `json:"name"`
Config json.RawMessage `json:"config"`
}
McpServerDecl is one MCP server an extension registered. Config is the raw `mcpServers` entry: the host validates it with extension.ValidateMcpServerConfig, as upstream's registerMcpServer does.
type McpServerRef ¶
type McpServerRef struct {
Name string `json:"name"`
}
McpServerRef names one server.
type McpServersResult ¶
type McpServersResult struct {
Servers []extension.RegisteredMcpServer `json:"servers"`
}
McpServersResult is the reply of the MCP registration calls: every registered server after the call, in registration order. The SDK replaces its replicated list with it, so a getMcpServers that follows sees the change.
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"`
// Runtime names the session graph ModelRuntime the stream runs on (CallSessionGraphNew, kind ModelRuntime); empty is the Session's.
Runtime string `json:"runtime,omitempty"`
}
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, sent only to a Node runtime, removes stdin as a Node keepalive and releases each command's suspension: a command's request_state suspended is sent only after it, as a re-evaluation of the command's closed window (a command that started or finished a host call since its window closed gets a fresh window). After it, a Node process reports when its event loop drained, without arguments, on each connection it hosts, and the host applies runtime_drained and runtime_quit_yield to the process after every connection it holds for that process reported or closed. runtime_drained reports a still-pending quit handler whose event loop drained: Pi's exit when its loop empties, which takes the host's loop-drain checkpoint. runtime_commands_drained reports, from a process with no pending quit handler, that its event loop drained with an unanswered command it had not reported: the process cannot answer the commands whose started request_state precedes the report on each connection, and the host does not end. A command read after a report is reported again if the loop drains with it unanswered. runtime_quit_yield reports a post-disposal boundary that suspended beyond its immediately fulfilled continuations: Pi's exit at the stdout flush, which applies the flush checkpoint. Command suspension travels as request_state, after runtime_input_end. 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"`
OpenBrowserOnConfirm *bool `json:"openBrowserOnConfirm,omitempty"`
CopyCodeOnConfirm *bool `json:"copyCodeOnConfirm,omitempty"`
IntervalSeconds float64 `json:"intervalSeconds,omitempty"`
ExpiresInSeconds float64 `json:"expiresInSeconds,omitempty"`
}
type OAuthInputResult ¶
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 OAuthSelectOptionWire ¶
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 OwnThinkingRunsPayload ¶
type OwnThinkingRunsPayload struct {
Enabled *bool `json:"enabled"`
}
OwnThinkingRunsPayload is the CallOwnThinkingRuns argument; enabled is required.
type ParseDateArgs ¶
type ParseDateArgs struct {
Text string `json:"text"`
}
ParseDateArgs is the argument of CallParseDate.
type ParseDateResult ¶
type ParseDateResult struct {
Ms *float64 `json:"ms"`
}
ParseDateResult is the result of CallParseDate: the time value in milliseconds, null when Date.parse reads NaN.
type ParseFrontmatterArgs ¶
type ParseFrontmatterArgs struct {
Content string `json:"content"`
}
ParseFrontmatterArgs is the argument of CallParseFrontmatter.
type ParseFrontmatterResult ¶
type ParseFrontmatterResult struct {
Frontmatter json.RawMessage `json:"frontmatter"`
Body string `json:"body"`
}
ParseFrontmatterResult is the result of CallParseFrontmatter. Frontmatter is the JSON of `parse(yaml) ?? {}`: an object lists its keys in the order a JavaScript object enumerates them (array-index keys first, ascending, then insertion order), and any other YAML document is its scalar or array.
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"`
// ImageAPIs and ClassifierAPIs name the APIs whose implementations (ProviderConfig images and classifiers) run in the extension.
ImageAPIs []string `json:"image_apis,omitempty"`
ClassifierAPIs []string `json:"classifier_apis,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 ProviderObjectCall ¶
type PushProxy ¶
type PushProxy struct {
// contains filtered or unexported fields
}
PushProxy renders cached extension frames or host-laid-out string lists without extension I/O.
pig-specific: no upstream equivalent.
func NewPushProxy ¶
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) FrontendView ¶
FrontendView reports the widget's structure to a D91 frontend (D107): the extension's view, or for a string list the Text components Pi lays it out with.
func (*PushProxy) Invalidate ¶
func (p *PushProxy) Invalidate()
Invalidate marks the component for re-render. Called by the TUI framework. Proxy updates request rendering directly, so this is a no-op.
func (*PushProxy) IsFrame ¶
Lines returns the current cached lines (for testing/inspection). IsFrame reports whether the proxy holds a frame a component rendered at a width, as opposed to a string list the host lays out.
func (*PushProxy) Render ¶
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 ¶
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 ¶
UpdateLines replaces the cached lines and triggers a TUI re-render.
func (*PushProxy) UpdateLinesAt ¶
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.
func (*PushProxy) UpdateView ¶
UpdateView draws the widget from view, an authoritative view (linesWidth 0) or one annotating lines rendered at linesWidth.
func (*PushProxy) WidgetLayout ¶
WidgetLayout returns the dock placement and insertion order of this widget.
type ReadyPayload ¶
type ReadyPayload struct {
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)
Models []json.RawMessage `json:"models,omitempty"` //portlint:allow emptydrop PiG-only ready member (the complete registry snapshot for a runtime that declared WantsModelRegistry); absent and [] both give the Node runtime an empty catalog (runtime.mjs replaceModels → catalogOf)
Theme json.RawMessage `json:"theme,omitempty"` // Current theme data
State *StatePayload `json:"state,omitempty"` // Initial extension-host state snapshot
// SourceInfo is the provenance the loader stamped on this extension (path, source, scope, origin, baseDir): upstream's extension.sourceInfo, which ExtensionRunner.getExtensionPaths reads. Absent when the host holds none.
SourceInfo *extension.SourceInfo `json:"sourceInfo,omitempty"`
}
ReadyPayload is sent after successful registration. The session name and the active model travel in State (State.Session.SessionName, State.Model), the one snapshot every state_update repeats.
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"`
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"`
// OwnsThinkingRuns reports that the extension owns the thinking runs of assistant messages (pi.ownThinkingRuns), as of the register frame. Later changes arrive as CallOwnThinkingRuns.
// pig additive (D214)
OwnsThinkingRuns bool `json:"owns_thinking_runs,omitempty"`
// ToolRenderers is the number of tool renderer resolvers the extension
// registered while loading (pi.registerToolRenderer). The host asks them
// with RequestResolveToolRenderers; NotifyToolRenderers reports later ones.
ToolRenderers int `json:"tool_renderers,omitempty"`
// McpServers are the MCP servers the extension registered while loading. The host queues them like upstream's load-time registerMcpServer.
McpServers []McpServerDecl `json:"mcp_servers,omitempty"`
// VirtualModels are the virtual models the extension registered while loading. Routing calls back with RequestVirtualModelRoute.
VirtualModels []VirtualModelDecl `json:"virtual_models,omitempty"`
// UnregisterVirtualModels are the virtual models the extension unregistered while loading, in call order. Upstream's unregisterVirtualModel filters the runtime-wide queue of models registered before the runner binds, including another extension's (loader.ts:228-232), so the host applies them to that queue before it applies VirtualModels.
UnregisterVirtualModels []VirtualModelRef `json:"unregister_virtual_models,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"`
// WantsModelRegistry subscribes this extension to model-registry
// replication: the ready payload's Models and every model_registry_update
// notify. Runtimes whose ctx.modelRegistry readers can block on the host
// read getModelRegistryState on use and leave this false, so the host
// neither builds nor sends them a catalog snapshot; a runtime that answers
// those readers synchronously over asynchronous IPC declares it here.
WantsModelRegistry bool `json:"wants_model_registry,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 RemoteOverlayFocusPayload ¶
RemoteOverlayFocusPayload is a NotifyUICustomFocus argument.
type RemoteOverlayFocusResult ¶
type RemoteOverlayFocusResult struct {
OK *bool `json:"ok,omitempty"`
extension.RemoteOverlayState
FocusedKey string `json:"focusedKey"`
}
RemoteOverlayFocusResult answers a ui.custom control, showOverlay, hideOverlay or setFocus call: the overlay's state when the call names one, and FocusedKey, the key of the extension's mounted overlay that holds TUI focus afterwards ("" for none), so the extension clears the focused flag of every other component as Pi's setFocus does. OK is false when the UI has no TUI (showOverlay only).
type RemoteOverlayInputPayload ¶
type RemoteOverlayInputPayload struct {
Key string `json:"key"`
Data string `json:"data"`
State *extension.RemoteOverlayState `json:"state,omitempty"`
}
type RemoteOverlayMousePayload ¶
type RemoteOverlayMousePayload struct {
Key string `json:"key"`
Event extension.RemoteMouseEvent `json:"event"`
}
RemoteOverlayMousePayload is a NotifyUICustomMouse argument: Event is local to the component's first rendered cell.
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"`
// Blocked is upstream ui.custom()'s blocked option, the status an inline component reports while it is visible.
Blocked *extension.CustomBlocked `json:"blocked,omitempty"`
}
type RemoteOverlayRenderPayload ¶
type RemoteOverlayRenderPayload struct {
Key string `json:"key"`
// Lines are the frame's rows. Absent (nil) with a View, the view is
// authoritative and the host renders it (D107).
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"`
// View is the frame's component structure, a [ViewPayload] (D107).
View json.RawMessage `json:"view,omitempty"`
// Mouse reports a component that takes the mouse:
// the host hands it NotifyUICustomMouse events inside its bounds.
Mouse bool `json:"mouse,omitempty"`
// CapturesViewportInput is the component's capturesViewportInput when the frame was drawn (Component.capturesViewportInput in
// packages/tui/src/tui.ts): the host keeps fullscreen viewport keys (PageUp, PageDown, ...) away from the transcript while it is true.
CapturesViewportInput bool `json:"capturesViewportInput,omitempty"`
}
type RemoteOverlayShowPayload ¶
type RemoteOverlayShowPayload struct {
Key string `json:"key"`
OverlayOptions *extension.OverlayLayout `json:"overlayOptions,omitempty"`
}
RemoteOverlayShowPayload is a CallUICustomShowOverlay argument: the key the extension names the raw overlay by, and Pi's showOverlay options that can cross the process boundary.
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"`
// View is the rendered component's structure (D107); with Lines absent
// the host renders it at the requested width.
View json.RawMessage `json:"view,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"`
OutputPad int `json:"outputPad"`
// DurationMs is the recorded execution time of a final result in milliseconds. Absent while the result is partial and for results stored without one. upstream: ToolRenderContext.durationMs
DurationMs *int64 `json:"durationMs,omitempty"`
}
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"
// Renderers names resolved renderers (ResolvedToolRenderers.Renderers) to
// draw instead of the registered tool's.
Renderers string `json:"renderers,omitempty"`
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
// Batch, on tool_call, names the parallel batch the call belongs to: the same value for every call of one assistant message's batch, absent for a call of a sequential batch or one a tool makes inside its own. A runtime that runs each request on a thread of its own orders only the calls of one batch (Pi's single thread orders a batch's calls, not the calls of other sessions).
Batch string `json:"batch,omitempty"`
// ChildSession, on tool_call and tool_prepare_arguments, names the child agent session (CallChildSessionCreate) whose customTools define Tool: the tool is the one that session was created with, not one the extension registered. Absent, Tool is a registered tool.
ChildSession string `json:"child_session,omitempty"`
// ToolCallIndex, on tool_call, is the call's position among the tool calls of the assistant message that issued it (its batch). Absent for a call no assistant message issued (a nested executeTool call).
ToolCallIndex *int `json:"tool_call_index,omitempty"`
// SignalTimeoutMS, on oauth_refresh, tells a runtime whose refresh callback receives an AbortSignal that the signal is AbortSignal.timeout(SignalTimeoutMS) alone: the caller's cancellation never reaches it, as in Pi's refreshStoredOAuthCredential (auth/resolve.ts). Absent, the signal follows the request's cancellation.
SignalTimeoutMS *float64 `json:"signal_timeout_ms,omitempty"`
// OwnSignal, on tool_call, reports a nested call that runs with the signal its caller passed in options.signal: the tool's signal parameter is that signal, not the run's.
OwnSignal bool `json:"own_signal,omitempty"`
// ExecuteID, with OwnSignal, names the executeTool call of the same connection that made this nested call, so its runtime can hand the tool the very signal object its caller passed.
ExecuteID string `json:"execute_id,omitempty"`
// Stream, on a message_update or tool_execution_update event, says the payload is one of a numbered sequence on this connection: a request with Args is a keyframe the runtime keeps, a request without Args applies Stream.Ops to the payload numbered Stream.Base. The runtime hands the handler the full event either way.
Stream *EventStream `json:"stream,omitempty"`
// contains filtered or unexported fields
}
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 ResizeImageArgs ¶
type ResizeImageArgs struct {
Data string `json:"data"`
MimeType string `json:"mimeType"`
Options *struct {
MaxWidth int `json:"maxWidth,omitempty"`
MaxHeight int `json:"maxHeight,omitempty"`
MaxBytes int `json:"maxBytes,omitempty"`
JPEGQuality int `json:"jpegQuality,omitempty"`
} `json:"options,omitempty"`
}
ResizeImageArgs is the argument of CallResizeImage: Pi's `(inputBytes, mimeType, options?)` with the bytes in base64.
type ResolveToolRenderersPayload ¶
type ResolveToolRenderersPayload struct {
Tool string `json:"tool"`
Next *ToolRenderersDecl `json:"next"`
}
ResolveToolRenderersPayload is the RequestResolveToolRenderers argument. Next describes what next() returns: the renderers the remaining resolvers, then the registered tool, use, or null for none. The host evaluates it before asking; the extension's next() returns a marker for it.
type ResolvedToolRenderers ¶
type ResolvedToolRenderers struct {
Use string `json:"use"`
ToolRenderersDecl
Renderers string `json:"renderers,omitempty"`
}
ResolvedToolRenderers is the RequestResolveToolRenderers result. Use is "next" when the resolvers returned next()'s renderers, "none" when they returned none, and "own" for renderers of the extension, which the host draws with RequestRenderTool naming Renderers.
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 tool_call, Result carries a ToolCallResponsePayload. 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 SessionGraphBackend ¶
type SessionGraphBackend interface {
// New constructs the object kind's class builds with op (Pi's `new Class(...)` is op "new", a static factory is its name) from the positional JSON arguments. It never retains ctx past the call; scope is the connection's and lives as long as the object does.
New(ctx context.Context, scope SessionGraphScope, kind, op string, args json.RawMessage) (SessionGraphObject, error)
// Static runs a static function of kind's class that constructs no object, and answers its result in Pi's JSON shape. A nil result is JSON null.
Static(ctx context.Context, scope SessionGraphScope, kind, method string, args json.RawMessage) (any, error)
}
SessionGraphBackend constructs and serves the objects of the session graph (protocol_session_graph.go). The process that owns the coding package implements it; the host only keeps the objects for the connection that built them.
type SessionGraphCall ¶
type SessionGraphCall struct {
Handle string `json:"handle,omitempty"`
Kind string `json:"kind,omitempty"`
Method string `json:"method"`
Args json.RawMessage `json:"args,omitempty"`
}
SessionGraphCall is the CallSessionGraphCall and CallSessionGraphAsync argument. Handle names the object whose method runs; a static function (`SessionManager.list`, `hasTrustRequiringProjectResources`) names its class in Kind instead.
type SessionGraphCallbackArgs ¶
type SessionGraphCallbackArgs struct {
ID string `json:"id"`
Args json.RawMessage `json:"args,omitempty"`
}
SessionGraphCallbackArgs is the RequestSessionGraphCallback argument. ID is the name the extension gave the function in the option that carried it.
type SessionGraphHandle ¶
type SessionGraphHandle struct {
Handle string `json:"handle"`
}
SessionGraphHandle names an object of the connection.
type SessionGraphNew ¶
type SessionGraphNew struct {
Kind string `json:"kind"`
Op string `json:"op"`
Args json.RawMessage `json:"args,omitempty"`
}
SessionGraphNew is the CallSessionGraphNew argument. Op is the Pi constructor or static factory (`SessionManager.inMemory` is kind "SessionManager", op "inMemory"; a class constructed with `new` is op "new") and Args its positional arguments.
type SessionGraphObject ¶
type SessionGraphObject interface {
// Call runs the method Pi's class has under that name with the positional JSON arguments, and answers its result in Pi's JSON shape. A nil result is JSON null. A cancelled ctx is the method's aborted AbortSignal.
Call(ctx context.Context, method string, args json.RawMessage) (any, error)
}
SessionGraphObject is one object of the session graph.
type SessionGraphReleaser ¶
type SessionGraphReleaser interface {
Release()
}
SessionGraphReleaser is an object that holds resources past its last reference: the table calls Release once, when the last holder lets go. The extension's handle is one holder (it ends when the extension releases the handle or its connection closes) and every child session created over the object is another (it ends when the session closes), as an object of Pi's lives while anything reaches it.
type SessionGraphScope ¶
type SessionGraphScope interface {
// Object returns the live object handle names on the connection, which an option that takes an object (a loader's settingsManager) names by handle.
Object(handle string) (SessionGraphObject, bool)
// Retain adds a holder to the live object handle names, and returns the object and the function that ends that hold, which is idempotent; the object is released when its last holder lets go. An object that uses another (an ExtensionRunner over the loader whose extensions it dispatches to) holds it this way for as long as it lives.
Retain(handle string) (SessionGraphObject, func(), bool)
// Callback runs the function the extension named id (RequestSessionGraphCallback) and answers its result. A closed connection fails it.
Callback(ctx context.Context, id string, args json.RawMessage) (json.RawMessage, error)
// Add makes an object the host built (not one the extension constructed with CallSessionGraphNew) live for the connection and names it, so the extension can call its methods with CallSessionGraphCall. The extension's release call and the end of the connection drop it like any object; Remove drops it earlier.
Add(object SessionGraphObject) (handle string, err error)
// RegisterNativeProvider binds the Provider object the extension declared (a NativeProviderDeclaration as JSON: the callbacks stay in the extension) to the extension's connection and hands its carrier to register, which installs it in the registry of a graph ModelRuntime instead of the Session's. It answers the declaration with the host's handle for the object, and a release function that ends the registration: the object leaves the host when its last reference is gone.
RegisterNativeProvider(ctx context.Context, declaration json.RawMessage, register func(context.Context, *extension.NativeProvider) error) (declared json.RawMessage, release func(), err error)
// Remove drops the object Add named. A handle the extension already released is ignored.
Remove(handle string)
}
SessionGraphScope is the connection an object belongs to: the objects it holds and the functions it passed.
type SessionGraphStreamer ¶
type SessionGraphStreamer interface {
// StreamModel starts the stream for the model object and request an extension sent. ctx selects streamSimple (extension.ProviderStreamSimpleSelected) and carries the request's callbacks (extension.ModelStreamRequestFromContext).
StreamModel(ctx context.Context, model map[string]any, request map[string]any) (*ai.AssistantMessageEventStream, error)
}
SessionGraphStreamer is an object that serves a model stream (ModelRuntime.stream and streamSimple). A modelStream call that names the object's handle in its runtime field runs on it, and the call delivers the events as it does for the Session's runtime.
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 SetupArgs ¶
type SetupArgs struct {
Handle string `json:"handle"`
}
SetupArgs carries the setup callback handle.
type ShellInfo ¶
type ShellInfo struct {
Shell string `json:"shell,omitempty"`
//portlint:allow emptydrop Pi's ShellConfig.args is never empty: every shell Pi resolves carries its command flag
Args []string `json:"args,omitempty"`
CommandTransport string `json:"commandTransport,omitempty"`
Error string `json:"error,omitempty"`
}
ShellInfo is Pi's ShellConfig, or the error getShellConfig() throws when no shell is found.
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 {
// Commands is the wire form of the slash-command catalog ([]CommandInfo),
// pre-encoded so the host can omit it from a state_update whose recipient already holds it.
Commands json.RawMessage `json:"commands,omitempty"`
ThinkingLevel string `json:"thinkingLevel"`
Model 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"`
// Frontend reports that a D91 frontend session draws the interactive
// mode (D107): the Node runtime derives views only then, and SDKs send
// frontend-only view annotations only then.
Frontend bool `json:"frontend,omitempty"`
// Settings is the effective settings object behind pi.getSettings() (global and project merged, with overrides).
Settings json.RawMessage `json:"settings,omitempty"`
// McpServers is every server registered by extensions, behind pi.getMcpServers().
McpServers []extension.RegisteredMcpServer `json:"mcpServers"`
// 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.getThinkingLevel(), ctx.isIdle(), ctx.getContextUsage(), etc.). The tool registry is not state: pi.getAllTools() and pi.getActiveTools() are host calls, so a registration costs the SDK nothing in the size of the registry. 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. A state_update omits commands and systemPromptOptions while the recipient already holds them byte for byte; the ready state always carries them.
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 TimerDeferAckArgs ¶
type TimerDeferAckArgs struct {
Seq uint64 `json:"seq"`
}
TimerDeferAckArgs carries NotifyTimerDeferAck.
type TimerDeferArgs ¶
TimerDeferArgs carries NotifyTimerDefer. Seq numbers the frames of one connection; the runtime answers each with NotifyTimerDeferAck.
type ToolCallResponsePayload ¶
type ToolCallResponsePayload struct {
Input json.RawMessage `json:"_pigToolCallInput"`
Result json.RawMessage `json:"_pigToolCallResult"`
}
ToolCallResponsePayload is the result of a tool_call handler. Input is the event's input when the handler left it different from the one it received; an omitted Input means the handler made no edit. Result is the handler's ordinary block result. Any other member is an error: a reply in another shape would otherwise decode as no result and lose a block.
func (*ToolCallResponsePayload) UnmarshalJSON ¶
func (p *ToolCallResponsePayload) UnmarshalJSON(data []byte) error
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 *extension.ToolAnnotations `json:"annotations,omitempty"` // upstream ToolDefinition.annotations
// OutputSchema is upstream ToolDefinition.outputSchema.
OutputSchema json.RawMessage `json:"output_schema,omitempty"`
// Exposure is upstream ToolDefinition.exposure; empty is "direct".
Exposure string `json:"exposure,omitempty"`
// Namespace is upstream ToolDefinition.namespace.
Namespace *extension.ToolNamespace `json:"namespace,omitempty"`
// DefaultActive is upstream ToolDefinition.defaultActive; nil is the exposure's default.
DefaultActive *bool `json:"default_active,omitempty"`
// PreparesLoadout reports that the tool defines prepareLoadout. The host asks with RequestPrepareLoadout.
PreparesLoadout bool `json:"prepares_loadout,omitempty"`
// ReachesTools reports that the tool defines reachesTools (upstream ToolDefinition.reachesTools). The host asks with RequestReachesTools.
ReachesTools bool `json:"reaches_tools,omitempty"`
// PreparesArguments reports that the tool defines prepareArguments. The host asks with RequestPrepareArguments before it validates the arguments.
PreparesArguments bool `json:"prepares_arguments,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"`
}
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"`
// Exposure, Namespace, Annotations and ReachesTools are the tool definition's fields;
// upstream's Exposure is never absent (a definition without one is "direct").
// They precede sourceInfo, the member order of upstream's object literal,
// which a Node extension observes through Object.keys and JSON.stringify.
// upstream: types.ts:2122-2130 (ToolInfo), agent-session.ts:1498-1510 (getAllTools)
Exposure extension.ToolExposure `json:"exposure,omitempty"`
Namespace *extension.ToolNamespace `json:"namespace,omitempty"`
Annotations *extension.ToolAnnotations `json:"annotations,omitempty"`
ReachesTools ToolInfoReachesTools `json:"reachesTools,omitzero"`
// 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 ToolInfoReachesTools ¶
type ToolInfoReachesTools extension.ToolReachesToolsFunc
ToolInfoReachesTools is a ToolInfo's reachesTools: the definition's hook, nil for a tool that reaches no other tools. A function cannot cross the wire, so it encodes as true, the mark an SDK turns into a function that runs the hook with CallToolReachesTools.
upstream: types.ts:2122-2130 (ToolInfo picks reachesTools)
func (ToolInfoReachesTools) MarshalJSON ¶
func (ToolInfoReachesTools) MarshalJSON() ([]byte, error)
MarshalJSON encodes the hook as its mark.
type ToolLoadoutPayload ¶
type ToolLoadoutPayload struct {
Declared []extension.AgentTool `json:"declared"`
Callable []extension.AgentTool `json:"callable"`
Registered []extension.AgentTool `json:"registered"`
Exposures map[string]extension.ToolExposure `json:"exposures"`
Namespaces map[string]*extension.ToolNamespace `json:"namespaces,omitempty"`
// PromptGuidelines lists the guidelines of each registered tool that has any.
PromptGuidelines map[string][]string `json:"promptGuidelines,omitempty"`
}
ToolLoadoutPayload is upstream's ToolLoadout as JSON. Exposures, Namespaces and PromptGuidelines answer getExposure, getNamespace and getPromptGuidelines for every registered tool.
type ToolReachesToolsArgs ¶
type ToolReachesToolsArgs struct {
Tool string `json:"tool"`
Input json.RawMessage `json:"input,omitempty"`
}
ToolReachesToolsArgs are the arguments of CallToolReachesTools: the tool's name and the input to ask about. An absent input is an empty object.
type ToolRenderCardPayload ¶
type ToolRenderCardPayload struct {
Card string `json:"card"`
}
ToolRenderCardPayload names one tool card.
type ToolRenderersDecl ¶
type ToolRenderersDecl struct {
RenderShell string `json:"render_shell,omitempty"`
RendersCall bool `json:"renders_call,omitempty"`
RendersResult bool `json:"renders_result,omitempty"`
}
ToolRenderersDecl describes renderers by what they draw: upstream ToolRenderers' renderShell and whether renderCall and renderResult exist.
type ToolRenderersPayload ¶
type ToolRenderersPayload struct {
Count int `json:"count"`
}
ToolRenderersPayload is the NotifyToolRenderers argument.
type ToolResult ¶
type ToolResult struct {
// MemberOrder names the AgentToolResult members of the wire object in the order the tool wrote them, with upstream's names (isError for is_error). Pi hands the tool's own object on, so the events and the JSON stream write its members in that order (agent-loop.ts:778-786, 912-919).
MemberOrder []string `json:"-"`
Content []ai.ToolResultMessageContent `json:"-"`
Details json.RawMessage `json:"details,omitempty"`
IsError bool `json:"is_error,omitempty"`
// StructuredContent is upstream AgentToolResult.structuredContent: the machine-readable result of a tool that declares an outputSchema.
StructuredContent json.RawMessage `json:"structured_content,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"`
// pig additive (D160): the collapsed-view preview of a subprocess extension's tool result.
// 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 ¶
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 TypeEngineArgs ¶
type TypeEngineArgs struct {
Member string `json:"member"`
Args json.RawMessage `json:"args"`
}
TypeEngineArgs is the argument of CallTypeEngine. Args is the JSON list of the wire values of the member's arguments.
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()
// OnRunSignalChanged is called when a run begins or ends. Set by the Host, which brings every runtime up to date with the active run's signal (see [UIBridge.RunSignalChanged]).
OnRunSignalChanged func()
// OnHostStateChanged is called when host state that runtimes replicate changed with no extension call or event to announce it. Set by the Host, which pushes the new state to every connected runtime off the caller's goroutine (see [UIBridge.HostStateChanged]).
OnHostStateChanged 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 ¶
AllWidgets returns all widget proxies (for rendering).
func (*UIBridge) BatchModelCatalogPublication ¶
func (b *UIBridge) BatchModelCatalogPublication() func()
BatchModelCatalogPublication defers every PublishModelCatalog, including the ones SetModelCatalog and binding getModels or getModelRegistryState make, until the returned function runs; that function then publishes once if any publication was deferred. Binding the model operations together so sends each replica one snapshot of the finished binding instead of one per step: an extension idle until session_start would otherwise decode the whole catalog several times on the startup path. pig additive (D19): Pi's extensions read its ModelRegistry in process, so no snapshot crosses a process boundary there.
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 ¶
ClearExtension removes all widgets for a given extension (on crash/shutdown).
func (*UIBridge) ClearExtensionConn ¶
func (*UIBridge) ForgetProviderRegistration ¶
ForgetProviderRegistration drops a registered provider config. Upstream ModelRuntime.unregisterProvider.
func (*UIBridge) GetWidget ¶
GetWidget returns the PushProxy extName set under key, or nil when the key is unset or another extension's.
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, conn *Conn, push *WidgetPushPayload)
HandleWidgetPush processes a widget_push message from conn. 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. A push with a view (D107) is drawn from it.
func (*UIBridge) HostStateChanged ¶
func (b *UIBridge) HostStateChanged()
HostStateChanged tells the Host that state the runtimes replicate (the model, the thinking level, the session name, the settings, the MCP server list, the theme palette) changed without an extension call or an event to the extension, so every runtime learns it without waiting for its next request. Upstream's `ctx.model`, `pi.getSettings()`, `pi.getSessionName()`, `pi.getMcpServers()` and `ctx.ui.theme` read the live Session, the MCP registry and the global theme at every call (runner.ts:906, loader.ts:411-414 and 495-497, interactive-mode.ts:2665); a runtime replicates them, so a timer or thread that reads between two requests sees the host's value only when the host pushes it. The owner of the change reports it here, after the state changed. It returns at once: the push runs on a task the Host joins at Shutdown, because the owner may be the UI loop, which never waits for an extension.
func (*UIBridge) Invalidate ¶
func (b *UIBridge) Invalidate()
Invalidate requests a TUI render using the current host callback.
func (*UIBridge) ModelCatalog ¶
func (b *UIBridge) ModelCatalog() []json.RawMessage
func (*UIBridge) ModelRegistryState ¶
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 that replicates the model registry (RegisterPayload.WantsModelRegistry). With no such connection it builds nothing: a later one 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) (withdraw func())
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.
The returned function withdraws this registration again, as when the registry the host binds later refuses it: the config is rebuilt from the registrations that remain, and the provider disappears when none does. It does nothing once the provider was forgotten or replaced by a Provider object.
func (*UIBridge) RegisterExtConn ¶
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. A connection whose runtime declared RegisterPayload.WantsModelRegistry receives the current registry snapshot now and every later publication.
pig-specific: no upstream equivalent.
func (*UIBridge) RemoveWidget ¶
RemoveWidget drops the extension processes' widget under key, as a host-process extension setting the same key replaces it. It does not call the widget sync callback: the caller lays its widgets out itself.
func (*UIBridge) RunSignal ¶
RunSignal returns the active run's cancellation, or nil while no run is active or the host bound none.
func (*UIBridge) RunSignalChanged ¶
func (b *UIBridge) RunSignalChanged()
RunSignalChanged tells the Host that a run began or ended, so every runtime learns the new ctx.signal without waiting for its next request. Upstream's `ctx.signal` is a getter over `agent.signal` (runner.ts:917-920, agent.ts:336-338), live at every read; the Session or interactive owner reports each change here, after its agent's run state has changed.
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) SetFrontend ¶
SetFrontend records whether a frontend session draws the interactive mode and, when that changes, pushes a state_update so extensions see StatePayload.frontend: Node derives views and the SDKs send frontend-only annotations only while it is true. The push runs on the bridge's owned worker, off the caller's goroutine, because the caller is the UI loop and a push waits on every extension's connection.
pig additive (D107): stock PiG has no frontend and never sets it.
func (*UIBridge) SetHostAction ¶
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
- "getSettings": func() extension.Settings
- "getSettingsJSON": func() json.RawMessage
- "getCallableTools": func() []extension.AgentTool
- "executeTool": func(context.Context, string, string, json.RawMessage, extension.ExecuteToolOptions) (extension.AgentToolCallOutcome, error)
- "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
- "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
- "getSignal": func() context.Context
- "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 ¶
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() []json.RawMessage, 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 ¶
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 ¶
SetThemeFunc registers the source of the host's active theme palette, which every state snapshot carries.
func (*UIBridge) SetUIContext ¶
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) SetWidgetClearFunc ¶
SetWidgetClearFunc sets a callback for an extension clearing a widget key the extension processes do not hold: the key is one namespace with the host-process extensions' widgets, so the host clears its own widget under the key (Pi's setExtensionWidget).
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 ¶
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) 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) StopFrontendPushes ¶
func (b *UIBridge) StopFrontendPushes()
StopFrontendPushes stops the SetFrontend push worker and waits for a push in flight; later SetFrontend changes update the flag without a push.
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 UICancelDialog ¶
type UICancelDialog struct {
DialogID string `json:"dialogId"`
}
UICancelDialog is the CallUICancelDialog argument.
type UIPromptScope ¶
type UIPromptScope interface {
BeginUIPrompt(kind extension.UIPromptKind, title string) (end func())
// AwaitUIPromptEvents returns once every prompt event queued so far has reached its handlers, or when ctx ends.
AwaitUIPromptEvents(ctx context.Context)
}
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 UserBashExecArgs ¶
type UserBashExecArgs struct {
Command string `json:"command"`
Cwd string `json:"cwd"`
Timeout *float64 `json:"timeout,omitempty"`
Env *map[string]string `json:"env,omitempty"`
}
UserBashExecArgs is the RequestUserBashExec argument. Timeout is seconds; Env, when present even if empty, replaces the inherited environment.
type UserBashExecData ¶
type UserBashExecData struct {
Data string `json:"data"`
}
UserBashExecData is one onData chunk: the raw bytes, base64 encoded.
type UserBashExecResult ¶
type UserBashExecResult struct {
ExitCode *int `json:"exitCode"`
}
UserBashExecResult is the RequestUserBashExec answer: Pi's `{ exitCode: number | null }`. A null exit code is a failed command.
type ViewAssistantMessage ¶
type ViewAssistantMessage struct {
Content []ViewContentBlock `json:"content"`
StopReason string `json:"stopReason,omitempty"`
ErrorMessage string `json:"errorMessage,omitempty"`
}
ViewAssistantMessage is the part of upstream AssistantMessage that AssistantMessageComponent draws. StopReason "" is "stop".
type ViewAutocomplete ¶
type ViewAutocomplete struct {
//portlint:allow emptydrop the D107 view wire is PiG-owned with no Pi counterpart, and an absent and an empty command list mean the same: none
Commands []ViewSlashCommand `json:"commands,omitempty"`
BasePath string `json:"basePath,omitempty"`
}
ViewAutocomplete is a CombinedAutocompleteProvider(commands, basePath): the slash commands (without argument completion closures) and the directory its path completion starts from.
type ViewBashComplete ¶
type ViewBashComplete struct {
ExitCode *int `json:"exitCode,omitempty"`
Cancelled bool `json:"cancelled,omitempty"`
Truncated bool `json:"truncated,omitempty"`
FullOutputPath string `json:"fullOutputPath,omitempty"`
}
ViewBashComplete is a bash-execution's setComplete arguments: the exit code (nil: unknown), whether it was cancelled, whether the output was truncated, and where the full output is.
type ViewContentBlock ¶
type ViewContentBlock struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
Thinking string `json:"thinking,omitempty"`
Ref string `json:"ref,omitempty"`
MimeType string `json:"mimeType,omitempty"`
}
ViewContentBlock is a content block of an assistant message ("text" with Text, "thinking" with Thinking, or "toolCall") or of a tool result ("text" with Text, or "image" with Ref and MimeType).
type ViewCursor ¶
ViewCursor is an editor's cursor: a logical line and a UTF-16 column; an input's is its Col on line 0.
type ViewEventExtras ¶
type ViewEventExtras struct {
// Cursor is the cursor after a change, submit or escape of an input or editor.
Cursor *ViewCursor `json:"cursor,omitempty"`
// Mouse is the event a mouse-region took.
Mouse *extension.RemoteMouseEvent `json:"mouse,omitempty"`
}
ViewEventExtras are the ViewEventPayload fields of the widget events.
type ViewEventPayload ¶
type ViewEventPayload struct {
Key string `json:"key"`
Node string `json:"node"`
Type string `json:"type"`
Index int `json:"index"`
Item *ViewItem `json:"item,omitempty"`
ID string `json:"id,omitempty"`
Value string `json:"value,omitempty"`
ViewEventExtras
}
ViewEventPayload is a NotifyUIViewEvent argument. Index is the item's index among the shown (filtered) items for select and selectionChange; ID and Value are the setting and its new value for change.
type ViewEvictedPayload ¶
type ViewEvictedPayload struct {
Refs []string `json:"refs"`
}
ViewEvictedPayload is a NotifyUIViewEvicted argument.
type ViewImageData ¶
type ViewImageData struct {
Ref string `json:"ref"`
MimeType string `json:"mimeType"`
Data string `json:"data"` // base64
}
ViewImageData is image bytes: Ref is the lowercase hex SHA-256 of the decoded Data.
type ViewImageRef ¶
type ViewImageRef struct {
Ref string `json:"ref"`
}
ViewImageRef names image bytes already sent on the connection.
type ViewItem ¶
type ViewItem struct {
Value string `json:"value,omitempty"`
ID string `json:"id,omitempty"`
Label string `json:"label,omitempty"`
Description string `json:"description,omitempty"`
CurrentValue string `json:"currentValue,omitempty"`
//portlint:allow emptydrop the D107 view wire is PiG-owned with no Pi counterpart, and an absent and an empty value list mean the same: none
Values []string `json:"values,omitempty"`
}
ViewItem is a SelectItem (value, label, description) or a SettingItem (id, label, description, currentValue, values, submenu).
type ViewList ¶
type ViewList struct {
Items []ViewListItem `json:"items"`
SelectedIndex int `json:"selectedIndex"`
}
ViewList says a lines node's rows are a list: Items[i] is row i, so there are as many items as rows. SelectedIndex is the highlighted item, or -1.
type ViewListItem ¶
type ViewListItem struct {
Label string `json:"label"`
Detail string `json:"detail,omitempty"`
//portlint:allow emptydrop the D107 view wire is PiG-owned with no Pi counterpart, and an absent and an empty column list mean the same: none
Columns []string `json:"columns,omitempty"`
}
ViewListItem is one row of a ViewList: its primary text, an optional secondary text, and optional further cells of a table row (for example a track's artist, album and length).
type ViewLoaderIndicator ¶
type ViewLoaderIndicator struct {
Frames *[]string `json:"frames,omitempty"`
IntervalMs int `json:"intervalMs,omitempty"`
}
ViewLoaderIndicator mirrors LoaderIndicatorOptions. A given indicator is rendered verbatim, as upstream renders it; nil Frames are the default spinner and an empty list hides it.
type ViewMouseRegion ¶
type ViewMouseRegion struct {
//portlint:allow emptydrop the D107 view wire is PiG-owned with no Pi counterpart, and an absent and an empty type list mean the same: every type
Types []string `json:"types,omitempty"`
Handled *bool `json:"handled,omitempty"`
Capture bool `json:"capture,omitempty"`
Focus bool `json:"focus,omitempty"`
Render *bool `json:"render,omitempty"`
}
ViewMouseRegion is the handler of a mouse-region: onMouse returns this result for each event whose type is in Types (every type when none is named), and no result (undefined) for the others. The host answers the terminal at once with the result and reports each handled event to the extension as a "mouse" view event. Handled defaults to true.
type ViewNode ¶
type ViewNode struct {
Kind string `json:"kind"`
// ID names the node; required and unique for select-list and
// settings-list.
ID string `json:"id,omitempty"`
//portlint:allow emptydrop the D107 view wire is PiG-owned with no Pi counterpart, and an absent and an empty child list mean the same: none
Children []ViewNode `json:"children,omitempty"`
// Stack holds the StackEntry options of a child of hstack or vstack.
Stack *ViewStackEntry `json:"stack,omitempty"`
// Text is the text of text, truncated-text and markdown.
Text string `json:"text,omitempty"`
PaddingX *int `json:"paddingX,omitempty"`
PaddingY *int `json:"paddingY,omitempty"`
// Bg is the background token of box (bgFn) and text (customBgFn).
Bg string `json:"bg,omitempty"`
// Color is dynamic-border's foreground token (default "border").
Color string `json:"color,omitempty"`
DefaultTextStyle *ViewTextStyle `json:"defaultTextStyle,omitempty"`
RenderLatex *bool `json:"renderLatex,omitempty"`
// Lines is a spacer's line count.
Lines *int `json:"lines,omitempty"`
//portlint:allow emptydrop the D107 view wire is PiG-owned with no Pi counterpart, and an absent and an empty item list mean the same: none
Items []ViewItem `json:"items,omitempty"`
MaxVisible *int `json:"maxVisible,omitempty"`
Layout *ViewSelectLayout `json:"layout,omitempty"`
SelectedIndex *int `json:"selectedIndex,omitempty"`
Filter *string `json:"filter,omitempty"`
EnableSearch bool `json:"enableSearch,omitempty"`
// Ref names an image node's bytes.
Ref string `json:"ref,omitempty"`
MimeType string `json:"mimeType,omitempty"`
MaxWidthCells *int `json:"maxWidthCells,omitempty"`
MaxHeightCells *int `json:"maxHeightCells,omitempty"`
// ImageID is upstream ImageOptions.imageId, the Kitty image id; an
// absent one is allocated by the host as upstream allocates it.
ImageID *int `json:"imageId,omitempty"`
Filename string `json:"filename,omitempty"`
FallbackColor string `json:"fallbackColor,omitempty"`
// Message is a loader's message (default "Loading..."). On the wire an
// assistant-message's "message" is an object, [ViewNode.AssistantMessage].
Message *string `json:"message,omitempty"`
SpinnerColor string `json:"spinnerColor,omitempty"`
MessageColor string `json:"messageColor,omitempty"`
Indicator *ViewLoaderIndicator `json:"indicator,omitempty"`
// Frame is a loader's current frame index (upstream currentFrame);
// the host's animation continues from it.
Frame *int `json:"frame,omitempty"`
// Gap and Align are StackOptions of hstack and vstack.
Gap *int `json:"gap,omitempty"`
Align string `json:"align,omitempty"`
// Content is a lines node's rows, drawn verbatim.
//portlint:allow emptydrop the D107 view wire is PiG-owned with no Pi counterpart, and an absent and an empty row list mean the same: none
Content []string `json:"content,omitempty"`
// Image, Progress and List are frontend-only annotations of a lines
// node: the rows depict that image, show a position in a range, or are
// a list with one item per row.
Image *ViewImageRef `json:"image,omitempty"`
Progress *ViewProgress `json:"progress,omitempty"`
List *ViewList `json:"list,omitempty"`
// OutputPad is the outputPad of a user-message and an assistant-message
// (0 or 1), and of a tool-execution and a bash-execution (any
// non-negative integer, as their constructors and setOutputPad take it);
// default 1.
OutputPad *int `json:"outputPad,omitempty"`
// AssistantMessage is an assistant-message's message, the wire's
// "message" object; nil before one arrives.
AssistantMessage *ViewAssistantMessage `json:"-"`
HideThinkingBlock bool `json:"hideThinkingBlock,omitempty"`
HiddenThinkingLabel *string `json:"hiddenThinkingLabel,omitempty"`
IsStreaming bool `json:"isStreaming,omitempty"`
// ToolName, ToolCallID, Args, ToolDefinition and Cwd are a
// tool-execution's constructor arguments; Args is any JSON value
// (default {}) and ToolDefinition a ViewToolDefinition* name (default
// builtin).
ToolName string `json:"toolName,omitempty"`
ToolCallID string `json:"toolCallId,omitempty"`
Args json.RawMessage `json:"args,omitempty"`
ToolDefinition string `json:"toolDefinition,omitempty"`
Cwd string `json:"cwd,omitempty"`
ShowImages *bool `json:"showImages,omitempty"`
ImageWidthCells *int `json:"imageWidthCells,omitempty"`
// ExecutionStarted, ArgsComplete, Result and IsPartial (default true)
// are a tool-execution's state; Expanded is a tool-execution's and a
// bash-execution's.
ExecutionStarted bool `json:"executionStarted,omitempty"`
ArgsComplete bool `json:"argsComplete,omitempty"`
Expanded bool `json:"expanded,omitempty"`
Result *ViewToolResult `json:"result,omitempty"`
IsPartial *bool `json:"isPartial,omitempty"`
// Command, ExcludeFromContext, Output and Complete are a
// bash-execution's: Output is the output appended so far and Complete
// the setComplete arguments, nil while the command runs.
Command string `json:"command,omitempty"`
ExcludeFromContext bool `json:"excludeFromContext,omitempty"`
Output string `json:"output,omitempty"`
Complete *ViewBashComplete `json:"complete,omitempty"`
// Diff and FilePath are a diff node's renderDiff arguments.
Diff string `json:"diff,omitempty"`
FilePath string `json:"filePath,omitempty"`
// ViewWidgetFields are the fields of the widget kinds (view_widget_wire.go).
ViewWidgetFields
}
ViewNode is one component. Fields mirror the upstream constructor parameters and state; an omitted field takes the upstream default.
func (ViewNode) MarshalJSON ¶
MarshalJSON writes "message" from Message, or from AssistantMessage after the other fields.
func (*ViewNode) UnmarshalJSON ¶
UnmarshalJSON reads "message" as a loader's string or an assistant-message's object.
type ViewPayload ¶
type ViewPayload struct {
Root ViewNode `json:"root"`
// Focus is the id of the select-list or settings-list that receives
// the keys it binds (ui.custom only).
Focus string `json:"focus,omitempty"`
// Theme overrides theme tokens for this surface only: token name to
// "#rrggbb".
//portlint:allow emptydrop the D107 view wire is PiG-owned with no Pi counterpart, and an absent and an empty theme mean the same: none
Theme map[string]string `json:"theme,omitempty"`
// Width is the cells the sender laid the frame's lines out at; required
// when the frame also carries lines.
Width int `json:"width,omitempty"`
// Images carries image bytes the first time a frame on the connection
// references them.
//portlint:allow emptydrop the D107 view wire is PiG-owned with no Pi counterpart, and an absent and an empty image list mean the same: none
Images []ViewImageData `json:"images,omitempty"`
}
ViewPayload is one view: a component tree with the surface's focus, theme overrides and the image bytes first sent with this frame.
type ViewProgress ¶
ViewProgress is a position in a range.
type ViewSelectLayout ¶
type ViewSelectLayout struct {
MinPrimaryColumnWidth *int `json:"minPrimaryColumnWidth,omitempty"`
MaxPrimaryColumnWidth *int `json:"maxPrimaryColumnWidth,omitempty"`
}
ViewSelectLayout mirrors SelectListLayoutOptions without truncatePrimary.
type ViewSkill ¶
type ViewSkill struct {
Name string `json:"name,omitempty"`
Content string `json:"content,omitempty"`
}
ViewSkill is the part of a ParsedSkillBlock a skill-invocation draws.
type ViewSlashCommand ¶
type ViewSlashCommand struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
ArgumentHint string `json:"argumentHint,omitempty"`
}
ViewSlashCommand is a SlashCommand without getArgumentCompletions.
type ViewStackEntry ¶
type ViewStackEntry struct {
Basis *int `json:"basis,omitempty"`
Grow *int `json:"grow,omitempty"`
Shrink *int `json:"shrink,omitempty"`
MinSize *int `json:"minSize,omitempty"`
MaxSize *int `json:"maxSize,omitempty"`
}
ViewStackEntry mirrors upstream StackEntryOptions without visible. A nil Basis is "auto".
type ViewTextStyle ¶
type ViewTextStyle struct {
Color string `json:"color,omitempty"`
BgColor string `json:"bgColor,omitempty"`
Bold bool `json:"bold,omitempty"`
Italic bool `json:"italic,omitempty"`
Strikethrough bool `json:"strikethrough,omitempty"`
Underline bool `json:"underline,omitempty"`
}
ViewTextStyle mirrors upstream Markdown DefaultTextStyle with tokens for its color functions.
type ViewToolResult ¶
type ViewToolResult struct {
Content []ViewContentBlock `json:"content"`
IsError bool `json:"isError,omitempty"`
Details json.RawMessage `json:"details,omitempty"`
DurationMs *int64 `json:"durationMs,omitempty"`
}
ViewToolResult is the result a tool-execution's updateResult receives. DurationMs is the final result's recorded execution time in milliseconds, nil for none (upstream tool-execution.ts result.durationMs); a card shows it only once the result is final.
type ViewWidgetFields ¶
type ViewWidgetFields struct {
// Summary is the markdown of a branch-summary and a compaction-summary;
// TokensBefore a compaction-summary's context size before compaction.
Summary string `json:"summary,omitempty"`
TokensBefore *int `json:"tokensBefore,omitempty"`
// Skill is a skill-invocation's skill block.
Skill *ViewSkill `json:"skill,omitempty"`
// CustomType is a custom-message's customType; its content is Text.
CustomType string `json:"customType,omitempty"`
// Cancellable is a bordered-loader's `{cancellable}` option (default true).
Cancellable *bool `json:"cancellable,omitempty"`
// Value is an input's and an editor's text. Prompt, Placeholder and
// PlaceholderColor (a foreground token for placeholderStyle) are an
// input's InputOptions.
Value string `json:"value,omitempty"`
Prompt *string `json:"prompt,omitempty"`
Placeholder string `json:"placeholder,omitempty"`
PlaceholderColor string `json:"placeholderColor,omitempty"`
// Cursor and Focused are the state of an input or an editor whose
// component the sender owns (Node's): the cursor it holds and its
// Focusable flag, applied each frame when they differ from the frame
// before. A host-owned widget (the Go, Rust and Python SDKs') keeps its
// own cursor and takes its focus from the view's Focus, so those SDKs
// send neither.
Cursor *ViewCursor `json:"cursor,omitempty"`
Focused bool `json:"focused,omitempty"`
// AutocompleteMaxVisible, BorderColor (a foreground token for
// borderColor, default "borderMuted"), DisableSubmit, History (the
// addToHistory calls, oldest first) and Autocomplete (the
// CombinedAutocompleteProvider handed to setAutocompleteProvider) are an
// editor's.
AutocompleteMaxVisible *int `json:"autocompleteMaxVisible,omitempty"`
BorderColor string `json:"borderColor,omitempty"`
DisableSubmit bool `json:"disableSubmit,omitempty"`
//portlint:allow emptydrop the D107 view wire is PiG-owned with no Pi counterpart, and an absent and an empty history mean the same: none
History []string `json:"history,omitempty"`
Autocomplete *ViewAutocomplete `json:"autocomplete,omitempty"`
// Follow ("none" or "end"), Primary, Overscroll ("chain" or "contain"),
// Scrollbar ("hidden", "auto" or "always"), ScrollbarTrackColor and
// ScrollbarThumbColor (foreground tokens for the style closures),
// ScrollbarHideDelayMs and ScrollTop (state) are a scroll-view's
// ScrollViewOptions.
Follow string `json:"follow,omitempty"`
Primary bool `json:"primary,omitempty"`
Overscroll string `json:"overscroll,omitempty"`
Scrollbar string `json:"scrollbar,omitempty"`
ScrollbarTrackColor string `json:"scrollbarTrackColor,omitempty"`
ScrollbarThumbColor string `json:"scrollbarThumbColor,omitempty"`
ScrollbarHideDelayMs *int `json:"scrollbarHideDelayMs,omitempty"`
ScrollTop *int `json:"scrollTop,omitempty"`
// Region is a mouse-region's handler, which cannot cross as a closure.
Region *ViewMouseRegion `json:"region,omitempty"`
}
ViewWidgetFields are the ViewNode fields of the widget kinds; an omitted field takes the upstream default.
type VirtualModelDecl ¶
type VirtualModelDecl struct {
Provider string `json:"provider"`
ID string `json:"id"`
Name string `json:"name"`
ThinkingLevels []string `json:"thinkingLevels,omitempty"`
ContextWindow int `json:"contextWindow,omitempty"`
MaxTokens int `json:"maxTokens,omitempty"`
Input []string `json:"input,omitempty"`
}
VirtualModelDecl declares a virtual model. It carries every VirtualModelDefinition field except route, which the extension keeps and the host calls with RequestVirtualModelRoute.
type VirtualModelRef ¶
VirtualModelRef names one virtual model.
type VirtualModelRouteArgs ¶
type VirtualModelRouteArgs struct {
VirtualModelRef
Request VirtualModelRouteRequest `json:"request"`
}
VirtualModelRouteArgs is the RequestVirtualModelRoute argument.
type VirtualModelRouteFailed ¶
type VirtualModelRouteFailed struct {
Model json.RawMessage `json:"model"`
ThinkingLevel string `json:"thinkingLevel,omitempty"`
Message json.RawMessage `json:"message"`
}
VirtualModelRouteFailed is the failed request of a retry; Message is its AssistantMessage.
type VirtualModelRoutePrevious ¶
type VirtualModelRoutePrevious struct {
Model json.RawMessage `json:"model"`
ThinkingLevel string `json:"thinkingLevel,omitempty"`
}
VirtualModelRoutePrevious is the physical model and thinking level of the latest successful response.
type VirtualModelRouteRequest ¶
type VirtualModelRouteRequest struct {
Model json.RawMessage `json:"model"`
ThinkingLevel string `json:"thinkingLevel"`
Reason string `json:"reason"`
Previous *VirtualModelRoutePrevious `json:"previous,omitempty"`
Failed *VirtualModelRouteFailed `json:"failed,omitempty"`
State json.RawMessage `json:"state,omitempty"`
Messages []json.RawMessage `json:"messages"`
}
VirtualModelRouteRequest is upstream's ModelRouteRequest as JSON. Models are Pi's model objects (extension.ModelObject), Messages are session messages.
type VirtualModelRouteResult ¶
type VirtualModelRouteResult struct {
Model map[string]any `json:"model"`
ThinkingLevel string `json:"thinkingLevel"`
State json.RawMessage `json:"state,omitempty"`
// StateUnchanged reports that the router returned the state object it was given. Upstream stores a router's state unless `route.state === request.state` (agent-session.ts:788), and only a runtime that has object identity can say so: Node sends it, and the host answers the session with the request's own state. The other SDKs leave it unset and the host compares the JSON values.
StateUnchanged bool `json:"stateUnchanged,omitempty"`
}
VirtualModelRouteResult is upstream's ModelRoute as JSON. Model is the Model object the router returned; the host reads its provider and id and resolves the physical model. A State that is absent keeps the current state.
type WidgetPushPayload ¶
type WidgetPushPayload struct {
Key string `json:"key"` // Widget slot 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)
// View is the widget's component structure (D107); with Lines absent
// the host renders it at the widget's width.
View json.RawMessage `json:"view,omitempty"`
}
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.
type WithSessionArgs ¶
type WithSessionArgs struct {
Handle string `json:"handle"`
Ready *ReadyPayload `json:"ready"`
}
WithSessionArgs carries the callback handle and the replacement Session's ready payload. A runtime that answers context getters from local state answers the replacement context from Ready.
Source Files
¶
- accept_client.go
- accept_client_unix.go
- ack_hold.go
- autocomplete_bridge.go
- boundary_wire.go
- build_failure_group.go
- build_line.go
- builder.go
- builder_listing.go
- builder_node.go
- cache_roots.go
- cell_plan.go
- cell_start.go
- child_session.go
- child_session_delta.go
- conn.go
- content_hash.go
- declaration_registration.go
- doc.go
- early_model_stream.go
- editor_proxy.go
- embedded_cells.go
- event_bus.go
- event_bus_retention.go
- event_payload.go
- extension_listener_unix.go
- facet_bridge.go
- frame_buffers.go
- fused_conn.go
- fused_resolver.go
- generation_retirement.go
- harness_identity.go
- host.go
- host_builtin_tool.go
- host_calls.go
- host_extension_api.go
- host_file_mutation.go
- host_helpers.go
- host_state_push.go
- load_error_cause.go
- loop_turns.go
- markdown_transform_proxy.go
- message_update_delta.go
- model_fetch.go
- model_stream_callbacks.go
- native_provider.go
- native_provider_auth.go
- native_provider_login.go
- native_provider_models.go
- native_provider_oauth.go
- node_file_url.go
- node_recovery.go
- node_runtime_cache.go
- node_runtime_on.go
- oauth_bridge.go
- oauth_signal.go
- overlay_control.go
- own_thinking_runs.go
- packed_go.go
- packed_lisp.go
- packed_log.go
- packed_node.go
- packed_python.go
- packed_quarantine.go
- packed_rust.go
- peer_exit.go
- platform.go
- process_tree_unix.go
- prompt_options.go
- protocol.go
- protocol_builtin_tool.go
- protocol_child_session.go
- protocol_events.go
- protocol_extension_api.go
- protocol_session_graph.go
- provider_config_ref.go
- provider_object.go
- provider_object_lifetime.go
- provider_operations.go
- provider_stream.go
- push_proxy.go
- reload_cells.go
- reload_report.go
- render_proxy.go
- retention.go
- run_signal.go
- runtime_node_digest_generated.go
- scoped_model_snapshot.go
- sdk_fingerprint.go
- session_graph.go
- session_graph_native_provider.go
- socket_runtime_base_unix.go
- source_resolver.go
- startup.go
- supervisor.go
- sync_run_hold.go
- terminal_capabilities_env.go
- terminal_input_state.go
- timer_defer.go
- tool_registration.go
- tool_render_proxy.go
- tool_renderer_resolvers.go
- tool_update_delta.go
- ts_runtime.go
- tui_alt_bridge.go
- tui_alt_enable.go
- type_engine.go
- ui_bridge.go
- ui_prompt.go
- user_bash_operations.go
- user_id_unix.go
- view_images.go
- view_kit.go
- view_kit_bordered_loader.go
- view_kit_branch_summary.go
- view_kit_cancellable_loader.go
- view_kit_compaction_summary.go
- view_kit_conversation.go
- view_kit_custom_message.go
- view_kit_editor.go
- view_kit_expandable.go
- view_kit_input.go
- view_kit_mouse_region.go
- view_kit_scroll_view.go
- view_kit_skill_invocation.go
- view_kit_widgets.go
- view_widget_wire.go
- view_wire.go
- wire_equal.go
- with_session.go
- xref.go
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. |
|
noderuntimepack
Package noderuntimepack stores the embedded Node runtime as a few solid zstd blocks.
|
Package noderuntimepack stores the embedded Node runtime as a few solid zstd blocks. |
|
noderuntimepeers
Package noderuntimepeers generates the host peer packages of the Node runtime archive: package.json and entry modules under runtime-node/harness/node_modules.
|
Package noderuntimepeers generates the host peer packages of the Node runtime archive: package.json and entry modules under runtime-node/harness/node_modules. |