pi-namespace-patch 1.0.0-namespace.2 → 1.0.2-namespace.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +54 -0
- package/README.md +22 -4
- package/dist/bundle/chunks/{anthropic-messages-UID2PALB.js → anthropic-messages-MVG2FL56.js} +3 -3
- package/dist/bundle/chunks/azure-openai-responses-7AMFUIWJ.js +2 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +2 -2
- package/dist/bundle/chunks/chunk-2KAZSACP.js +2 -0
- package/dist/bundle/chunks/{chunk-2KTBZM5G.js → chunk-6FX7UEPL.js} +5 -5
- package/dist/bundle/chunks/{chunk-2VNGUWBO.js → chunk-BYB6ZAAQ.js} +1 -1
- package/dist/bundle/chunks/chunk-DN3QEIXS.js +2 -0
- package/dist/bundle/chunks/chunk-F5ZABL6Z.js +20 -0
- package/dist/bundle/chunks/{chunk-3LH3ZQKY.js → chunk-G7EDXK4D.js} +1 -1
- package/dist/bundle/chunks/chunk-IKZJX7ZT.js +2 -0
- package/dist/bundle/chunks/{chunk-4N5K4RKC.js → chunk-OLBCNJCL.js} +31 -32
- package/dist/bundle/chunks/{chunk-PRD6WYBT.js → chunk-OYBSLV7Y.js} +1 -1
- package/dist/bundle/chunks/{chunk-IBCPYVFK.js → chunk-PDFMCAOZ.js} +4 -4
- package/dist/bundle/chunks/{chunk-LTXEMVMA.js → chunk-SYF2TF6W.js} +2 -2
- package/dist/bundle/chunks/chunk-WCQZGZ6I.js +82 -0
- package/dist/bundle/chunks/{chunk-KDN6RCEQ.js → chunk-ZSI3BL5Q.js} +2 -2
- package/dist/bundle/chunks/{cli-QOMC26IJ.js → cli-KILDDGW3.js} +2 -2
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-NPQN263E.js → cloudflare-workers-ai-system-one-X5PVWWYJ.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +24 -3
- package/dist/bundle/chunks/easter-egg-3d-T5FFWIBR.js +2 -0
- package/dist/bundle/chunks/{execute-GVRSEGHL.js → execute-RYVK27GT.js} +25 -4
- package/dist/bundle/chunks/{google-generative-ai-APTPZOQL.js → google-generative-ai-ZOK6CV7D.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-MXCOSOY3.js → google-vertex-VKWZQ3AY.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-DKVFNQL6.js → mistral-conversations-7DAUEE4N.js} +1 -1
- package/dist/bundle/chunks/node-N5BSDOA5.js +16 -0
- package/dist/bundle/chunks/openai-chatgpt.js +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-GK67DQQJ.js → openai-codex-responses-TC3OK7B4.js} +1 -1
- package/dist/bundle/chunks/openai-completions-GWHGMQ3T.js +7 -0
- package/dist/bundle/chunks/openai-responses-EZ7FJ2KL.js +3 -0
- package/dist/bundle/chunks/{runtime-2SO2JDWM.js → runtime-D5I2NTIF.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-J2M3WAR2.js +2 -0
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +4 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +3 -0
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +1 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/export-html/tool-renderer.d.ts +3 -3
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +3 -3
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +5 -0
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +3 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +6 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +9 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +6 -0
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +11 -0
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/model-config.d.ts +36 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +14 -2
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/provider-composer.d.ts +2 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +13 -0
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/tools/renderers/index.d.ts +2 -2
- package/dist/core/tools/renderers/index.d.ts.map +1 -1
- package/dist/core/tools/renderers/index.js.map +1 -1
- package/dist/extensions/mcp/cli.d.ts.map +1 -1
- package/dist/extensions/mcp/cli.js +3 -0
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/config.d.ts +15 -3
- package/dist/extensions/mcp/config.d.ts.map +1 -1
- package/dist/extensions/mcp/config.js +46 -10
- package/dist/extensions/mcp/config.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts +4 -1
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +80 -45
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/oauth.d.ts +4 -1
- package/dist/extensions/mcp/oauth.d.ts.map +1 -1
- package/dist/extensions/mcp/oauth.js +54 -10
- package/dist/extensions/mcp/oauth.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +1 -0
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts +3 -1
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +19 -13
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/extensions/mcp/ui.d.ts.map +1 -1
- package/dist/extensions/mcp/ui.js +8 -4
- package/dist/extensions/mcp/ui.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/armin.d.ts +3 -0
- package/dist/modes/interactive/components/armin.d.ts.map +1 -1
- package/dist/modes/interactive/components/armin.js +7 -5
- package/dist/modes/interactive/components/armin.js.map +1 -1
- package/dist/modes/interactive/components/auth-url.d.ts +14 -0
- package/dist/modes/interactive/components/auth-url.d.ts.map +1 -0
- package/dist/modes/interactive/components/auth-url.js +37 -0
- package/dist/modes/interactive/components/auth-url.js.map +1 -0
- package/dist/modes/interactive/components/easter-egg-3d.d.ts +104 -0
- package/dist/modes/interactive/components/easter-egg-3d.d.ts.map +1 -0
- package/dist/modes/interactive/components/{pi-logo-animation.js → easter-egg-3d.js} +127 -74
- package/dist/modes/interactive/components/easter-egg-3d.js.map +1 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.d.ts +6 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.d.ts.map +1 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.js +23 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.js.map +1 -0
- package/dist/modes/interactive/components/index.d.ts +0 -1
- package/dist/modes/interactive/components/index.d.ts.map +1 -1
- package/dist/modes/interactive/components/index.js +0 -1
- package/dist/modes/interactive/components/index.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +2 -0
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +11 -5
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +6 -18
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +22 -45
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +2 -2
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +15 -17
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +12 -0
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/image-convert.d.ts +12 -0
- package/dist/utils/image-convert.d.ts.map +1 -1
- package/dist/utils/image-convert.js +45 -6
- package/dist/utils/image-convert.js.map +1 -1
- package/docs/cli.md +2 -0
- package/docs/codemode.md +1 -1
- package/docs/extensions.md +4 -0
- package/docs/keybindings.md +1 -1
- package/docs/mcp.md +23 -1
- package/docs/models.md +28 -2
- package/docs/quickstart.md +16 -2
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +13 -14
- package/dist/bundle/chunks/azure-openai-responses-AFMVM6NP.js +0 -2
- package/dist/bundle/chunks/chunk-6D7LHLKG.js +0 -2
- package/dist/bundle/chunks/chunk-7FH3BDRG.js +0 -82
- package/dist/bundle/chunks/chunk-DTD7JQ7Y.js +0 -42
- package/dist/bundle/chunks/chunk-MJOHEBV7.js +0 -2
- package/dist/bundle/chunks/node-O3RIBJRH.js +0 -16
- package/dist/bundle/chunks/openai-completions-JXDDPZ23.js +0 -7
- package/dist/bundle/chunks/openai-responses-CQDDLDQF.js +0 -3
- package/dist/bundle/chunks/pi-logo-animation-MPKZE4EK.js +0 -2
- package/dist/bundle/chunks/virtual-modules-3THEGRQQ.js +0 -2
- package/dist/modes/interactive/components/daxnuts.d.ts +0 -23
- package/dist/modes/interactive/components/daxnuts.d.ts.map +0 -1
- package/dist/modes/interactive/components/daxnuts.js +0 -140
- package/dist/modes/interactive/components/daxnuts.js.map +0 -1
- package/dist/modes/interactive/components/pi-logo-animation.d.ts +0 -68
- package/dist/modes/interactive/components/pi-logo-animation.d.ts.map +0 -1
- package/dist/modes/interactive/components/pi-logo-animation.js.map +0 -1
- package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts +0 -7
- package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts.map +0 -1
- package/dist/modes/interactive/components/pi-logo-animation.lazy.js +0 -12
- package/dist/modes/interactive/components/pi-logo-animation.lazy.js.map +0 -1
- package/npm-shrinkwrap.json +0 -1952
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/extensions/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAgoBH;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CACzB,IAA+C;IAE/C,OAAO,IAAqE,CAAC;AAC9E,CAAC;AAsnBD,kCAAkC;AAClC,MAAM,UAAU,gBAAgB,CAAC,CAAkB;IAClD,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAC9B,CAAC;AACD,MAAM,UAAU,sBAAsB,CAAC,CAAkB;IACxD,OAAO,CAAC,CAAC,QAAQ,KAAK,YAAY,CAAC;AACpC,CAAC;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB;IAClD,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAC9B,CAAC;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB;IAClD,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAC9B,CAAC;AACD,MAAM,UAAU,iBAAiB,CAAC,CAAkB;IACnD,OAAO,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC;AAC/B,CAAC;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB;IAClD,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAC9B,CAAC;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB;IAClD,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAC9B,CAAC;AACD,MAAM,UAAU,cAAc,CAAC,CAAkB;IAChD,OAAO,CAAC,CAAC,QAAQ,KAAK,IAAI,CAAC;AAC5B,CAAC;AAkCD,MAAM,UAAU,mBAAmB,CAAC,QAAgB,EAAE,KAAoB;IACzE,OAAO,KAAK,CAAC,QAAQ,KAAK,QAAQ,CAAC;AACpC,CAAC","sourcesContent":["/**\n * Extension system types.\n *\n * Extensions are TypeScript modules that can:\n * - Subscribe to agent lifecycle events\n * - Register LLM-callable tools\n * - Register commands, keyboard shortcuts, and CLI flags\n * - Interact with the user via UI primitives\n */\n\nimport type {\n\tAgentMessage,\n\tAgentTool,\n\tAgentToolCallOutcome,\n\tAgentToolResult,\n\tAgentToolUpdateCallback,\n\tThinkingLevel,\n\tToolExecutionMode,\n} from \"@earendil-works/pi-agent-core\";\nimport type {\n\tAnyModel,\n\tApi,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tClassifierApi,\n\tConstrainedSamplingConfig,\n\tImageApi,\n\tImageContent,\n\tJsonValue,\n\tMessage,\n\tModel,\n\tOAuthCredentials,\n\tOAuthLoginCallbacks,\n\tProvider,\n\tProviderClassifier,\n\tProviderHeaders,\n\tProviderId,\n\tProviderImages,\n\tRefreshModelsContext,\n\tSimpleStreamOptions,\n\tTextContent,\n\tToolResultMessage,\n\tTranscriptContext,\n\tUsage,\n} from \"@earendil-works/pi-ai\";\nimport type {\n\tAutocompleteItem,\n\tAutocompleteProvider,\n\tComponent,\n\tEditorComponent,\n\tEditorTheme,\n\tKeyId,\n\tOverlayHandle,\n\tOverlayOptions,\n\tTUI,\n} from \"@earendil-works/pi-tui\";\nimport type { Static, TSchema } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { BashResult } from \"../bash-executor.ts\";\nimport type { CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult } from \"../cache-warmer.ts\";\nimport type { CompactionPreparation, CompactionResult } from \"../compaction/index.ts\";\nimport type { EventBus } from \"../event-bus.ts\";\nimport type { ExecOptions, ExecResult } from \"../exec.ts\";\nimport type { ReadonlyFooterDataProvider } from \"../footer-data-provider.ts\";\nimport type { KeybindingsManager } from \"../keybindings.ts\";\nimport type { McpServerConfig, McpServerRegistry, RegisteredMcpServer } from \"../mcp-servers.ts\";\nimport type { CustomMessage } from \"../messages.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type { ScopedModel } from \"../model-resolver.ts\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tContextEditEntry,\n\tCustomEntry,\n\tProjectedSessionEntry,\n\tReadonlySessionManager,\n\tSessionEntry,\n\tSessionManager,\n} from \"../session-manager.ts\";\nimport type { Settings } from \"../settings-manager.ts\";\nimport type { SlashCommandInfo } from \"../slash-commands.ts\";\nimport type { SourceInfo } from \"../source-info.ts\";\nimport type { BuildSystemPromptOptions, NormalizedBuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type { BashOperations } from \"../tools/bash.ts\";\nimport type { EditToolDetails } from \"../tools/edit.ts\";\nimport type {\n\tBashToolDetails,\n\tBashToolInput,\n\tEditToolInput,\n\tFindToolDetails,\n\tFindToolInput,\n\tGrepToolDetails,\n\tGrepToolInput,\n\tLsToolDetails,\n\tLsToolInput,\n\tPowerShellToolDetails,\n\tPowerShellToolInput,\n\tReadToolDetails,\n\tReadToolInput,\n\tWriteToolInput,\n} from \"../tools/index.ts\";\nimport type { ModelRoute, ModelRouteRequest, VirtualModelDefinition } from \"../virtual-models.ts\";\n\nexport type { ExecOptions, ExecResult } from \"../exec.ts\";\nexport type { BuildSystemPromptOptions, NormalizedBuildSystemPromptOptions } from \"../system-prompt.ts\";\nexport type { AgentToolResult, AgentToolUpdateCallback, ToolExecutionMode };\nexport type { AppKeybinding, KeybindingsManager } from \"../keybindings.ts\";\n\n// ============================================================================\n// UI Context\n// ============================================================================\n\n/** Options for extension UI dialogs. */\nexport interface ExtensionUIDialogOptions {\n\t/** AbortSignal to programmatically dismiss the dialog. */\n\tsignal?: AbortSignal;\n\t/** Timeout in milliseconds. Dialog auto-dismisses with live countdown display. */\n\ttimeout?: number;\n}\n\n/** Placement for extension widgets. */\nexport type WidgetPlacement = \"aboveEditor\" | \"belowEditor\";\n\n/** Options for extension widgets. */\nexport interface ExtensionWidgetOptions {\n\t/** Where the widget is rendered. Defaults to \"aboveEditor\". */\n\tplacement?: WidgetPlacement;\n}\n\n/** Raw terminal input listener for extensions. */\nexport type TerminalInputHandler = (data: string) => { consume?: boolean; data?: string } | undefined;\n\n/** Working indicator configuration for the interactive streaming loader. */\nexport interface WorkingIndicatorOptions {\n\t/** Animation frames. Use an empty array to hide the indicator entirely. Custom frames are rendered verbatim. */\n\tframes?: string[];\n\t/** Frame interval in milliseconds for animated indicators. */\n\tintervalMs?: number;\n}\n\n/** Wrap the current autocomplete provider with additional behavior. */\nexport type AutocompleteProviderFactory = (current: AutocompleteProvider) => AutocompleteProvider;\nexport type EditorFactory = (tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager) => EditorComponent;\n\n/**\n * UI context for extensions to request interactive UI.\n * Each mode (interactive, RPC, print) provides its own implementation.\n */\nexport interface ExtensionUIContext {\n\t/** Show a selector and return the user's choice. */\n\tselect(title: string, options: string[], opts?: ExtensionUIDialogOptions): Promise<string | undefined>;\n\n\t/** Show a confirmation dialog. */\n\tconfirm(title: string, message: string, opts?: ExtensionUIDialogOptions): Promise<boolean>;\n\n\t/** Show a text input dialog. */\n\tinput(title: string, placeholder?: string, opts?: ExtensionUIDialogOptions): Promise<string | undefined>;\n\n\t/** Show a notification to the user. */\n\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n\n\t/** Listen to raw terminal input (interactive mode only). Returns an unsubscribe function. */\n\tonTerminalInput(handler: TerminalInputHandler): () => void;\n\n\t/** Set status text in the footer/status bar. Pass undefined to clear. */\n\tsetStatus(key: string, text: string | undefined): void;\n\n\t/** Set the working/loading message shown during streaming. Call with no argument to restore default. */\n\tsetWorkingMessage(message?: string): void;\n\n\t/** Show or hide the built-in interactive working loader row during streaming. */\n\tsetWorkingVisible(visible: boolean): void;\n\n\t/**\n\t * Configure the interactive working indicator shown during streaming.\n\t *\n\t * - Omit the argument to restore the default animated spinner.\n\t * - Use `frames: [\"●\"]` for a static indicator.\n\t * - Use `frames: []` to hide the indicator entirely.\n\t * - Custom frames are rendered as provided, so extensions must add their own colors.\n\t */\n\tsetWorkingIndicator(options?: WorkingIndicatorOptions): void;\n\n\t/** Set the label shown for hidden thinking blocks. Call with no argument to restore default. */\n\tsetHiddenThinkingLabel(label?: string): void;\n\n\t/** Set a widget to display above or below the editor. Accepts string array or component factory. */\n\tsetWidget(key: string, content: string[] | undefined, options?: ExtensionWidgetOptions): void;\n\tsetWidget(\n\t\tkey: string,\n\t\tcontent: ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined,\n\t\toptions?: ExtensionWidgetOptions,\n\t): void;\n\n\t/** Set a custom footer component, or undefined to restore the built-in footer.\n\t *\n\t * The factory receives a FooterDataProvider for data not otherwise accessible:\n\t * git branch and extension statuses from setStatus(). Context usage is on\n\t * ctx.getContextUsage(), token stats on ctx.sessionManager.getEntries(), model info on ctx.model.\n\t */\n\tsetFooter(\n\t\tfactory:\n\t\t\t| ((tui: TUI, theme: Theme, footerData: ReadonlyFooterDataProvider) => Component & { dispose?(): void })\n\t\t\t| undefined,\n\t): void;\n\n\t/** Set a custom header component (shown at startup, above chat), or undefined to restore the built-in header. */\n\tsetHeader(factory: ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined): void;\n\n\t/** Set the terminal window/tab title. */\n\tsetTitle(title: string): void;\n\n\t/** Show a custom component with keyboard focus. */\n\tcustom<T>(\n\t\tfactory: (\n\t\t\ttui: TUI,\n\t\t\ttheme: Theme,\n\t\t\tkeybindings: KeybindingsManager,\n\t\t\tdone: (result: T) => void,\n\t\t) => (Component & { dispose?(): void }) | Promise<Component & { dispose?(): void }>,\n\t\toptions?: {\n\t\t\toverlay?: boolean;\n\t\t\t/** Overlay positioning/sizing options. Can be static or a function for dynamic updates. */\n\t\t\toverlayOptions?: OverlayOptions | (() => OverlayOptions);\n\t\t\t/** Called with the overlay handle after the overlay is shown. Use to control visibility. */\n\t\t\tonHandle?: (handle: OverlayHandle) => void;\n\t\t},\n\t): Promise<T>;\n\n\t/** Paste text into the editor, triggering paste handling (collapse for large content). */\n\tpasteToEditor(text: string): void;\n\n\t/** Set the text in the core input editor. */\n\tsetEditorText(text: string): void;\n\n\t/** Get the current text from the core input editor. */\n\tgetEditorText(): string;\n\n\t/** Show a multi-line editor for text editing. */\n\teditor(title: string, prefill?: string): Promise<string | undefined>;\n\n\t/** Stack additional autocomplete behavior on top of the built-in provider. */\n\taddAutocompleteProvider(factory: AutocompleteProviderFactory): void;\n\n\t/**\n\t * Set a custom editor component via factory function.\n\t * Pass undefined to restore the default editor.\n\t *\n\t * The factory receives:\n\t * - `theme`: EditorTheme for styling borders and autocomplete\n\t * - `keybindings`: KeybindingsManager for app-level keybindings\n\t *\n\t * For full app keybinding support (escape, ctrl+d, model switching, etc.),\n\t * extend `CustomEditor` from `@earendil-works/pi-coding-agent` and call\n\t * `super.handleInput(data)` for keys you don't handle.\n\t *\n\t * @example\n\t * ```ts\n\t * import { CustomEditor } from \"@earendil-works/pi-coding-agent\";\n\t *\n\t * class VimEditor extends CustomEditor {\n\t * private mode: \"normal\" | \"insert\" = \"insert\";\n\t *\n\t * handleInput(data: string): void {\n\t * if (this.mode === \"normal\") {\n\t * // Handle vim normal mode keys...\n\t * if (data === \"i\") { this.mode = \"insert\"; return; }\n\t * }\n\t * super.handleInput(data); // App keybindings + text editing\n\t * }\n\t * }\n\t *\n\t * ctx.ui.setEditorComponent((tui, theme, keybindings) =>\n\t * new VimEditor(tui, theme, keybindings)\n\t * );\n\t * ```\n\t */\n\tsetEditorComponent(factory: EditorFactory | undefined): void;\n\n\t/** Get the currently configured custom editor factory, or undefined when using the default editor. */\n\tgetEditorComponent(): EditorFactory | undefined;\n\n\t/** Get the current theme for styling. */\n\treadonly theme: Theme;\n\n\t/** Get all available themes with their names and file paths. */\n\tgetAllThemes(): { name: string; path: string | undefined }[];\n\n\t/** Load a theme by name without switching to it. Returns undefined if not found. */\n\tgetTheme(name: string): Theme | undefined;\n\n\t/** Set the current theme by name or Theme object. */\n\tsetTheme(theme: string | Theme): { success: boolean; error?: string };\n\n\t/** Get current tool output expansion state. */\n\tgetToolsExpanded(): boolean;\n\n\t/** Set tool output expansion state. */\n\tsetToolsExpanded(expanded: boolean): void;\n}\n\n// ============================================================================\n// Extension Context\n// ============================================================================\n\nexport interface ContextUsage {\n\t/** Estimated context tokens, or null if unknown (e.g. right after compaction, before next LLM response). */\n\ttokens: number | null;\n\tcontextWindow: number;\n\t/** Context usage as percentage of context window, or null if tokens is unknown. */\n\tpercent: number | null;\n}\n\nexport interface CompactOptions {\n\tcustomInstructions?: string;\n\tonComplete?: (result: CompactionResult) => void;\n\tonError?: (error: Error) => void;\n}\n\n/**\n * Context passed to extension event handlers.\n */\nexport type ExtensionMode = \"tui\" | \"rpc\" | \"json\" | \"print\";\n\nexport interface ExtensionContext {\n\t/** UI methods for user interaction */\n\tui: ExtensionUIContext;\n\t/** Current run mode. Use \"tui\" to guard terminal-only UI such as custom components. */\n\tmode: ExtensionMode;\n\t/** Whether dialog-capable UI is available (true in TUI and RPC modes) */\n\thasUI: boolean;\n\t/** Current working directory */\n\tcwd: string;\n\t/** Session manager (read-only) */\n\tsessionManager: ReadonlySessionManager;\n\t/** Model registry for API key resolution */\n\tmodelRegistry: ModelRegistry;\n\t/** Current model (may be undefined) */\n\tmodel: Model<any> | undefined;\n\t/** Models scoped to this session (resolved from `--models` /\n\t * `enabledModels` settings against the available catalogue). Same set\n\t * the `/scoped-models` command shows. Empty when no scoping is\n\t * configured (all available models are usable). Read-only snapshot. */\n\tscopedModels: readonly ScopedModel[];\n\t/** Current thinking level, when provided by the session runtime. */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Whether the agent is idle (not streaming) */\n\tisIdle(): boolean;\n\t/** Whether project-local trust is active for this context. */\n\tisProjectTrusted(): boolean;\n\t/** The current abort signal, or undefined when the agent is not streaming. */\n\tsignal: AbortSignal | undefined;\n\t/** Abort the current agent operation */\n\tabort(): void;\n\t/** Whether there are queued messages waiting */\n\thasPendingMessages(): boolean;\n\t/** Gracefully shutdown pi and exit. Available in all contexts. */\n\tshutdown(): void;\n\t/** Get current context usage for the active model. */\n\tgetContextUsage(): ContextUsage | undefined;\n\t/** Trigger compaction without awaiting completion. */\n\tcompact(options?: CompactOptions): void;\n\t/** Get the current effective system prompt. */\n\tgetSystemPrompt(): string;\n}\n\n/** Options for {@link ExtensionToolContext.executeTool}. */\nexport interface ExecuteToolOptions {\n\t/** Defaults to the calling tool's signal. */\n\tsignal?: AbortSignal;\n\t/** Receives partial results of the nested tool, in addition to `tool_execution_update` events. */\n\tonUpdate?: AgentToolUpdateCallback;\n}\n\n/**\n * Context passed to tool `execute()` in a session: the extension context plus `executeTool()`\n * for running other tools through the same validation, hooks, and permission checks as\n * model-issued calls.\n *\n * A tool wrapped with `wrapToolDefinition()` without a context factory, such as a built-in tool\n * created with `createBashTool()` and run in a plain `Agent` or called directly, gets no context.\n */\nexport interface ExtensionToolContext extends ExtensionContext {\n\t/** Tools {@link executeTool} can call. */\n\treadonly tools: readonly AgentTool[];\n\t/**\n\t * Run another tool. The call gets the id `<calling id>/<n>`, and the `tool_call`, `tool_result`,\n\t * and `tool_execution_*` events carry `parentToolCallId`. It does not appear in the transcript;\n\t * a bounded record of it is kept as `nestedCalls` on the calling tool's result message.\n\t *\n\t * Never rejects for tool failures: unknown tools, validation errors, blocked calls, and thrown\n\t * errors come back as `isError: true`.\n\t */\n\texecuteTool(name: string, args: unknown, options?: ExecuteToolOptions): Promise<AgentToolCallOutcome>;\n}\n\n/**\n * Extended context for command handlers.\n * Includes session control methods only safe in user-initiated commands.\n */\nexport interface ExtensionCommandContext extends ExtensionContext {\n\t/** Get the current base system-prompt construction options. */\n\tgetSystemPromptOptions(): BuildSystemPromptOptions;\n\n\t/** Wait for the agent to finish streaming */\n\twaitForIdle(): Promise<void>;\n\n\t/** Start a new session, optionally with initialization. */\n\tnewSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }>;\n\n\t/** Fork from a specific entry, creating a new session file. */\n\tfork(\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Navigate to a different point in the session tree. */\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Switch to a different session file. */\n\tswitchSession(\n\t\tsessionPath: string,\n\t\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Reload extensions, skills, prompts, themes, and context files. */\n\treload(): Promise<void>;\n}\n\n/**\n * Fresh command-capable context bound to the replacement session after a session switch.\n *\n * This is passed to `withSession()` callbacks on `newSession()`, `fork()`, and `switchSession()`.\n */\nexport interface ReplacedSessionContext extends ExtensionCommandContext {\n\tsendMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n\t): Promise<void>;\n\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\"; expandPromptTemplates?: boolean },\n\t): Promise<void>;\n}\n\n// ============================================================================\n// Tool Types\n// ============================================================================\n\n/** Rendering options for tool results */\nexport interface ToolRenderResultOptions {\n\t/** Whether the result view is expanded */\n\texpanded: boolean;\n\t/** Whether this is a partial/streaming result */\n\tisPartial: boolean;\n}\n\n/** Context passed to tool renderers. */\nexport interface ToolRenderContext<TState = any, TArgs = any> {\n\t/** Current tool call arguments. Shared across call/result renders for the same tool call. */\n\targs: TArgs;\n\t/** Unique id for this tool execution. Stable across call/result renders for the same tool call. */\n\ttoolCallId: string;\n\t/** Invalidate just this tool execution component for redraw. */\n\tinvalidate: () => void;\n\t/** Previously returned component for this render slot, if any. */\n\tlastComponent: Component | undefined;\n\t/** Shared renderer state for this tool row. Initialized by tool-execution.ts. */\n\tstate: TState;\n\t/** Working directory for this tool execution. */\n\tcwd: string;\n\t/** Whether the tool execution has started. */\n\texecutionStarted: boolean;\n\t/** Whether the tool call arguments are complete. */\n\targsComplete: boolean;\n\t/** Whether the tool result is partial/streaming. */\n\tisPartial: boolean;\n\t/** Whether the result view is expanded. */\n\texpanded: boolean;\n\t/** Whether inline images are currently shown in the TUI. */\n\tshowImages: boolean;\n\t/** Whether the current result is an error. */\n\tisError: boolean;\n}\n\n/**\n * How the model reaches a tool. \"Callable\" means callable from other tools through\n * `ctx.executeTool()`, as the `codemode` tool does.\n *\n * - `direct`: declared to the model while active, and callable while active.\n * - `model-only`: declared to the model while active, never callable. Use it for orchestrating or\n * interactive tools.\n * - `codemode`: callable whenever registered. Not declared to the model unless explicitly\n * activated. Codemode tools list it in their description.\n * - `deferred`: like `codemode`, but codemode tools do not list it; tool search can find it.\n * - `hidden`: registered but unreachable. Activating it has no effect.\n *\n * `direct` and `model-only` tools are activated when they are registered; the others are not.\n * The active tool set (`getActiveTools`/`setActiveTools`) is the set declared to the model.\n */\nexport type ToolExposure = \"direct\" | \"model-only\" | \"codemode\" | \"deferred\" | \"hidden\";\n\n/**\n * Hints about what a tool does, with the meaning of MCP tool annotations. They come from the tool's\n * author and are not verified; permission extensions can use them to decide which calls to confirm.\n */\nexport interface ToolAnnotations {\n\t/** The tool does not modify its environment. */\n\treadOnlyHint?: boolean;\n\t/** The tool may delete or overwrite data, rather than only add to it. Meaningful when not read-only. */\n\tdestructiveHint?: boolean;\n\t/** Repeating a call with the same arguments has no further effect. Meaningful when not read-only. */\n\tidempotentHint?: boolean;\n\t/** The tool reaches an open world of external entities, such as the web, rather than a closed domain. */\n\topenWorldHint?: boolean;\n}\n\n/** A group of related tools, such as the tools of one MCP server. Codemode tools list them together. */\nexport interface ToolNamespace {\n\t/** For example `mcp__docs`. */\n\tname: string;\n\t/** Short summary shown once with the group in model-facing tool listings. */\n\tdescription?: string;\n\t/**\n\t * Longer usage guidance, such as MCP server instructions. Not part of tool listings; tools that\n\t * describe the namespace on request (codemode's `describeNamespace()`) return it.\n\t */\n\tinstructions?: string;\n}\n\n/** The tools of a session as {@link ToolDefinition.prepareLoadout} sees them. */\nexport interface ToolLoadout {\n\t/** Tools declared to the model (the active tools), in order, with their original descriptions. */\n\treadonly declared: readonly AgentTool[];\n\t/** Tools callable through `ctx.executeTool()`. */\n\treadonly callable: readonly AgentTool[];\n\t/** Every registered tool. */\n\treadonly registered: readonly AgentTool[];\n\tgetExposure(name: string): ToolExposure;\n\tgetNamespace(name: string): ToolNamespace | undefined;\n}\n\n/** Changes {@link ToolDefinition.prepareLoadout} makes to what the model sees. */\nexport interface ToolLoadoutChanges {\n\t/** Model-facing descriptions of declared tools, by tool name. */\n\tdescriptions?: Readonly<Record<string, string>>;\n\t/**\n\t * Declared tools whose declarations requests leave out. They stay active and callable, and the\n\t * transcript still declares them, so the active set survives `/tree` and resume.\n\t */\n\thiddenDeclarations?: readonly string[];\n}\n\n/**\n * Tool definition for registerTool().\n */\nexport interface ToolDefinition<TParams extends TSchema = TSchema, TDetails = unknown, TState = any> {\n\t/** Tool name (used in LLM tool calls) */\n\tname: string;\n\t/** Human-readable label for UI */\n\tlabel: string;\n\t/** Description for LLM */\n\tdescription: string;\n\t/** Optional one-line snippet for the Available tools section in the default system prompt. Custom tools are omitted from that section when this is not provided. */\n\tpromptSnippet?: string;\n\t/** Optional guideline bullets appended to the default system prompt Guidelines section when this tool is active. */\n\tpromptGuidelines?: string[];\n\t/** Parameter schema (TypeBox) */\n\tparameters: TParams;\n\t/** Optional provider-side constrained sampling request for this tool. Set false to explicitly disable it, equivalent to leaving it undefined. */\n\tconstrainedSampling?: false | ConstrainedSamplingConfig;\n\t/** Controls whether ToolExecutionComponent renders the standard colored shell or the tool renders its own framing. */\n\trenderShell?: \"default\" | \"self\";\n\n\t/** Optional compatibility shim to prepare raw tool call arguments before schema validation. Must return an object conforming to TParams. */\n\tprepareArguments?: (args: unknown) => Static<TParams>;\n\n\t/**\n\t * JSON Schema of `structuredContent` in successful results. Tools that declare it should always\n\t * set `structuredContent`; codemode scripts then receive it instead of the text content.\n\t */\n\toutputSchema?: TSchema;\n\n\t/**\n\t * How the model reaches the tool. Default: `\"direct\"`. See {@link ToolExposure}.\n\t */\n\texposure?: ToolExposure;\n\n\t/** Group the tool belongs to, for example its MCP server. */\n\tnamespace?: ToolNamespace;\n\n\t/** Hints about what the tool does, for example from an MCP server. */\n\tannotations?: ToolAnnotations;\n\n\t/**\n\t * Whether registering the tool activates it. Default: `true` for `direct` and `model-only` tools;\n\t * other exposures are never activated on registration. A tool with `defaultActive: false` is\n\t * activated by naming it in `--tools` or the `defaultTools` setting, or with `setActiveTools()`.\n\t */\n\tdefaultActive?: boolean;\n\n\t/**\n\t * Adjust how the loadout is presented to the model while this tool is active. Called whenever\n\t * the active tools change. Tools that orchestrate other tools use it, for example to list the\n\t * callable tools in their own description.\n\t */\n\tprepareLoadout?: (loadout: ToolLoadout) => ToolLoadoutChanges | undefined;\n\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n\n\t/** Execute the tool. */\n\texecute(\n\t\ttoolCallId: string,\n\t\tparams: Static<TParams>,\n\t\tsignal: AbortSignal | undefined,\n\t\tonUpdate: AgentToolUpdateCallback<TDetails> | undefined,\n\t\tctx: ExtensionToolContext,\n\t): Promise<AgentToolResult<TDetails>>;\n\n\t/** Custom rendering for tool call display */\n\trenderCall?: (args: Static<TParams>, theme: Theme, context: ToolRenderContext<TState, Static<TParams>>) => Component;\n\n\t/** Custom rendering for tool result display */\n\trenderResult?: (\n\t\tresult: AgentToolResult<TDetails>,\n\t\toptions: ToolRenderResultOptions,\n\t\ttheme: Theme,\n\t\tcontext: ToolRenderContext<TState, Static<TParams>>,\n\t) => Component;\n}\n\ntype AnyToolDefinition = ToolDefinition<any, any, any>;\n\n/**\n * Preserve parameter inference for standalone tool definitions.\n *\n * Use this when assigning a tool to a variable or passing it through arrays such\n * as `customTools`, where contextual typing would otherwise widen params to\n * `unknown`.\n */\nexport function defineTool<TParams extends TSchema, TDetails = unknown, TState = any>(\n\ttool: ToolDefinition<TParams, TDetails, TState>,\n): ToolDefinition<TParams, TDetails, TState> & AnyToolDefinition {\n\treturn tool as ToolDefinition<TParams, TDetails, TState> & AnyToolDefinition;\n}\n\n// ============================================================================\n// Startup/Resource Events\n// ============================================================================\n\nexport interface ProjectTrustEvent {\n\ttype: \"project_trust\";\n\tcwd: string;\n}\n\nexport type ProjectTrustEventDecision = \"yes\" | \"no\" | \"undecided\";\n\nexport interface ProjectTrustEventResult {\n\ttrusted: ProjectTrustEventDecision;\n\tremember?: boolean;\n}\n\nexport interface ProjectTrustContext {\n\tcwd: string;\n\tmode: ExtensionMode;\n\thasUI: boolean;\n\tui: Pick<ExtensionUIContext, \"select\" | \"confirm\" | \"input\" | \"notify\">;\n}\n\nexport type ProjectTrustHandler = (\n\tevent: ProjectTrustEvent,\n\tctx: ProjectTrustContext,\n) => Promise<ProjectTrustEventResult> | ProjectTrustEventResult;\n\n/** Fired after session_start to allow extensions to provide additional resource paths. */\nexport interface ResourcesDiscoverEvent {\n\ttype: \"resources_discover\";\n\tcwd: string;\n\treason: \"startup\" | \"reload\";\n}\n\n/** Result from resources_discover event handler */\nexport interface ResourcesDiscoverResult {\n\tskillPaths?: string[];\n\tpromptPaths?: string[];\n\tthemePaths?: string[];\n}\n\n/**\n * Fired when an extension registers or unregisters an MCP server after the extensions are bound\n * (see {@link ExtensionAPI.registerMcpServer}). Servers registered while extensions load are read\n * with `pi.getMcpServers()` on `session_start`. Handling this event marks an extension as the one\n * that connects registered servers.\n */\nexport interface McpServersChangeEvent {\n\ttype: \"mcp_servers_change\";\n\t/** Every registered server after the change. */\n\tservers: RegisteredMcpServer[];\n}\n\n// ============================================================================\n// Session Events\n// ============================================================================\n\n/** Fired when a session is started, loaded, or reloaded */\nexport interface SessionStartEvent {\n\ttype: \"session_start\";\n\t/** Why this session start happened. */\n\treason: \"startup\" | \"reload\" | \"new\" | \"resume\" | \"fork\";\n\t/** Previously active session file. Present for \"new\", \"resume\", and \"fork\". */\n\tpreviousSessionFile?: string;\n}\n\n/** Fired when the current session metadata changes. */\nexport interface SessionInfoChangedEvent {\n\ttype: \"session_info_changed\";\n\t/** Current normalized session name. Undefined when the name is cleared. */\n\tname: string | undefined;\n}\n\n/** Fired before switching to another session (can be cancelled) */\nexport interface SessionBeforeSwitchEvent {\n\ttype: \"session_before_switch\";\n\treason: \"new\" | \"resume\";\n\ttargetSessionFile?: string;\n}\n\n/** Fired before forking a session (can be cancelled) */\nexport interface SessionBeforeForkEvent {\n\ttype: \"session_before_fork\";\n\tentryId: string;\n\tposition: \"before\" | \"at\";\n}\n\n/** Fired before context compaction (can be cancelled or customized) */\nexport interface SessionBeforeCompactEvent {\n\ttype: \"session_before_compact\";\n\tpreparation: CompactionPreparation;\n\tbranchEntries: SessionEntry[];\n\tcustomInstructions?: string;\n\t/** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** True when the aborted turn is retried after this compaction (overflow recovery) */\n\twillRetry: boolean;\n\tsignal: AbortSignal;\n}\n\n/** Fired after context compaction succeeds */\nexport interface SessionCompactEvent {\n\ttype: \"session_compact\";\n\tcompactionEntry: CompactionEntry;\n\tfromExtension: boolean;\n\t/** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** True when the aborted turn is retried after this compaction (overflow recovery) */\n\twillRetry: boolean;\n}\n\n/** Fired after context compaction fails or is aborted */\nexport interface SessionCompactFailedEvent {\n\ttype: \"session_compact_failed\";\n\t/** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** Error text when compaction failed for a non-abort reason. */\n\terrorMessage?: string;\n\t/** True when compaction was cancelled or aborted. */\n\taborted: boolean;\n\t/** True when the aborted turn would have been retried after this compaction (overflow recovery) */\n\twillRetry: boolean;\n\t/** True when the failing compaction content came from a session_before_compact handler. */\n\tfromExtension: boolean;\n}\n\n/** Fired before an extension runtime is torn down due to quit, reload, or session replacement. */\nexport interface SessionShutdownEvent {\n\ttype: \"session_shutdown\";\n\treason: \"quit\" | \"reload\" | \"new\" | \"resume\" | \"fork\";\n\t/** Destination session file when shutting down due to session replacement. */\n\ttargetSessionFile?: string;\n}\n\n/** Preparation data for tree navigation */\nexport interface TreePreparation {\n\ttargetId: string;\n\toldLeafId: string | null;\n\tcommonAncestorId: string | null;\n\tentriesToSummarize: SessionEntry[];\n\tuserWantsSummary: boolean;\n\t/** Custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** If true, customInstructions replaces the default prompt instead of being appended */\n\treplaceInstructions?: boolean;\n\t/** Label to attach to the branch summary entry */\n\tlabel?: string;\n}\n\n/** Fired before navigating in the session tree (can be cancelled) */\nexport interface SessionBeforeTreeEvent {\n\ttype: \"session_before_tree\";\n\tpreparation: TreePreparation;\n\tsignal: AbortSignal;\n}\n\n/** Fired after navigating in the session tree */\nexport interface SessionTreeEvent {\n\ttype: \"session_tree\";\n\tnewLeafId: string | null;\n\toldLeafId: string | null;\n\tsummaryEntry?: BranchSummaryEntry;\n\tfromExtension?: boolean;\n}\n\nexport type SessionEvent =\n\t| SessionStartEvent\n\t| SessionInfoChangedEvent\n\t| SessionBeforeSwitchEvent\n\t| SessionBeforeForkEvent\n\t| SessionBeforeCompactEvent\n\t| SessionCompactEvent\n\t| SessionCompactFailedEvent\n\t| SessionShutdownEvent\n\t| SessionBeforeTreeEvent\n\t| SessionTreeEvent;\n\n// ============================================================================\n// Agent Events\n// ============================================================================\n\n/**\n * Fired before each LLM call. Can modify messages.\n *\n * `messages` holds the conversation without system messages. The prompt and tool state\n * belong to Pi: it restores them after the handler returns, so a handler cannot drop\n * them and does not need to preserve them.\n */\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\n/**\n * Fired before each LLM call, after every `context` handler has run and Pi has restored\n * the prompt and tool state. `messages` is the full transcript including system messages,\n * and the result is sent as returned: the handler owns the prompt and tool declarations.\n */\nexport interface ContextWithSystemEvent {\n\ttype: \"context_with_system\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired before a provider request is sent. Can replace the payload. */\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tpayload: unknown;\n}\n\n/**\n * Fired after request headers are assembled, before the provider HTTP call.\n * Handlers mutate `headers` in place (e.g. to inject tracing/session headers);\n * the return value is ignored. A `null` value deletes that header.\n */\nexport interface BeforeProviderHeadersEvent {\n\ttype: \"before_provider_headers\";\n\theaders: ProviderHeaders;\n}\n\n/** Fired after a provider response is received and before the response stream is consumed. */\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\n/** Fired for a parsed provider stream event before Pi normalizes it. */\nexport interface ProviderStreamEvent {\n\ttype: \"provider_stream_event\";\n\tprovider: ProviderId;\n\tapi: Api;\n\tmodel: string;\n\tdata: unknown;\n}\n\n/** Fired after user submits prompt but before agent loop. */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The raw user prompt text (after expansion). */\n\tprompt: string;\n\t/** Images attached to the user prompt, if any. */\n\timages?: ImageContent[];\n\t/** The current system prompt, rendered from systemPromptOptions and earlier handler changes. */\n\treadonly systemPrompt: string;\n\t/** Mutable prompt sections. Later handlers observe mutations made by earlier handlers. */\n\tsystemPromptOptions: NormalizedBuildSystemPromptOptions;\n}\n\n/** Fired when an agent loop starts */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/** Fired when an agent loop ends */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\nexport type AgentActivityOutcome = \"completed\" | \"aborted\" | \"error\";\n\nexport interface CustomEntryDraft {\n\ttype: \"custom\";\n\tcustomType: string;\n\tdata?: unknown;\n}\n\nexport interface CustomMessageEntryDraft {\n\ttype: \"custom_message\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdisplay: boolean;\n\tdetails?: unknown;\n}\n\nexport interface ContextEditEntryDraft {\n\ttype: \"context_edit\";\n\ttargetId: string;\n\treplacement: ContextEditEntry[\"replacement\"];\n}\n\nexport interface CompactionEntryDraft {\n\ttype: \"compaction\";\n\tsummary: string;\n\t/** Null creates a self-retaining compaction that keeps no preceding entries. */\n\tfirstKeptEntryId: string | null;\n\tdetails?: unknown;\n\tusage?: Usage;\n}\n\nexport type SessionBoundaryDraft =\n\t| CustomEntryDraft\n\t| CustomMessageEntryDraft\n\t| ContextEditEntryDraft\n\t| CompactionEntryDraft;\n\nexport interface BoundaryContextPreview {\n\tcontextEntries: ProjectedSessionEntry[];\n\tcontextMessages: AgentMessage[];\n\tllmMessages: Message[];\n\tpendingMessages: AgentMessage[];\n\tcanContinue: boolean;\n}\n\nexport interface BoundaryState {\n\tentries: SessionBoundaryDraft[];\n\tcontinue: boolean;\n\tcontext: BoundaryContextPreview;\n\toutcome: AgentActivityOutcome;\n}\n\nexport interface BoundaryResult {\n\tentries?: SessionBoundaryDraft[];\n\tcontinue?: boolean;\n}\n\n/** Fired before final settlement. May append entries and ensure one next provider request. */\nexport interface AgentBeforeSettleEvent extends BoundaryState {\n\ttype: \"agent_before_settle\";\n}\n\n/** Fired after an agent run has fully settled and no automatic retry, compaction, or queued continuation will run. */\nexport interface AgentSettledEvent {\n\ttype: \"agent_settled\";\n}\n\nexport type UIPromptKind = \"select\" | \"confirm\" | \"input\" | \"editor\" | \"custom\";\n\n/** Fired when Pi starts waiting on a blocking user-facing extension UI prompt. */\nexport interface UIPromptStartEvent {\n\ttype: \"ui_prompt_start\";\n\treason: \"ui_prompt\";\n\tkind: UIPromptKind;\n\ttitle?: string;\n}\n\n/** Fired when Pi is no longer waiting on a blocking user-facing extension UI prompt. */\nexport interface UIPromptEndEvent {\n\ttype: \"ui_prompt_end\";\n\treason: \"ui_prompt\";\n\tkind: UIPromptKind;\n\ttitle?: string;\n}\n\n/** Fired at the start of each turn */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/** Fired at the end of each turn */\nexport interface TurnEndEvent extends BoundaryState {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n\tmessageEntryId: string;\n\ttoolResultEntryIds: string[];\n}\n\n/** Fired when a message starts (user, assistant, or toolResult) */\nexport interface MessageStartEvent {\n\ttype: \"message_start\";\n\tmessage: AgentMessage;\n}\n\n/** Fired during assistant message streaming with token-by-token updates */\nexport interface MessageUpdateEvent {\n\ttype: \"message_update\";\n\tmessage: AgentMessage;\n\tassistantMessageEvent: AssistantMessageEvent;\n}\n\n/** Fired when a message ends */\nexport interface MessageEndEvent {\n\ttype: \"message_end\";\n\tmessage: AgentMessage;\n}\n\n/** Fired when a tool starts executing */\nexport interface ToolExecutionStartEvent {\n\ttype: \"tool_execution_start\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: any;\n\t/** Set when another tool (for example a codemode script) made this call. */\n\tparentToolCallId?: string;\n}\n\n/** Fired during tool execution with partial/streaming output */\nexport interface ToolExecutionUpdateEvent {\n\ttype: \"tool_execution_update\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: any;\n\tpartialResult: any;\n\t/** Set when another tool (for example a codemode script) made this call. */\n\tparentToolCallId?: string;\n}\n\n/** Fired when a tool finishes executing */\nexport interface ToolExecutionEndEvent {\n\ttype: \"tool_execution_end\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tresult: any;\n\tisError: boolean;\n\t/** Set when another tool (for example a codemode script) made this call. */\n\tparentToolCallId?: string;\n}\n\n// ============================================================================\n// Model Events\n// ============================================================================\n\nexport type ModelSelectSource = \"set\" | \"cycle\" | \"restore\";\n\n/** Fired when a new model is selected */\nexport interface ModelSelectEvent {\n\ttype: \"model_select\";\n\tmodel: Model<any>;\n\tpreviousModel: Model<any> | undefined;\n\tsource: ModelSelectSource;\n}\n\n/** Fired when a new thinking level is selected */\nexport interface ThinkingLevelSelectEvent {\n\ttype: \"thinking_level_select\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\n}\n\n// ============================================================================\n// User Bash Events\n// ============================================================================\n\n/** Fired when user executes a bash command via ! or !! prefix */\nexport interface UserBashEvent {\n\ttype: \"user_bash\";\n\t/** The command to execute */\n\tcommand: string;\n\t/** True if !! prefix was used (excluded from LLM context) */\n\texcludeFromContext: boolean;\n\t/** Current working directory */\n\tcwd: string;\n}\n\n// ============================================================================\n// Input Events\n// ============================================================================\n\n/** Source of user input */\nexport type InputSource = \"interactive\" | \"rpc\" | \"extension\";\n\n/** Fired when user input is received, before agent processing */\nexport interface InputEvent {\n\ttype: \"input\";\n\t/** The input text */\n\ttext: string;\n\t/** Attached images, if any */\n\timages?: ImageContent[];\n\t/** Where the input came from */\n\tsource: InputSource;\n\t/** How the input will be delivered during streaming, or undefined when idle */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n}\n\n/** Result from input event handler */\nexport type InputEventResult =\n\t| { action: \"continue\" }\n\t| { action: \"transform\"; text: string; images?: ImageContent[] }\n\t| { action: \"handled\" };\n\n// ============================================================================\n// Tool Events\n// ============================================================================\n\ninterface ToolCallEventBase {\n\ttype: \"tool_call\";\n\t/**\n\t * The call's id. For calls another tool made (with `parentToolCallId` set), pi assigns\n\t * `<parent id>/<n>`; such ids never appear as tool calls or tool results in the transcript, only\n\t * in the parent result's `nestedCalls` record.\n\t */\n\ttoolCallId: string;\n\t/** Set when another tool (for example a codemode script) issued this call. */\n\tparentToolCallId?: string;\n}\n\nexport interface BashToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"bash\";\n\tinput: BashToolInput;\n}\n\nexport interface PowerShellToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"powershell\";\n\tinput: PowerShellToolInput;\n}\n\nexport interface ReadToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"read\";\n\tinput: ReadToolInput;\n}\n\nexport interface EditToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"edit\";\n\tinput: EditToolInput;\n}\n\nexport interface WriteToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"write\";\n\tinput: WriteToolInput;\n}\n\nexport interface GrepToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"grep\";\n\tinput: GrepToolInput;\n}\n\nexport interface FindToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"find\";\n\tinput: FindToolInput;\n}\n\nexport interface LsToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"ls\";\n\tinput: LsToolInput;\n}\n\nexport interface CustomToolCallEvent extends ToolCallEventBase {\n\ttoolName: string;\n\tinput: Record<string, unknown>;\n}\n\n/**\n * Fired before a tool executes. Can block.\n *\n * `event.input` is mutable. Mutate it in place to patch tool arguments before execution.\n * Later `tool_call` handlers see earlier mutations. No re-validation is performed after mutation.\n */\nexport type ToolCallEvent =\n\t| BashToolCallEvent\n\t| PowerShellToolCallEvent\n\t| ReadToolCallEvent\n\t| EditToolCallEvent\n\t| WriteToolCallEvent\n\t| GrepToolCallEvent\n\t| FindToolCallEvent\n\t| LsToolCallEvent\n\t| CustomToolCallEvent;\n\ninterface ToolResultEventBase {\n\ttype: \"tool_result\";\n\t/** The call's id; `<parent id>/<n>` for nested calls, see `ToolCallEvent`. */\n\ttoolCallId: string;\n\t/** Set when another tool (for example a codemode script) issued this call. */\n\tparentToolCallId?: string;\n\tinput: Record<string, unknown>;\n\tcontent: (TextContent | ImageContent)[];\n\t/**\n\t * Machine-readable result for tools that declare an `outputSchema`. Handlers that redact\n\t * `content` should also replace this; replacing `content` alone drops it.\n\t */\n\tstructuredContent?: JsonValue;\n\tisError: boolean;\n\t/** Usage from the tool execution itself, if available. */\n\tusage?: Usage;\n}\n\nexport interface BashToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"bash\";\n\tdetails: BashToolDetails | undefined;\n}\n\nexport interface PowerShellToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"powershell\";\n\tdetails: PowerShellToolDetails | undefined;\n}\n\nexport interface ReadToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"read\";\n\tdetails: ReadToolDetails | undefined;\n}\n\nexport interface EditToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"edit\";\n\tdetails: EditToolDetails | undefined;\n}\n\nexport interface WriteToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"write\";\n\tdetails: undefined;\n}\n\nexport interface GrepToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"grep\";\n\tdetails: GrepToolDetails | undefined;\n}\n\nexport interface FindToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"find\";\n\tdetails: FindToolDetails | undefined;\n}\n\nexport interface LsToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"ls\";\n\tdetails: LsToolDetails | undefined;\n}\n\nexport interface CustomToolResultEvent extends ToolResultEventBase {\n\ttoolName: string;\n\tdetails: unknown;\n}\n\n/** Fired after a tool executes. Can modify result. */\nexport type ToolResultEvent =\n\t| BashToolResultEvent\n\t| PowerShellToolResultEvent\n\t| ReadToolResultEvent\n\t| EditToolResultEvent\n\t| WriteToolResultEvent\n\t| GrepToolResultEvent\n\t| FindToolResultEvent\n\t| LsToolResultEvent\n\t| CustomToolResultEvent;\n\n// Type guards for ToolResultEvent\nexport function isBashToolResult(e: ToolResultEvent): e is BashToolResultEvent {\n\treturn e.toolName === \"bash\";\n}\nexport function isPowerShellToolResult(e: ToolResultEvent): e is PowerShellToolResultEvent {\n\treturn e.toolName === \"powershell\";\n}\nexport function isReadToolResult(e: ToolResultEvent): e is ReadToolResultEvent {\n\treturn e.toolName === \"read\";\n}\nexport function isEditToolResult(e: ToolResultEvent): e is EditToolResultEvent {\n\treturn e.toolName === \"edit\";\n}\nexport function isWriteToolResult(e: ToolResultEvent): e is WriteToolResultEvent {\n\treturn e.toolName === \"write\";\n}\nexport function isGrepToolResult(e: ToolResultEvent): e is GrepToolResultEvent {\n\treturn e.toolName === \"grep\";\n}\nexport function isFindToolResult(e: ToolResultEvent): e is FindToolResultEvent {\n\treturn e.toolName === \"find\";\n}\nexport function isLsToolResult(e: ToolResultEvent): e is LsToolResultEvent {\n\treturn e.toolName === \"ls\";\n}\n\n/**\n * Type guard for narrowing ToolCallEvent by tool name.\n *\n * Built-in tools narrow automatically (no type params needed):\n * ```ts\n * if (isToolCallEventType(\"bash\", event)) {\n * event.input.command; // string\n * }\n * ```\n *\n * Custom tools require explicit type parameters:\n * ```ts\n * if (isToolCallEventType<\"my_tool\", MyToolInput>(\"my_tool\", event)) {\n * event.input.action; // typed\n * }\n * ```\n *\n * Note: Direct narrowing via `event.toolName === \"bash\"` doesn't work because\n * CustomToolCallEvent.toolName is `string` which overlaps with all literals.\n */\nexport function isToolCallEventType(toolName: \"bash\", event: ToolCallEvent): event is BashToolCallEvent;\nexport function isToolCallEventType(toolName: \"powershell\", event: ToolCallEvent): event is PowerShellToolCallEvent;\nexport function isToolCallEventType(toolName: \"read\", event: ToolCallEvent): event is ReadToolCallEvent;\nexport function isToolCallEventType(toolName: \"edit\", event: ToolCallEvent): event is EditToolCallEvent;\nexport function isToolCallEventType(toolName: \"write\", event: ToolCallEvent): event is WriteToolCallEvent;\nexport function isToolCallEventType(toolName: \"grep\", event: ToolCallEvent): event is GrepToolCallEvent;\nexport function isToolCallEventType(toolName: \"find\", event: ToolCallEvent): event is FindToolCallEvent;\nexport function isToolCallEventType(toolName: \"ls\", event: ToolCallEvent): event is LsToolCallEvent;\nexport function isToolCallEventType<TName extends string, TInput extends Record<string, unknown>>(\n\ttoolName: TName,\n\tevent: ToolCallEvent,\n): event is ToolCallEvent & { toolName: TName; input: TInput };\nexport function isToolCallEventType(toolName: string, event: ToolCallEvent): boolean {\n\treturn event.toolName === toolName;\n}\n\n/** Union of all event types */\nexport type ExtensionEvent =\n\t| ProjectTrustEvent\n\t| ResourcesDiscoverEvent\n\t| McpServersChangeEvent\n\t| SessionEvent\n\t| ContextEvent\n\t| ContextWithSystemEvent\n\t| CacheWarmingDecisionEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeProviderHeadersEvent\n\t| AfterProviderResponseEvent\n\t| ProviderStreamEvent\n\t| BeforeAgentStartEvent\n\t| AgentStartEvent\n\t| AgentEndEvent\n\t| AgentBeforeSettleEvent\n\t| AgentSettledEvent\n\t| UIPromptStartEvent\n\t| UIPromptEndEvent\n\t| TurnStartEvent\n\t| TurnEndEvent\n\t| MessageStartEvent\n\t| MessageUpdateEvent\n\t| MessageEndEvent\n\t| ToolExecutionStartEvent\n\t| ToolExecutionUpdateEvent\n\t| ToolExecutionEndEvent\n\t| ModelSelectEvent\n\t| ThinkingLevelSelectEvent\n\t| UserBashEvent\n\t| InputEvent\n\t| ToolCallEvent\n\t| ToolResultEvent;\n\n// ============================================================================\n// Event Results\n// ============================================================================\n\nexport interface ContextEventResult {\n\tmessages?: AgentMessage[];\n}\n\nexport type TurnEndEventResult = BoundaryResult;\nexport type AgentBeforeSettleEventResult = BoundaryResult;\n\nexport type BeforeProviderRequestEventResult = unknown;\n\nexport type { CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult } from \"../cache-warmer.ts\";\n\nexport interface ToolCallEventResult {\n\t/** Block tool execution. To modify arguments, mutate `event.input` in place instead. */\n\tblock?: boolean;\n\treason?: string;\n\t/**\n\t * Hint that the agent should stop after the current tool batch when this call is blocked.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Result from user_bash event handler */\nexport type UserBashEventResult =\n\t| {\n\t\t\t/** Custom operations to use for execution */\n\t\t\toperations: BashOperations;\n\t\t\tresult?: never;\n\t }\n\t| {\n\t\t\toperations?: never;\n\t\t\t/** Full replacement: extension handled execution, use this result */\n\t\t\tresult: BashResult;\n\t };\n\n/**\n * Changes a `tool_result` handler makes. Omitted fields stay as they are, except that replacing\n * `content` without returning `structuredContent` drops the structured content, because it may no\n * longer match. Return it along with `content` to keep it.\n */\nexport interface ToolResultEventResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tstructuredContent?: JsonValue;\n\tisError?: boolean;\n\tusage?: Usage;\n}\n\nexport interface MessageEndEventResult {\n\t/** Replace the finalized message. The replacement must keep the original message role. */\n\tmessage?: AgentMessage;\n}\n\nexport interface BeforeAgentStartEventResult {\n\tmessage?: Pick<CustomMessage, \"customType\" | \"content\" | \"display\" | \"details\">;\n\t/** Replace the complete system prompt for this turn. Later handlers observe this exact override. */\n\tsystemPrompt?: string;\n}\n\nexport interface SessionBeforeSwitchResult {\n\tcancel?: boolean;\n}\n\nexport interface SessionBeforeForkResult {\n\tcancel?: boolean;\n\tskipConversationRestore?: boolean;\n}\n\nexport interface SessionBeforeCompactResult {\n\tcancel?: boolean;\n\tcompaction?: CompactionResult;\n}\n\nexport interface SessionBeforeTreeResult {\n\tcancel?: boolean;\n\tsummary?: {\n\t\tsummary: string;\n\t\tdetails?: unknown;\n\t\tusage?: Usage;\n\t};\n\t/** Override custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** Override whether customInstructions replaces the default prompt */\n\treplaceInstructions?: boolean;\n\t/** Override label to attach to the branch summary entry */\n\tlabel?: string;\n}\n\n// ============================================================================\n// Message and Entry Rendering\n// ============================================================================\n\nexport interface MessageRenderOptions {\n\texpanded: boolean;\n\t/** Horizontal padding configured by the outputPad setting. */\n\toutputPad: number;\n}\n\nexport interface MarkdownTransformContext {\n\tmessageType: \"user\" | \"assistant\" | \"assistant-thinking\";\n\tisStreaming: boolean;\n\tavailableWidth: number;\n}\n\nexport type MarkdownTransformer = (markdown: string, context: MarkdownTransformContext) => string;\n\nexport interface EntryRenderOptions {\n\texpanded: boolean;\n}\n\nexport type MessageRenderer<T = unknown> = (\n\tmessage: CustomMessage<T>,\n\toptions: MessageRenderOptions,\n\ttheme: Theme,\n) => Component | undefined;\n\nexport type EntryRenderer<T = unknown> = (\n\tentry: CustomEntry<T>,\n\toptions: EntryRenderOptions,\n\ttheme: Theme,\n) => Component | undefined;\n\n// ============================================================================\n// Command Registration\n// ============================================================================\n\nexport interface RegisteredCommand {\n\tname: string;\n\tsourceInfo: SourceInfo;\n\tdescription?: string;\n\tgetArgumentCompletions?: (argumentPrefix: string) => AutocompleteItem[] | null | Promise<AutocompleteItem[] | null>;\n\thandler: (args: string, ctx: ExtensionCommandContext) => Promise<void>;\n}\n\nexport interface ResolvedCommand extends RegisteredCommand {\n\tinvocationName: string;\n}\n\n// ============================================================================\n// Extension API\n// ============================================================================\n\n/** Handler function type for events */\n// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements\nexport type ExtensionHandler<E, R = undefined> = (event: E, ctx: ExtensionContext) => Promise<R | void> | R | void;\n\n/**\n * ExtensionAPI passed to extension factory functions.\n */\nexport interface ExtensionAPI {\n\t// =========================================================================\n\t// Event Subscription\n\t// =========================================================================\n\n\ton(event: \"project_trust\", handler: ProjectTrustHandler): () => void;\n\ton(\n\t\tevent: \"resources_discover\",\n\t\thandler: ExtensionHandler<ResourcesDiscoverEvent, ResourcesDiscoverResult>,\n\t): () => void;\n\ton(event: \"session_start\", handler: ExtensionHandler<SessionStartEvent>): () => void;\n\ton(event: \"session_info_changed\", handler: ExtensionHandler<SessionInfoChangedEvent>): () => void;\n\ton(\n\t\tevent: \"session_before_switch\",\n\t\thandler: ExtensionHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>,\n\t): () => void;\n\ton(\n\t\tevent: \"session_before_fork\",\n\t\thandler: ExtensionHandler<SessionBeforeForkEvent, SessionBeforeForkResult>,\n\t): () => void;\n\ton(\n\t\tevent: \"session_before_compact\",\n\t\thandler: ExtensionHandler<SessionBeforeCompactEvent, SessionBeforeCompactResult>,\n\t): () => void;\n\ton(event: \"session_compact\", handler: ExtensionHandler<SessionCompactEvent>): () => void;\n\ton(event: \"session_compact_failed\", handler: ExtensionHandler<SessionCompactFailedEvent>): () => void;\n\ton(event: \"session_shutdown\", handler: ExtensionHandler<SessionShutdownEvent>): () => void;\n\ton(event: \"mcp_servers_change\", handler: ExtensionHandler<McpServersChangeEvent>): () => void;\n\ton(\n\t\tevent: \"session_before_tree\",\n\t\thandler: ExtensionHandler<SessionBeforeTreeEvent, SessionBeforeTreeResult>,\n\t): () => void;\n\ton(event: \"session_tree\", handler: ExtensionHandler<SessionTreeEvent>): () => void;\n\ton(event: \"context\", handler: ExtensionHandler<ContextEvent, ContextEventResult>): () => void;\n\ton(event: \"context_with_system\", handler: ExtensionHandler<ContextWithSystemEvent, ContextEventResult>): () => void;\n\ton(\n\t\tevent: \"cache_warming_decision\",\n\t\thandler: ExtensionHandler<CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult>,\n\t): () => void;\n\ton(\n\t\tevent: \"before_provider_request\",\n\t\thandler: ExtensionHandler<BeforeProviderRequestEvent, BeforeProviderRequestEventResult>,\n\t): () => void;\n\ton(event: \"before_provider_headers\", handler: ExtensionHandler<BeforeProviderHeadersEvent>): () => void;\n\ton(event: \"after_provider_response\", handler: ExtensionHandler<AfterProviderResponseEvent>): () => void;\n\ton(event: \"provider_stream_event\", handler: ExtensionHandler<ProviderStreamEvent>): () => void;\n\ton(\n\t\tevent: \"before_agent_start\",\n\t\thandler: ExtensionHandler<BeforeAgentStartEvent, BeforeAgentStartEventResult>,\n\t): () => void;\n\ton(event: \"agent_start\", handler: ExtensionHandler<AgentStartEvent>): () => void;\n\ton(event: \"agent_end\", handler: ExtensionHandler<AgentEndEvent>): () => void;\n\ton(\n\t\tevent: \"agent_before_settle\",\n\t\thandler: ExtensionHandler<AgentBeforeSettleEvent, AgentBeforeSettleEventResult>,\n\t): () => void;\n\ton(event: \"agent_settled\", handler: ExtensionHandler<AgentSettledEvent>): () => void;\n\ton(event: \"ui_prompt_start\", handler: ExtensionHandler<UIPromptStartEvent>): () => void;\n\ton(event: \"ui_prompt_end\", handler: ExtensionHandler<UIPromptEndEvent>): () => void;\n\ton(event: \"turn_start\", handler: ExtensionHandler<TurnStartEvent>): () => void;\n\ton(event: \"turn_end\", handler: ExtensionHandler<TurnEndEvent, TurnEndEventResult>): () => void;\n\ton(event: \"message_start\", handler: ExtensionHandler<MessageStartEvent>): () => void;\n\ton(event: \"message_update\", handler: ExtensionHandler<MessageUpdateEvent>): () => void;\n\ton(event: \"message_end\", handler: ExtensionHandler<MessageEndEvent, MessageEndEventResult>): () => void;\n\ton(event: \"tool_execution_start\", handler: ExtensionHandler<ToolExecutionStartEvent>): () => void;\n\ton(event: \"tool_execution_update\", handler: ExtensionHandler<ToolExecutionUpdateEvent>): () => void;\n\ton(event: \"tool_execution_end\", handler: ExtensionHandler<ToolExecutionEndEvent>): () => void;\n\ton(event: \"model_select\", handler: ExtensionHandler<ModelSelectEvent>): () => void;\n\ton(event: \"thinking_level_select\", handler: ExtensionHandler<ThinkingLevelSelectEvent>): () => void;\n\ton(event: \"tool_call\", handler: ExtensionHandler<ToolCallEvent, ToolCallEventResult>): () => void;\n\ton(event: \"tool_result\", handler: ExtensionHandler<ToolResultEvent, ToolResultEventResult>): () => void;\n\ton(event: \"user_bash\", handler: ExtensionHandler<UserBashEvent, UserBashEventResult>): () => void;\n\ton(event: \"input\", handler: ExtensionHandler<InputEvent, InputEventResult>): () => void;\n\n\t// =========================================================================\n\t// Tool Registration\n\t// =========================================================================\n\n\t/** Register a tool that the LLM can call. */\n\tregisterTool<TParams extends TSchema = TSchema, TDetails = unknown, TState = any>(\n\t\ttool: ToolDefinition<TParams, TDetails, TState>,\n\t): void;\n\n\t// =========================================================================\n\t// Command, Shortcut, Flag Registration\n\t// =========================================================================\n\n\t/** Register a custom command. */\n\tregisterCommand(name: string, options: Omit<RegisteredCommand, \"name\" | \"sourceInfo\">): void;\n\n\t/** Register a keyboard shortcut. */\n\tregisterShortcut(\n\t\tshortcut: KeyId,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\thandler: (ctx: ExtensionContext) => Promise<void> | void;\n\t\t},\n\t): void;\n\n\t/** Register a CLI flag. */\n\tregisterFlag(\n\t\tname: string,\n\t\toptions:\n\t\t\t| {\n\t\t\t\t\tdescription?: string;\n\t\t\t\t\ttype: \"boolean\";\n\t\t\t\t\tdefault?: boolean;\n\t\t\t }\n\t\t\t| {\n\t\t\t\t\tdescription?: string;\n\t\t\t\t\ttype: \"string\";\n\t\t\t\t\tdefault?: string;\n\t\t\t },\n\t): void;\n\n\t/** Get the value of a registered CLI flag. */\n\tgetFlag(name: string): boolean | string | undefined;\n\n\t// =========================================================================\n\t// Message Rendering\n\t// =========================================================================\n\n\t/** Register a custom renderer for CustomMessageEntry. */\n\tregisterMessageRenderer<T = unknown>(customType: string, renderer: MessageRenderer<T>): void;\n\n\t/** Register a transformer for user and assistant Markdown before Pi renders it in the interactive transcript. */\n\tregisterMarkdownTransformer(transformer: MarkdownTransformer): void;\n\n\t/** Register a custom renderer for CustomEntry. Custom entries do not participate in LLM context. */\n\tregisterEntryRenderer<T = unknown>(customType: string, renderer: EntryRenderer<T>): void;\n\n\t// =========================================================================\n\t// Actions\n\t// =========================================================================\n\n\t/** Send a custom message to the session. */\n\tsendMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n\t): void;\n\n\t/**\n\t * Send a user message to the agent. Always triggers a turn.\n\t * When the agent is streaming, use deliverAs to specify how to queue the message.\n\t * Set expandPromptTemplates to dispatch extension commands and expand skill commands and prompt templates.\n\t */\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\"; expandPromptTemplates?: boolean },\n\t): void;\n\n\t/** Append a custom entry to the session for state persistence (not sent to LLM). */\n\tappendEntry<T = unknown>(customType: string, data?: T): void;\n\n\t// =========================================================================\n\t// Session Metadata\n\t// =========================================================================\n\n\t/** Set the session display name (shown in session selector). */\n\tsetSessionName(name: string): void;\n\n\t/** Get the current session name, if set. */\n\tgetSessionName(): string | undefined;\n\n\t/** Set or clear a label on an entry. Labels are user-defined markers for bookmarking/navigation. */\n\tsetLabel(entryId: string, label: string | undefined): void;\n\n\t/** Execute a shell command. */\n\texec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;\n\n\t/** Get the names of the active tools, which are the tools declared to the model. */\n\tgetActiveTools(): string[];\n\n\t/** Get all configured tools with parameter schema, prompt guidelines, exposure, and source metadata. */\n\tgetAllTools(): ToolInfo[];\n\n\t/** Get a copy of the effective settings (global and project settings merged, with overrides). */\n\tgetSettings(): Settings;\n\n\t/**\n\t * Set the active tools by name. Unknown and `hidden` tools are ignored. Tools with `codemode` or\n\t * `deferred` exposure stay callable from codemode scripts whether active or not.\n\t */\n\tsetActiveTools(toolNames: string[]): void;\n\n\t/** Get available slash commands in the current session. */\n\tgetCommands(): SlashCommandInfo[];\n\n\t// =========================================================================\n\t// Model and Thinking Level\n\t// =========================================================================\n\n\t/**\n\t * Set the model for the current session without changing the configured default for new sessions.\n\t * Returns false if authentication is not configured for the model's provider.\n\t */\n\tsetModel(model: Model<any>): Promise<boolean>;\n\n\t/** Get current thinking level. */\n\tgetThinkingLevel(): ThinkingLevel;\n\n\t/**\n\t * Set the thinking level (clamped to model capabilities) for the current session without changing the configured default\n\t * for new sessions.\n\t */\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\n\t// =========================================================================\n\t// Provider Registration\n\t// =========================================================================\n\n\t/**\n\t * Register or override a model provider.\n\t *\n\t * If `models` is provided: replaces all existing models for this provider.\n\t * If only `baseUrl` is provided: overrides the URL for existing models.\n\t * If `oauth` is provided: registers OAuth provider for /login support.\n\t * If `streamSimple` is provided: registers a custom API stream handler.\n\t *\n\t * During initial extension load this call is queued and applied once the\n\t * runner has bound its context. After that it takes effect immediately, so\n\t * it is safe to call from command handlers or event callbacks without\n\t * requiring a `/reload`.\n\t *\n\t * @example\n\t * // Register a new provider with custom models\n\t * pi.registerProvider(\"my-proxy\", {\n\t * baseUrl: \"https://proxy.example.com\",\n\t * apiKey: \"$PROXY_API_KEY\",\n\t * api: \"anthropic-messages\",\n\t * models: [\n\t * {\n\t * id: \"claude-sonnet-4-20250514\",\n\t * name: \"Claude 4 Sonnet (proxy)\",\n\t * reasoning: false,\n\t * input: [\"text\", \"image\"],\n\t * cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t * contextWindow: 200000,\n\t * maxTokens: 16384\n\t * }\n\t * ]\n\t * });\n\t *\n\t * @example\n\t * // Override baseUrl for an existing provider\n\t * pi.registerProvider(\"anthropic\", {\n\t * baseUrl: \"https://proxy.example.com\"\n\t * });\n\t *\n\t * @example\n\t * // Register provider with OAuth support\n\t * pi.registerProvider(\"corporate-ai\", {\n\t * baseUrl: \"https://ai.corp.com\",\n\t * api: \"openai-responses\",\n\t * models: [...],\n\t * oauth: {\n\t * name: \"Corporate AI (SSO)\",\n\t * async login(callbacks) { ... },\n\t * async refreshToken(credentials) { ... },\n\t * getApiKey(credentials) { return credentials.access; }\n\t * }\n\t * });\n\t */\n\tregisterProvider(provider: Provider): void;\n\tregisterProvider(name: string, config: ProviderConfig): void;\n\n\t/**\n\t * Unregister a previously registered provider.\n\t *\n\t * Removes all models belonging to the named provider and restores any\n\t * built-in models that were overridden by it. Has no effect if the provider\n\t * is not currently registered.\n\t *\n\t * Like `registerProvider`, this takes effect immediately when called after\n\t * the initial load phase.\n\t *\n\t * @example\n\t * pi.unregisterProvider(\"my-proxy\");\n\t */\n\tunregisterProvider(name: string): void;\n\n\t// =========================================================================\n\t// MCP Servers\n\t// =========================================================================\n\n\t/**\n\t * Register an MCP server for this session, with the same config as an `mcpServers` entry in\n\t * `mcp.json`. The server connects next to the configured servers: on `session_start` when\n\t * registered during extension load, right away when registered later. Registering a name again\n\t * replaces the extension's earlier registration.\n\t *\n\t * The registration is not saved; register again on every load. A server of the same name in\n\t * `mcp.json` takes precedence. Throws for invalid configs and for names another extension\n\t * registered. When no loaded extension handles MCP servers (for example because another MCP\n\t * extension replaced the built-in one), the registration is reported as an extension error.\n\t *\n\t * @example\n\t * pi.registerMcpServer(\"jira\", { url: \"https://mcp.example.com/jira\" });\n\t */\n\tregisterMcpServer(name: string, config: McpServerConfig): void;\n\n\t/** Remove an MCP server this extension registered and close its connection. */\n\tunregisterMcpServer(name: string): void;\n\n\t/** Every MCP server registered by extensions. For extensions that connect MCP servers. */\n\tgetMcpServers(): RegisteredMcpServer[];\n\n\t/**\n\t * Register a virtual model: a selectable catalog entry that routes each request to a physical\n\t * model. The selection (`ctx.model`, `model_change` entries) names the virtual model; assistant\n\t * messages record the physical model and thinking level the router picked.\n\t *\n\t * `provider` may be any provider id, including one with physical models, and may list several\n\t * virtual models. Registering the same provider and id again replaces the virtual model. See\n\t * docs/virtual-models.md.\n\t */\n\tregisterVirtualModel<TState = unknown>(model: ExtensionVirtualModel<TState>): void;\n\n\t/** Remove a virtual model registered with `registerVirtualModel()`. */\n\tunregisterVirtualModel(provider: string, id: string): void;\n\n\t/** Shared event bus for extension communication. */\n\tevents: EventBus;\n}\n\n// ============================================================================\n// Provider Registration Types\n// ============================================================================\n\n/** Virtual model registered via pi.registerVirtualModel(). */\nexport interface ExtensionVirtualModel<TState = unknown> extends Omit<VirtualModelDefinition<TState>, \"route\"> {\n\t/** Like `VirtualModelDefinition.route`, with an extension context. */\n\troute(request: ModelRouteRequest<TState>, ctx: ExtensionContext): ModelRoute<TState> | Promise<ModelRoute<TState>>;\n}\n\n/** Configuration for registering a provider via pi.registerProvider(). */\nexport interface ProviderConfig {\n\t/** Display name for the provider in UI. */\n\tname?: string;\n\t/** Base URL for the API endpoint. Required when defining models. */\n\tbaseUrl?: string;\n\t/** API key literal, env interpolation ($ENV_VAR or ${ENV_VAR}), or leading !command. Required when defining models (unless oauth provided). */\n\tapiKey?: string;\n\t/** API type. Required at provider or model level when defining models. */\n\tapi?: Api;\n\t/**\n\t * Optional streamSimple handler for custom APIs.\n\t * The context is a normalized transcript: read the prompt and tools from its system messages\n\t * (`getCurrentSystemPrompt(context.messages)`, `getCurrentTools(context.messages)`).\n\t * Implementations must invoke `options.onPayload` before sending the provider request and use any\n\t * returned replacement payload. They must invoke `options.onResponse` after receiving the response\n\t * and before consuming its body, matching built-in providers. Implementations may invoke\n\t * `options.onProviderStreamEvent(data, model)` with parsed stream events before normalization.\n\t * Event data is adapter-owned and must be treated as read-only.\n\t */\n\tstreamSimple?: (\n\t\tmodel: Model<Api>,\n\t\tcontext: TranscriptContext,\n\t\toptions?: SimpleStreamOptions,\n\t) => AssistantMessageEventStream;\n\t/** Image-generation implementations keyed by image API. */\n\timages?: Partial<Record<ImageApi, ProviderImages>>;\n\t/** Classifier implementations keyed by classifier API. */\n\tclassifiers?: Partial<Record<ClassifierApi, ProviderClassifier>>;\n\t/** Custom headers to include in requests. */\n\theaders?: Record<string, string>;\n\t/** If true, adds Authorization: Bearer header with the resolved API key. */\n\tauthHeader?: boolean;\n\t/** Models to register. If provided, replaces all existing models for this provider. */\n\tmodels?: ProviderModelConfig[];\n\t/**\n\t * Refresh this provider's model list. The returned list replaces extension-provided models.\n\t * Use context.publish({ persist: entry }) when the catalog should persist across sessions.\n\t */\n\trefreshModels?(context: RefreshModelsContext): Promise<ProviderModelConfig[]>;\n\t/** OAuth provider for /login support. The `id` is set automatically from the provider name. */\n\toauth?: {\n\t\t/** Display name for the provider in login UI. */\n\t\tname: string;\n\t\t/** Whether access through this auth method is backed by a provider subscription. */\n\t\tisSubscription?: boolean;\n\t\t/** @deprecated Retained for source compatibility; canonical auth flows ignore it. */\n\t\tusesCallbackServer?: boolean;\n\t\t/** Run the login flow, return credentials to persist. */\n\t\tlogin(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials>;\n\t\t/** Refresh expired credentials, return updated credentials to persist. */\n\t\trefreshToken(credentials: OAuthCredentials, signal: AbortSignal): Promise<OAuthCredentials>;\n\t\t/** Convert credentials to API key string for the provider. */\n\t\tgetApiKey(credentials: OAuthCredentials): string;\n\t\t/** Legacy synchronous credential-dependent model projection. */\n\t\tmodifyModels?(models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[];\n\t};\n}\n\ninterface ProviderModelConfigBase {\n\t/** Model ID. */\n\tid: string;\n\t/** Display name. */\n\tname: string;\n\t/** API type override for this model. */\n\tapi?: string;\n\t/** API endpoint URL override for this model. */\n\tbaseUrl?: string;\n\t/** Supported input types. */\n\tinput: (\"text\" | \"image\")[];\n\t/** Provider input limits and cache-safe image preprocessing metadata. */\n\tinputLimits?: AnyModel[\"inputLimits\"];\n\t/** Per-million-token cost rates and optional request-wide input pricing tiers. */\n\tcost: AnyModel[\"cost\"];\n\t/** Custom headers for this model. */\n\theaders?: Record<string, string>;\n}\n\n/** Chat model configuration. Omitted `type` is normalized to `\"chat\"`. */\nexport interface ProviderChatModelConfig extends ProviderModelConfigBase {\n\ttype?: \"chat\";\n\tapi?: Api;\n\t/** Whether the model supports extended thinking. */\n\treasoning: boolean;\n\t/** Maps pi thinking levels to provider/model-specific values; null marks a level unsupported. */\n\tthinkingLevelMap?: Model<Api>[\"thinkingLevelMap\"];\n\t/** Best-effort prompt cache lifetime in seconds per retention tier. Unset disables cache warming. */\n\tpromptCache?: Model<Api>[\"promptCache\"];\n\t/** Maximum context window size in tokens. */\n\tcontextWindow: number;\n\t/** Maximum output tokens. */\n\tmaxTokens: number;\n\tsamplingParams?: Record<string, unknown>;\n\t/** OpenAI compatibility settings. */\n\tcompat?: Model<Api>[\"compat\"];\n}\n\n/** Image-generation model configuration. */\nexport interface ProviderImageModelConfig extends ProviderModelConfigBase {\n\ttype: \"image\";\n\tapi?: ImageApi;\n\toutput: (\"text\" | \"image\")[];\n}\n\n/** Structured classifier model configuration. */\nexport interface ProviderClassifierModelConfig extends ProviderModelConfigBase {\n\ttype: \"classifier\";\n\tapi?: ClassifierApi;\n\tcontextWindow: number;\n}\n\n/** Configuration for a model within a provider. */\nexport type ProviderModelConfig = ProviderChatModelConfig | ProviderImageModelConfig | ProviderClassifierModelConfig;\n\n/** Extension factory function type. Supports both sync and async initialization. */\nexport type ExtensionFactory = (pi: ExtensionAPI) => void | Promise<void>;\n\nexport type InlineExtension =\n\t| ExtensionFactory\n\t| {\n\t\t\t/**\n\t\t\t * Display name shown as `<inline:name>` in the startup Extensions list and errors. With\n\t\t\t * `builtin`, the extension is named `builtin:name` in errors and diagnostics.\n\t\t\t */\n\t\t\tname: string;\n\t\t\tfactory: ExtensionFactory;\n\t\t\t/** Omit this extension from the startup Extensions list. */\n\t\t\thidden?: boolean;\n\t\t\t/**\n\t\t\t * Leave this extension out when another extension registers a tool, command, or flag with a\n\t\t\t * name it registers during loading, instead of reporting a conflict. The CLI's built-in MCP,\n\t\t\t * codemode, and tool search extensions use it, so for example an MCP extension that registers\n\t\t\t * `/mcp` replaces the built-in MCP support. The factory still runs, so it should only register\n\t\t\t * tools, commands, flags, and event handlers.\n\t\t\t */\n\t\t\treplaceable?: boolean;\n\t\t\t/**\n\t\t\t * Supply the code of the `builtin:<name>` extension instead of loading as an inline extension.\n\t\t\t * `builtin:<name>` is an extension resource like a file: it loads by default, `pi config` lists\n\t\t\t * it, `-builtin:<name>` in the `extensions` setting and `--no-extensions` disable it, and\n\t\t\t * `-e builtin:<name>` loads it explicitly. It is hidden from the startup Extensions list and\n\t\t\t * loads after project trust is resolved, so it cannot handle `project_trust`. The CLI's built-in\n\t\t\t * extensions use it.\n\t\t\t */\n\t\t\tbuiltin?: boolean;\n\t };\n\n// ============================================================================\n// Loaded Extension Types\n// ============================================================================\n\nexport interface RegisteredTool {\n\tdefinition: ToolDefinition;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface ExtensionFlag {\n\tname: string;\n\tdescription?: string;\n\ttype: \"boolean\" | \"string\";\n\tdefault?: boolean | string;\n\textensionPath: string;\n}\n\nexport interface ExtensionShortcut {\n\tshortcut: KeyId;\n\tdescription?: string;\n\thandler: (ctx: ExtensionContext) => Promise<void> | void;\n\textensionPath: string;\n}\n\ntype HandlerFn = (...args: unknown[]) => Promise<unknown>;\n\nexport type SendMessageHandler = <T = unknown>(\n\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n) => void;\n\nexport type SendUserMessageHandler = (\n\tcontent: string | (TextContent | ImageContent)[],\n\toptions?: { deliverAs?: \"steer\" | \"followUp\"; expandPromptTemplates?: boolean },\n) => void;\n\nexport type AppendEntryHandler = <T = unknown>(customType: string, data?: T) => void;\n\nexport type SetSessionNameHandler = (name: string) => void;\n\nexport type GetSessionNameHandler = () => string | undefined;\n\nexport type GetActiveToolsHandler = () => string[];\n\n/** Tool info with name, description, parameter schema, prompt guidelines, and source metadata. */\nexport type ToolInfo = Pick<ToolDefinition, \"name\" | \"description\" | \"parameters\" | \"promptGuidelines\"> & {\n\texposure: ToolExposure;\n\tnamespace?: ToolNamespace;\n\tannotations?: ToolAnnotations;\n\tsourceInfo: SourceInfo;\n};\n\nexport type GetAllToolsHandler = () => ToolInfo[];\n\nexport type GetSettingsHandler = () => Settings;\n\nexport type GetCommandsHandler = () => SlashCommandInfo[];\n\nexport type SetActiveToolsHandler = (toolNames: string[]) => void;\n\nexport type RefreshToolsHandler = () => void;\n\nexport type SetModelHandler = (model: Model<any>) => Promise<boolean>;\n\nexport type GetThinkingLevelHandler = () => ThinkingLevel;\n\nexport type SetThinkingLevelHandler = (level: ThinkingLevel) => void;\n\nexport type SetLabelHandler = (entryId: string, label: string | undefined) => void;\n\n/**\n * Shared state created by loader, used during registration and runtime.\n * Contains flag values (defaults set during registration, CLI values set after).\n */\nexport interface ExtensionRuntimeState {\n\tflagValues: Map<string, boolean | string>;\n\t/** Legacy provider-config registrations queued during extension loading, processed when runner binds. */\n\tpendingProviderRegistrations: Array<{ name: string; config: ProviderConfig; extensionPath: string }>;\n\t/** Native pi-ai provider registrations queued during extension loading, processed when runner binds. */\n\tpendingNativeProviderRegistrations: Array<{ provider: Provider; extensionPath: string }>;\n\t/** Virtual model registrations queued during extension loading, processed when runner binds. */\n\tpendingVirtualModelRegistrations: Array<{ definition: VirtualModelDefinition; extensionPath: string }>;\n\t/** Create an extension context. Throws before the runner binds. */\n\tcreateContext: () => ExtensionContext;\n\t/** Throws when this extension instance is stale after runtime replacement. */\n\tassertActive: () => void;\n\t/** Marks this extension instance as stale after runtime replacement or reload. */\n\tinvalidate: (message?: string) => void;\n\t/** Retain an event-bus subscription until this runtime is invalidated. */\n\ttrackEventBusSubscription: (unsubscribe: () => void) => () => void;\n\t/**\n\t * Register or unregister a provider.\n\t *\n\t * Before bindCore(): queues registrations / removes from queue.\n\t * After bindCore(): calls ModelRegistry directly for immediate effect.\n\t */\n\tregisterProvider: (name: string, config: ProviderConfig, extensionPath?: string) => void;\n\tregisterNativeProvider: (provider: Provider, extensionPath?: string) => void;\n\tunregisterProvider: (name: string, extensionPath?: string) => void;\n\t/** Servers registered with `pi.registerMcpServer()`. */\n\tmcpServers: McpServerRegistry;\n\tregisterVirtualModel: (definition: VirtualModelDefinition, extensionPath?: string) => void;\n\tunregisterVirtualModel: (provider: string, id: string) => void;\n}\n\n/**\n * Action implementations for pi.* API methods.\n * Provided to runner.initialize(), copied into the shared runtime.\n */\nexport interface ExtensionActions {\n\tsendMessage: SendMessageHandler;\n\tsendUserMessage: SendUserMessageHandler;\n\tappendEntry: AppendEntryHandler;\n\tsetSessionName: SetSessionNameHandler;\n\tgetSessionName: GetSessionNameHandler;\n\tsetLabel: SetLabelHandler;\n\tgetActiveTools: GetActiveToolsHandler;\n\tgetAllTools: GetAllToolsHandler;\n\tgetSettings: GetSettingsHandler;\n\tsetActiveTools: SetActiveToolsHandler;\n\trefreshTools: RefreshToolsHandler;\n\tgetCommands: GetCommandsHandler;\n\tsetModel: SetModelHandler;\n\tgetThinkingLevel: GetThinkingLevelHandler;\n\tsetThinkingLevel: SetThinkingLevelHandler;\n}\n\n/**\n * Actions for ExtensionContext (ctx.* in event handlers).\n * Required by all modes.\n */\nexport interface ExtensionContextActions {\n\tgetModel: () => Model<any> | undefined;\n\tgetScopedModels: () => readonly ScopedModel[];\n\tisIdle: () => boolean;\n\tisProjectTrusted: () => boolean;\n\tgetSignal: () => AbortSignal | undefined;\n\tabort: () => void;\n\thasPendingMessages: () => boolean;\n\tshutdown: () => void;\n\tgetContextUsage: () => ContextUsage | undefined;\n\tcompact: (options?: CompactOptions) => void;\n\tgetSystemPrompt: () => string;\n\tgetSystemPromptOptions?: () => BuildSystemPromptOptions;\n\t/** Backs `ExtensionToolContext.executeTool()`. Without it, nested calls fail. */\n\texecuteTool?: (\n\t\tcallerId: string,\n\t\tname: string,\n\t\targs: unknown,\n\t\toptions: ExecuteToolOptions,\n\t) => Promise<AgentToolCallOutcome>;\n\t/** Backs `ExtensionToolContext.tools`. */\n\tgetCallableTools?: () => readonly AgentTool[];\n}\n\n/**\n * Actions for ExtensionCommandContext (ctx.* in command handlers).\n * Only needed for interactive mode where extension commands are invokable.\n */\nexport interface ExtensionCommandContextActions {\n\twaitForIdle: () => Promise<void>;\n\tnewSession: (options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t}) => Promise<{ cancelled: boolean }>;\n\tfork: (\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t) => Promise<{ cancelled: boolean }>;\n\tnavigateTree: (\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t) => Promise<{ cancelled: boolean }>;\n\tswitchSession: (\n\t\tsessionPath: string,\n\t\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t) => Promise<{ cancelled: boolean }>;\n\treload: () => Promise<void>;\n}\n\n/**\n * Full runtime = state + actions.\n * Created by loader with throwing action stubs, completed by runner.initialize().\n */\nexport interface ExtensionRuntime extends ExtensionRuntimeState, ExtensionActions {}\n\n/** Loaded extension with all registered items. */\nexport interface Extension {\n\tpath: string;\n\tresolvedPath: string;\n\thidden?: boolean;\n\t/** See {@link InlineExtension}. */\n\treplaceable?: boolean;\n\tsourceInfo: SourceInfo;\n\thandlers: Map<string, HandlerFn[]>;\n\ttools: Map<string, RegisteredTool>;\n\tmessageRenderers: Map<string, MessageRenderer>;\n\tmarkdownTransformer?: MarkdownTransformer;\n\tentryRenderers?: Map<string, EntryRenderer>;\n\tcommands: Map<string, RegisteredCommand>;\n\tflags: Map<string, ExtensionFlag>;\n\tshortcuts: Map<KeyId, ExtensionShortcut>;\n}\n\n/** Result of loading extensions. */\nexport interface LoadExtensionsResult {\n\textensions: Extension[];\n\terrors: Array<{ path: string; error: string }>;\n\twarnings?: Array<{ path: string; warning: string }>;\n\t/** Shared runtime - actions are throwing stubs until runner.initialize() */\n\truntime: ExtensionRuntime;\n}\n\n// ============================================================================\n// Extension Error\n// ============================================================================\n\nexport interface ExtensionError {\n\textensionPath: string;\n\tevent: string;\n\terror: string;\n\tstack?: string;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/extensions/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AA2oBH;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CACzB,IAA+C;IAE/C,OAAO,IAAqE,CAAC;AAC9E,CAAC;AAsnBD,kCAAkC;AAClC,MAAM,UAAU,gBAAgB,CAAC,CAAkB;IAClD,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAC9B,CAAC;AACD,MAAM,UAAU,sBAAsB,CAAC,CAAkB;IACxD,OAAO,CAAC,CAAC,QAAQ,KAAK,YAAY,CAAC;AACpC,CAAC;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB;IAClD,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAC9B,CAAC;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB;IAClD,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAC9B,CAAC;AACD,MAAM,UAAU,iBAAiB,CAAC,CAAkB;IACnD,OAAO,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC;AAC/B,CAAC;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB;IAClD,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAC9B,CAAC;AACD,MAAM,UAAU,gBAAgB,CAAC,CAAkB;IAClD,OAAO,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC;AAC9B,CAAC;AACD,MAAM,UAAU,cAAc,CAAC,CAAkB;IAChD,OAAO,CAAC,CAAC,QAAQ,KAAK,IAAI,CAAC;AAC5B,CAAC;AAkCD,MAAM,UAAU,mBAAmB,CAAC,QAAgB,EAAE,KAAoB;IACzE,OAAO,KAAK,CAAC,QAAQ,KAAK,QAAQ,CAAC;AACpC,CAAC","sourcesContent":["/**\n * Extension system types.\n *\n * Extensions are TypeScript modules that can:\n * - Subscribe to agent lifecycle events\n * - Register LLM-callable tools\n * - Register commands, keyboard shortcuts, and CLI flags\n * - Interact with the user via UI primitives\n */\n\nimport type {\n\tAgentMessage,\n\tAgentTool,\n\tAgentToolCallOutcome,\n\tAgentToolResult,\n\tAgentToolUpdateCallback,\n\tThinkingLevel,\n\tToolExecutionMode,\n} from \"@earendil-works/pi-agent-core\";\nimport type {\n\tAnyModel,\n\tApi,\n\tAssistantMessageEvent,\n\tAssistantMessageEventStream,\n\tClassifierApi,\n\tConstrainedSamplingConfig,\n\tImageApi,\n\tImageContent,\n\tJsonValue,\n\tMessage,\n\tModel,\n\tOAuthCredentials,\n\tOAuthLoginCallbacks,\n\tProvider,\n\tProviderClassifier,\n\tProviderHeaders,\n\tProviderId,\n\tProviderImages,\n\tRefreshModelsContext,\n\tSimpleStreamOptions,\n\tTextContent,\n\tToolResultMessage,\n\tTranscriptContext,\n\tUsage,\n} from \"@earendil-works/pi-ai\";\nimport type {\n\tAutocompleteItem,\n\tAutocompleteProvider,\n\tComponent,\n\tEditorComponent,\n\tEditorTheme,\n\tKeyId,\n\tOverlayHandle,\n\tOverlayOptions,\n\tTUI,\n} from \"@earendil-works/pi-tui\";\nimport type { Static, TSchema } from \"typebox\";\nimport type { Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { BashResult } from \"../bash-executor.ts\";\nimport type { CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult } from \"../cache-warmer.ts\";\nimport type { CompactionPreparation, CompactionResult } from \"../compaction/index.ts\";\nimport type { EventBus } from \"../event-bus.ts\";\nimport type { ExecOptions, ExecResult } from \"../exec.ts\";\nimport type { ReadonlyFooterDataProvider } from \"../footer-data-provider.ts\";\nimport type { KeybindingsManager } from \"../keybindings.ts\";\nimport type { McpServerConfig, McpServerRegistry, RegisteredMcpServer } from \"../mcp-servers.ts\";\nimport type { CustomMessage } from \"../messages.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type { ScopedModel } from \"../model-resolver.ts\";\nimport type {\n\tBranchSummaryEntry,\n\tCompactionEntry,\n\tContextEditEntry,\n\tCustomEntry,\n\tProjectedSessionEntry,\n\tReadonlySessionManager,\n\tSessionEntry,\n\tSessionManager,\n} from \"../session-manager.ts\";\nimport type { Settings } from \"../settings-manager.ts\";\nimport type { SlashCommandInfo } from \"../slash-commands.ts\";\nimport type { SourceInfo } from \"../source-info.ts\";\nimport type { BuildSystemPromptOptions, NormalizedBuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type { BashOperations } from \"../tools/bash.ts\";\nimport type { EditToolDetails } from \"../tools/edit.ts\";\nimport type {\n\tBashToolDetails,\n\tBashToolInput,\n\tEditToolInput,\n\tFindToolDetails,\n\tFindToolInput,\n\tGrepToolDetails,\n\tGrepToolInput,\n\tLsToolDetails,\n\tLsToolInput,\n\tPowerShellToolDetails,\n\tPowerShellToolInput,\n\tReadToolDetails,\n\tReadToolInput,\n\tWriteToolInput,\n} from \"../tools/index.ts\";\nimport type { ModelRoute, ModelRouteRequest, VirtualModelDefinition } from \"../virtual-models.ts\";\n\nexport type { ExecOptions, ExecResult } from \"../exec.ts\";\nexport type { BuildSystemPromptOptions, NormalizedBuildSystemPromptOptions } from \"../system-prompt.ts\";\nexport type { AgentToolResult, AgentToolUpdateCallback, ToolExecutionMode };\nexport type { AppKeybinding, KeybindingsManager } from \"../keybindings.ts\";\n\n// ============================================================================\n// UI Context\n// ============================================================================\n\n/** Options for extension UI dialogs. */\nexport interface ExtensionUIDialogOptions {\n\t/** AbortSignal to programmatically dismiss the dialog. */\n\tsignal?: AbortSignal;\n\t/** Timeout in milliseconds. Dialog auto-dismisses with live countdown display. */\n\ttimeout?: number;\n}\n\n/** Placement for extension widgets. */\nexport type WidgetPlacement = \"aboveEditor\" | \"belowEditor\";\n\n/** Options for extension widgets. */\nexport interface ExtensionWidgetOptions {\n\t/** Where the widget is rendered. Defaults to \"aboveEditor\". */\n\tplacement?: WidgetPlacement;\n}\n\n/** Raw terminal input listener for extensions. */\nexport type TerminalInputHandler = (data: string) => { consume?: boolean; data?: string } | undefined;\n\n/** Working indicator configuration for the interactive streaming loader. */\nexport interface WorkingIndicatorOptions {\n\t/** Animation frames. Use an empty array to hide the indicator entirely. Custom frames are rendered verbatim. */\n\tframes?: string[];\n\t/** Frame interval in milliseconds for animated indicators. */\n\tintervalMs?: number;\n}\n\n/** Wrap the current autocomplete provider with additional behavior. */\nexport type AutocompleteProviderFactory = (current: AutocompleteProvider) => AutocompleteProvider;\nexport type EditorFactory = (tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager) => EditorComponent;\n\n/**\n * UI context for extensions to request interactive UI.\n * Each mode (interactive, RPC, print) provides its own implementation.\n */\nexport interface ExtensionUIContext {\n\t/** Show a selector and return the user's choice. */\n\tselect(title: string, options: string[], opts?: ExtensionUIDialogOptions): Promise<string | undefined>;\n\n\t/** Show a confirmation dialog. */\n\tconfirm(title: string, message: string, opts?: ExtensionUIDialogOptions): Promise<boolean>;\n\n\t/** Show a text input dialog. */\n\tinput(title: string, placeholder?: string, opts?: ExtensionUIDialogOptions): Promise<string | undefined>;\n\n\t/** Show a notification to the user. */\n\tnotify(message: string, type?: \"info\" | \"warning\" | \"error\"): void;\n\n\t/** Listen to raw terminal input (interactive mode only). Returns an unsubscribe function. */\n\tonTerminalInput(handler: TerminalInputHandler): () => void;\n\n\t/** Set status text in the footer/status bar. Pass undefined to clear. */\n\tsetStatus(key: string, text: string | undefined): void;\n\n\t/** Set the working/loading message shown during streaming. Call with no argument to restore default. */\n\tsetWorkingMessage(message?: string): void;\n\n\t/** Show or hide the built-in interactive working loader row during streaming. */\n\tsetWorkingVisible(visible: boolean): void;\n\n\t/**\n\t * Configure the interactive working indicator shown during streaming.\n\t *\n\t * - Omit the argument to restore the default animated spinner.\n\t * - Use `frames: [\"●\"]` for a static indicator.\n\t * - Use `frames: []` to hide the indicator entirely.\n\t * - Custom frames are rendered as provided, so extensions must add their own colors.\n\t */\n\tsetWorkingIndicator(options?: WorkingIndicatorOptions): void;\n\n\t/** Set the label shown for hidden thinking blocks. Call with no argument to restore default. */\n\tsetHiddenThinkingLabel(label?: string): void;\n\n\t/** Set a widget to display above or below the editor. Accepts string array or component factory. */\n\tsetWidget(key: string, content: string[] | undefined, options?: ExtensionWidgetOptions): void;\n\tsetWidget(\n\t\tkey: string,\n\t\tcontent: ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined,\n\t\toptions?: ExtensionWidgetOptions,\n\t): void;\n\n\t/** Set a custom footer component, or undefined to restore the built-in footer.\n\t *\n\t * The factory receives a FooterDataProvider for data not otherwise accessible:\n\t * git branch and extension statuses from setStatus(). Context usage is on\n\t * ctx.getContextUsage(), token stats on ctx.sessionManager.getEntries(), model info on ctx.model.\n\t */\n\tsetFooter(\n\t\tfactory:\n\t\t\t| ((tui: TUI, theme: Theme, footerData: ReadonlyFooterDataProvider) => Component & { dispose?(): void })\n\t\t\t| undefined,\n\t): void;\n\n\t/** Set a custom header component (shown at startup, above chat), or undefined to restore the built-in header. */\n\tsetHeader(factory: ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined): void;\n\n\t/** Set the terminal window/tab title. */\n\tsetTitle(title: string): void;\n\n\t/** Show a custom component with keyboard focus. */\n\tcustom<T>(\n\t\tfactory: (\n\t\t\ttui: TUI,\n\t\t\ttheme: Theme,\n\t\t\tkeybindings: KeybindingsManager,\n\t\t\tdone: (result: T) => void,\n\t\t) => (Component & { dispose?(): void }) | Promise<Component & { dispose?(): void }>,\n\t\toptions?: {\n\t\t\toverlay?: boolean;\n\t\t\t/** Overlay positioning/sizing options. Can be static or a function for dynamic updates. */\n\t\t\toverlayOptions?: OverlayOptions | (() => OverlayOptions);\n\t\t\t/** Called with the overlay handle after the overlay is shown. Use to control visibility. */\n\t\t\tonHandle?: (handle: OverlayHandle) => void;\n\t\t},\n\t): Promise<T>;\n\n\t/** Paste text into the editor, triggering paste handling (collapse for large content). */\n\tpasteToEditor(text: string): void;\n\n\t/** Set the text in the core input editor. */\n\tsetEditorText(text: string): void;\n\n\t/** Get the current text from the core input editor. */\n\tgetEditorText(): string;\n\n\t/** Show a multi-line editor for text editing. */\n\teditor(title: string, prefill?: string): Promise<string | undefined>;\n\n\t/** Stack additional autocomplete behavior on top of the built-in provider. */\n\taddAutocompleteProvider(factory: AutocompleteProviderFactory): void;\n\n\t/**\n\t * Set a custom editor component via factory function.\n\t * Pass undefined to restore the default editor.\n\t *\n\t * The factory receives:\n\t * - `theme`: EditorTheme for styling borders and autocomplete\n\t * - `keybindings`: KeybindingsManager for app-level keybindings\n\t *\n\t * For full app keybinding support (escape, ctrl+d, model switching, etc.),\n\t * extend `CustomEditor` from `@earendil-works/pi-coding-agent` and call\n\t * `super.handleInput(data)` for keys you don't handle.\n\t *\n\t * @example\n\t * ```ts\n\t * import { CustomEditor } from \"@earendil-works/pi-coding-agent\";\n\t *\n\t * class VimEditor extends CustomEditor {\n\t * private mode: \"normal\" | \"insert\" = \"insert\";\n\t *\n\t * handleInput(data: string): void {\n\t * if (this.mode === \"normal\") {\n\t * // Handle vim normal mode keys...\n\t * if (data === \"i\") { this.mode = \"insert\"; return; }\n\t * }\n\t * super.handleInput(data); // App keybindings + text editing\n\t * }\n\t * }\n\t *\n\t * ctx.ui.setEditorComponent((tui, theme, keybindings) =>\n\t * new VimEditor(tui, theme, keybindings)\n\t * );\n\t * ```\n\t */\n\tsetEditorComponent(factory: EditorFactory | undefined): void;\n\n\t/** Get the currently configured custom editor factory, or undefined when using the default editor. */\n\tgetEditorComponent(): EditorFactory | undefined;\n\n\t/** Get the current theme for styling. */\n\treadonly theme: Theme;\n\n\t/** Get all available themes with their names and file paths. */\n\tgetAllThemes(): { name: string; path: string | undefined }[];\n\n\t/** Load a theme by name without switching to it. Returns undefined if not found. */\n\tgetTheme(name: string): Theme | undefined;\n\n\t/** Set the current theme by name or Theme object. */\n\tsetTheme(theme: string | Theme): { success: boolean; error?: string };\n\n\t/** Get current tool output expansion state. */\n\tgetToolsExpanded(): boolean;\n\n\t/** Set tool output expansion state. */\n\tsetToolsExpanded(expanded: boolean): void;\n}\n\n// ============================================================================\n// Extension Context\n// ============================================================================\n\nexport interface ContextUsage {\n\t/** Estimated context tokens, or null if unknown (e.g. right after compaction, before next LLM response). */\n\ttokens: number | null;\n\tcontextWindow: number;\n\t/** Context usage as percentage of context window, or null if tokens is unknown. */\n\tpercent: number | null;\n}\n\nexport interface CompactOptions {\n\tcustomInstructions?: string;\n\tonComplete?: (result: CompactionResult) => void;\n\tonError?: (error: Error) => void;\n}\n\n/**\n * Context passed to extension event handlers.\n */\nexport type ExtensionMode = \"tui\" | \"rpc\" | \"json\" | \"print\";\n\nexport interface ExtensionContext {\n\t/** UI methods for user interaction */\n\tui: ExtensionUIContext;\n\t/** Current run mode. Use \"tui\" to guard terminal-only UI such as custom components. */\n\tmode: ExtensionMode;\n\t/** Whether dialog-capable UI is available (true in TUI and RPC modes) */\n\thasUI: boolean;\n\t/** Current working directory */\n\tcwd: string;\n\t/** Session manager (read-only) */\n\tsessionManager: ReadonlySessionManager;\n\t/** Model registry for API key resolution */\n\tmodelRegistry: ModelRegistry;\n\t/** Current model (may be undefined) */\n\tmodel: Model<any> | undefined;\n\t/** Models scoped to this session (resolved from `--models` /\n\t * `enabledModels` settings against the available catalogue). Same set\n\t * the `/scoped-models` command shows. Empty when no scoping is\n\t * configured (all available models are usable). Read-only snapshot. */\n\tscopedModels: readonly ScopedModel[];\n\t/** Current thinking level, when provided by the session runtime. */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Whether the agent is idle (not streaming) */\n\tisIdle(): boolean;\n\t/** Whether project-local trust is active for this context. */\n\tisProjectTrusted(): boolean;\n\t/** The current abort signal, or undefined when the agent is not streaming. */\n\tsignal: AbortSignal | undefined;\n\t/** Abort the current agent operation */\n\tabort(): void;\n\t/** Whether there are queued messages waiting */\n\thasPendingMessages(): boolean;\n\t/** Gracefully shutdown pi and exit. Available in all contexts. */\n\tshutdown(): void;\n\t/** Get current context usage for the active model. */\n\tgetContextUsage(): ContextUsage | undefined;\n\t/** Trigger compaction without awaiting completion. */\n\tcompact(options?: CompactOptions): void;\n\t/** Get the current effective system prompt. */\n\tgetSystemPrompt(): string;\n}\n\n/** Options for {@link ExtensionToolContext.executeTool}. */\nexport interface ExecuteToolOptions {\n\t/** Defaults to the calling tool's signal. */\n\tsignal?: AbortSignal;\n\t/** Receives partial results of the nested tool, in addition to `tool_execution_update` events. */\n\tonUpdate?: AgentToolUpdateCallback;\n}\n\n/**\n * Context passed to tool `execute()` in a session: the extension context plus `executeTool()`\n * for running other tools through the same validation, hooks, and permission checks as\n * model-issued calls.\n *\n * A tool wrapped with `wrapToolDefinition()` without a context factory, such as a built-in tool\n * created with `createBashTool()` and run in a plain `Agent` or called directly, gets no context.\n */\nexport interface ExtensionToolContext extends ExtensionContext {\n\t/** Tools {@link executeTool} can call. */\n\treadonly tools: readonly AgentTool[];\n\t/**\n\t * Run another tool. The call gets the id `<calling id>/<n>`, and the `tool_call`, `tool_result`,\n\t * and `tool_execution_*` events carry `parentToolCallId`. It does not appear in the transcript;\n\t * a bounded record of it is kept as `nestedCalls` on the calling tool's result message.\n\t *\n\t * Never rejects for tool failures: unknown tools, validation errors, blocked calls, and thrown\n\t * errors come back as `isError: true`.\n\t */\n\texecuteTool(name: string, args: unknown, options?: ExecuteToolOptions): Promise<AgentToolCallOutcome>;\n}\n\n/**\n * Extended context for command handlers.\n * Includes session control methods only safe in user-initiated commands.\n */\nexport interface ExtensionCommandContext extends ExtensionContext {\n\t/** Get the current base system-prompt construction options. */\n\tgetSystemPromptOptions(): BuildSystemPromptOptions;\n\n\t/** Wait for the agent to finish streaming */\n\twaitForIdle(): Promise<void>;\n\n\t/** Start a new session, optionally with initialization. */\n\tnewSession(options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t}): Promise<{ cancelled: boolean }>;\n\n\t/** Fork from a specific entry, creating a new session file. */\n\tfork(\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Navigate to a different point in the session tree. */\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Switch to a different session file. */\n\tswitchSession(\n\t\tsessionPath: string,\n\t\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t): Promise<{ cancelled: boolean }>;\n\n\t/** Reload extensions, skills, prompts, themes, and context files. */\n\treload(): Promise<void>;\n}\n\n/**\n * Fresh command-capable context bound to the replacement session after a session switch.\n *\n * This is passed to `withSession()` callbacks on `newSession()`, `fork()`, and `switchSession()`.\n */\nexport interface ReplacedSessionContext extends ExtensionCommandContext {\n\tsendMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n\t): Promise<void>;\n\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\"; expandPromptTemplates?: boolean },\n\t): Promise<void>;\n}\n\n// ============================================================================\n// Tool Types\n// ============================================================================\n\n/** Rendering options for tool results */\nexport interface ToolRenderResultOptions {\n\t/** Whether the result view is expanded */\n\texpanded: boolean;\n\t/** Whether this is a partial/streaming result */\n\tisPartial: boolean;\n}\n\n/** Context passed to tool renderers. */\nexport interface ToolRenderContext<TState = any, TArgs = any> {\n\t/** Current tool call arguments. Shared across call/result renders for the same tool call. */\n\targs: TArgs;\n\t/** Unique id for this tool execution. Stable across call/result renders for the same tool call. */\n\ttoolCallId: string;\n\t/** Invalidate just this tool execution component for redraw. */\n\tinvalidate: () => void;\n\t/** Previously returned component for this render slot, if any. */\n\tlastComponent: Component | undefined;\n\t/** Shared renderer state for this tool row. Initialized by tool-execution.ts. */\n\tstate: TState;\n\t/** Working directory for this tool execution. */\n\tcwd: string;\n\t/** Whether the tool execution has started. */\n\texecutionStarted: boolean;\n\t/** Whether the tool call arguments are complete. */\n\targsComplete: boolean;\n\t/** Whether the tool result is partial/streaming. */\n\tisPartial: boolean;\n\t/** Whether the result view is expanded. */\n\texpanded: boolean;\n\t/** Whether inline images are currently shown in the TUI. */\n\tshowImages: boolean;\n\t/** Whether the current result is an error. */\n\tisError: boolean;\n}\n\n/**\n * How the model reaches a tool. \"Callable\" means callable from other tools through\n * `ctx.executeTool()`, as the `codemode` tool does.\n *\n * - `direct`: declared to the model while active, and callable while active.\n * - `model-only`: declared to the model while active, never callable. Use it for orchestrating or\n * interactive tools.\n * - `codemode`: callable whenever registered. Not declared to the model unless explicitly\n * activated. Codemode tools list it in their description.\n * - `deferred`: like `codemode`, but codemode tools do not list it; tool search can find it.\n * - `hidden`: registered but unreachable. Activating it has no effect.\n *\n * `direct` and `model-only` tools are activated when they are registered; the others are not.\n * The active tool set (`getActiveTools`/`setActiveTools`) is the set declared to the model.\n */\nexport type ToolExposure = \"direct\" | \"model-only\" | \"codemode\" | \"deferred\" | \"hidden\";\n\n/**\n * Hints about what a tool does, with the meaning of MCP tool annotations. They come from the tool's\n * author and are not verified; permission extensions can use them to decide which calls to confirm.\n */\nexport interface ToolAnnotations {\n\t/** The tool does not modify its environment. */\n\treadOnlyHint?: boolean;\n\t/** The tool may delete or overwrite data, rather than only add to it. Meaningful when not read-only. */\n\tdestructiveHint?: boolean;\n\t/** Repeating a call with the same arguments has no further effect. Meaningful when not read-only. */\n\tidempotentHint?: boolean;\n\t/** The tool reaches an open world of external entities, such as the web, rather than a closed domain. */\n\topenWorldHint?: boolean;\n}\n\n/** A group of related tools, such as the tools of one MCP server. Codemode tools list them together. */\nexport interface ToolNamespace {\n\t/** For example `mcp__docs`. */\n\tname: string;\n\t/** Short summary shown once with the group in model-facing tool listings. */\n\tdescription?: string;\n\t/**\n\t * Longer usage guidance, such as MCP server instructions. Not part of tool listings; tools that\n\t * describe the namespace on request (codemode's `describeNamespace()`) return it.\n\t */\n\tinstructions?: string;\n}\n\n/** The tools of a session as {@link ToolDefinition.prepareLoadout} sees them. */\nexport interface ToolLoadout {\n\t/** Tools declared to the model (the active tools), in order, with their original descriptions. */\n\treadonly declared: readonly AgentTool[];\n\t/** Tools callable through `ctx.executeTool()`. */\n\treadonly callable: readonly AgentTool[];\n\t/** Every registered tool. */\n\treadonly registered: readonly AgentTool[];\n\tgetExposure(name: string): ToolExposure;\n\tgetNamespace(name: string): ToolNamespace | undefined;\n}\n\n/** Changes {@link ToolDefinition.prepareLoadout} makes to what the model sees. */\nexport interface ToolLoadoutChanges {\n\t/** Model-facing descriptions of declared tools, by tool name. */\n\tdescriptions?: Readonly<Record<string, string>>;\n\t/**\n\t * Declared tools whose declarations requests leave out. They stay active and callable, and the\n\t * transcript still declares them, so the active set survives `/tree` and resume.\n\t */\n\thiddenDeclarations?: readonly string[];\n}\n\n/**\n * Tool definition for registerTool().\n */\nexport interface ToolDefinition<TParams extends TSchema = TSchema, TDetails = unknown, TState = any> {\n\t/** Tool name (used in LLM tool calls) */\n\tname: string;\n\t/** Human-readable label for UI */\n\tlabel: string;\n\t/** Description for LLM */\n\tdescription: string;\n\t/** Optional one-line snippet for the Available tools section in the default system prompt. Custom tools are omitted from that section when this is not provided. */\n\tpromptSnippet?: string;\n\t/** Optional guideline bullets appended to the default system prompt Guidelines section when this tool is active. */\n\tpromptGuidelines?: string[];\n\t/** Parameter schema (TypeBox) */\n\tparameters: TParams;\n\t/** Optional provider-side constrained sampling request for this tool. Set false to explicitly disable it, equivalent to leaving it undefined. */\n\tconstrainedSampling?: false | ConstrainedSamplingConfig;\n\t/** Controls whether ToolExecutionComponent renders the standard colored shell or the tool renders its own framing. */\n\trenderShell?: \"default\" | \"self\";\n\n\t/** Optional compatibility shim to prepare raw tool call arguments before schema validation. Must return an object conforming to TParams. */\n\tprepareArguments?: (args: unknown) => Static<TParams>;\n\n\t/**\n\t * JSON Schema of `structuredContent` in successful results. Tools that declare it should always\n\t * set `structuredContent`; codemode scripts then receive it instead of the text content.\n\t */\n\toutputSchema?: TSchema;\n\n\t/**\n\t * How the model reaches the tool. Default: `\"direct\"`. See {@link ToolExposure}.\n\t */\n\texposure?: ToolExposure;\n\n\t/** Group the tool belongs to, for example its MCP server. */\n\tnamespace?: ToolNamespace;\n\n\t/** Hints about what the tool does, for example from an MCP server. */\n\tannotations?: ToolAnnotations;\n\n\t/**\n\t * Whether registering the tool activates it. Default: `true` for `direct` and `model-only` tools;\n\t * other exposures are never activated on registration. A tool with `defaultActive: false` is\n\t * activated by naming it in `--tools` or the `defaultTools` setting, or with `setActiveTools()`.\n\t */\n\tdefaultActive?: boolean;\n\n\t/**\n\t * Adjust how the loadout is presented to the model while this tool is active. Called whenever\n\t * the active tools change. Tools that orchestrate other tools use it, for example to list the\n\t * callable tools in their own description.\n\t */\n\tprepareLoadout?: (loadout: ToolLoadout) => ToolLoadoutChanges | undefined;\n\n\t/**\n\t * Per-tool execution mode override.\n\t * - \"sequential\": this tool must execute one at a time with other tool calls.\n\t * - \"parallel\": this tool can execute concurrently with other tool calls.\n\t *\n\t * If omitted, the default execution mode applies.\n\t */\n\texecutionMode?: ToolExecutionMode;\n\n\t/** Execute the tool. */\n\texecute(\n\t\ttoolCallId: string,\n\t\tparams: Static<TParams>,\n\t\tsignal: AbortSignal | undefined,\n\t\tonUpdate: AgentToolUpdateCallback<TDetails> | undefined,\n\t\tctx: ExtensionToolContext,\n\t): Promise<AgentToolResult<TDetails>>;\n\n\t/** Custom rendering for tool call display */\n\trenderCall?: (args: Static<TParams>, theme: Theme, context: ToolRenderContext<TState, Static<TParams>>) => Component;\n\n\t/** Custom rendering for tool result display */\n\trenderResult?: (\n\t\tresult: AgentToolResult<TDetails>,\n\t\toptions: ToolRenderResultOptions,\n\t\ttheme: Theme,\n\t\tcontext: ToolRenderContext<TState, Static<TParams>>,\n\t) => Component;\n}\n\ntype AnyToolDefinition = ToolDefinition<any, any, any>;\n\nexport type ToolRenderers = Pick<AnyToolDefinition, \"renderShell\" | \"renderCall\" | \"renderResult\">;\n\n/**\n * Chooses how calls to a tool are drawn, including tools that are not registered. `next()` returns\n * the renderers the remaining resolvers, then the registered tool, would use.\n */\nexport type ToolRendererResolver = (\n\ttoolName: string,\n\tnext: () => ToolRenderers | undefined,\n) => ToolRenderers | undefined;\n\n/**\n * Preserve parameter inference for standalone tool definitions.\n *\n * Use this when assigning a tool to a variable or passing it through arrays such\n * as `customTools`, where contextual typing would otherwise widen params to\n * `unknown`.\n */\nexport function defineTool<TParams extends TSchema, TDetails = unknown, TState = any>(\n\ttool: ToolDefinition<TParams, TDetails, TState>,\n): ToolDefinition<TParams, TDetails, TState> & AnyToolDefinition {\n\treturn tool as ToolDefinition<TParams, TDetails, TState> & AnyToolDefinition;\n}\n\n// ============================================================================\n// Startup/Resource Events\n// ============================================================================\n\nexport interface ProjectTrustEvent {\n\ttype: \"project_trust\";\n\tcwd: string;\n}\n\nexport type ProjectTrustEventDecision = \"yes\" | \"no\" | \"undecided\";\n\nexport interface ProjectTrustEventResult {\n\ttrusted: ProjectTrustEventDecision;\n\tremember?: boolean;\n}\n\nexport interface ProjectTrustContext {\n\tcwd: string;\n\tmode: ExtensionMode;\n\thasUI: boolean;\n\tui: Pick<ExtensionUIContext, \"select\" | \"confirm\" | \"input\" | \"notify\">;\n}\n\nexport type ProjectTrustHandler = (\n\tevent: ProjectTrustEvent,\n\tctx: ProjectTrustContext,\n) => Promise<ProjectTrustEventResult> | ProjectTrustEventResult;\n\n/** Fired after session_start to allow extensions to provide additional resource paths. */\nexport interface ResourcesDiscoverEvent {\n\ttype: \"resources_discover\";\n\tcwd: string;\n\treason: \"startup\" | \"reload\";\n}\n\n/** Result from resources_discover event handler */\nexport interface ResourcesDiscoverResult {\n\tskillPaths?: string[];\n\tpromptPaths?: string[];\n\tthemePaths?: string[];\n}\n\n/**\n * Fired when an extension registers or unregisters an MCP server after the extensions are bound\n * (see {@link ExtensionAPI.registerMcpServer}). Servers registered while extensions load are read\n * with `pi.getMcpServers()` on `session_start`. Handling this event marks an extension as the one\n * that connects registered servers.\n */\nexport interface McpServersChangeEvent {\n\ttype: \"mcp_servers_change\";\n\t/** Every registered server after the change. */\n\tservers: RegisteredMcpServer[];\n}\n\n// ============================================================================\n// Session Events\n// ============================================================================\n\n/** Fired when a session is started, loaded, or reloaded */\nexport interface SessionStartEvent {\n\ttype: \"session_start\";\n\t/** Why this session start happened. */\n\treason: \"startup\" | \"reload\" | \"new\" | \"resume\" | \"fork\";\n\t/** Previously active session file. Present for \"new\", \"resume\", and \"fork\". */\n\tpreviousSessionFile?: string;\n}\n\n/** Fired when the current session metadata changes. */\nexport interface SessionInfoChangedEvent {\n\ttype: \"session_info_changed\";\n\t/** Current normalized session name. Undefined when the name is cleared. */\n\tname: string | undefined;\n}\n\n/** Fired before switching to another session (can be cancelled) */\nexport interface SessionBeforeSwitchEvent {\n\ttype: \"session_before_switch\";\n\treason: \"new\" | \"resume\";\n\ttargetSessionFile?: string;\n}\n\n/** Fired before forking a session (can be cancelled) */\nexport interface SessionBeforeForkEvent {\n\ttype: \"session_before_fork\";\n\tentryId: string;\n\tposition: \"before\" | \"at\";\n}\n\n/** Fired before context compaction (can be cancelled or customized) */\nexport interface SessionBeforeCompactEvent {\n\ttype: \"session_before_compact\";\n\tpreparation: CompactionPreparation;\n\tbranchEntries: SessionEntry[];\n\tcustomInstructions?: string;\n\t/** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** True when the aborted turn is retried after this compaction (overflow recovery) */\n\twillRetry: boolean;\n\tsignal: AbortSignal;\n}\n\n/** Fired after context compaction succeeds */\nexport interface SessionCompactEvent {\n\ttype: \"session_compact\";\n\tcompactionEntry: CompactionEntry;\n\tfromExtension: boolean;\n\t/** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** True when the aborted turn is retried after this compaction (overflow recovery) */\n\twillRetry: boolean;\n}\n\n/** Fired after context compaction fails or is aborted */\nexport interface SessionCompactFailedEvent {\n\ttype: \"session_compact_failed\";\n\t/** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** Error text when compaction failed for a non-abort reason. */\n\terrorMessage?: string;\n\t/** True when compaction was cancelled or aborted. */\n\taborted: boolean;\n\t/** True when the aborted turn would have been retried after this compaction (overflow recovery) */\n\twillRetry: boolean;\n\t/** True when the failing compaction content came from a session_before_compact handler. */\n\tfromExtension: boolean;\n}\n\n/** Fired before an extension runtime is torn down due to quit, reload, or session replacement. */\nexport interface SessionShutdownEvent {\n\ttype: \"session_shutdown\";\n\treason: \"quit\" | \"reload\" | \"new\" | \"resume\" | \"fork\";\n\t/** Destination session file when shutting down due to session replacement. */\n\ttargetSessionFile?: string;\n}\n\n/** Preparation data for tree navigation */\nexport interface TreePreparation {\n\ttargetId: string;\n\toldLeafId: string | null;\n\tcommonAncestorId: string | null;\n\tentriesToSummarize: SessionEntry[];\n\tuserWantsSummary: boolean;\n\t/** Custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** If true, customInstructions replaces the default prompt instead of being appended */\n\treplaceInstructions?: boolean;\n\t/** Label to attach to the branch summary entry */\n\tlabel?: string;\n}\n\n/** Fired before navigating in the session tree (can be cancelled) */\nexport interface SessionBeforeTreeEvent {\n\ttype: \"session_before_tree\";\n\tpreparation: TreePreparation;\n\tsignal: AbortSignal;\n}\n\n/** Fired after navigating in the session tree */\nexport interface SessionTreeEvent {\n\ttype: \"session_tree\";\n\tnewLeafId: string | null;\n\toldLeafId: string | null;\n\tsummaryEntry?: BranchSummaryEntry;\n\tfromExtension?: boolean;\n}\n\nexport type SessionEvent =\n\t| SessionStartEvent\n\t| SessionInfoChangedEvent\n\t| SessionBeforeSwitchEvent\n\t| SessionBeforeForkEvent\n\t| SessionBeforeCompactEvent\n\t| SessionCompactEvent\n\t| SessionCompactFailedEvent\n\t| SessionShutdownEvent\n\t| SessionBeforeTreeEvent\n\t| SessionTreeEvent;\n\n// ============================================================================\n// Agent Events\n// ============================================================================\n\n/**\n * Fired before each LLM call. Can modify messages.\n *\n * `messages` holds the conversation without system messages. The prompt and tool state\n * belong to Pi: it restores them after the handler returns, so a handler cannot drop\n * them and does not need to preserve them.\n */\nexport interface ContextEvent {\n\ttype: \"context\";\n\tmessages: AgentMessage[];\n}\n\n/**\n * Fired before each LLM call, after every `context` handler has run and Pi has restored\n * the prompt and tool state. `messages` is the full transcript including system messages,\n * and the result is sent as returned: the handler owns the prompt and tool declarations.\n */\nexport interface ContextWithSystemEvent {\n\ttype: \"context_with_system\";\n\tmessages: AgentMessage[];\n}\n\n/** Fired before a provider request is sent. Can replace the payload. */\nexport interface BeforeProviderRequestEvent {\n\ttype: \"before_provider_request\";\n\tpayload: unknown;\n}\n\n/**\n * Fired after request headers are assembled, before the provider HTTP call.\n * Handlers mutate `headers` in place (e.g. to inject tracing/session headers);\n * the return value is ignored. A `null` value deletes that header.\n */\nexport interface BeforeProviderHeadersEvent {\n\ttype: \"before_provider_headers\";\n\theaders: ProviderHeaders;\n}\n\n/** Fired after a provider response is received and before the response stream is consumed. */\nexport interface AfterProviderResponseEvent {\n\ttype: \"after_provider_response\";\n\tstatus: number;\n\theaders: Record<string, string>;\n}\n\n/** Fired for a parsed provider stream event before Pi normalizes it. */\nexport interface ProviderStreamEvent {\n\ttype: \"provider_stream_event\";\n\tprovider: ProviderId;\n\tapi: Api;\n\tmodel: string;\n\tdata: unknown;\n}\n\n/** Fired after user submits prompt but before agent loop. */\nexport interface BeforeAgentStartEvent {\n\ttype: \"before_agent_start\";\n\t/** The raw user prompt text (after expansion). */\n\tprompt: string;\n\t/** Images attached to the user prompt, if any. */\n\timages?: ImageContent[];\n\t/** The current system prompt, rendered from systemPromptOptions and earlier handler changes. */\n\treadonly systemPrompt: string;\n\t/** Mutable prompt sections. Later handlers observe mutations made by earlier handlers. */\n\tsystemPromptOptions: NormalizedBuildSystemPromptOptions;\n}\n\n/** Fired when an agent loop starts */\nexport interface AgentStartEvent {\n\ttype: \"agent_start\";\n}\n\n/** Fired when an agent loop ends */\nexport interface AgentEndEvent {\n\ttype: \"agent_end\";\n\tmessages: AgentMessage[];\n}\n\nexport type AgentActivityOutcome = \"completed\" | \"aborted\" | \"error\";\n\nexport interface CustomEntryDraft {\n\ttype: \"custom\";\n\tcustomType: string;\n\tdata?: unknown;\n}\n\nexport interface CustomMessageEntryDraft {\n\ttype: \"custom_message\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdisplay: boolean;\n\tdetails?: unknown;\n}\n\nexport interface ContextEditEntryDraft {\n\ttype: \"context_edit\";\n\ttargetId: string;\n\treplacement: ContextEditEntry[\"replacement\"];\n}\n\nexport interface CompactionEntryDraft {\n\ttype: \"compaction\";\n\tsummary: string;\n\t/** Null creates a self-retaining compaction that keeps no preceding entries. */\n\tfirstKeptEntryId: string | null;\n\tdetails?: unknown;\n\tusage?: Usage;\n}\n\nexport type SessionBoundaryDraft =\n\t| CustomEntryDraft\n\t| CustomMessageEntryDraft\n\t| ContextEditEntryDraft\n\t| CompactionEntryDraft;\n\nexport interface BoundaryContextPreview {\n\tcontextEntries: ProjectedSessionEntry[];\n\tcontextMessages: AgentMessage[];\n\tllmMessages: Message[];\n\tpendingMessages: AgentMessage[];\n\tcanContinue: boolean;\n}\n\nexport interface BoundaryState {\n\tentries: SessionBoundaryDraft[];\n\tcontinue: boolean;\n\tcontext: BoundaryContextPreview;\n\toutcome: AgentActivityOutcome;\n}\n\nexport interface BoundaryResult {\n\tentries?: SessionBoundaryDraft[];\n\tcontinue?: boolean;\n}\n\n/** Fired before final settlement. May append entries and ensure one next provider request. */\nexport interface AgentBeforeSettleEvent extends BoundaryState {\n\ttype: \"agent_before_settle\";\n}\n\n/** Fired after an agent run has fully settled and no automatic retry, compaction, or queued continuation will run. */\nexport interface AgentSettledEvent {\n\ttype: \"agent_settled\";\n}\n\nexport type UIPromptKind = \"select\" | \"confirm\" | \"input\" | \"editor\" | \"custom\";\n\n/** Fired when Pi starts waiting on a blocking user-facing extension UI prompt. */\nexport interface UIPromptStartEvent {\n\ttype: \"ui_prompt_start\";\n\treason: \"ui_prompt\";\n\tkind: UIPromptKind;\n\ttitle?: string;\n}\n\n/** Fired when Pi is no longer waiting on a blocking user-facing extension UI prompt. */\nexport interface UIPromptEndEvent {\n\ttype: \"ui_prompt_end\";\n\treason: \"ui_prompt\";\n\tkind: UIPromptKind;\n\ttitle?: string;\n}\n\n/** Fired at the start of each turn */\nexport interface TurnStartEvent {\n\ttype: \"turn_start\";\n\tturnIndex: number;\n\ttimestamp: number;\n}\n\n/** Fired at the end of each turn */\nexport interface TurnEndEvent extends BoundaryState {\n\ttype: \"turn_end\";\n\tturnIndex: number;\n\tmessage: AgentMessage;\n\ttoolResults: ToolResultMessage[];\n\tmessageEntryId: string;\n\ttoolResultEntryIds: string[];\n}\n\n/** Fired when a message starts (user, assistant, or toolResult) */\nexport interface MessageStartEvent {\n\ttype: \"message_start\";\n\tmessage: AgentMessage;\n}\n\n/** Fired during assistant message streaming with token-by-token updates */\nexport interface MessageUpdateEvent {\n\ttype: \"message_update\";\n\tmessage: AgentMessage;\n\tassistantMessageEvent: AssistantMessageEvent;\n}\n\n/** Fired when a message ends */\nexport interface MessageEndEvent {\n\ttype: \"message_end\";\n\tmessage: AgentMessage;\n}\n\n/** Fired when a tool starts executing */\nexport interface ToolExecutionStartEvent {\n\ttype: \"tool_execution_start\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: any;\n\t/** Set when another tool (for example a codemode script) made this call. */\n\tparentToolCallId?: string;\n}\n\n/** Fired during tool execution with partial/streaming output */\nexport interface ToolExecutionUpdateEvent {\n\ttype: \"tool_execution_update\";\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: any;\n\tpartialResult: any;\n\t/** Set when another tool (for example a codemode script) made this call. */\n\tparentToolCallId?: string;\n}\n\n/** Fired when a tool finishes executing */\nexport interface ToolExecutionEndEvent {\n\ttype: \"tool_execution_end\";\n\ttoolCallId: string;\n\ttoolName: string;\n\tresult: any;\n\tisError: boolean;\n\t/** Set when another tool (for example a codemode script) made this call. */\n\tparentToolCallId?: string;\n}\n\n// ============================================================================\n// Model Events\n// ============================================================================\n\nexport type ModelSelectSource = \"set\" | \"cycle\" | \"restore\";\n\n/** Fired when a new model is selected */\nexport interface ModelSelectEvent {\n\ttype: \"model_select\";\n\tmodel: Model<any>;\n\tpreviousModel: Model<any> | undefined;\n\tsource: ModelSelectSource;\n}\n\n/** Fired when a new thinking level is selected */\nexport interface ThinkingLevelSelectEvent {\n\ttype: \"thinking_level_select\";\n\tlevel: ThinkingLevel;\n\tpreviousLevel: ThinkingLevel;\n}\n\n// ============================================================================\n// User Bash Events\n// ============================================================================\n\n/** Fired when user executes a bash command via ! or !! prefix */\nexport interface UserBashEvent {\n\ttype: \"user_bash\";\n\t/** The command to execute */\n\tcommand: string;\n\t/** True if !! prefix was used (excluded from LLM context) */\n\texcludeFromContext: boolean;\n\t/** Current working directory */\n\tcwd: string;\n}\n\n// ============================================================================\n// Input Events\n// ============================================================================\n\n/** Source of user input */\nexport type InputSource = \"interactive\" | \"rpc\" | \"extension\";\n\n/** Fired when user input is received, before agent processing */\nexport interface InputEvent {\n\ttype: \"input\";\n\t/** The input text */\n\ttext: string;\n\t/** Attached images, if any */\n\timages?: ImageContent[];\n\t/** Where the input came from */\n\tsource: InputSource;\n\t/** How the input will be delivered during streaming, or undefined when idle */\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n}\n\n/** Result from input event handler */\nexport type InputEventResult =\n\t| { action: \"continue\" }\n\t| { action: \"transform\"; text: string; images?: ImageContent[] }\n\t| { action: \"handled\" };\n\n// ============================================================================\n// Tool Events\n// ============================================================================\n\ninterface ToolCallEventBase {\n\ttype: \"tool_call\";\n\t/**\n\t * The call's id. For calls another tool made (with `parentToolCallId` set), pi assigns\n\t * `<parent id>/<n>`; such ids never appear as tool calls or tool results in the transcript, only\n\t * in the parent result's `nestedCalls` record.\n\t */\n\ttoolCallId: string;\n\t/** Set when another tool (for example a codemode script) issued this call. */\n\tparentToolCallId?: string;\n}\n\nexport interface BashToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"bash\";\n\tinput: BashToolInput;\n}\n\nexport interface PowerShellToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"powershell\";\n\tinput: PowerShellToolInput;\n}\n\nexport interface ReadToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"read\";\n\tinput: ReadToolInput;\n}\n\nexport interface EditToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"edit\";\n\tinput: EditToolInput;\n}\n\nexport interface WriteToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"write\";\n\tinput: WriteToolInput;\n}\n\nexport interface GrepToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"grep\";\n\tinput: GrepToolInput;\n}\n\nexport interface FindToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"find\";\n\tinput: FindToolInput;\n}\n\nexport interface LsToolCallEvent extends ToolCallEventBase {\n\ttoolName: \"ls\";\n\tinput: LsToolInput;\n}\n\nexport interface CustomToolCallEvent extends ToolCallEventBase {\n\ttoolName: string;\n\tinput: Record<string, unknown>;\n}\n\n/**\n * Fired before a tool executes. Can block.\n *\n * `event.input` is mutable. Mutate it in place to patch tool arguments before execution.\n * Later `tool_call` handlers see earlier mutations. No re-validation is performed after mutation.\n */\nexport type ToolCallEvent =\n\t| BashToolCallEvent\n\t| PowerShellToolCallEvent\n\t| ReadToolCallEvent\n\t| EditToolCallEvent\n\t| WriteToolCallEvent\n\t| GrepToolCallEvent\n\t| FindToolCallEvent\n\t| LsToolCallEvent\n\t| CustomToolCallEvent;\n\ninterface ToolResultEventBase {\n\ttype: \"tool_result\";\n\t/** The call's id; `<parent id>/<n>` for nested calls, see `ToolCallEvent`. */\n\ttoolCallId: string;\n\t/** Set when another tool (for example a codemode script) issued this call. */\n\tparentToolCallId?: string;\n\tinput: Record<string, unknown>;\n\tcontent: (TextContent | ImageContent)[];\n\t/**\n\t * Machine-readable result for tools that declare an `outputSchema`. Handlers that redact\n\t * `content` should also replace this; replacing `content` alone drops it.\n\t */\n\tstructuredContent?: JsonValue;\n\tisError: boolean;\n\t/** Usage from the tool execution itself, if available. */\n\tusage?: Usage;\n}\n\nexport interface BashToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"bash\";\n\tdetails: BashToolDetails | undefined;\n}\n\nexport interface PowerShellToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"powershell\";\n\tdetails: PowerShellToolDetails | undefined;\n}\n\nexport interface ReadToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"read\";\n\tdetails: ReadToolDetails | undefined;\n}\n\nexport interface EditToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"edit\";\n\tdetails: EditToolDetails | undefined;\n}\n\nexport interface WriteToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"write\";\n\tdetails: undefined;\n}\n\nexport interface GrepToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"grep\";\n\tdetails: GrepToolDetails | undefined;\n}\n\nexport interface FindToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"find\";\n\tdetails: FindToolDetails | undefined;\n}\n\nexport interface LsToolResultEvent extends ToolResultEventBase {\n\ttoolName: \"ls\";\n\tdetails: LsToolDetails | undefined;\n}\n\nexport interface CustomToolResultEvent extends ToolResultEventBase {\n\ttoolName: string;\n\tdetails: unknown;\n}\n\n/** Fired after a tool executes. Can modify result. */\nexport type ToolResultEvent =\n\t| BashToolResultEvent\n\t| PowerShellToolResultEvent\n\t| ReadToolResultEvent\n\t| EditToolResultEvent\n\t| WriteToolResultEvent\n\t| GrepToolResultEvent\n\t| FindToolResultEvent\n\t| LsToolResultEvent\n\t| CustomToolResultEvent;\n\n// Type guards for ToolResultEvent\nexport function isBashToolResult(e: ToolResultEvent): e is BashToolResultEvent {\n\treturn e.toolName === \"bash\";\n}\nexport function isPowerShellToolResult(e: ToolResultEvent): e is PowerShellToolResultEvent {\n\treturn e.toolName === \"powershell\";\n}\nexport function isReadToolResult(e: ToolResultEvent): e is ReadToolResultEvent {\n\treturn e.toolName === \"read\";\n}\nexport function isEditToolResult(e: ToolResultEvent): e is EditToolResultEvent {\n\treturn e.toolName === \"edit\";\n}\nexport function isWriteToolResult(e: ToolResultEvent): e is WriteToolResultEvent {\n\treturn e.toolName === \"write\";\n}\nexport function isGrepToolResult(e: ToolResultEvent): e is GrepToolResultEvent {\n\treturn e.toolName === \"grep\";\n}\nexport function isFindToolResult(e: ToolResultEvent): e is FindToolResultEvent {\n\treturn e.toolName === \"find\";\n}\nexport function isLsToolResult(e: ToolResultEvent): e is LsToolResultEvent {\n\treturn e.toolName === \"ls\";\n}\n\n/**\n * Type guard for narrowing ToolCallEvent by tool name.\n *\n * Built-in tools narrow automatically (no type params needed):\n * ```ts\n * if (isToolCallEventType(\"bash\", event)) {\n * event.input.command; // string\n * }\n * ```\n *\n * Custom tools require explicit type parameters:\n * ```ts\n * if (isToolCallEventType<\"my_tool\", MyToolInput>(\"my_tool\", event)) {\n * event.input.action; // typed\n * }\n * ```\n *\n * Note: Direct narrowing via `event.toolName === \"bash\"` doesn't work because\n * CustomToolCallEvent.toolName is `string` which overlaps with all literals.\n */\nexport function isToolCallEventType(toolName: \"bash\", event: ToolCallEvent): event is BashToolCallEvent;\nexport function isToolCallEventType(toolName: \"powershell\", event: ToolCallEvent): event is PowerShellToolCallEvent;\nexport function isToolCallEventType(toolName: \"read\", event: ToolCallEvent): event is ReadToolCallEvent;\nexport function isToolCallEventType(toolName: \"edit\", event: ToolCallEvent): event is EditToolCallEvent;\nexport function isToolCallEventType(toolName: \"write\", event: ToolCallEvent): event is WriteToolCallEvent;\nexport function isToolCallEventType(toolName: \"grep\", event: ToolCallEvent): event is GrepToolCallEvent;\nexport function isToolCallEventType(toolName: \"find\", event: ToolCallEvent): event is FindToolCallEvent;\nexport function isToolCallEventType(toolName: \"ls\", event: ToolCallEvent): event is LsToolCallEvent;\nexport function isToolCallEventType<TName extends string, TInput extends Record<string, unknown>>(\n\ttoolName: TName,\n\tevent: ToolCallEvent,\n): event is ToolCallEvent & { toolName: TName; input: TInput };\nexport function isToolCallEventType(toolName: string, event: ToolCallEvent): boolean {\n\treturn event.toolName === toolName;\n}\n\n/** Union of all event types */\nexport type ExtensionEvent =\n\t| ProjectTrustEvent\n\t| ResourcesDiscoverEvent\n\t| McpServersChangeEvent\n\t| SessionEvent\n\t| ContextEvent\n\t| ContextWithSystemEvent\n\t| CacheWarmingDecisionEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeProviderHeadersEvent\n\t| AfterProviderResponseEvent\n\t| ProviderStreamEvent\n\t| BeforeAgentStartEvent\n\t| AgentStartEvent\n\t| AgentEndEvent\n\t| AgentBeforeSettleEvent\n\t| AgentSettledEvent\n\t| UIPromptStartEvent\n\t| UIPromptEndEvent\n\t| TurnStartEvent\n\t| TurnEndEvent\n\t| MessageStartEvent\n\t| MessageUpdateEvent\n\t| MessageEndEvent\n\t| ToolExecutionStartEvent\n\t| ToolExecutionUpdateEvent\n\t| ToolExecutionEndEvent\n\t| ModelSelectEvent\n\t| ThinkingLevelSelectEvent\n\t| UserBashEvent\n\t| InputEvent\n\t| ToolCallEvent\n\t| ToolResultEvent;\n\n// ============================================================================\n// Event Results\n// ============================================================================\n\nexport interface ContextEventResult {\n\tmessages?: AgentMessage[];\n}\n\nexport type TurnEndEventResult = BoundaryResult;\nexport type AgentBeforeSettleEventResult = BoundaryResult;\n\nexport type BeforeProviderRequestEventResult = unknown;\n\nexport type { CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult } from \"../cache-warmer.ts\";\n\nexport interface ToolCallEventResult {\n\t/** Block tool execution. To modify arguments, mutate `event.input` in place instead. */\n\tblock?: boolean;\n\treason?: string;\n\t/**\n\t * Hint that the agent should stop after the current tool batch when this call is blocked.\n\t * Early termination only happens when every finalized tool result in the batch sets this to true.\n\t */\n\tterminate?: boolean;\n}\n\n/** Result from user_bash event handler */\nexport type UserBashEventResult =\n\t| {\n\t\t\t/** Custom operations to use for execution */\n\t\t\toperations: BashOperations;\n\t\t\tresult?: never;\n\t }\n\t| {\n\t\t\toperations?: never;\n\t\t\t/** Full replacement: extension handled execution, use this result */\n\t\t\tresult: BashResult;\n\t };\n\n/**\n * Changes a `tool_result` handler makes. Omitted fields stay as they are, except that replacing\n * `content` without returning `structuredContent` drops the structured content, because it may no\n * longer match. Return it along with `content` to keep it.\n */\nexport interface ToolResultEventResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tstructuredContent?: JsonValue;\n\tisError?: boolean;\n\tusage?: Usage;\n}\n\nexport interface MessageEndEventResult {\n\t/** Replace the finalized message. The replacement must keep the original message role. */\n\tmessage?: AgentMessage;\n}\n\nexport interface BeforeAgentStartEventResult {\n\tmessage?: Pick<CustomMessage, \"customType\" | \"content\" | \"display\" | \"details\">;\n\t/** Replace the complete system prompt for this turn. Later handlers observe this exact override. */\n\tsystemPrompt?: string;\n}\n\nexport interface SessionBeforeSwitchResult {\n\tcancel?: boolean;\n}\n\nexport interface SessionBeforeForkResult {\n\tcancel?: boolean;\n\tskipConversationRestore?: boolean;\n}\n\nexport interface SessionBeforeCompactResult {\n\tcancel?: boolean;\n\tcompaction?: CompactionResult;\n}\n\nexport interface SessionBeforeTreeResult {\n\tcancel?: boolean;\n\tsummary?: {\n\t\tsummary: string;\n\t\tdetails?: unknown;\n\t\tusage?: Usage;\n\t};\n\t/** Override custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** Override whether customInstructions replaces the default prompt */\n\treplaceInstructions?: boolean;\n\t/** Override label to attach to the branch summary entry */\n\tlabel?: string;\n}\n\n// ============================================================================\n// Message and Entry Rendering\n// ============================================================================\n\nexport interface MessageRenderOptions {\n\texpanded: boolean;\n\t/** Horizontal padding configured by the outputPad setting. */\n\toutputPad: number;\n}\n\nexport interface MarkdownTransformContext {\n\tmessageType: \"user\" | \"assistant\" | \"assistant-thinking\";\n\tisStreaming: boolean;\n\tavailableWidth: number;\n}\n\nexport type MarkdownTransformer = (markdown: string, context: MarkdownTransformContext) => string;\n\nexport interface EntryRenderOptions {\n\texpanded: boolean;\n}\n\nexport type MessageRenderer<T = unknown> = (\n\tmessage: CustomMessage<T>,\n\toptions: MessageRenderOptions,\n\ttheme: Theme,\n) => Component | undefined;\n\nexport type EntryRenderer<T = unknown> = (\n\tentry: CustomEntry<T>,\n\toptions: EntryRenderOptions,\n\ttheme: Theme,\n) => Component | undefined;\n\n// ============================================================================\n// Command Registration\n// ============================================================================\n\nexport interface RegisteredCommand {\n\tname: string;\n\tsourceInfo: SourceInfo;\n\tdescription?: string;\n\tgetArgumentCompletions?: (argumentPrefix: string) => AutocompleteItem[] | null | Promise<AutocompleteItem[] | null>;\n\thandler: (args: string, ctx: ExtensionCommandContext) => Promise<void>;\n}\n\nexport interface ResolvedCommand extends RegisteredCommand {\n\tinvocationName: string;\n}\n\n// ============================================================================\n// Extension API\n// ============================================================================\n\n/** Handler function type for events */\n// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements\nexport type ExtensionHandler<E, R = undefined> = (event: E, ctx: ExtensionContext) => Promise<R | void> | R | void;\n\n/**\n * ExtensionAPI passed to extension factory functions.\n */\nexport interface ExtensionAPI {\n\t// =========================================================================\n\t// Event Subscription\n\t// =========================================================================\n\n\ton(event: \"project_trust\", handler: ProjectTrustHandler): () => void;\n\ton(\n\t\tevent: \"resources_discover\",\n\t\thandler: ExtensionHandler<ResourcesDiscoverEvent, ResourcesDiscoverResult>,\n\t): () => void;\n\ton(event: \"session_start\", handler: ExtensionHandler<SessionStartEvent>): () => void;\n\ton(event: \"session_info_changed\", handler: ExtensionHandler<SessionInfoChangedEvent>): () => void;\n\ton(\n\t\tevent: \"session_before_switch\",\n\t\thandler: ExtensionHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>,\n\t): () => void;\n\ton(\n\t\tevent: \"session_before_fork\",\n\t\thandler: ExtensionHandler<SessionBeforeForkEvent, SessionBeforeForkResult>,\n\t): () => void;\n\ton(\n\t\tevent: \"session_before_compact\",\n\t\thandler: ExtensionHandler<SessionBeforeCompactEvent, SessionBeforeCompactResult>,\n\t): () => void;\n\ton(event: \"session_compact\", handler: ExtensionHandler<SessionCompactEvent>): () => void;\n\ton(event: \"session_compact_failed\", handler: ExtensionHandler<SessionCompactFailedEvent>): () => void;\n\ton(event: \"session_shutdown\", handler: ExtensionHandler<SessionShutdownEvent>): () => void;\n\ton(event: \"mcp_servers_change\", handler: ExtensionHandler<McpServersChangeEvent>): () => void;\n\ton(\n\t\tevent: \"session_before_tree\",\n\t\thandler: ExtensionHandler<SessionBeforeTreeEvent, SessionBeforeTreeResult>,\n\t): () => void;\n\ton(event: \"session_tree\", handler: ExtensionHandler<SessionTreeEvent>): () => void;\n\ton(event: \"context\", handler: ExtensionHandler<ContextEvent, ContextEventResult>): () => void;\n\ton(event: \"context_with_system\", handler: ExtensionHandler<ContextWithSystemEvent, ContextEventResult>): () => void;\n\ton(\n\t\tevent: \"cache_warming_decision\",\n\t\thandler: ExtensionHandler<CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult>,\n\t): () => void;\n\ton(\n\t\tevent: \"before_provider_request\",\n\t\thandler: ExtensionHandler<BeforeProviderRequestEvent, BeforeProviderRequestEventResult>,\n\t): () => void;\n\ton(event: \"before_provider_headers\", handler: ExtensionHandler<BeforeProviderHeadersEvent>): () => void;\n\ton(event: \"after_provider_response\", handler: ExtensionHandler<AfterProviderResponseEvent>): () => void;\n\ton(event: \"provider_stream_event\", handler: ExtensionHandler<ProviderStreamEvent>): () => void;\n\ton(\n\t\tevent: \"before_agent_start\",\n\t\thandler: ExtensionHandler<BeforeAgentStartEvent, BeforeAgentStartEventResult>,\n\t): () => void;\n\ton(event: \"agent_start\", handler: ExtensionHandler<AgentStartEvent>): () => void;\n\ton(event: \"agent_end\", handler: ExtensionHandler<AgentEndEvent>): () => void;\n\ton(\n\t\tevent: \"agent_before_settle\",\n\t\thandler: ExtensionHandler<AgentBeforeSettleEvent, AgentBeforeSettleEventResult>,\n\t): () => void;\n\ton(event: \"agent_settled\", handler: ExtensionHandler<AgentSettledEvent>): () => void;\n\ton(event: \"ui_prompt_start\", handler: ExtensionHandler<UIPromptStartEvent>): () => void;\n\ton(event: \"ui_prompt_end\", handler: ExtensionHandler<UIPromptEndEvent>): () => void;\n\ton(event: \"turn_start\", handler: ExtensionHandler<TurnStartEvent>): () => void;\n\ton(event: \"turn_end\", handler: ExtensionHandler<TurnEndEvent, TurnEndEventResult>): () => void;\n\ton(event: \"message_start\", handler: ExtensionHandler<MessageStartEvent>): () => void;\n\ton(event: \"message_update\", handler: ExtensionHandler<MessageUpdateEvent>): () => void;\n\ton(event: \"message_end\", handler: ExtensionHandler<MessageEndEvent, MessageEndEventResult>): () => void;\n\ton(event: \"tool_execution_start\", handler: ExtensionHandler<ToolExecutionStartEvent>): () => void;\n\ton(event: \"tool_execution_update\", handler: ExtensionHandler<ToolExecutionUpdateEvent>): () => void;\n\ton(event: \"tool_execution_end\", handler: ExtensionHandler<ToolExecutionEndEvent>): () => void;\n\ton(event: \"model_select\", handler: ExtensionHandler<ModelSelectEvent>): () => void;\n\ton(event: \"thinking_level_select\", handler: ExtensionHandler<ThinkingLevelSelectEvent>): () => void;\n\ton(event: \"tool_call\", handler: ExtensionHandler<ToolCallEvent, ToolCallEventResult>): () => void;\n\ton(event: \"tool_result\", handler: ExtensionHandler<ToolResultEvent, ToolResultEventResult>): () => void;\n\ton(event: \"user_bash\", handler: ExtensionHandler<UserBashEvent, UserBashEventResult>): () => void;\n\ton(event: \"input\", handler: ExtensionHandler<InputEvent, InputEventResult>): () => void;\n\n\t// =========================================================================\n\t// Tool Registration\n\t// =========================================================================\n\n\t/** Register a tool that the LLM can call. */\n\tregisterTool<TParams extends TSchema = TSchema, TDetails = unknown, TState = any>(\n\t\ttool: ToolDefinition<TParams, TDetails, TState>,\n\t): void;\n\n\t// =========================================================================\n\t// Command, Shortcut, Flag Registration\n\t// =========================================================================\n\n\t/** Register a custom command. */\n\tregisterCommand(name: string, options: Omit<RegisteredCommand, \"name\" | \"sourceInfo\">): void;\n\n\t/** Register a keyboard shortcut. */\n\tregisterShortcut(\n\t\tshortcut: KeyId,\n\t\toptions: {\n\t\t\tdescription?: string;\n\t\t\thandler: (ctx: ExtensionContext) => Promise<void> | void;\n\t\t},\n\t): void;\n\n\t/** Register a CLI flag. */\n\tregisterFlag(\n\t\tname: string,\n\t\toptions:\n\t\t\t| {\n\t\t\t\t\tdescription?: string;\n\t\t\t\t\ttype: \"boolean\";\n\t\t\t\t\tdefault?: boolean;\n\t\t\t }\n\t\t\t| {\n\t\t\t\t\tdescription?: string;\n\t\t\t\t\ttype: \"string\";\n\t\t\t\t\tdefault?: string;\n\t\t\t },\n\t): void;\n\n\t/** Get the value of a registered CLI flag. */\n\tgetFlag(name: string): boolean | string | undefined;\n\n\t// =========================================================================\n\t// Message Rendering\n\t// =========================================================================\n\n\t/** Register a custom renderer for CustomMessageEntry. */\n\tregisterMessageRenderer<T = unknown>(customType: string, renderer: MessageRenderer<T>): void;\n\n\t/** Register a transformer for user and assistant Markdown before Pi renders it in the interactive transcript. */\n\tregisterMarkdownTransformer(transformer: MarkdownTransformer): void;\n\n\t/** Register a custom renderer for CustomEntry. Custom entries do not participate in LLM context. */\n\tregisterEntryRenderer<T = unknown>(customType: string, renderer: EntryRenderer<T>): void;\n\n\t/** Choose how tool calls are drawn. Resolvers run in extension load order. */\n\tregisterToolRenderer(resolver: ToolRendererResolver): void;\n\n\t// =========================================================================\n\t// Actions\n\t// =========================================================================\n\n\t/** Send a custom message to the session. */\n\tsendMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n\t): void;\n\n\t/**\n\t * Send a user message to the agent. Always triggers a turn.\n\t * When the agent is streaming, use deliverAs to specify how to queue the message.\n\t * Set expandPromptTemplates to dispatch extension commands and expand skill commands and prompt templates.\n\t */\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\"; expandPromptTemplates?: boolean },\n\t): void;\n\n\t/** Append a custom entry to the session for state persistence (not sent to LLM). */\n\tappendEntry<T = unknown>(customType: string, data?: T): void;\n\n\t// =========================================================================\n\t// Session Metadata\n\t// =========================================================================\n\n\t/** Set the session display name (shown in session selector). */\n\tsetSessionName(name: string): void;\n\n\t/** Get the current session name, if set. */\n\tgetSessionName(): string | undefined;\n\n\t/** Set or clear a label on an entry. Labels are user-defined markers for bookmarking/navigation. */\n\tsetLabel(entryId: string, label: string | undefined): void;\n\n\t/** Execute a shell command. */\n\texec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;\n\n\t/** Get the names of the active tools, which are the tools declared to the model. */\n\tgetActiveTools(): string[];\n\n\t/** Get all configured tools with parameter schema, prompt guidelines, exposure, and source metadata. */\n\tgetAllTools(): ToolInfo[];\n\n\t/** Get a copy of the effective settings (global and project settings merged, with overrides). */\n\tgetSettings(): Settings;\n\n\t/**\n\t * Set the active tools by name. Unknown and `hidden` tools are ignored. Tools with `codemode` or\n\t * `deferred` exposure stay callable from codemode scripts whether active or not.\n\t */\n\tsetActiveTools(toolNames: string[]): void;\n\n\t/** Get available slash commands in the current session. */\n\tgetCommands(): SlashCommandInfo[];\n\n\t// =========================================================================\n\t// Model and Thinking Level\n\t// =========================================================================\n\n\t/**\n\t * Set the model for the current session without changing the configured default for new sessions.\n\t * Returns false if authentication is not configured for the model's provider.\n\t */\n\tsetModel(model: Model<any>): Promise<boolean>;\n\n\t/** Get current thinking level. */\n\tgetThinkingLevel(): ThinkingLevel;\n\n\t/**\n\t * Set the thinking level (clamped to model capabilities) for the current session without changing the configured default\n\t * for new sessions.\n\t */\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\n\t// =========================================================================\n\t// Provider Registration\n\t// =========================================================================\n\n\t/**\n\t * Register or override a model provider.\n\t *\n\t * If `models` is provided: replaces all existing models for this provider.\n\t * If only `baseUrl` is provided: overrides the URL for existing models.\n\t * If `oauth` is provided: registers OAuth provider for /login support.\n\t * If `streamSimple` is provided: registers a custom API stream handler.\n\t *\n\t * During initial extension load this call is queued and applied once the\n\t * runner has bound its context. After that it takes effect immediately, so\n\t * it is safe to call from command handlers or event callbacks without\n\t * requiring a `/reload`.\n\t *\n\t * @example\n\t * // Register a new provider with custom models\n\t * pi.registerProvider(\"my-proxy\", {\n\t * baseUrl: \"https://proxy.example.com\",\n\t * apiKey: \"$PROXY_API_KEY\",\n\t * api: \"anthropic-messages\",\n\t * models: [\n\t * {\n\t * id: \"claude-sonnet-4-20250514\",\n\t * name: \"Claude 4 Sonnet (proxy)\",\n\t * reasoning: false,\n\t * input: [\"text\", \"image\"],\n\t * cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t * contextWindow: 200000,\n\t * maxTokens: 16384\n\t * }\n\t * ]\n\t * });\n\t *\n\t * @example\n\t * // Override baseUrl for an existing provider\n\t * pi.registerProvider(\"anthropic\", {\n\t * baseUrl: \"https://proxy.example.com\"\n\t * });\n\t *\n\t * @example\n\t * // Register provider with OAuth support\n\t * pi.registerProvider(\"corporate-ai\", {\n\t * baseUrl: \"https://ai.corp.com\",\n\t * api: \"openai-responses\",\n\t * models: [...],\n\t * oauth: {\n\t * name: \"Corporate AI (SSO)\",\n\t * async login(callbacks) { ... },\n\t * async refreshToken(credentials) { ... },\n\t * getApiKey(credentials) { return credentials.access; }\n\t * }\n\t * });\n\t */\n\tregisterProvider(provider: Provider): void;\n\tregisterProvider(name: string, config: ProviderConfig): void;\n\n\t/**\n\t * Unregister a previously registered provider.\n\t *\n\t * Removes all models belonging to the named provider and restores any\n\t * built-in models that were overridden by it. Has no effect if the provider\n\t * is not currently registered.\n\t *\n\t * Like `registerProvider`, this takes effect immediately when called after\n\t * the initial load phase.\n\t *\n\t * @example\n\t * pi.unregisterProvider(\"my-proxy\");\n\t */\n\tunregisterProvider(name: string): void;\n\n\t// =========================================================================\n\t// MCP Servers\n\t// =========================================================================\n\n\t/**\n\t * Register an MCP server for this session, with the same config as an `mcpServers` entry in\n\t * `mcp.json`. The server connects next to the configured servers: on `session_start` when\n\t * registered during extension load, right away when registered later. Registering a name again\n\t * replaces the extension's earlier registration.\n\t *\n\t * The registration is not saved; register again on every load. A server of the same name in\n\t * `mcp.json` takes precedence. Throws for invalid configs and for names another extension\n\t * registered. When no loaded extension handles MCP servers (for example because another MCP\n\t * extension replaced the built-in one), the registration is reported as an extension error.\n\t *\n\t * @example\n\t * pi.registerMcpServer(\"jira\", { url: \"https://mcp.example.com/jira\" });\n\t */\n\tregisterMcpServer(name: string, config: McpServerConfig): void;\n\n\t/** Remove an MCP server this extension registered and close its connection. */\n\tunregisterMcpServer(name: string): void;\n\n\t/** Every MCP server registered by extensions. For extensions that connect MCP servers. */\n\tgetMcpServers(): RegisteredMcpServer[];\n\n\t/**\n\t * Register a virtual model: a selectable catalog entry that routes each request to a physical\n\t * model. The selection (`ctx.model`, `model_change` entries) names the virtual model; assistant\n\t * messages record the physical model and thinking level the router picked.\n\t *\n\t * `provider` may be any provider id, including one with physical models, and may list several\n\t * virtual models. Registering the same provider and id again replaces the virtual model. See\n\t * docs/virtual-models.md.\n\t */\n\tregisterVirtualModel<TState = unknown>(model: ExtensionVirtualModel<TState>): void;\n\n\t/** Remove a virtual model registered with `registerVirtualModel()`. */\n\tunregisterVirtualModel(provider: string, id: string): void;\n\n\t/** Shared event bus for extension communication. */\n\tevents: EventBus;\n}\n\n// ============================================================================\n// Provider Registration Types\n// ============================================================================\n\n/** Virtual model registered via pi.registerVirtualModel(). */\nexport interface ExtensionVirtualModel<TState = unknown> extends Omit<VirtualModelDefinition<TState>, \"route\"> {\n\t/** Like `VirtualModelDefinition.route`, with an extension context. */\n\troute(request: ModelRouteRequest<TState>, ctx: ExtensionContext): ModelRoute<TState> | Promise<ModelRoute<TState>>;\n}\n\n/** Configuration for registering a provider via pi.registerProvider(). */\nexport interface ProviderConfig {\n\t/** Display name for the provider in UI. */\n\tname?: string;\n\t/** Base URL for the API endpoint. Required when defining models. */\n\tbaseUrl?: string;\n\t/** API key literal, env interpolation ($ENV_VAR or ${ENV_VAR}), or leading !command. Required when defining models (unless oauth provided). */\n\tapiKey?: string;\n\t/** API type. Required at provider or model level when defining models. */\n\tapi?: Api;\n\t/**\n\t * Optional streamSimple handler for custom APIs.\n\t * The context is a normalized transcript: read the prompt and tools from its system messages\n\t * (`getCurrentSystemPrompt(context.messages)`, `getCurrentTools(context.messages)`).\n\t * Implementations must invoke `options.onPayload` before sending the provider request and use any\n\t * returned replacement payload. They must invoke `options.onResponse` after receiving the response\n\t * and before consuming its body, matching built-in providers. Implementations may invoke\n\t * `options.onProviderStreamEvent(data, model)` with parsed stream events before normalization.\n\t * Event data is adapter-owned and must be treated as read-only.\n\t */\n\tstreamSimple?: (\n\t\tmodel: Model<Api>,\n\t\tcontext: TranscriptContext,\n\t\toptions?: SimpleStreamOptions,\n\t) => AssistantMessageEventStream;\n\t/** Image-generation implementations keyed by image API. */\n\timages?: Partial<Record<ImageApi, ProviderImages>>;\n\t/** Classifier implementations keyed by classifier API. */\n\tclassifiers?: Partial<Record<ClassifierApi, ProviderClassifier>>;\n\t/** Custom headers to include in requests. */\n\theaders?: Record<string, string>;\n\t/** If true, adds Authorization: Bearer header with the resolved API key. */\n\tauthHeader?: boolean;\n\t/** Models to register. If provided, replaces all existing models for this provider. */\n\tmodels?: ProviderModelConfig[];\n\t/**\n\t * Refresh this provider's model list. The returned list replaces extension-provided models.\n\t * Use context.publish({ persist: entry }) when the catalog should persist across sessions.\n\t */\n\trefreshModels?(context: RefreshModelsContext): Promise<ProviderModelConfig[]>;\n\t/** OAuth provider for /login support. The `id` is set automatically from the provider name. */\n\toauth?: {\n\t\t/** Display name for the provider in login UI. */\n\t\tname: string;\n\t\t/** Whether access through this auth method is backed by a provider subscription. */\n\t\tisSubscription?: boolean;\n\t\t/** @deprecated Retained for source compatibility; canonical auth flows ignore it. */\n\t\tusesCallbackServer?: boolean;\n\t\t/** Run the login flow, return credentials to persist. */\n\t\tlogin(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials>;\n\t\t/** Refresh expired credentials, return updated credentials to persist. */\n\t\trefreshToken(credentials: OAuthCredentials, signal: AbortSignal): Promise<OAuthCredentials>;\n\t\t/** Convert credentials to API key string for the provider. */\n\t\tgetApiKey(credentials: OAuthCredentials): string;\n\t\t/** Legacy synchronous credential-dependent model projection. */\n\t\tmodifyModels?(models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[];\n\t};\n}\n\ninterface ProviderModelConfigBase {\n\t/** Model ID. */\n\tid: string;\n\t/** Display name. */\n\tname: string;\n\t/** API type override for this model. */\n\tapi?: string;\n\t/** API endpoint URL override for this model. */\n\tbaseUrl?: string;\n\t/** Supported input types. */\n\tinput: (\"text\" | \"image\")[];\n\t/** Provider input limits and cache-safe image preprocessing metadata. */\n\tinputLimits?: AnyModel[\"inputLimits\"];\n\t/** Per-million-token cost rates and optional request-wide input pricing tiers. */\n\tcost: AnyModel[\"cost\"];\n\t/** Custom headers for this model. */\n\theaders?: Record<string, string>;\n}\n\n/** Chat model configuration. Omitted `type` is normalized to `\"chat\"`. */\nexport interface ProviderChatModelConfig extends ProviderModelConfigBase {\n\ttype?: \"chat\";\n\tapi?: Api;\n\t/** Whether the model supports extended thinking. */\n\treasoning: boolean;\n\t/** Maps pi thinking levels to provider/model-specific values; null marks a level unsupported. */\n\tthinkingLevelMap?: Model<Api>[\"thinkingLevelMap\"];\n\t/** Best-effort prompt cache lifetime in seconds per retention tier. Unset disables cache warming. */\n\tpromptCache?: Model<Api>[\"promptCache\"];\n\t/** Maximum context window size in tokens. */\n\tcontextWindow: number;\n\t/** Maximum output tokens. */\n\tmaxTokens: number;\n\tsamplingParams?: Record<string, unknown>;\n\t/** OpenAI compatibility settings. */\n\tcompat?: Model<Api>[\"compat\"];\n}\n\n/** Image-generation model configuration. */\nexport interface ProviderImageModelConfig extends ProviderModelConfigBase {\n\ttype: \"image\";\n\tapi?: ImageApi;\n\toutput: (\"text\" | \"image\")[];\n}\n\n/** Structured classifier model configuration. */\nexport interface ProviderClassifierModelConfig extends ProviderModelConfigBase {\n\ttype: \"classifier\";\n\tapi?: ClassifierApi;\n\tcontextWindow: number;\n}\n\n/** Configuration for a model within a provider. */\nexport type ProviderModelConfig = ProviderChatModelConfig | ProviderImageModelConfig | ProviderClassifierModelConfig;\n\n/** Extension factory function type. Supports both sync and async initialization. */\nexport type ExtensionFactory = (pi: ExtensionAPI) => void | Promise<void>;\n\nexport type InlineExtension =\n\t| ExtensionFactory\n\t| {\n\t\t\t/**\n\t\t\t * Display name shown as `<inline:name>` in the startup Extensions list and errors. With\n\t\t\t * `builtin`, the extension is named `builtin:name` in errors and diagnostics.\n\t\t\t */\n\t\t\tname: string;\n\t\t\tfactory: ExtensionFactory;\n\t\t\t/** Omit this extension from the startup Extensions list. */\n\t\t\thidden?: boolean;\n\t\t\t/**\n\t\t\t * Leave this extension out when another extension registers a tool, command, or flag with a\n\t\t\t * name it registers during loading, instead of reporting a conflict. The CLI's built-in MCP,\n\t\t\t * codemode, and tool search extensions use it, so for example an MCP extension that registers\n\t\t\t * `/mcp` replaces the built-in MCP support. The factory still runs, so it should only register\n\t\t\t * tools, commands, flags, and event handlers.\n\t\t\t */\n\t\t\treplaceable?: boolean;\n\t\t\t/**\n\t\t\t * Supply the code of the `builtin:<name>` extension instead of loading as an inline extension.\n\t\t\t * `builtin:<name>` is an extension resource like a file: it loads by default, `pi config` lists\n\t\t\t * it, `-builtin:<name>` in the `extensions` setting and `--no-extensions` disable it, and\n\t\t\t * `-e builtin:<name>` loads it explicitly. It is hidden from the startup Extensions list and\n\t\t\t * loads after project trust is resolved, so it cannot handle `project_trust`. The CLI's built-in\n\t\t\t * extensions use it.\n\t\t\t */\n\t\t\tbuiltin?: boolean;\n\t };\n\n// ============================================================================\n// Loaded Extension Types\n// ============================================================================\n\nexport interface RegisteredTool {\n\tdefinition: ToolDefinition;\n\tsourceInfo: SourceInfo;\n}\n\nexport interface ExtensionFlag {\n\tname: string;\n\tdescription?: string;\n\ttype: \"boolean\" | \"string\";\n\tdefault?: boolean | string;\n\textensionPath: string;\n}\n\nexport interface ExtensionShortcut {\n\tshortcut: KeyId;\n\tdescription?: string;\n\thandler: (ctx: ExtensionContext) => Promise<void> | void;\n\textensionPath: string;\n}\n\ntype HandlerFn = (...args: unknown[]) => Promise<unknown>;\n\nexport type SendMessageHandler = <T = unknown>(\n\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\toptions?: { triggerTurn?: boolean; deliverAs?: \"steer\" | \"followUp\" | \"nextTurn\" },\n) => void;\n\nexport type SendUserMessageHandler = (\n\tcontent: string | (TextContent | ImageContent)[],\n\toptions?: { deliverAs?: \"steer\" | \"followUp\"; expandPromptTemplates?: boolean },\n) => void;\n\nexport type AppendEntryHandler = <T = unknown>(customType: string, data?: T) => void;\n\nexport type SetSessionNameHandler = (name: string) => void;\n\nexport type GetSessionNameHandler = () => string | undefined;\n\nexport type GetActiveToolsHandler = () => string[];\n\n/** Tool info with name, description, parameter schema, prompt guidelines, and source metadata. */\nexport type ToolInfo = Pick<ToolDefinition, \"name\" | \"description\" | \"parameters\" | \"promptGuidelines\"> & {\n\texposure: ToolExposure;\n\tnamespace?: ToolNamespace;\n\tannotations?: ToolAnnotations;\n\tsourceInfo: SourceInfo;\n};\n\nexport type GetAllToolsHandler = () => ToolInfo[];\n\nexport type GetSettingsHandler = () => Settings;\n\nexport type GetCommandsHandler = () => SlashCommandInfo[];\n\nexport type SetActiveToolsHandler = (toolNames: string[]) => void;\n\nexport type RefreshToolsHandler = () => void;\n\nexport type SetModelHandler = (model: Model<any>) => Promise<boolean>;\n\nexport type GetThinkingLevelHandler = () => ThinkingLevel;\n\nexport type SetThinkingLevelHandler = (level: ThinkingLevel) => void;\n\nexport type SetLabelHandler = (entryId: string, label: string | undefined) => void;\n\n/**\n * Shared state created by loader, used during registration and runtime.\n * Contains flag values (defaults set during registration, CLI values set after).\n */\nexport interface ExtensionRuntimeState {\n\tflagValues: Map<string, boolean | string>;\n\t/** Legacy provider-config registrations queued during extension loading, processed when runner binds. */\n\tpendingProviderRegistrations: Array<{ name: string; config: ProviderConfig; extensionPath: string }>;\n\t/** Native pi-ai provider registrations queued during extension loading, processed when runner binds. */\n\tpendingNativeProviderRegistrations: Array<{ provider: Provider; extensionPath: string }>;\n\t/** Virtual model registrations queued during extension loading, processed when runner binds. */\n\tpendingVirtualModelRegistrations: Array<{ definition: VirtualModelDefinition; extensionPath: string }>;\n\t/** Create an extension context. Throws before the runner binds. */\n\tcreateContext: () => ExtensionContext;\n\t/** Throws when this extension instance is stale after runtime replacement. */\n\tassertActive: () => void;\n\t/** Marks this extension instance as stale after runtime replacement or reload. */\n\tinvalidate: (message?: string) => void;\n\t/** Retain an event-bus subscription until this runtime is invalidated. */\n\ttrackEventBusSubscription: (unsubscribe: () => void) => () => void;\n\t/**\n\t * Register or unregister a provider.\n\t *\n\t * Before bindCore(): queues registrations / removes from queue.\n\t * After bindCore(): calls ModelRegistry directly for immediate effect.\n\t */\n\tregisterProvider: (name: string, config: ProviderConfig, extensionPath?: string) => void;\n\tregisterNativeProvider: (provider: Provider, extensionPath?: string) => void;\n\tunregisterProvider: (name: string, extensionPath?: string) => void;\n\t/** Servers registered with `pi.registerMcpServer()`. */\n\tmcpServers: McpServerRegistry;\n\tregisterVirtualModel: (definition: VirtualModelDefinition, extensionPath?: string) => void;\n\tunregisterVirtualModel: (provider: string, id: string) => void;\n}\n\n/**\n * Action implementations for pi.* API methods.\n * Provided to runner.initialize(), copied into the shared runtime.\n */\nexport interface ExtensionActions {\n\tsendMessage: SendMessageHandler;\n\tsendUserMessage: SendUserMessageHandler;\n\tappendEntry: AppendEntryHandler;\n\tsetSessionName: SetSessionNameHandler;\n\tgetSessionName: GetSessionNameHandler;\n\tsetLabel: SetLabelHandler;\n\tgetActiveTools: GetActiveToolsHandler;\n\tgetAllTools: GetAllToolsHandler;\n\tgetSettings: GetSettingsHandler;\n\tsetActiveTools: SetActiveToolsHandler;\n\trefreshTools: RefreshToolsHandler;\n\tgetCommands: GetCommandsHandler;\n\tsetModel: SetModelHandler;\n\tgetThinkingLevel: GetThinkingLevelHandler;\n\tsetThinkingLevel: SetThinkingLevelHandler;\n}\n\n/**\n * Actions for ExtensionContext (ctx.* in event handlers).\n * Required by all modes.\n */\nexport interface ExtensionContextActions {\n\tgetModel: () => Model<any> | undefined;\n\tgetScopedModels: () => readonly ScopedModel[];\n\tisIdle: () => boolean;\n\tisProjectTrusted: () => boolean;\n\tgetSignal: () => AbortSignal | undefined;\n\tabort: () => void;\n\thasPendingMessages: () => boolean;\n\tshutdown: () => void;\n\tgetContextUsage: () => ContextUsage | undefined;\n\tcompact: (options?: CompactOptions) => void;\n\tgetSystemPrompt: () => string;\n\tgetSystemPromptOptions?: () => BuildSystemPromptOptions;\n\t/** Backs `ExtensionToolContext.executeTool()`. Without it, nested calls fail. */\n\texecuteTool?: (\n\t\tcallerId: string,\n\t\tname: string,\n\t\targs: unknown,\n\t\toptions: ExecuteToolOptions,\n\t) => Promise<AgentToolCallOutcome>;\n\t/** Backs `ExtensionToolContext.tools`. */\n\tgetCallableTools?: () => readonly AgentTool[];\n}\n\n/**\n * Actions for ExtensionCommandContext (ctx.* in command handlers).\n * Only needed for interactive mode where extension commands are invokable.\n */\nexport interface ExtensionCommandContextActions {\n\twaitForIdle: () => Promise<void>;\n\tnewSession: (options?: {\n\t\tparentSession?: string;\n\t\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\t\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n\t}) => Promise<{ cancelled: boolean }>;\n\tfork: (\n\t\tentryId: string,\n\t\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t) => Promise<{ cancelled: boolean }>;\n\tnavigateTree: (\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t) => Promise<{ cancelled: boolean }>;\n\tswitchSession: (\n\t\tsessionPath: string,\n\t\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n\t) => Promise<{ cancelled: boolean }>;\n\treload: () => Promise<void>;\n}\n\n/**\n * Full runtime = state + actions.\n * Created by loader with throwing action stubs, completed by runner.initialize().\n */\nexport interface ExtensionRuntime extends ExtensionRuntimeState, ExtensionActions {}\n\n/** Loaded extension with all registered items. */\nexport interface Extension {\n\tpath: string;\n\tresolvedPath: string;\n\thidden?: boolean;\n\t/** See {@link InlineExtension}. */\n\treplaceable?: boolean;\n\tsourceInfo: SourceInfo;\n\thandlers: Map<string, HandlerFn[]>;\n\ttools: Map<string, RegisteredTool>;\n\tmessageRenderers: Map<string, MessageRenderer>;\n\ttoolRenderers?: ToolRendererResolver[];\n\tmarkdownTransformer?: MarkdownTransformer;\n\tentryRenderers?: Map<string, EntryRenderer>;\n\tcommands: Map<string, RegisteredCommand>;\n\tflags: Map<string, ExtensionFlag>;\n\tshortcuts: Map<KeyId, ExtensionShortcut>;\n}\n\n/** Result of loading extensions. */\nexport interface LoadExtensionsResult {\n\textensions: Extension[];\n\terrors: Array<{ path: string; error: string }>;\n\twarnings?: Array<{ path: string; warning: string }>;\n\t/** Shared runtime - actions are throwing stubs until runner.initialize() */\n\truntime: ExtensionRuntime;\n}\n\n// ============================================================================\n// Extension Error\n// ============================================================================\n\nexport interface ExtensionError {\n\textensionPath: string;\n\tevent: string;\n\terror: string;\n\tstack?: string;\n}\n"]}
|
|
@@ -67,6 +67,12 @@ export interface McpOAuthConfig {
|
|
|
67
67
|
* Default: `pi`.
|
|
68
68
|
*/
|
|
69
69
|
clientName?: string;
|
|
70
|
+
/**
|
|
71
|
+
* How pi identifies itself without `clientId`. `dcr` (default): dynamic client registration. `cimd`:
|
|
72
|
+
* pi's Client ID Metadata Document on pi.dev, for authorization servers that allow pi by that URL. The
|
|
73
|
+
* server must support it for public clients, and the callback must use the default path `/callback`.
|
|
74
|
+
*/
|
|
75
|
+
clientRegistration?: "dcr" | "cimd";
|
|
70
76
|
/**
|
|
71
77
|
* Authorization server metadata document (RFC 8414 or OpenID Connect discovery) to use instead of
|
|
72
78
|
* discovery through the server, for servers that advertise a wrong authorization server or none.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-servers.d.ts","sourceRoot":"","sources":["../../src/core/mcp-servers.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;;;;;;GAQG;AACH,MAAM,MAAM,WAAW,GAAG,UAAU,GAAG,UAAU,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAOxE,UAAU,mBAAmB;IAC5B,2BAA2B;IAC3B,QAAQ,CAAC,EAAE,WAAW,CAAC;IACvB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IAC3C,wEAAwE;IACxE,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,oGAAoG;IACpG,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,oBAAqB,SAAQ,mBAAmB;IAChE,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB,mFAAmF;IACnF,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,oEAAoE;IACpE,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAED,yFAAyF;AACzF,MAAM,WAAW,cAAc;IAC9B,iGAAiG;IACjG,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,4EAA4E;IAC5E,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,yFAAyF;IACzF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAC/B;AAID,6EAA6E;AAC7E,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAI5D;AAED,MAAM,WAAW,mBAAoB,SAAQ,mBAAmB;IAC/D,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,mFAAmF;IACnF,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,KAAK,CAAC,EAAE,cAAc,CAAC;IACvB;;;OAGG;IACH,IAAI,CAAC,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;CAC5B;AAED,MAAM,MAAM,eAAe,GAAG,oBAAoB,GAAG,mBAAmB,CAAC;AAIzE,oGAAoG;AACpG,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAEnD;
|
|
1
|
+
{"version":3,"file":"mcp-servers.d.ts","sourceRoot":"","sources":["../../src/core/mcp-servers.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;;;;;;GAQG;AACH,MAAM,MAAM,WAAW,GAAG,UAAU,GAAG,UAAU,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAOxE,UAAU,mBAAmB;IAC5B,2BAA2B;IAC3B,QAAQ,CAAC,EAAE,WAAW,CAAC;IACvB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IAC3C,wEAAwE;IACxE,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,oGAAoG;IACpG,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,oBAAqB,SAAQ,mBAAmB;IAChE,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB,mFAAmF;IACnF,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,oEAAoE;IACpE,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAED,yFAAyF;AACzF,MAAM,WAAW,cAAc;IAC9B,iGAAiG;IACjG,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,4EAA4E;IAC5E,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,yFAAyF;IACzF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;IACpC;;;;OAIG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAC/B;AAID,6EAA6E;AAC7E,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAI5D;AAED,MAAM,WAAW,mBAAoB,SAAQ,mBAAmB;IAC/D,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,mFAAmF;IACnF,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,KAAK,CAAC,EAAE,cAAc,CAAC;IACvB;;;OAGG;IACH,IAAI,CAAC,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;CAC5B;AAED,MAAM,MAAM,eAAe,GAAG,oBAAoB,GAAG,mBAAmB,CAAC;AAIzE,oGAAoG;AACpG,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAEnD;AAoFD,gGAAgG;AAChG,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,GAAG,WAAW,CAQzF;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,GAAG,eAAe,GAAG,MAAM,CAyD5F;AAED,sEAAsE;AACtE,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,eAAe,CAAC;IACxB,wDAAwD;IACxD,aAAa,EAAE,MAAM,CAAC;CACtB;AAED,2DAA2D;AAC3D,qBAAa,iBAAiB;IAC7B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA0C;IAClE,OAAO,CAAC,cAAc,CAA2B;IAEjD,iEAAiE;IACjE,QAAQ,CAAC,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAG1C;IAED,iGAAiG;IACjG,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,GAAG,IAAI,CAIpD;IAED,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,mBAAmB,GAAG,SAAS,CAEjD;IAED,+DAA+D;IAC/D,IAAI,IAAI,mBAAmB,EAAE,CAE5B;IAED,iGAAiG;IACjG,iBAAiB,CAAC,QAAQ,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,GAAG,IAAI,CAE1D;CACD"}
|
package/dist/core/mcp-servers.js
CHANGED
|
@@ -54,6 +54,17 @@ function validateOAuth(value) {
|
|
|
54
54
|
if (value.clientName !== undefined && (typeof value.clientName !== "string" || !value.clientName.trim())) {
|
|
55
55
|
return "oauth.clientName must be a non-empty string";
|
|
56
56
|
}
|
|
57
|
+
if (value.clientRegistration !== undefined && value.clientRegistration !== "dcr") {
|
|
58
|
+
if (value.clientRegistration !== "cimd")
|
|
59
|
+
return 'oauth.clientRegistration must be "dcr" or "cimd"';
|
|
60
|
+
if (value.clientId !== undefined || value.clientName !== undefined) {
|
|
61
|
+
return 'oauth.clientRegistration "cimd" cannot be combined with oauth.clientId or oauth.clientName';
|
|
62
|
+
}
|
|
63
|
+
const callback = typeof value.callbackUrl === "string" ? new URL(value.callbackUrl) : undefined;
|
|
64
|
+
if (callback && (callback.hostname === "[::1]" || callback.pathname !== "/callback")) {
|
|
65
|
+
return 'oauth.clientRegistration "cimd" requires oauth.callbackUrl on localhost or 127.0.0.1 with path /callback';
|
|
66
|
+
}
|
|
67
|
+
}
|
|
57
68
|
const metadataUrl = value.authServerMetadataUrl;
|
|
58
69
|
if (metadataUrl !== undefined) {
|
|
59
70
|
const url = typeof metadataUrl === "string" && URL.canParse(metadataUrl) ? new URL(metadataUrl) : undefined;
|