inproc

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package inproc implements the in-process Go dispatch runner for extensions.

Architecture. Extensions are loaded as pre-populated `extension.Extension` state containers (the loader, not this package, runs the factory functions and populates the maps). A Runner wraps `[]Extension` and:

  • Dispatches events to typed handlers (the hot path).
  • Aggregates registered tools, commands, shortcuts, flags, and renderers from across all loaded extensions for the agent core and TUI to consume.
  • Owns the staleness lifecycle: on /reload or session replacement, the host calls `Runner.Invalidate(message)` and any subsequent API call captured by a context bound to this runner returns ErrStaleContext. This mirrors upstream `runner.ts:461-471`.

Scope. This package owns the parity dispatch engine: stale-state lifecycle, resource aggregation, event dispatch, handler errors, providers, and resource diagnostics. Loading and transport adaptation live outside this package.

Sync compatibility. Field names and method names mirror upstream `runner.ts` private/public names verbatim where the Go semantics permit. Each exported method's doc comment cites `// upstream: runner.ts:NNN`. The atomic.Pointer used for the stale flag is a TS→Go translation rule (docs/parity/DIVERGENCES.md), not a divergence.

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

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EmitProjectTrust

EmitProjectTrust dispatches project_trust in extension and registration order, passing each handler the event, the dispatch context and trust (runner.ts emitProjectTrustEvent ctx). Undecided handlers fall through; the first decisive result wins. Handler failures are collected and do not stop later handlers, matching the pre-runtime upstream helper.

func RenderSystemPrompt

func RenderSystemPrompt(options extension.BuildSystemPromptOptions) (string, error)

RenderSystemPrompt is Pi's buildSystemPrompt(options) (system-prompt.ts:208): an exact forced prompt, or the base sections for the options with their custom sections applied, rendered as the transcript's system message replays them. An invalid custom section is an error, as Pi's builder throws.

Types

type BoundaryDispatchResult

type BoundaryDispatchResult struct {
	Entries  []extension.SessionBoundaryDraft
	Continue bool
	Context  extension.BoundaryContextPreview
	Valid    bool
}

BoundaryDispatchResult is the chained, validated result of turn_end or agent_before_settle handlers.

type ExtensionSource

type ExtensionSource struct {
	ResolvedPath string
	SourceInfo   extension.SourceInfo
	Hidden       bool
}

ExtensionSource is one loaded extension's resolved path and SourceInfo. Hidden extensions are omitted from the startup Extensions list (upstream extension.hidden, types.ts:2213).

type Runner

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

Runner is the in-process Go dispatch runner for extensions.

upstream: runner.ts:219 (export class ExtensionRunner)

func NewExtensionRunner

func NewExtensionRunner(extensions []extension.Extension, runtime *extension.ExtensionRuntime, cwd string, sessionManager extension.SessionManager, modelRegistry extension.ModelRegistry) *Runner

NewExtensionRunner is Pi's ExtensionRunner constructor (extensions, runtime, cwd, sessionManager, modelRegistry): the runner over the loader's extensions and its shared runtime, with the log ctx.sessionManager exposes and the registry ctx.modelRegistry and provider registration read. A nil runtime gives the runner a fresh one; a nil sessionManager or modelRegistry waits for the binding that supplies it (Runner.BindSessionManager, Runner.BindCore).

upstream: runner.ts:395-408 (constructor)

func NewRunner

func NewRunner(extensions []extension.Extension, cwd string, sharedRuntime ...*extension.ExtensionRuntime) *Runner

NewRunner constructs a Runner over the given pre-populated extensions. Supply the loader's shared runtime to bind its pending provider registrations; otherwise the runner owns a fresh runtime.

extensions is typically produced by a loader (compiled-in registration or the subprocess transport adapter). cwd is captured for relative path resolution by extension factories.

upstream: runner.ts:395-408 (constructor)

func (*Runner) ActiveCommands

func (r *Runner) ActiveCommands() int

ActiveCommands reports how many command handlers are running.

func (*Runner) AddErrorListener

func (r *Runner) AddErrorListener(listener extension.ErrorListener) func()

AddErrorListener registers a synchronous callback. Each call creates an independent registration. The returned function removes only that registration.

func (*Runner) AwaitEventLoopTurns

func (r *Runner) AwaitEventLoopTurns(ctx context.Context, event string)

AwaitEventLoopTurns gives each extension that handles event and runs on an event loop of its own (Extension.EventLoopTurn) one turn of that loop, concurrently, and returns when every one took it. Pi runs its tools on the extensions' event loop, so the callbacks an event handler queued run before the tool's result; this keeps that order when the tool ran elsewhere. pig additive (D19): a turn that fails is not waited for; the extension's next dispatch reports its connection.

func (*Runner) AwaitUIPromptEvents

func (r *Runner) AwaitUIPromptEvents(ctx context.Context)

AwaitUIPromptEvents returns once the handlers of every ui_prompt event queued before the call have been invoked, or when ctx ends.

upstream: runner.ts emitUIPromptEvent queues the emission in a microtask before withUIPrompt's promise settles, so each handler's synchronous part runs before the prompting extension continues. The subprocess bridge waits here before it answers a dialog call.

func (*Runner) BeginUIPrompt

func (r *Runner) BeginUIPrompt(kind extension.UIPromptKind, title string) (end func())

BeginUIPrompt records that a blocking extension UI prompt started and returns the function that records its end. Call end exactly once when the prompt settles, whether it resolved, was cancelled, or failed; extra calls are ignored.

The runner wraps the UI surface bound by Runner.SetUIContext with this scope for in-process extensions. Subprocess prompts reach the terminal through the subprocess UI bridge, which calls BeginUIPrompt when the host call arrives, before it waits for terminal focus.

upstream: runner.ts withUIPrompt (private; pig exposes it because the subprocess bridge sits outside the runner).

func (*Runner) BindAbort

func (r *Runner) BindAbort(abort func())

BindAbort installs the active Session's non-blocking abort action without replacing the mode's other context actions. Call it before dispatching handlers. upstream: packages/coding-agent/src/core/agent-session.ts:_bindExtensionCore

func (*Runner) BindCommandActions

func (r *Runner) BindCommandActions(actions extension.CommandActions)

BindCommandActions installs the command-specific actions used by Runner.CreateCommandContext. Each non-nil action replaces the bound one and a nil action keeps it, so the Session's own actions (bound in every mode) and a mode's actions compose whichever binds first.

upstream: runner.ts:628 (createCommandContext consumes runner.* fields set during bindExtensions)

func (*Runner) BindCore

func (r *Runner) BindCore(
	actions extension.ExtensionActions,
	contextActions extension.ContextActions,
	providerActions *extension.ProviderActions,
)

BindCore installs the host-injected callbacks that back the dynamic surfaces on extension.Context (Model, IsIdle, Shutdown, etc.) plus the agent-loop and provider action sets. It reports queued provider failures through error listeners without stopping the drain; subsequent registration calls use the registry immediately.

Idempotent in spirit but NOT thread-safe relative to in-flight dispatches: the host must call this during runtime construction, before the runner is exposed to handlers. Per upstream's bindCore invariant: "called once during runtime initialization".

upstream: runner.ts:265-294

func (*Runner) BindScopedModels

func (r *Runner) BindScopedModels(getScopedModels func() []extension.ScopedModel)

BindScopedModels binds the Session's scope without replacing the mode's other context actions. Bind before dispatch; existing contexts retain their captured callback. upstream: packages/coding-agent/src/core/agent-session.ts:_bindExtensionCore

func (*Runner) BindSessionManager

func (r *Runner) BindSessionManager(manager extension.ReadonlySessionManager)

BindSessionManager rebinds the log ctx.sessionManager exposes to contexts made afterwards. It is safe to call while handlers run.

upstream: runner.ts:889-891 (`get sessionManager()` reads the runner's session manager); a replacement binds a new AgentSession's manager to a new runner (agent-session-runtime.ts), which Go's in-place Session.ReplaceInner has no counterpart for.

func (*Runner) BindSystemPromptOptions

func (r *Runner) BindSystemPromptOptions(get func() *extension.BuildSystemPromptOptions)

BindSystemPromptOptions installs a live Session options source when the mode has not supplied one. Bind before handler dispatch.

func (*Runner) BindTools

func (r *Runner) BindTools(actions extension.ContextActions)

BindTools installs the Session's live tool/state views and message delivery action without replacing unrelated mode callbacks. Call it before dispatching handlers. upstream: packages/coding-agent/src/core/agent-session.ts:_bindExtensionCore

func (*Runner) Command

func (r *Runner) Command(invocationName string) (extension.ResolvedCommand, bool)

Command returns the resolved command whose invocation name matches. The boolean reports whether it was found.

upstream: runner.ts:550-552 (getCommand). Upstream re-resolves on every call: so does this. No caching.

func (*Runner) CommandDiagnostics

func (r *Runner) CommandDiagnostics() []extension.ResourceDiagnostic

CommandDiagnostics returns the warnings/errors collected during the most recent Commands() call. Empty until Commands() runs at least once.

upstream: runner.ts:546-548 (getCommandDiagnostics)

func (*Runner) Commands

func (r *Runner) Commands() []extension.ResolvedCommand

Commands returns the resolved slash commands across all extensions, with first-wins suffix-disambiguated invocation names. Two commands with the same name `foo` produce invocation names `foo:1` and `foo:2` (occurrence order = load order); a unique name keeps the bare form.

Side effect: clears the command diagnostics buffer (mirrors upstream `getRegisteredCommands` runner.ts:541-544 which assigns `this.commandDiagnostics = []` before running resolveRegisteredCommands).

upstream: runner.ts:505-544 (resolveRegisteredCommands + getRegisteredCommands)

func (*Runner) CommandsVersion

func (r *Runner) CommandsVersion() (uint64, bool)

CommandsVersion reports a counter that moves whenever Commands can return something different: the sum of the extensions' command versions, which only grow. The boolean is false when an extension's commands have no version.

func (*Runner) CreateCommandContext

func (r *Runner) CreateCommandContext() *extension.CommandContext

CreateCommandContext builds an extension.CommandContext for dispatching an extension-registered slash command. The returned context embeds the base Context (CWD + all ContextActions surfaces) plus the command-specific actions (WaitForIdle, Fork, etc.).

upstream: runner.ts:628-660 (createCommandContext)

func (*Runner) CreateToolContext

func (r *Runner) CreateToolContext(ctx context.Context, toolCallID string) *extension.ToolContext

CreateToolContext returns the extension.ToolContext of the tool call toolCallID: the extension context plus the callable tools and executeTool. ctx is the default cancellation of nested calls (upstream's `signal`).

upstream: runner.ts:958-985 (createToolContext(toolCallId, signal): ExtensionToolContext)

func (*Runner) DispatchContext

func (r *Runner) DispatchContext(ctx context.Context) context.Context

DispatchContext builds a context.Context enriched with the runner's extension.Context. Used by the command bridge (interactive.go) to call new-style command handlers from the legacy slash dispatch path.

upstream: runner.ts:566-630 (createContext factory, invoked per-event)

func (*Runner) Emit

func (r *Runner) Emit(ctx context.Context, event extension.ExtensionEvent) (any, error)

Emit dispatches a generic ExtensionEvent to every handler registered for the event's type, in load order. Used for events that don't have a dedicated EmitXxx method: session_start, session_shutdown, session_before_switch/fork/compact/tree, session_compact, session_tree, agent_start/end, turn_start/end, message_start/update/end, tool_execution_start/update/end, model_select, after_provider_response.

Result type:

  • For SessionBefore* events (Switch/Fork/Compact/Tree): if any handler returns a result with Cancel=true, dispatch halts and that result is returned. Otherwise the LAST non-nil result is returned. Callers type-assert against the appropriate *SessionBefore*Result.
  • For all other events: returns nil after running all handlers.

An invalidated runner still delivers the event, as upstream emit does; the ctx getters and actions a handler uses report the stale runner.

Handler errors are routed via emitError and the chain continues (matches upstream's try/catch at runner.ts:691-699). An invocation acknowledgment marks the first handler's return or runtime suspension; Emit itself still awaits the entire chain.

upstream: runner.ts:988-1017 (emit<TEvent>)

pig note: upstream uses TS conditional types (`RunnerEmitResult<TEvent>`) for type-narrowing the result based on the input event type. Go's type system can't express this, so the result is `any` and callers type-assert. The 4 SessionBefore* event types are documented as the only types whose result is non-nil in the godoc above.

func (*Runner) EmitBeforeAgentStart

EmitBeforeAgentStart dispatches a before_agent_start event to every handler. Specialized aggregator: each handler can (a) push a custom message into the result; (b) mutate the system prompt for subsequent handlers. Returns the combined result, or nil if no handler modified state.

**Upstream-specific shape**: the system prompt is mutable across the chain: each handler sees the LATEST mutated value via `event.SystemPrompt` and can override it via `result.SystemPrompt`. Subsequent handlers see the override. The final SystemPrompt in the returned result is the cumulatively-mutated value.

The event and Context getter both expose the latest system prompt. Each handler's override becomes the input observed by the next handler.

Every handler receives the same per-run copy of systemPromptOptions. Its section and selectedTools edits reach later handlers and the result, and they persist when the handler then fails.

Returns (nil, *StaleError) if the runner has been invalidated.

Handler errors route via emitError; chain continues.

upstream: runner.ts:1427-1477 (emitBeforeAgentStart(trigger, systemPromptOptions)): each handler's event spreads the trigger, a user prompt or the custom message that starts the run.

func (*Runner) EmitBeforeProviderHeaders

func (r *Runner) EmitBeforeProviderHeaders(ctx context.Context, headers extension.ProviderHeaders) (extension.ProviderHeaders, error)

EmitBeforeProviderHeaders lets every "before_provider_headers" handler mutate the outgoing request headers in place; a nil value deletes a header. A subprocess handler cannot share the map, so a returned header map replaces the current headers instead. Handler errors are reported and the chain continues.

upstream: runner.ts:1284-1310 (emitBeforeProviderHeaders)

func (*Runner) EmitBeforeProviderRequest

func (r *Runner) EmitBeforeProviderRequest(ctx context.Context, payload any) (any, error)

EmitBeforeProviderRequest threads a provider-request payload through every "before_provider_request" handler. Each handler can return a new payload; subsequent handlers see the previous handler's output. The runner returns the final chained payload.

Returns (nil, *StaleError) if the runner has been invalidated.

Handler errors route via emitError; chain continues.

upstream: runner.ts:841-873 (emitBeforeProviderRequest)

pig note: the payload type is `any` because upstream types it as `unknown` (provider-specific). Callers cast back to the concrete provider request type after this returns.

func (*Runner) EmitBoundary

EmitBoundary awaits boundary handlers in extension and registration order. Each handler observes the previous proposal and a freshly projected preview; invalid drafts are reported and may be repaired by a later handler.

func (*Runner) EmitCacheWarmingDecision

func (r *Runner) EmitCacheWarmingDecision(ctx context.Context, event extension.CacheWarmingDecisionEvent) (extension.CacheWarmingAction, error)

EmitCacheWarmingDecision awaits handlers in registration order and returns the last supplied action, or the event's action when no handler overrides it. Handler errors are reported without stopping subsequent handlers.

func (*Runner) EmitContext

func (r *Runner) EmitContext(ctx context.Context, messages []extension.AgentMessage) ([]extension.AgentMessage, error)

func (*Runner) EmitContextTracked

func (r *Runner) EmitContextTracked(ctx context.Context, messages []extension.AgentMessage) ([]extension.AgentMessage, bool, error)

EmitContextTracked is EmitContext that also reports whether any handler replaced the conversation list. Upstream compares list and message identity after each handler: an in-place edit, or a returned list holding the same message objects in the same order, leaves the conversation "unchanged", so the caller keeps every system message where it was (restoreSystemMessages). Only a replacement collapses them into one leading system message.

upstream: runner.ts emitContext, sameMessages, restoreSystemMessages

func (*Runner) EmitContextWithSystem

func (r *Runner) EmitContextWithSystem(ctx context.Context, messages []extension.AgentMessage) ([]extension.AgentMessage, error)

EmitContextWithSystem runs the second request-time phase: every "context_with_system" handler sees the full transcript, system messages included, and its returned messages are used as returned. Removing the leading system message is reported but honored. Handler errors are reported and the chain continues.

upstream: runner.ts emitContext, context_with_system phase

func (*Runner) EmitError

func (r *Runner) EmitError(err *extension.ExtensionError)

EmitError reports err to the error listeners. Hosts use it for failures they detect around extension dispatch. Mirrors upstream runner.emitError, which agent-session calls for boundary, command, and skill failures.

func (*Runner) EmitInput

func (r *Runner) EmitInput(ctx context.Context, text string, images []extension.ImageContent, source extension.InputSource, streamingBehavior string) (extension.InputEventResult, error)

EmitInput dispatches an input event to every "input" handler across all extensions, in load order. streamingBehavior identifies a prompt queued as a steer or follow-up; an empty value represents idle input. The dispatch is a chain-transform with **handled-short-circuit** semantics:

  • InputEventResultContinue no-op (next handler sees same text/images)
  • InputEventResultTransform text/images update for next handler
  • InputEventResultHandled halts dispatch, surfaces "input was consumed"

Return contract:

  • If any handler returned Handled, that result is returned (chain stops).
  • Otherwise, if any handler transformed text or images, returns a Transform result with the final chained values.
  • Otherwise returns Continue.

Returns (nil, *StaleError) if the runner has been invalidated.

Handler errors are routed via emitError and the chain continues (matches upstream's explicit try/catch at runner.ts:1004-1011).

upstream: runner.ts:1196-1228 (emitInput)

func (*Runner) EmitMessageEnd

func (r *Runner) EmitMessageEnd(ctx context.Context, event extension.MessageEndEvent) (*extension.AgentMessage, error)

EmitMessageEnd dispatches message_end to every handler in load order. Each handler sees the event with the latest message; a handler may return a replacement with the same role. It returns the final replacement, or nil (upstream undefined) when no handler replaced the message. Handler errors and role changes are reported and skipped.

upstream: runner.ts:1043-1080 (emitMessageEnd)

func (*Runner) EmitResourcesDiscover

func (r *Runner) EmitResourcesDiscover(
	ctx context.Context,
	cwd string,
	reason string,
) (*extension.ResourcesDiscoverAggregateResult, error)

EmitResourcesDiscover dispatches a resources_discover event to every handler and aggregates the returned skill/prompt/theme paths, attributing each path to its source extension.

Returns the aggregated result with empty (non-nil) slices when no handler returned any paths. Returns (nil, *StaleError) if the runner has been invalidated.

Handler errors route via emitError; chain continues.

upstream: runner.ts:941-988 (emitResourcesDiscover)

func (*Runner) EmitToolCall

EmitToolCall dispatches a ToolCallEvent to each handler in load order. It returns the first blocking result or the last non-blocking result. Handler errors stop dispatch and return to the caller, as in upstream.

func (*Runner) EmitToolResult

EmitToolResult dispatches a ToolResultEvent to every "tool_result" handler across all extensions, in load order. Each handler can mutate `content` / `details` / `isError`; mutations chain through subsequent handlers (the next handler sees the previous handler's output, not the original input). Returns the combined modification, or nil if no handler modified anything.

Returns (nil, *StaleError) if the runner has been invalidated.

upstream: runner.ts:707-755 (emitToolResult)

pig-specific: handler errors route via emitError (matches upstream's explicit try/catch in this method, runner.ts:733-740).

func (*Runner) EmitUserBash

EmitUserBash dispatches a user_bash event to every "user_bash" handler. The first handler that returns a result wins and later handlers do not run (first-wins, opposite of EmitToolCall).

A handler error, or a result that is not exactly one valid operations or result object, is reported through emitError and returned, so callers fail closed instead of running the command locally (upstream #9068).

Returns (nil, *StaleError) if the runner has been invalidated.

upstream: runner.ts emitUserBash, isUserBashEventResult

func (*Runner) EntryRenderer

func (r *Runner) EntryRenderer(customType string) extension.EntryRenderer

EntryRenderer returns the renderer for the given custom entry type if any extension registered one. First match across extensions wins (load order).

upstream: runner.ts (getEntryRenderer)

func (*Runner) ExecuteCommand

func (r *Runner) ExecuteCommand(ctx context.Context, invocationName, args string) bool

ExecuteCommand resolves and invokes an extension slash command through the active runner and its command context. Handler errors are reported through the runner error channel and still count as handled, matching pinned Pi.

func (*Runner) ExtensionCount

func (r *Runner) ExtensionCount() int

ExtensionCount returns the number of loaded extensions. SDK-surface accessor: a Go read-only helper so callers get the count without exposing the internal extensions slice. Upstream TS callers reach into runner state freely; this is a language-surface addition over the same wire protocol, not a behavioral divergence.

func (*Runner) ExtensionNames

func (r *Runner) ExtensionNames() []string

ExtensionNames returns human-readable extension names in load order.

func (*Runner) ExtensionPaths

func (r *Runner) ExtensionPaths() []string

ExtensionPaths returns the resolved paths of all loaded extensions, in load order. Used for diagnostics, "/extensions" listing, and provenance tracking.

upstream: runner.ts:146-149 (getExtensionPaths)

func (*Runner) ExtensionSources

func (r *Runner) ExtensionSources() []ExtensionSource

ExtensionSources returns the resolved path and SourceInfo of every loaded extension in load order, which the interactive loaded-resources listing labels and groups as upstream does.

func (*Runner) Flags

func (r *Runner) Flags() map[string]extension.ExtensionFlag

Flags returns declarations from the first extension registering each name. upstream: packages/coding-agent/src/core/extensions/runner.ts:getFlags

func (*Runner) GetActiveTools

func (r *Runner) GetActiveTools() ([]string, error)

GetActiveTools is upstream runner.getActiveTools (runner.ts:868-871): the names of the tools declared to the model, read through the runtime's bound action. A stale runner returns its stale error, and a runtime no host has bound returns extension.ErrRuntimeNotInitialized, as upstream's `notInitialized` throws.

func (*Runner) GetFlagValues

func (r *Runner) GetFlagValues() map[string]any

GetFlagValues returns a copy of the runtime flags, including registered defaults. upstream: packages/coding-agent/src/core/extensions/runner.ts:getFlagValues

func (*Runner) GetMarkdownTransformers

func (r *Runner) GetMarkdownTransformers() []extension.MarkdownTransformer

GetMarkdownTransformers returns the Markdown transformers extensions registered, in extension load order.

upstream: runner.ts getMarkdownTransformers

func (*Runner) GetModelRegistry

func (r *Runner) GetModelRegistry() extension.ModelRegistry

GetModelRegistry is upstream runner.getModelRegistry (runner.ts:843-845): the registry the runner was given, or the one a mode's BindCore or BindTools replaced it with. It is nil before any binding supplies one.

func (*Runner) GetToolDefinition

func (r *Runner) GetToolDefinition(toolName string) (extension.ToolDefinition, bool)

GetToolDefinition returns the definition for the named tool. The boolean reports whether the tool was found. First-wins by name across extensions (mirrors the dedup rule in Runner.Tools).

upstream: runner.ts:382-390 (getToolDefinition)

func (*Runner) GetUIContext

func (r *Runner) GetUIContext() extension.UIContext

GetUIContext returns the currently bound UI surface. Always non-nil; defaults to extension.NoopUIContext.

upstream: runner.ts:356-358

func (*Runner) HasHandlers

func (r *Runner) HasHandlers(eventType string) bool

HasHandlers reports whether any extension declares a non-empty handler list for the given event type. Used by the host to skip emit calls for events nobody listens to (perf), and by test/diagnostics to introspect runner state.

upstream: runner.ts:485-493 (hasHandlers)

func (*Runner) HasUI

func (r *Runner) HasUI() bool

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

upstream: runner.ts:359-362

func (*Runner) Invalidate

func (r *Runner) Invalidate(message string)

Invalidate marks the runner as stale. After this returns, IsStale() reports true and assertActive() (via every API method that checks it) returns a *StaleError matching ErrStaleContext. Emit and EmitBoundary still deliver events, as upstream emit and emitBoundary do; the ctx getters and actions a handler uses report the stale runner.

First-call-wins: subsequent Invalidate calls with different messages are no-ops. This mirrors upstream runner.ts:461-466 (`if (!this.staleMessage)`).

Pass message="" to use the upstream default; pass a custom message to surface a specific reason in error reporting.

upstream: runner.ts:461-466 (invalidate)

func (*Runner) InvalidateKeepingRuntime

func (r *Runner) InvalidateKeepingRuntime(message string)

InvalidateKeepingRuntime marks the runner stale like Invalidate but leaves its ExtensionRuntime active, for a runner whose runtime was handed to its replacement (a reload rebuilds the runner over the host's registrations, which the replacement keeps using). Invalidating that runtime would make the replacement's every context report stale.

func (*Runner) IsStale

func (r *Runner) IsStale() bool

IsStale reports whether Invalidate has been called.

SDK-surface accessor: upstream has no public introspection method: TS callers detect staleness only by catching the throw from a guarded API call. This Go read-only helper lets hosts check status without an emit call (e.g. `coding/Session` lifecycle code asking "is this runner still mine?"). A language-surface addition over the same wire protocol, not a behavioral divergence.

upstream: derived from the staleMessage check in runner.ts:468.

func (*Runner) MessageRenderer

func (r *Runner) MessageRenderer(customType string) extension.MessageRenderer

MessageRenderer returns the renderer for the given custom message type if any extension registered one. First match across extensions wins (load order).

upstream: runner.ts:495-503 (getMessageRenderer)

func (*Runner) ObserveThinkingRuns

func (r *Runner) ObserveThinkingRuns(fn func()) (stop func())

ObserveThinkingRuns calls fn after the ownership of thinking runs of any of the runner's extensions changes, until stop is called. pig additive (D214)

func (*Runner) OwnsThinkingRuns

func (r *Runner) OwnsThinkingRuns() bool

OwnsThinkingRuns reports whether any of the runner's extensions owns the thinking runs of assistant messages: the flags of the extensions are ORed, and an extension that unloaded or reloaded left the runner with its flag. pig additive (D214)

func (*Runner) ReportUnhandledMcpServers

func (r *Runner) ReportUnhandledMcpServers()

ReportUnhandledMcpServers reports each registered MCP server once as a `register_mcp_server` extension error when no loaded extension handles `mcp_servers_change`: nothing connects the servers, for example because another MCP extension replaced the built-in one.

upstream: runner.ts:747-762 (reportUnhandledMcpServers)

func (*Runner) ResolveToolRenderers

func (r *Runner) ResolveToolRenderers(toolName string, base func() *extension.ToolRenderers) *extension.ToolRenderers

ResolveToolRenderers returns the renderers of calls to toolName: extension resolvers in load order, then base.

upstream: runner.ts resolveToolRenderers

func (*Runner) Runtime

func (r *Runner) Runtime() *extension.ExtensionRuntime

Runtime returns the registration state the runner shares with its loader: MCP servers, providers and virtual models.

func (*Runner) SetFlagValue

func (r *Runner) SetFlagValue(name string, value any)

SetFlagValue stores a runtime CLI override. Flag values are booleans or strings. Ports packages/coding-agent/src/core/extensions/runner.ts upstream: packages/coding-agent/src/core/extensions/runner.ts:setFlagValue

func (*Runner) SetUIContext

func (r *Runner) SetUIContext(uiContext extension.UIContext, mode ...extension.ExtensionMode)

SetUIContext replaces the UI binding and mode. An omitted mode means print. Nil UI means no UI, independently of the selected mode. Existing contexts read the new binding. Dialogs on a supplied UI report prompt start and end through this runner. upstream: packages/coding-agent/src/core/extensions/runner.ts:setUIContext

func (*Runner) ShortcutDiagnostics

func (r *Runner) ShortcutDiagnostics() []extension.ResourceDiagnostic

ShortcutDiagnostics returns the warnings accumulated during the most recent Shortcuts() call. Empty until Shortcuts() runs at least once.

upstream: runner.ts:457-459 (getShortcutDiagnostics)

func (*Runner) Shortcuts

func (r *Runner) Shortcuts(resolvedKeybindings map[string][]string) []ShortcutEntry

Shortcuts is getShortcuts (runner.ts:673): the entries of Pi's Map in iteration order. A key keeps the position of its first registration and takes the value of its last.

func (*Runner) Shutdown

func (r *Runner) Shutdown()

Shutdown triggers graceful shutdown via the host-installed shutdown handler. No-op if no handler is wired (matches upstream default at runner.ts:345: `this.shutdownHandler = async () => {};`).

upstream: runner.ts:558 (`shutdown(): void { this.shutdownHandler(); }`)

func (*Runner) StaleMessage

func (r *Runner) StaleMessage() string

StaleMessage returns the invalidation message, or "" if the runner is active.

SDK-surface accessor: see IsStale.

func (*Runner) ToolCallContext

func (r *Runner) ToolCallContext(ctx context.Context, toolCallID string) context.Context

ToolCallContext returns ctx with the extension extension.Context and the tool call's extension.ToolContext attached. Tool wrappers call it once per call, as upstream's wrapToolDefinition calls its context factory with the call id and signal.

upstream: wrapper.ts:14-19, tool-definition-wrapper.ts:7-30

func (*Runner) ToolSourceInfo

func (r *Runner) ToolSourceInfo(toolName string) (extension.SourceInfo, bool)

ToolSourceInfo returns the SourceInfo of the extension whose tool Runner.Tools reports under toolName. Upstream registerTool stamps the registering extension's sourceInfo onto the tool (loader.ts), and getAllTools reports it. extension.RegisteredTool.SourceInfo carries PiG's per-tool source attribution for Piglet scoping instead (D23).

upstream: runner.ts getAllRegisteredTools (RegisteredTool.sourceInfo)

func (*Runner) Tools

func (r *Runner) Tools() []extension.RegisteredTool

Tools returns the tool definitions registered across all extensions, deduplicated by tool name with first-wins semantics: when two extensions register a tool with the same name, the earlier-loaded extension's registration is kept and the later one is silently skipped.

upstream: runner.ts:369-379 (getAllRegisteredTools)

func (*Runner) WaitForCommands

func (r *Runner) WaitForCommands(ctx context.Context) error

WaitForCommands blocks until no command handler is running or ctx ends. A handler that awaits a Session replacement is still running while the replacement retires this Runner, so callers wait from a goroutine they own.

type ShortcutEntry

type ShortcutEntry struct {
	Key      extension.KeyID
	Shortcut extension.ExtensionShortcut
}

ShortcutEntry is one extension shortcut under its normalized key.

type StaleError

type StaleError struct {
	Message string
}

StaleError carries the invalidation message alongside the canonical extension.ErrStaleContext sentinel. Use errors.Is for the sentinel check; errors.As for access to the message.

The sentinel lives in the parent `coding/extension` package so every host package matches the same identity with errors.Is.

upstream: runner.ts:467-471 (private assertActive throws Error(staleMessage))

func (*StaleError) Error

func (e *StaleError) Error() string

func (*StaleError) Is

func (e *StaleError) Is(target error) bool

Is implements errors.Is so callers can match the canonical extension.ErrStaleContext sentinel.

Jump to

Keyboard shortcuts

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