返回源码地图

packages/coding-agent/src/core/extensions/types.ts

v1.3.0 · 71023aec1546 · 08/12:before_agent_start discriminated union、暴露和可达能力

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1/**
2 * Extension system types.
3 *
4 * Extensions are TypeScript modules that can:
5 * - Subscribe to agent lifecycle events
6 * - Register LLM-callable tools
7 * - Register commands, keyboard shortcuts, and CLI flags
8 * - Interact with the user via UI primitives
9 */
10
11import type {
12 AgentMessage,
13 AgentTool,
14 AgentToolCallOutcome,
15 AgentToolResult,
16 AgentToolUpdateCallback,
17 ThinkingLevel,
18 ToolExecutionMode,
19} from "@earendil-works/pi-agent-core";
20import type {
21 AnyModel,
22 Api,
23 AssistantMessageEvent,
24 AssistantMessageEventStream,
25 ClassifierApi,
26 ConstrainedSamplingConfig,
27 ImageApi,
28 ImageContent,
29 JsonValue,
30 Message,
31 Model,
32 OAuthCredentials,
33 OAuthLoginCallbacks,
34 Provider,
35 ProviderClassifier,
36 ProviderHeaders,
37 ProviderId,
38 ProviderImages,
39 RefreshModelsContext,
40 SimpleStreamOptions,
41 TextContent,
42 ToolResultMessage,
43 TranscriptContext,
44 Usage,
45} from "@earendil-works/pi-ai";
46import type {
47 AutocompleteItem,
48 AutocompleteProvider,
49 Component,
50 EditorComponent,
51 EditorTheme,
52 KeyId,
53 OverlayHandle,
54 OverlayOptions,
55 TUI,
56} from "@earendil-works/pi-tui";
57import type { Static, TSchema } from "typebox";
58import type { Theme } from "../../modes/interactive/theme/theme.ts";
59import type { BashResult } from "../bash-executor.ts";
60import type { CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult } from "../cache-warmer.ts";
61import type { CompactionPreparation, CompactionResult } from "../compaction/index.ts";
62import type { EventBus } from "../event-bus.ts";
63import type { ExecOptions, ExecResult } from "../exec.ts";
64import type { ReadonlyFooterDataProvider } from "../footer-data-provider.ts";
65import type { KeybindingsManager } from "../keybindings.ts";
66import type { McpServerConfig, McpServerRegistry, RegisteredMcpServer } from "../mcp-servers.ts";
67import type { CustomMessage } from "../messages.ts";
68import type { ModelRegistry } from "../model-registry.ts";
69import type { ScopedModel } from "../model-resolver.ts";
70import type {
71 BranchSummaryEntry,
72 CompactionEntry,
73 ContextEditEntry,
74 CustomEntry,
75 ProjectedSessionEntry,
76 ReadonlySessionManager,
77 SessionEntry,
78 SessionManager,
79} from "../session-manager.ts";
80import type { Settings } from "../settings-manager.ts";
81import type { SlashCommandInfo } from "../slash-commands.ts";
82import type { SourceInfo } from "../source-info.ts";
83import type { BuildSystemPromptOptions, NormalizedBuildSystemPromptOptions } from "../system-prompt.ts";
84import type { BashOperations } from "../tools/bash.ts";
85import type { EditToolDetails } from "../tools/edit.ts";
86import type {
87 BashToolDetails,
88 BashToolInput,
89 EditToolInput,
90 FindToolDetails,
91 FindToolInput,
92 GrepToolDetails,
93 GrepToolInput,
94 LsToolDetails,
95 LsToolInput,
96 PowerShellToolDetails,
97 PowerShellToolInput,
98 ReadToolDetails,
99 ReadToolInput,
100 WriteToolInput,
101} from "../tools/index.ts";
102import type { ModelRoute, ModelRouteRequest, VirtualModelDefinition } from "../virtual-models.ts";
103
104export type { ExecOptions, ExecResult } from "../exec.ts";
105export type { BuildSystemPromptOptions, NormalizedBuildSystemPromptOptions } from "../system-prompt.ts";
106export type { AgentToolResult, AgentToolUpdateCallback, ToolExecutionMode };
107export type { AppKeybinding, KeybindingsManager } from "../keybindings.ts";
108
109// ============================================================================
110// UI Context
111// ============================================================================
112
113/** Options for extension UI dialogs. */
114export interface ExtensionUIDialogOptions {
115 /** AbortSignal to programmatically dismiss the dialog. */
116 signal?: AbortSignal;
117 /** Timeout in milliseconds. Dialog auto-dismisses with live countdown display. */
118 timeout?: number;
119}
120
121/** Placement for extension widgets. */
122export type WidgetPlacement = "aboveEditor" | "belowEditor";
123
124/** Options for extension widgets. */
125export interface ExtensionWidgetOptions {
126 /** Where the widget is rendered. Defaults to "aboveEditor". */
127 placement?: WidgetPlacement;
128}
129
130/** Raw terminal input listener for extensions. */
131export type TerminalInputHandler = (data: string) => { consume?: boolean; data?: string } | undefined;
132
133/** Working indicator configuration for the interactive streaming loader. */
134export interface WorkingIndicatorOptions {
135 /** Animation frames. Use an empty array to hide the indicator entirely. Custom frames are rendered verbatim. */
136 frames?: string[];
137 /** Frame interval in milliseconds for animated indicators. */
138 intervalMs?: number;
139}
140
141/** Wrap the current autocomplete provider with additional behavior. */
142export type AutocompleteProviderFactory = (current: AutocompleteProvider) => AutocompleteProvider;
143export type EditorFactory = (tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager) => EditorComponent;
144
145/**
146 * UI context for extensions to request interactive UI.
147 * Each mode (interactive, RPC, print) provides its own implementation.
148 */
149export interface ExtensionUIContext {
150 /** Show a selector and return the user's choice. */
151 select(title: string, options: string[], opts?: ExtensionUIDialogOptions): Promise<string | undefined>;
152
153 /** Show a confirmation dialog. */
154 confirm(title: string, message: string, opts?: ExtensionUIDialogOptions): Promise<boolean>;
155
156 /** Show a text input dialog. */
157 input(title: string, placeholder?: string, opts?: ExtensionUIDialogOptions): Promise<string | undefined>;
158
159 /** Show a notification to the user. */
160 notify(message: string, type?: "info" | "warning" | "error"): void;
161
162 /** Listen to raw terminal input (interactive mode only). Returns an unsubscribe function. */
163 onTerminalInput(handler: TerminalInputHandler): () => void;
164
165 /** Set status text in the footer/status bar. Pass undefined to clear. */
166 setStatus(key: string, text: string | undefined): void;
167
168 /** Set the working/loading message shown during streaming. Call with no argument to restore default. */
169 setWorkingMessage(message?: string): void;
170
171 /** Show or hide the built-in interactive working loader row during streaming. */
172 setWorkingVisible(visible: boolean): void;
173
174 /**
175 * Configure the interactive working indicator shown during streaming.
176 *
177 * - Omit the argument to restore the default animated spinner.
178 * - Use `frames: ["●"]` for a static indicator.
179 * - Use `frames: []` to hide the indicator entirely.
180 * - Custom frames are rendered as provided, so extensions must add their own colors.
181 */
182 setWorkingIndicator(options?: WorkingIndicatorOptions): void;
183
184 /** Set the label shown for hidden thinking blocks. Call with no argument to restore default. */
185 setHiddenThinkingLabel(label?: string): void;
186
187 /** Set a widget to display above or below the editor. Accepts string array or component factory. */
188 setWidget(key: string, content: string[] | undefined, options?: ExtensionWidgetOptions): void;
189 setWidget(
190 key: string,
191 content: ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined,
192 options?: ExtensionWidgetOptions,
193 ): void;
194
195 /** Set a custom footer component, or undefined to restore the built-in footer.
196 *
197 * The factory receives a FooterDataProvider for data not otherwise accessible:
198 * git branch and extension statuses from setStatus(). Context usage is on
199 * ctx.getContextUsage(), token stats on ctx.sessionManager.getEntries(), model info on ctx.model.
200 */
201 setFooter(
202 factory:
203 | ((tui: TUI, theme: Theme, footerData: ReadonlyFooterDataProvider) => Component & { dispose?(): void })
204 | undefined,
205 ): void;
206
207 /** Set a custom header component (shown at startup, above chat), or undefined to restore the built-in header. */
208 setHeader(factory: ((tui: TUI, theme: Theme) => Component & { dispose?(): void }) | undefined): void;
209
210 /** Set the terminal window/tab title. */
211 setTitle(title: string): void;
212
213 /** Show a custom component with keyboard focus. */
214 custom<T>(
215 factory: (
216 tui: TUI,
217 theme: Theme,
218 keybindings: KeybindingsManager,
219 done: (result: T) => void,
220 ) => (Component & { dispose?(): void }) | Promise<Component & { dispose?(): void }>,
221 options?: {
222 overlay?: boolean;
223 /** Overlay positioning/sizing options. Can be static or a function for dynamic updates. */
224 overlayOptions?: OverlayOptions | (() => OverlayOptions);
225 /** Called with the overlay handle after the overlay is shown. Use to control visibility. */
226 onHandle?: (handle: OverlayHandle) => void;
227 },
228 ): Promise<T>;
229
230 /** Paste text into the editor, triggering paste handling (collapse for large content). */
231 pasteToEditor(text: string): void;
232
233 /** Set the text in the core input editor. */
234 setEditorText(text: string): void;
235
236 /** Get the current text from the core input editor. */
237 getEditorText(): string;
238
239 /** Show a multi-line editor for text editing. */
240 editor(title: string, prefill?: string): Promise<string | undefined>;
241
242 /** Stack additional autocomplete behavior on top of the built-in provider. */
243 addAutocompleteProvider(factory: AutocompleteProviderFactory): void;
244
245 /**
246 * Set a custom editor component via factory function.
247 * Pass undefined to restore the default editor.
248 *
249 * The factory receives:
250 * - `theme`: EditorTheme for styling borders and autocomplete
251 * - `keybindings`: KeybindingsManager for app-level keybindings
252 *
253 * For full app keybinding support (escape, ctrl+d, model switching, etc.),
254 * extend `CustomEditor` from `@earendil-works/pi-coding-agent` and call
255 * `super.handleInput(data)` for keys you don't handle.
256 *
257 * @example
258 * ```ts
259 * import { CustomEditor } from "@earendil-works/pi-coding-agent";
260 *
261 * class VimEditor extends CustomEditor {
262 * private mode: "normal" | "insert" = "insert";
263 *
264 * handleInput(data: string): void {
265 * if (this.mode === "normal") {
266 * // Handle vim normal mode keys...
267 * if (data === "i") { this.mode = "insert"; return; }
268 * }
269 * super.handleInput(data); // App keybindings + text editing
270 * }
271 * }
272 *
273 * ctx.ui.setEditorComponent((tui, theme, keybindings) =>
274 * new VimEditor(tui, theme, keybindings)
275 * );
276 * ```
277 */
278 setEditorComponent(factory: EditorFactory | undefined): void;
279
280 /** Get the currently configured custom editor factory, or undefined when using the default editor. */
281 getEditorComponent(): EditorFactory | undefined;
282
283 /** Get the current theme for styling. */
284 readonly theme: Theme;
285
286 /** Get all available themes with their names and file paths. */
287 getAllThemes(): { name: string; path: string | undefined }[];
288
289 /** Load a theme by name without switching to it. Returns undefined if not found. */
290 getTheme(name: string): Theme | undefined;
291
292 /** Set the current theme by name or Theme object. */
293 setTheme(theme: string | Theme): { success: boolean; error?: string };
294
295 /** Get current tool output expansion state. */
296 getToolsExpanded(): boolean;
297
298 /** Set tool output expansion state. */
299 setToolsExpanded(expanded: boolean): void;
300}
301
302// ============================================================================
303// Extension Context
304// ============================================================================
305
306export interface ContextUsage {
307 /** Estimated context tokens, or null if unknown (e.g. right after compaction, before next LLM response). */
308 tokens: number | null;
309 contextWindow: number;
310 /** Context usage as percentage of context window, or null if tokens is unknown. */
311 percent: number | null;
312}
313
314export interface CompactOptions {
315 customInstructions?: string;
316 onComplete?: (result: CompactionResult) => void;
317 onError?: (error: Error) => void;
318}
319
320/**
321 * Context passed to extension event handlers.
322 */
323export type ExtensionMode = "tui" | "rpc" | "json" | "print";
324
325export interface ExtensionContext {
326 /** UI methods for user interaction */
327 ui: ExtensionUIContext;
328 /** Current run mode. Use "tui" to guard terminal-only UI such as custom components. */
329 mode: ExtensionMode;
330 /** Whether dialog-capable UI is available (true in TUI and RPC modes) */
331 hasUI: boolean;
332 /** Current working directory */
333 cwd: string;
334 /** Session manager (read-only) */
335 sessionManager: ReadonlySessionManager;
336 /** Model registry for API key resolution */
337 modelRegistry: ModelRegistry;
338 /** Current model (may be undefined) */
339 model: Model<any> | undefined;
340 /** Models scoped to this session (resolved from `--models` /
341 * `enabledModels` settings against the available catalogue). Same set
342 * the `/scoped-models` command shows. Empty when no scoping is
343 * configured (all available models are usable). Read-only snapshot. */
344 scopedModels: readonly ScopedModel[];
345 /** Current thinking level, when provided by the session runtime. */
346 thinkingLevel?: ThinkingLevel;
347 /** Whether the agent is idle (not streaming) */
348 isIdle(): boolean;
349 /** Whether project-local trust is active for this context. */
350 isProjectTrusted(): boolean;
351 /** The current abort signal, or undefined when the agent is not streaming. */
352 signal: AbortSignal | undefined;
353 /** Abort the current agent operation */
354 abort(): void;
355 /** Whether there are queued messages waiting */
356 hasPendingMessages(): boolean;
357 /** Gracefully shutdown pi and exit. Available in all contexts. */
358 shutdown(): void;
359 /** Get current context usage for the active model. */
360 getContextUsage(): ContextUsage | undefined;
361 /** Trigger compaction without awaiting completion. */
362 compact(options?: CompactOptions): void;
363 /** Get the current effective system prompt. */
364 getSystemPrompt(): string;
365}
366
367/** Options for {@link ExtensionToolContext.executeTool}. */
368export interface ExecuteToolOptions {
369 /** Defaults to the calling tool's signal. */
370 signal?: AbortSignal;
371 /** Receives partial results of the nested tool, in addition to `tool_execution_update` events. */
372 onUpdate?: AgentToolUpdateCallback;
373}
374
375/**
376 * Context passed to tool `execute()` in a session: the extension context plus `executeTool()`
377 * for running other tools through the same validation, hooks, and permission checks as
378 * model-issued calls.
379 *
380 * A tool wrapped with `wrapToolDefinition()` without a context factory, such as a built-in tool
381 * created with `createBashTool()` and run in a plain `Agent` or called directly, gets no context.
382 */
383export interface ExtensionToolContext extends ExtensionContext {
384 /** Tools {@link executeTool} can call. */
385 readonly tools: readonly AgentTool[];
386 /**
387 * Run another tool. The call gets the id `<calling id>/<n>`, and the `tool_call`, `tool_result`,
388 * and `tool_execution_*` events carry `parentToolCallId`. It does not appear in the transcript;
389 * a bounded record of it is kept as `nestedCalls` on the calling tool's result message.
390 *
391 * Never rejects for tool failures: unknown tools, validation errors, blocked calls, and thrown
392 * errors come back as `isError: true`.
393 */
394 executeTool(name: string, args: unknown, options?: ExecuteToolOptions): Promise<AgentToolCallOutcome>;
395}
396
397/**
398 * Extended context for command handlers.
399 * Includes session control methods only safe in user-initiated commands.
400 */
401export interface ExtensionCommandContext extends ExtensionContext {
402 /** Get the current base system-prompt construction options. */
403 getSystemPromptOptions(): BuildSystemPromptOptions;
404
405 /** Wait for the agent to finish streaming */
406 waitForIdle(): Promise<void>;
407
408 /** Start a new session, optionally with initialization. */
409 newSession(options?: {
410 parentSession?: string;
411 setup?: (sessionManager: SessionManager) => Promise<void>;
412 withSession?: (ctx: ReplacedSessionContext) => Promise<void>;
413 }): Promise<{ cancelled: boolean }>;
414
415 /** Fork from a specific entry, creating a new session file. */
416 fork(
417 entryId: string,
418 options?: { position?: "before" | "at"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },
419 ): Promise<{ cancelled: boolean }>;
420
421 /** Navigate to a different point in the session tree. */
422 navigateTree(
423 targetId: string,
424 options?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },
425 ): Promise<{ cancelled: boolean }>;
426
427 /** Switch to a different session file. */
428 switchSession(
429 sessionPath: string,
430 options?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },
431 ): Promise<{ cancelled: boolean }>;
432
433 /** Reload extensions, skills, prompts, themes, and context files. */
434 reload(): Promise<void>;
435}
436
437/**
438 * Fresh command-capable context bound to the replacement session after a session switch.
439 *
440 * This is passed to `withSession()` callbacks on `newSession()`, `fork()`, and `switchSession()`.
441 */
442export interface ReplacedSessionContext extends ExtensionCommandContext {
443 sendMessage<T = unknown>(
444 message: Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">,
445 options?: { triggerTurn?: boolean; deliverAs?: "steer" | "followUp" | "nextTurn" },
446 ): Promise<void>;
447
448 sendUserMessage(
449 content: string | (TextContent | ImageContent)[],
450 options?: { deliverAs?: "steer" | "followUp"; expandPromptTemplates?: boolean },
451 ): Promise<void>;
452}
453
454// ============================================================================
455// Tool Types
456// ============================================================================
457
458/** Rendering options for tool results */
459export interface ToolRenderResultOptions {
460 /** Whether the result view is expanded */
461 expanded: boolean;
462 /** Whether this is a partial/streaming result */
463 isPartial: boolean;
464}
465
466/** Context passed to tool renderers. */
467export interface ToolRenderContext<TState = any, TArgs = any> {
468 /** Current tool call arguments. Shared across call/result renders for the same tool call. */
469 args: TArgs;
470 /** Unique id for this tool execution. Stable across call/result renders for the same tool call. */
471 toolCallId: string;
472 /** Invalidate just this tool execution component for redraw. */
473 invalidate: () => void;
474 /** Previously returned component for this render slot, if any. */
475 lastComponent: Component | undefined;
476 /** Shared renderer state for this tool row. Initialized by tool-execution.ts. */
477 state: TState;
478 /** Working directory for this tool execution. */
479 cwd: string;
480 /** Whether the tool execution has started. */
481 executionStarted: boolean;
482 /** Whether the tool call arguments are complete. */
483 argsComplete: boolean;
484 /** Whether the tool result is partial/streaming. */
485 isPartial: boolean;
486 /** Whether the result view is expanded. */
487 expanded: boolean;
488 /** Whether inline images are currently shown in the TUI. */
489 showImages: boolean;
490 /** Whether the current result is an error. */
491 isError: boolean;
492 /**
493 * Milliseconds the tool's execution took, from the final result; `undefined` while it runs, when it did not run, or
494 * for results stored before durations were recorded.
495 */
496 durationMs: number | undefined;
497 /** Horizontal padding configured by the outputPad setting. Renderers with `renderShell: "self"` apply it themselves. */
498 outputPad: number;
499}
500
501/**
502 * How the model reaches a tool. "Callable" means callable from other tools through
503 * `ctx.executeTool()`, as the `codemode` tool does.
504 *
505 * - `direct`: declared to the model while active, and callable while active.
506 * - `model-only`: declared to the model while active, never callable. Use it for orchestrating or
507 * interactive tools.
508 * - `codemode`: callable whenever registered. Not declared to the model unless explicitly
509 * activated. Codemode tools list it in their description.
510 * - `deferred`: like `codemode`, but codemode tools do not list it; tool search can find it.
511 * - `hidden`: registered but unreachable. Activating it has no effect.
512 *
513 * `direct` and `model-only` tools are activated when they are registered; the others are not.
514 * The active tool set (`getActiveTools`/`setActiveTools`) is the set declared to the model.
515 */
516export type ToolExposure = "direct" | "model-only" | "codemode" | "deferred" | "hidden";
517
518/**
519 * Hints about what a tool does, with the meaning of MCP tool annotations. They come from the tool's
520 * author and are not verified; permission extensions can use them to decide which calls to confirm.
521 */
522export interface ToolAnnotations {
523 /** The tool does not modify its environment. */
524 readOnlyHint?: boolean;
525 /** The tool may delete or overwrite data, rather than only add to it. Meaningful when not read-only. */
526 destructiveHint?: boolean;
527 /** Repeating a call with the same arguments has no further effect. Meaningful when not read-only. */
528 idempotentHint?: boolean;
529 /** The tool reaches an open world of external entities, such as the web, rather than a closed domain. */
530 openWorldHint?: boolean;
531}
532
533/** A group of related tools, such as the tools of one MCP server. Codemode tools list them together. */
534export interface ToolNamespace {
535 /** For example `mcp__docs`. */
536 name: string;
537 /**
538 * Other names that refer to the namespace where tools look it up by name (codemode's
539 * `describeNamespace()` and the `namespace` option of `searchTools()`), for example `docs`.
540 */
541 aliases?: readonly string[];
542 /** Short summary shown once with the group in model-facing tool listings. */
543 description?: string;
544 /**
545 * Longer usage guidance, such as MCP server instructions. Not part of tool listings; tools that
546 * describe the namespace on request (codemode's `describeNamespace()`) return it.
547 */
548 instructions?: string;
549}
550
551/** The tools of a session as {@link ToolDefinition.prepareLoadout} sees them. */
552export interface ToolLoadout {
553 /** Tools declared to the model (the active tools), in order, with their original descriptions. */
554 readonly declared: readonly AgentTool[];
555 /** Tools callable through `ctx.executeTool()`. */
556 readonly callable: readonly AgentTool[];
557 /** Every registered tool. */
558 readonly registered: readonly AgentTool[];
559 getExposure(name: string): ToolExposure;
560 getNamespace(name: string): ToolNamespace | undefined;
561 /** A tool's `promptGuidelines`. Hidden declarations leave them out of the system prompt. */
562 getPromptGuidelines(name: string): readonly string[];
563}
564
565/** Changes {@link ToolDefinition.prepareLoadout} makes to what the model sees. */
566export interface ToolLoadoutChanges {
567 /** Model-facing descriptions of declared tools, by tool name. */
568 descriptions?: Readonly<Record<string, string>>;
569 /**
570 * Declared tools whose declarations requests leave out. They stay active and callable, and the
571 * transcript still declares them, so the active set survives `/tree` and resume.
572 */
573 hiddenDeclarations?: readonly string[];
574}
575
576/**
577 * Tool definition for registerTool().
578 */
579export interface ToolDefinition<TParams extends TSchema = TSchema, TDetails = unknown, TState = any> {
580 /** Tool name (used in LLM tool calls) */
581 name: string;
582 /** Human-readable label for UI */
583 label: string;
584 /** Description for LLM */
585 description: string;
586 /** 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. */
587 promptSnippet?: string;
588 /** Optional guideline bullets appended to the default system prompt Guidelines section when this tool is active. */
589 promptGuidelines?: string[];
590 /** Parameter schema (TypeBox) */
591 parameters: TParams;
592 /** Optional provider-side constrained sampling request for this tool. Set false to explicitly disable it, equivalent to leaving it undefined. */
593 constrainedSampling?: false | ConstrainedSamplingConfig;
594 /** Controls whether ToolExecutionComponent renders the standard colored shell or the tool renders its own framing. */
595 renderShell?: "default" | "self";
596
597 /** Optional compatibility shim to prepare raw tool call arguments before schema validation. Must return an object conforming to TParams. */
598 prepareArguments?: (args: unknown) => Static<TParams>;
599
600 /**
601 * JSON Schema of `structuredContent` in successful results. Tools that declare it should always
602 * set `structuredContent`; codemode scripts then receive it instead of the text content.
603 */
604 outputSchema?: TSchema;
605
606 /**
607 * How the model reaches the tool. Default: `"direct"`. See {@link ToolExposure}.
608 */
609 exposure?: ToolExposure;
610
611 /** Group the tool belongs to, for example its MCP server. */
612 namespace?: ToolNamespace;
613
614 /**
615 * For tools that reach other tools (such as `codemode`, which calls them, and `tool_search`, which
616 * loads them): which tools a call with `input` may reach. `"all"`, or the words of the input that
617 * may name them, where a word refers to a tool or namespace whose name it contains, so words may
618 * over-match. Extensions that register tools late, such as MCP servers that are still connecting,
619 * use it from their `tool_call` handler to finish registering those tools before the call runs.
620 */
621 reachesTools?: (input: Record<string, unknown>) => "all" | readonly string[];
622
623 /** Hints about what the tool does, for example from an MCP server. */
624 annotations?: ToolAnnotations;
625
626 /**
627 * Whether registering the tool activates it. Default: `true` for `direct` and `model-only` tools;
628 * other exposures are never activated on registration. A tool with `defaultActive: false` is
629 * activated by naming it in `--tools` or the `defaultTools` setting, or with `setActiveTools()`.
630 */
631 defaultActive?: boolean;
632
633 /**
634 * Adjust how the loadout is presented to the model while this tool is active. Called whenever
635 * the active tools change. Tools that orchestrate other tools use it, for example to list the
636 * callable tools in their own description.
637 */
638 prepareLoadout?: (loadout: ToolLoadout) => ToolLoadoutChanges | undefined;
639
640 /**
641 * Per-tool execution mode override.
642 * - "sequential": this tool must execute one at a time with other tool calls.
643 * - "parallel": this tool can execute concurrently with other tool calls.
644 *
645 * If omitted, the default execution mode applies.
646 */
647 executionMode?: ToolExecutionMode;
648
649 /** Execute the tool. */
650 execute(
651 toolCallId: string,
652 params: Static<TParams>,
653 signal: AbortSignal | undefined,
654 onUpdate: AgentToolUpdateCallback<TDetails> | undefined,
655 ctx: ExtensionToolContext,
656 ): Promise<AgentToolResult<TDetails>>;
657
658 /** Custom rendering for tool call display */
659 renderCall?: (args: Static<TParams>, theme: Theme, context: ToolRenderContext<TState, Static<TParams>>) => Component;
660
661 /** Custom rendering for tool result display */
662 renderResult?: (
663 result: AgentToolResult<TDetails>,
664 options: ToolRenderResultOptions,
665 theme: Theme,
666 context: ToolRenderContext<TState, Static<TParams>>,
667 ) => Component;
668}
669
670type AnyToolDefinition = ToolDefinition<any, any, any>;
671
672export type ToolRenderers = Pick<AnyToolDefinition, "renderShell" | "renderCall" | "renderResult">;
673
674/**
675 * Chooses how calls to a tool are drawn, including tools that are not registered. `next()` returns
676 * the renderers the remaining resolvers, then the registered tool, would use.
677 */
678export type ToolRendererResolver = (
679 toolName: string,
680 next: () => ToolRenderers | undefined,
681) => ToolRenderers | undefined;
682
683/**
684 * Preserve parameter inference for standalone tool definitions.
685 *
686 * Use this when assigning a tool to a variable or passing it through arrays such
687 * as `customTools`, where contextual typing would otherwise widen params to
688 * `unknown`.
689 */
690export function defineTool<TParams extends TSchema, TDetails = unknown, TState = any>(
691 tool: ToolDefinition<TParams, TDetails, TState>,
692): ToolDefinition<TParams, TDetails, TState> & AnyToolDefinition {
693 return tool as ToolDefinition<TParams, TDetails, TState> & AnyToolDefinition;
694}
695
696// ============================================================================
697// Startup/Resource Events
698// ============================================================================
699
700export interface ProjectTrustEvent {
701 type: "project_trust";
702 cwd: string;
703}
704
705export type ProjectTrustEventDecision = "yes" | "no" | "undecided";
706
707export interface ProjectTrustEventResult {
708 trusted: ProjectTrustEventDecision;
709 remember?: boolean;
710}
711
712export interface ProjectTrustContext {
713 cwd: string;
714 mode: ExtensionMode;
715 hasUI: boolean;
716 ui: Pick<ExtensionUIContext, "select" | "confirm" | "input" | "notify">;
717}
718
719export type ProjectTrustHandler = (
720 event: ProjectTrustEvent,
721 ctx: ProjectTrustContext,
722) => Promise<ProjectTrustEventResult> | ProjectTrustEventResult;
723
724/** Fired after session_start to allow extensions to provide additional resource paths. */
725export interface ResourcesDiscoverEvent {
726 type: "resources_discover";
727 cwd: string;
728 reason: "startup" | "reload";
729}
730
731/** Result from resources_discover event handler */
732export interface ResourcesDiscoverResult {
733 skillPaths?: string[];
734 promptPaths?: string[];
735 themePaths?: string[];
736}
737
738/**
739 * Fired when an extension registers or unregisters an MCP server after the extensions are bound
740 * (see {@link ExtensionAPI.registerMcpServer}). Servers registered while extensions load are read
741 * with `pi.getMcpServers()` on `session_start`. Handling this event marks an extension as the one
742 * that connects registered servers.
743 */
744export interface McpServersChangeEvent {
745 type: "mcp_servers_change";
746 /** Every registered server after the change. */
747 servers: RegisteredMcpServer[];
748}
749
750// ============================================================================
751// Session Events
752// ============================================================================
753
754/** Fired when a session is started, loaded, or reloaded */
755export interface SessionStartEvent {
756 type: "session_start";
757 /** Why this session start happened. */
758 reason: "startup" | "reload" | "new" | "resume" | "fork";
759 /** Previously active session file. Present for "new", "resume", and "fork". */
760 previousSessionFile?: string;
761}
762
763/** Fired when the current session metadata changes. */
764export interface SessionInfoChangedEvent {
765 type: "session_info_changed";
766 /** Current normalized session name. Undefined when the name is cleared. */
767 name: string | undefined;
768}
769
770/** Fired before switching to another session (can be cancelled) */
771export interface SessionBeforeSwitchEvent {
772 type: "session_before_switch";
773 reason: "new" | "resume";
774 targetSessionFile?: string;
775}
776
777/** Fired before forking a session (can be cancelled) */
778export interface SessionBeforeForkEvent {
779 type: "session_before_fork";
780 entryId: string;
781 position: "before" | "at";
782}
783
784/** Fired before context compaction (can be cancelled or customized) */
785export interface SessionBeforeCompactEvent {
786 type: "session_before_compact";
787 preparation: CompactionPreparation;
788 branchEntries: SessionEntry[];
789 customInstructions?: string;
790 /** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */
791 reason: "manual" | "threshold" | "overflow";
792 /** True when the aborted turn is retried after this compaction (overflow recovery) */
793 willRetry: boolean;
794 signal: AbortSignal;
795}
796
797/** Fired after context compaction succeeds */
798export interface SessionCompactEvent {
799 type: "session_compact";
800 compactionEntry: CompactionEntry;
801 fromExtension: boolean;
802 /** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */
803 reason: "manual" | "threshold" | "overflow";
804 /** True when the aborted turn is retried after this compaction (overflow recovery) */
805 willRetry: boolean;
806}
807
808/** Fired after context compaction fails or is aborted */
809export interface SessionCompactFailedEvent {
810 type: "session_compact_failed";
811 /** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */
812 reason: "manual" | "threshold" | "overflow";
813 /** Error text when compaction failed for a non-abort reason. */
814 errorMessage?: string;
815 /** True when compaction was cancelled or aborted. */
816 aborted: boolean;
817 /** True when the aborted turn would have been retried after this compaction (overflow recovery) */
818 willRetry: boolean;
819 /** True when the failing compaction content came from a session_before_compact handler. */
820 fromExtension: boolean;
821}
822
823/** Fired before an extension runtime is torn down due to quit, reload, or session replacement. */
824export interface SessionShutdownEvent {
825 type: "session_shutdown";
826 reason: "quit" | "reload" | "new" | "resume" | "fork";
827 /** Destination session file when shutting down due to session replacement. */
828 targetSessionFile?: string;
829}
830
831/** Preparation data for tree navigation */
832export interface TreePreparation {
833 targetId: string;
834 oldLeafId: string | null;
835 commonAncestorId: string | null;
836 entriesToSummarize: SessionEntry[];
837 userWantsSummary: boolean;
838 /** Custom instructions for summarization */
839 customInstructions?: string;
840 /** If true, customInstructions replaces the default prompt instead of being appended */
841 replaceInstructions?: boolean;
842 /** Label to attach to the branch summary entry */
843 label?: string;
844}
845
846/** Fired before navigating in the session tree (can be cancelled) */
847export interface SessionBeforeTreeEvent {
848 type: "session_before_tree";
849 preparation: TreePreparation;
850 signal: AbortSignal;
851}
852
853/** Fired after navigating in the session tree */
854export interface SessionTreeEvent {
855 type: "session_tree";
856 newLeafId: string | null;
857 oldLeafId: string | null;
858 summaryEntry?: BranchSummaryEntry;
859 fromExtension?: boolean;
860}
861
862export type SessionEvent =
863 | SessionStartEvent
864 | SessionInfoChangedEvent
865 | SessionBeforeSwitchEvent
866 | SessionBeforeForkEvent
867 | SessionBeforeCompactEvent
868 | SessionCompactEvent
869 | SessionCompactFailedEvent
870 | SessionShutdownEvent
871 | SessionBeforeTreeEvent
872 | SessionTreeEvent;
873
874// ============================================================================
875// Agent Events
876// ============================================================================
877
878/**
879 * Fired before each LLM call. Can modify messages.
880 *
881 * `messages` holds the conversation without system messages. The prompt and tool state
882 * belong to Pi: it restores them after the handler returns, so a handler cannot drop
883 * them and does not need to preserve them.
884 */
885export interface ContextEvent {
886 type: "context";
887 messages: AgentMessage[];
888}
889
890/**
891 * Fired before each LLM call, after every `context` handler has run and Pi has restored
892 * the prompt and tool state. `messages` is the full transcript including system messages,
893 * and the result is sent as returned: the handler owns the prompt and tool declarations.
894 */
895export interface ContextWithSystemEvent {
896 type: "context_with_system";
897 messages: AgentMessage[];
898}
899
900/** Fired before a provider request is sent. Can replace the payload. */
901export interface BeforeProviderRequestEvent {
902 type: "before_provider_request";
903 payload: unknown;
904}
905
906/**
907 * Fired after request headers are assembled, before the provider HTTP call.
908 * Handlers mutate `headers` in place (e.g. to inject tracing/session headers);
909 * the return value is ignored. A `null` value deletes that header.
910 */
911export interface BeforeProviderHeadersEvent {
912 type: "before_provider_headers";
913 headers: ProviderHeaders;
914}
915
916/** Fired after a provider response is received and before the response stream is consumed. */
917export interface AfterProviderResponseEvent {
918 type: "after_provider_response";
919 status: number;
920 headers: Record<string, string>;
921}
922
923/** Fired for a parsed provider stream event before Pi normalizes it. */
924export interface ProviderStreamEvent {
925 type: "provider_stream_event";
926 provider: ProviderId;
927 api: Api;
928 model: string;
929 data: unknown;
930}
931
932interface BeforeAgentStartEventBase {
933 type: "before_agent_start";
934 /** The current system prompt, rendered from systemPromptOptions and earlier handler changes. */
935 readonly systemPrompt: string;
936 /** Mutable prompt sections. Later handlers observe mutations made by earlier handlers. */
937 systemPromptOptions: NormalizedBuildSystemPromptOptions;
938}
939
940/** A run started by a submitted prompt, RPC prompt, or `pi.sendUserMessage()`. */
941export interface BeforeAgentStartUserEvent extends BeforeAgentStartEventBase {
942 messageType: "user";
943 /** The raw user prompt text (after expansion). */
944 prompt: string;
945 /** Images attached to the user prompt, if any. */
946 images?: ImageContent[];
947}
948
949/** A run started by `pi.sendMessage(..., { triggerTurn: true })` while idle. */
950export interface BeforeAgentStartCustomEvent extends BeforeAgentStartEventBase {
951 messageType: "custom";
952 /** The custom message that starts the run. */
953 message: CustomMessage;
954}
955
956/** Fired before a run starts from a user message or an idle custom message with `triggerTurn`. */
957export type BeforeAgentStartEvent = BeforeAgentStartUserEvent | BeforeAgentStartCustomEvent;
958
959/** Fired when an agent loop starts */
960export interface AgentStartEvent {
961 type: "agent_start";
962}
963
964/** Fired when an agent loop ends */
965export interface AgentEndEvent {
966 type: "agent_end";
967 messages: AgentMessage[];
968}
969
970export type AgentActivityOutcome = "completed" | "aborted" | "error";
971
972export interface CustomEntryDraft {
973 type: "custom";
974 customType: string;
975 data?: unknown;
976}
977
978export interface CustomMessageEntryDraft {
979 type: "custom_message";
980 customType: string;
981 content: string | (TextContent | ImageContent)[];
982 display: boolean;
983 details?: unknown;
984}
985
986export interface ContextEditEntryDraft {
987 type: "context_edit";
988 targetId: string;
989 replacement: ContextEditEntry["replacement"];
990}
991
992export interface CompactionEntryDraft {
993 type: "compaction";
994 summary: string;
995 /** Null creates a self-retaining compaction that keeps no preceding entries. */
996 firstKeptEntryId: string | null;
997 details?: unknown;
998 usage?: Usage;
999}
1000
1001export type SessionBoundaryDraft =
1002 | CustomEntryDraft
1003 | CustomMessageEntryDraft
1004 | ContextEditEntryDraft
1005 | CompactionEntryDraft;
1006
1007export interface BoundaryContextPreview {
1008 contextEntries: ProjectedSessionEntry[];
1009 contextMessages: AgentMessage[];
1010 llmMessages: Message[];
1011 pendingMessages: AgentMessage[];
1012 canContinue: boolean;
1013}
1014
1015export interface BoundaryState {
1016 entries: SessionBoundaryDraft[];
1017 continue: boolean;
1018 context: BoundaryContextPreview;
1019 outcome: AgentActivityOutcome;
1020}
1021
1022export interface BoundaryResult {
1023 entries?: SessionBoundaryDraft[];
1024 continue?: boolean;
1025}
1026
1027/** Fired before final settlement. May append entries and ensure one next provider request. */
1028export interface AgentBeforeSettleEvent extends BoundaryState {
1029 type: "agent_before_settle";
1030}
1031
1032/** Fired after an agent run has fully settled and no automatic retry, compaction, or queued continuation will run. */
1033export interface AgentSettledEvent {
1034 type: "agent_settled";
1035 /** Whether the run ended because it was aborted, for example with Escape. */
1036 aborted: boolean;
1037}
1038
1039export type UIPromptKind = "select" | "confirm" | "input" | "editor" | "custom";
1040
1041/** Fired when Pi starts waiting on a blocking user-facing extension UI prompt. */
1042export interface UIPromptStartEvent {
1043 type: "ui_prompt_start";
1044 reason: "ui_prompt";
1045 kind: UIPromptKind;
1046 title?: string;
1047}
1048
1049/** Fired when Pi is no longer waiting on a blocking user-facing extension UI prompt. */
1050export interface UIPromptEndEvent {
1051 type: "ui_prompt_end";
1052 reason: "ui_prompt";
1053 kind: UIPromptKind;
1054 title?: string;
1055}
1056
1057/** Fired at the start of each turn */
1058export interface TurnStartEvent {
1059 type: "turn_start";
1060 turnIndex: number;
1061 timestamp: number;
1062}
1063
1064/** Fired at the end of each turn */
1065export interface TurnEndEvent extends BoundaryState {
1066 type: "turn_end";
1067 turnIndex: number;
1068 message: AgentMessage;
1069 toolResults: ToolResultMessage[];
1070 messageEntryId: string;
1071 toolResultEntryIds: string[];
1072}
1073
1074/** Fired when a message starts (user, assistant, or toolResult) */
1075export interface MessageStartEvent {
1076 type: "message_start";
1077 message: AgentMessage;
1078}
1079
1080/** Fired during assistant message streaming with token-by-token updates */
1081export interface MessageUpdateEvent {
1082 type: "message_update";
1083 message: AgentMessage;
1084 assistantMessageEvent: AssistantMessageEvent;
1085}
1086
1087/** Fired when a message ends */
1088export interface MessageEndEvent {
1089 type: "message_end";
1090 message: AgentMessage;
1091}
1092
1093/** Fired when a tool starts executing */
1094export interface ToolExecutionStartEvent {
1095 type: "tool_execution_start";
1096 toolCallId: string;
1097 toolName: string;
1098 args: any;
1099 /** Set when another tool (for example a codemode script) made this call. */
1100 parentToolCallId?: string;
1101}
1102
1103/** Fired during tool execution with partial/streaming output */
1104export interface ToolExecutionUpdateEvent {
1105 type: "tool_execution_update";
1106 toolCallId: string;
1107 toolName: string;
1108 args: any;
1109 partialResult: any;
1110 /** Set when another tool (for example a codemode script) made this call. */
1111 parentToolCallId?: string;
1112}
1113
1114/** Fired when a tool finishes executing */
1115export interface ToolExecutionEndEvent {
1116 type: "tool_execution_end";
1117 toolCallId: string;
1118 toolName: string;
1119 result: any;
1120 isError: boolean;
1121 /** Milliseconds `execute()` took, measured with a monotonic clock; absent when the tool did not run. */
1122 durationMs?: number;
1123 /** Set when another tool (for example a codemode script) made this call. */
1124 parentToolCallId?: string;
1125}
1126
1127// ============================================================================
1128// Model Events
1129// ============================================================================
1130
1131export type ModelSelectSource = "set" | "cycle" | "restore";
1132
1133/** Fired when a new model is selected */
1134export interface ModelSelectEvent {
1135 type: "model_select";
1136 model: Model<any>;
1137 previousModel: Model<any> | undefined;
1138 source: ModelSelectSource;
1139}
1140
1141/** Fired when a new thinking level is selected */
1142export interface ThinkingLevelSelectEvent {
1143 type: "thinking_level_select";
1144 level: ThinkingLevel;
1145 previousLevel: ThinkingLevel;
1146}
1147
1148// ============================================================================
1149// User Bash Events
1150// ============================================================================
1151
1152/** Fired when user executes a bash command via ! or !! prefix */
1153export interface UserBashEvent {
1154 type: "user_bash";
1155 /** The command to execute */
1156 command: string;
1157 /** True if !! prefix was used (excluded from LLM context) */
1158 excludeFromContext: boolean;
1159 /** Current working directory */
1160 cwd: string;
1161}
1162
1163// ============================================================================
1164// Input Events
1165// ============================================================================
1166
1167/** Source of user input */
1168export type InputSource = "interactive" | "rpc" | "extension";
1169
1170/** Fired when user input is received, before agent processing */
1171export interface InputEvent {
1172 type: "input";
1173 /** The input text */
1174 text: string;
1175 /** Attached images, if any */
1176 images?: ImageContent[];
1177 /** Where the input came from */
1178 source: InputSource;
1179 /** How the input will be delivered during streaming, or undefined when idle */
1180 streamingBehavior?: "steer" | "followUp";
1181}
1182
1183/** Result from input event handler */
1184export type InputEventResult =
1185 | { action: "continue" }
1186 | { action: "transform"; text: string; images?: ImageContent[] }
1187 | { action: "handled" };
1188
1189// ============================================================================
1190// Tool Events
1191// ============================================================================
1192
1193interface ToolCallEventBase {
1194 type: "tool_call";
1195 /**
1196 * The call's id. For calls another tool made (with `parentToolCallId` set), pi assigns
1197 * `<parent id>/<n>`; such ids never appear as tool calls or tool results in the transcript, only
1198 * in the parent result's `nestedCalls` record.
1199 */
1200 toolCallId: string;
1201 /** Set when another tool (for example a codemode script) issued this call. */
1202 parentToolCallId?: string;
1203}
1204
1205export interface BashToolCallEvent extends ToolCallEventBase {
1206 toolName: "bash";
1207 input: BashToolInput;
1208}
1209
1210export interface PowerShellToolCallEvent extends ToolCallEventBase {
1211 toolName: "powershell";
1212 input: PowerShellToolInput;
1213}
1214
1215export interface ReadToolCallEvent extends ToolCallEventBase {
1216 toolName: "read";
1217 input: ReadToolInput;
1218}
1219
1220export interface EditToolCallEvent extends ToolCallEventBase {
1221 toolName: "edit";
1222 input: EditToolInput;
1223}
1224
1225export interface WriteToolCallEvent extends ToolCallEventBase {
1226 toolName: "write";
1227 input: WriteToolInput;
1228}
1229
1230export interface GrepToolCallEvent extends ToolCallEventBase {
1231 toolName: "grep";
1232 input: GrepToolInput;
1233}
1234
1235export interface FindToolCallEvent extends ToolCallEventBase {
1236 toolName: "find";
1237 input: FindToolInput;
1238}
1239
1240export interface LsToolCallEvent extends ToolCallEventBase {
1241 toolName: "ls";
1242 input: LsToolInput;
1243}
1244
1245export interface CustomToolCallEvent extends ToolCallEventBase {
1246 toolName: string;
1247 input: Record<string, unknown>;
1248}
1249
1250/**
1251 * Fired before a tool executes. Can block.
1252 *
1253 * `event.input` is mutable. Mutate it in place to patch tool arguments before execution.
1254 * Later `tool_call` handlers see earlier mutations. No re-validation is performed after mutation.
1255 */
1256export type ToolCallEvent =
1257 | BashToolCallEvent
1258 | PowerShellToolCallEvent
1259 | ReadToolCallEvent
1260 | EditToolCallEvent
1261 | WriteToolCallEvent
1262 | GrepToolCallEvent
1263 | FindToolCallEvent
1264 | LsToolCallEvent
1265 | CustomToolCallEvent;
1266
1267interface ToolResultEventBase {
1268 type: "tool_result";
1269 /** The call's id; `<parent id>/<n>` for nested calls, see `ToolCallEvent`. */
1270 toolCallId: string;
1271 /** Set when another tool (for example a codemode script) issued this call. */
1272 parentToolCallId?: string;
1273 input: Record<string, unknown>;
1274 content: (TextContent | ImageContent)[];
1275 /**
1276 * Machine-readable result for tools that declare an `outputSchema`. Handlers that redact
1277 * `content` should also replace this; replacing `content` alone drops it.
1278 */
1279 structuredContent?: JsonValue;
1280 isError: boolean;
1281 /** Usage from the tool execution itself, if available. */
1282 usage?: Usage;
1283}
1284
1285export interface BashToolResultEvent extends ToolResultEventBase {
1286 toolName: "bash";
1287 details: BashToolDetails | undefined;
1288}
1289
1290export interface PowerShellToolResultEvent extends ToolResultEventBase {
1291 toolName: "powershell";
1292 details: PowerShellToolDetails | undefined;
1293}
1294
1295export interface ReadToolResultEvent extends ToolResultEventBase {
1296 toolName: "read";
1297 details: ReadToolDetails | undefined;
1298}
1299
1300export interface EditToolResultEvent extends ToolResultEventBase {
1301 toolName: "edit";
1302 details: EditToolDetails | undefined;
1303}
1304
1305export interface WriteToolResultEvent extends ToolResultEventBase {
1306 toolName: "write";
1307 details: undefined;
1308}
1309
1310export interface GrepToolResultEvent extends ToolResultEventBase {
1311 toolName: "grep";
1312 details: GrepToolDetails | undefined;
1313}
1314
1315export interface FindToolResultEvent extends ToolResultEventBase {
1316 toolName: "find";
1317 details: FindToolDetails | undefined;
1318}
1319
1320export interface LsToolResultEvent extends ToolResultEventBase {
1321 toolName: "ls";
1322 details: LsToolDetails | undefined;
1323}
1324
1325export interface CustomToolResultEvent extends ToolResultEventBase {
1326 toolName: string;
1327 details: unknown;
1328}
1329
1330/** Fired after a tool executes. Can modify result. */
1331export type ToolResultEvent =
1332 | BashToolResultEvent
1333 | PowerShellToolResultEvent
1334 | ReadToolResultEvent
1335 | EditToolResultEvent
1336 | WriteToolResultEvent
1337 | GrepToolResultEvent
1338 | FindToolResultEvent
1339 | LsToolResultEvent
1340 | CustomToolResultEvent;
1341
1342// Type guards for ToolResultEvent
1343export function isBashToolResult(e: ToolResultEvent): e is BashToolResultEvent {
1344 return e.toolName === "bash";
1345}
1346export function isPowerShellToolResult(e: ToolResultEvent): e is PowerShellToolResultEvent {
1347 return e.toolName === "powershell";
1348}
1349export function isReadToolResult(e: ToolResultEvent): e is ReadToolResultEvent {
1350 return e.toolName === "read";
1351}
1352export function isEditToolResult(e: ToolResultEvent): e is EditToolResultEvent {
1353 return e.toolName === "edit";
1354}
1355export function isWriteToolResult(e: ToolResultEvent): e is WriteToolResultEvent {
1356 return e.toolName === "write";
1357}
1358export function isGrepToolResult(e: ToolResultEvent): e is GrepToolResultEvent {
1359 return e.toolName === "grep";
1360}
1361export function isFindToolResult(e: ToolResultEvent): e is FindToolResultEvent {
1362 return e.toolName === "find";
1363}
1364export function isLsToolResult(e: ToolResultEvent): e is LsToolResultEvent {
1365 return e.toolName === "ls";
1366}
1367
1368/**
1369 * Type guard for narrowing ToolCallEvent by tool name.
1370 *
1371 * Built-in tools narrow automatically (no type params needed):
1372 * ```ts
1373 * if (isToolCallEventType("bash", event)) {
1374 * event.input.command; // string
1375 * }
1376 * ```
1377 *
1378 * Custom tools require explicit type parameters:
1379 * ```ts
1380 * if (isToolCallEventType<"my_tool", MyToolInput>("my_tool", event)) {
1381 * event.input.action; // typed
1382 * }
1383 * ```
1384 *
1385 * Note: Direct narrowing via `event.toolName === "bash"` doesn't work because
1386 * CustomToolCallEvent.toolName is `string` which overlaps with all literals.
1387 */
1388export function isToolCallEventType(toolName: "bash", event: ToolCallEvent): event is BashToolCallEvent;
1389export function isToolCallEventType(toolName: "powershell", event: ToolCallEvent): event is PowerShellToolCallEvent;
1390export function isToolCallEventType(toolName: "read", event: ToolCallEvent): event is ReadToolCallEvent;
1391export function isToolCallEventType(toolName: "edit", event: ToolCallEvent): event is EditToolCallEvent;
1392export function isToolCallEventType(toolName: "write", event: ToolCallEvent): event is WriteToolCallEvent;
1393export function isToolCallEventType(toolName: "grep", event: ToolCallEvent): event is GrepToolCallEvent;
1394export function isToolCallEventType(toolName: "find", event: ToolCallEvent): event is FindToolCallEvent;
1395export function isToolCallEventType(toolName: "ls", event: ToolCallEvent): event is LsToolCallEvent;
1396export function isToolCallEventType<TName extends string, TInput extends Record<string, unknown>>(
1397 toolName: TName,
1398 event: ToolCallEvent,
1399): event is ToolCallEvent & { toolName: TName; input: TInput };
1400export function isToolCallEventType(toolName: string, event: ToolCallEvent): boolean {
1401 return event.toolName === toolName;
1402}
1403
1404/** Union of all event types */
1405export type ExtensionEvent =
1406 | ProjectTrustEvent
1407 | ResourcesDiscoverEvent
1408 | McpServersChangeEvent
1409 | SessionEvent
1410 | ContextEvent
1411 | ContextWithSystemEvent
1412 | CacheWarmingDecisionEvent
1413 | BeforeProviderRequestEvent
1414 | BeforeProviderHeadersEvent
1415 | AfterProviderResponseEvent
1416 | ProviderStreamEvent
1417 | BeforeAgentStartEvent
1418 | AgentStartEvent
1419 | AgentEndEvent
1420 | AgentBeforeSettleEvent
1421 | AgentSettledEvent
1422 | UIPromptStartEvent
1423 | UIPromptEndEvent
1424 | TurnStartEvent
1425 | TurnEndEvent
1426 | MessageStartEvent
1427 | MessageUpdateEvent
1428 | MessageEndEvent
1429 | ToolExecutionStartEvent
1430 | ToolExecutionUpdateEvent
1431 | ToolExecutionEndEvent
1432 | ModelSelectEvent
1433 | ThinkingLevelSelectEvent
1434 | UserBashEvent
1435 | InputEvent
1436 | ToolCallEvent
1437 | ToolResultEvent;
1438
1439// ============================================================================
1440// Event Results
1441// ============================================================================
1442
1443export interface ContextEventResult {
1444 messages?: AgentMessage[];
1445}
1446
1447export type TurnEndEventResult = BoundaryResult;
1448export type AgentBeforeSettleEventResult = BoundaryResult;
1449
1450export type BeforeProviderRequestEventResult = unknown;
1451
1452export type { CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult } from "../cache-warmer.ts";
1453
1454export interface ToolCallEventResult {
1455 /** Block tool execution. To modify arguments, mutate `event.input` in place instead. */
1456 block?: boolean;
1457 reason?: string;
1458 /**
1459 * Hint that the agent should stop after the current tool batch when this call is blocked.
1460 * Early termination only happens when every finalized tool result in the batch sets this to true.
1461 */
1462 terminate?: boolean;
1463}
1464
1465/** Result from user_bash event handler */
1466export type UserBashEventResult =
1467 | {
1468 /** Custom operations to use for execution */
1469 operations: BashOperations;
1470 result?: never;
1471 }
1472 | {
1473 operations?: never;
1474 /** Full replacement: extension handled execution, use this result */
1475 result: BashResult;
1476 };
1477
1478/**
1479 * Changes a `tool_result` handler makes. Omitted fields stay as they are, except that replacing
1480 * `content` without returning `structuredContent` drops the structured content, because it may no
1481 * longer match. Return it along with `content` to keep it.
1482 */
1483export interface ToolResultEventResult {
1484 content?: (TextContent | ImageContent)[];
1485 details?: unknown;
1486 structuredContent?: JsonValue;
1487 isError?: boolean;
1488 usage?: Usage;
1489}
1490
1491export interface MessageEndEventResult {
1492 /** Replace the finalized message. The replacement must keep the original message role. */
1493 message?: AgentMessage;
1494}
1495
1496export interface BeforeAgentStartEventResult {
1497 message?: Pick<CustomMessage, "customType" | "content" | "display" | "details">;
1498 /** Replace the complete system prompt for this turn. Later handlers observe this exact override. */
1499 systemPrompt?: string;
1500}
1501
1502export interface SessionBeforeSwitchResult {
1503 cancel?: boolean;
1504}
1505
1506export interface SessionBeforeForkResult {
1507 cancel?: boolean;
1508 skipConversationRestore?: boolean;
1509}
1510
1511export interface SessionBeforeCompactResult {
1512 cancel?: boolean;
1513 compaction?: CompactionResult;
1514}
1515
1516export interface SessionBeforeTreeResult {
1517 cancel?: boolean;
1518 summary?: {
1519 summary: string;
1520 details?: unknown;
1521 usage?: Usage;
1522 };
1523 /** Override custom instructions for summarization */
1524 customInstructions?: string;
1525 /** Override whether customInstructions replaces the default prompt */
1526 replaceInstructions?: boolean;
1527 /** Override label to attach to the branch summary entry */
1528 label?: string;
1529}
1530
1531// ============================================================================
1532// Message and Entry Rendering
1533// ============================================================================
1534
1535export interface MessageRenderOptions {
1536 expanded: boolean;
1537 /** Horizontal padding configured by the outputPad setting. */
1538 outputPad: number;
1539}
1540
1541export interface MarkdownTransformContext {
1542 messageType: "user" | "assistant" | "assistant-thinking";
1543 isStreaming: boolean;
1544 availableWidth: number;
1545}
1546
1547export type MarkdownTransformer = (markdown: string, context: MarkdownTransformContext) => string;
1548
1549export interface EntryRenderOptions {
1550 expanded: boolean;
1551}
1552
1553export type MessageRenderer<T = unknown> = (
1554 message: CustomMessage<T>,
1555 options: MessageRenderOptions,
1556 theme: Theme,
1557) => Component | undefined;
1558
1559export type EntryRenderer<T = unknown> = (
1560 entry: CustomEntry<T>,
1561 options: EntryRenderOptions,
1562 theme: Theme,
1563) => Component | undefined;
1564
1565// ============================================================================
1566// Command Registration
1567// ============================================================================
1568
1569export interface RegisteredCommand {
1570 name: string;
1571 sourceInfo: SourceInfo;
1572 description?: string;
1573 getArgumentCompletions?: (argumentPrefix: string) => AutocompleteItem[] | null | Promise<AutocompleteItem[] | null>;
1574 handler: (args: string, ctx: ExtensionCommandContext) => Promise<void>;
1575}
1576
1577export interface ResolvedCommand extends RegisteredCommand {
1578 invocationName: string;
1579}
1580
1581// ============================================================================
1582// Extension API
1583// ============================================================================
1584
1585/** Handler function type for events */
1586// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements
1587export type ExtensionHandler<E, R = undefined> = (event: E, ctx: ExtensionContext) => Promise<R | void> | R | void;
1588
1589/**
1590 * ExtensionAPI passed to extension factory functions.
1591 */
1592export interface ExtensionAPI {
1593 // =========================================================================
1594 // Event Subscription
1595 // =========================================================================
1596
1597 on(event: "project_trust", handler: ProjectTrustHandler): () => void;
1598 on(
1599 event: "resources_discover",
1600 handler: ExtensionHandler<ResourcesDiscoverEvent, ResourcesDiscoverResult>,
1601 ): () => void;
1602 on(event: "session_start", handler: ExtensionHandler<SessionStartEvent>): () => void;
1603 on(event: "session_info_changed", handler: ExtensionHandler<SessionInfoChangedEvent>): () => void;
1604 on(
1605 event: "session_before_switch",
1606 handler: ExtensionHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>,
1607 ): () => void;
1608 on(
1609 event: "session_before_fork",
1610 handler: ExtensionHandler<SessionBeforeForkEvent, SessionBeforeForkResult>,
1611 ): () => void;
1612 on(
1613 event: "session_before_compact",
1614 handler: ExtensionHandler<SessionBeforeCompactEvent, SessionBeforeCompactResult>,
1615 ): () => void;
1616 on(event: "session_compact", handler: ExtensionHandler<SessionCompactEvent>): () => void;
1617 on(event: "session_compact_failed", handler: ExtensionHandler<SessionCompactFailedEvent>): () => void;
1618 on(event: "session_shutdown", handler: ExtensionHandler<SessionShutdownEvent>): () => void;
1619 on(event: "mcp_servers_change", handler: ExtensionHandler<McpServersChangeEvent>): () => void;
1620 on(
1621 event: "session_before_tree",
1622 handler: ExtensionHandler<SessionBeforeTreeEvent, SessionBeforeTreeResult>,
1623 ): () => void;
1624 on(event: "session_tree", handler: ExtensionHandler<SessionTreeEvent>): () => void;
1625 on(event: "context", handler: ExtensionHandler<ContextEvent, ContextEventResult>): () => void;
1626 on(event: "context_with_system", handler: ExtensionHandler<ContextWithSystemEvent, ContextEventResult>): () => void;
1627 on(
1628 event: "cache_warming_decision",
1629 handler: ExtensionHandler<CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult>,
1630 ): () => void;
1631 on(
1632 event: "before_provider_request",
1633 handler: ExtensionHandler<BeforeProviderRequestEvent, BeforeProviderRequestEventResult>,
1634 ): () => void;
1635 on(event: "before_provider_headers", handler: ExtensionHandler<BeforeProviderHeadersEvent>): () => void;
1636 on(event: "after_provider_response", handler: ExtensionHandler<AfterProviderResponseEvent>): () => void;
1637 on(event: "provider_stream_event", handler: ExtensionHandler<ProviderStreamEvent>): () => void;
1638 on(
1639 event: "before_agent_start",
1640 handler: ExtensionHandler<BeforeAgentStartEvent, BeforeAgentStartEventResult>,
1641 ): () => void;
1642 on(event: "agent_start", handler: ExtensionHandler<AgentStartEvent>): () => void;
1643 on(event: "agent_end", handler: ExtensionHandler<AgentEndEvent>): () => void;
1644 on(
1645 event: "agent_before_settle",
1646 handler: ExtensionHandler<AgentBeforeSettleEvent, AgentBeforeSettleEventResult>,
1647 ): () => void;
1648 on(event: "agent_settled", handler: ExtensionHandler<AgentSettledEvent>): () => void;
1649 on(event: "ui_prompt_start", handler: ExtensionHandler<UIPromptStartEvent>): () => void;
1650 on(event: "ui_prompt_end", handler: ExtensionHandler<UIPromptEndEvent>): () => void;
1651 on(event: "turn_start", handler: ExtensionHandler<TurnStartEvent>): () => void;
1652 on(event: "turn_end", handler: ExtensionHandler<TurnEndEvent, TurnEndEventResult>): () => void;
1653 on(event: "message_start", handler: ExtensionHandler<MessageStartEvent>): () => void;
1654 on(event: "message_update", handler: ExtensionHandler<MessageUpdateEvent>): () => void;
1655 on(event: "message_end", handler: ExtensionHandler<MessageEndEvent, MessageEndEventResult>): () => void;
1656 on(event: "tool_execution_start", handler: ExtensionHandler<ToolExecutionStartEvent>): () => void;
1657 on(event: "tool_execution_update", handler: ExtensionHandler<ToolExecutionUpdateEvent>): () => void;
1658 on(event: "tool_execution_end", handler: ExtensionHandler<ToolExecutionEndEvent>): () => void;
1659 on(event: "model_select", handler: ExtensionHandler<ModelSelectEvent>): () => void;
1660 on(event: "thinking_level_select", handler: ExtensionHandler<ThinkingLevelSelectEvent>): () => void;
1661 on(event: "tool_call", handler: ExtensionHandler<ToolCallEvent, ToolCallEventResult>): () => void;
1662 on(event: "tool_result", handler: ExtensionHandler<ToolResultEvent, ToolResultEventResult>): () => void;
1663 on(event: "user_bash", handler: ExtensionHandler<UserBashEvent, UserBashEventResult>): () => void;
1664 on(event: "input", handler: ExtensionHandler<InputEvent, InputEventResult>): () => void;
1665
1666 // =========================================================================
1667 // Tool Registration
1668 // =========================================================================
1669
1670 /** Register a tool that the LLM can call. */
1671 registerTool<TParams extends TSchema = TSchema, TDetails = unknown, TState = any>(
1672 tool: ToolDefinition<TParams, TDetails, TState>,
1673 ): void;
1674
1675 // =========================================================================
1676 // Command, Shortcut, Flag Registration
1677 // =========================================================================
1678
1679 /** Register a custom command. */
1680 registerCommand(name: string, options: Omit<RegisteredCommand, "name" | "sourceInfo">): void;
1681
1682 /** Register a keyboard shortcut. */
1683 registerShortcut(
1684 shortcut: KeyId,
1685 options: {
1686 description?: string;
1687 handler: (ctx: ExtensionContext) => Promise<void> | void;
1688 },
1689 ): void;
1690
1691 /** Register a CLI flag. */
1692 registerFlag(
1693 name: string,
1694 options:
1695 | {
1696 description?: string;
1697 type: "boolean";
1698 default?: boolean;
1699 }
1700 | {
1701 description?: string;
1702 type: "string";
1703 default?: string;
1704 },
1705 ): void;
1706
1707 /** Get the value of a registered CLI flag. */
1708 getFlag(name: string): boolean | string | undefined;
1709
1710 // =========================================================================
1711 // Message Rendering
1712 // =========================================================================
1713
1714 /** Register a custom renderer for CustomMessageEntry. */
1715 registerMessageRenderer<T = unknown>(customType: string, renderer: MessageRenderer<T>): void;
1716
1717 /** Register a transformer for user and assistant Markdown before Pi renders it in the interactive transcript. */
1718 registerMarkdownTransformer(transformer: MarkdownTransformer): void;
1719
1720 /** Register a custom renderer for CustomEntry. Custom entries do not participate in LLM context. */
1721 registerEntryRenderer<T = unknown>(customType: string, renderer: EntryRenderer<T>): void;
1722
1723 /** Choose how tool calls are drawn. Resolvers run in extension load order. */
1724 registerToolRenderer(resolver: ToolRendererResolver): void;
1725
1726 // =========================================================================
1727 // Actions
1728 // =========================================================================
1729
1730 /** Send a custom message to the session. */
1731 sendMessage<T = unknown>(
1732 message: Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">,
1733 options?: { triggerTurn?: boolean; deliverAs?: "steer" | "followUp" | "nextTurn" },
1734 ): void;
1735
1736 /**
1737 * Send a user message to the agent. Always triggers a turn.
1738 * When the agent is streaming, use deliverAs to specify how to queue the message.
1739 * Set expandPromptTemplates to dispatch extension commands and expand skill commands and prompt templates.
1740 */
1741 sendUserMessage(
1742 content: string | (TextContent | ImageContent)[],
1743 options?: { deliverAs?: "steer" | "followUp"; expandPromptTemplates?: boolean },
1744 ): void;
1745
1746 /** Append a custom entry to the session for state persistence (not sent to LLM). */
1747 appendEntry<T = unknown>(customType: string, data?: T): void;
1748
1749 // =========================================================================
1750 // Session Metadata
1751 // =========================================================================
1752
1753 /** Set the session display name (shown in session selector). */
1754 setSessionName(name: string): void;
1755
1756 /** Get the current session name, if set. */
1757 getSessionName(): string | undefined;
1758
1759 /** Set or clear a label on an entry. Labels are user-defined markers for bookmarking/navigation. */
1760 setLabel(entryId: string, label: string | undefined): void;
1761
1762 /** Execute a shell command. */
1763 exec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;
1764
1765 /** Get the names of the active tools, which are the tools declared to the model. */
1766 getActiveTools(): string[];
1767
1768 /** Get all configured tools with parameter schema, prompt guidelines, exposure, and source metadata. */
1769 getAllTools(): ToolInfo[];
1770
1771 /** Get a copy of the effective settings (global and project settings merged, with overrides). */
1772 getSettings(): Settings;
1773
1774 /**
1775 * Set the active tools by name. Unknown and `hidden` tools are ignored. Tools with `codemode` or
1776 * `deferred` exposure stay callable from codemode scripts whether active or not.
1777 */
1778 setActiveTools(toolNames: string[]): void;
1779
1780 /** Get available slash commands in the current session. */
1781 getCommands(): SlashCommandInfo[];
1782
1783 // =========================================================================
1784 // Model and Thinking Level
1785 // =========================================================================
1786
1787 /**
1788 * Set the model for the current session without changing the configured default for new sessions.
1789 * Returns false if authentication is not configured for the model's provider.
1790 */
1791 setModel(model: Model<any>): Promise<boolean>;
1792
1793 /** Get current thinking level. */
1794 getThinkingLevel(): ThinkingLevel;
1795
1796 /**
1797 * Set the thinking level (clamped to model capabilities) for the current session without changing the configured default
1798 * for new sessions.
1799 */
1800 setThinkingLevel(level: ThinkingLevel): void;
1801
1802 // =========================================================================
1803 // Provider Registration
1804 // =========================================================================
1805
1806 /**
1807 * Register or override a model provider.
1808 *
1809 * If `models` is provided: replaces all existing models for this provider.
1810 * If only `baseUrl` is provided: overrides the URL for existing models.
1811 * If `oauth` is provided: registers OAuth provider for /login support.
1812 * If `streamSimple` is provided: registers a custom API stream handler.
1813 *
1814 * During initial extension load this call is queued and applied once the
1815 * runner has bound its context. After that it takes effect immediately, so
1816 * it is safe to call from command handlers or event callbacks without
1817 * requiring a `/reload`.
1818 *
1819 * @example
1820 * // Register a new provider with custom models
1821 * pi.registerProvider("my-proxy", {
1822 * baseUrl: "https://proxy.example.com",
1823 * apiKey: "$PROXY_API_KEY",
1824 * api: "anthropic-messages",
1825 * models: [
1826 * {
1827 * id: "claude-sonnet-4-20250514",
1828 * name: "Claude 4 Sonnet (proxy)",
1829 * reasoning: false,
1830 * input: ["text", "image"],
1831 * cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1832 * contextWindow: 200000,
1833 * maxTokens: 16384
1834 * }
1835 * ]
1836 * });
1837 *
1838 * @example
1839 * // Override baseUrl for an existing provider
1840 * pi.registerProvider("anthropic", {
1841 * baseUrl: "https://proxy.example.com"
1842 * });
1843 *
1844 * @example
1845 * // Register provider with OAuth support
1846 * pi.registerProvider("corporate-ai", {
1847 * baseUrl: "https://ai.corp.com",
1848 * api: "openai-responses",
1849 * models: [...],
1850 * oauth: {
1851 * name: "Corporate AI (SSO)",
1852 * async login(callbacks) { ... },
1853 * async refreshToken(credentials) { ... },
1854 * getApiKey(credentials) { return credentials.access; }
1855 * }
1856 * });
1857 */
1858 registerProvider(provider: Provider): void;
1859 registerProvider(name: string, config: ProviderConfig): void;
1860
1861 /**
1862 * Unregister a previously registered provider.
1863 *
1864 * Removes all models belonging to the named provider and restores any
1865 * built-in models that were overridden by it. Has no effect if the provider
1866 * is not currently registered.
1867 *
1868 * Like `registerProvider`, this takes effect immediately when called after
1869 * the initial load phase.
1870 *
1871 * @example
1872 * pi.unregisterProvider("my-proxy");
1873 */
1874 unregisterProvider(name: string): void;
1875
1876 // =========================================================================
1877 // MCP Servers
1878 // =========================================================================
1879
1880 /**
1881 * Register an MCP server for this session, with the same config as an `mcpServers` entry in
1882 * `mcp.json`. The server connects next to the configured servers: on `session_start` when
1883 * registered during extension load, right away when registered later. Registering a name again
1884 * replaces the extension's earlier registration.
1885 *
1886 * The registration is not saved; register again on every load. A server of the same name in
1887 * `mcp.json` takes precedence. Throws for invalid configs and for names another extension
1888 * registered. When no loaded extension handles MCP servers (for example because another MCP
1889 * extension replaced the built-in one), the registration is reported as an extension error.
1890 *
1891 * @example
1892 * pi.registerMcpServer("jira", { url: "https://mcp.example.com/jira" });
1893 */
1894 registerMcpServer(name: string, config: McpServerConfig): void;
1895
1896 /** Remove an MCP server this extension registered and close its connection. */
1897 unregisterMcpServer(name: string): void;
1898
1899 /** Every MCP server registered by extensions. For extensions that connect MCP servers. */
1900 getMcpServers(): RegisteredMcpServer[];
1901
1902 /**
1903 * Register a virtual model: a selectable catalog entry that routes each request to a physical
1904 * model. The selection (`ctx.model`, `model_change` entries) names the virtual model; assistant
1905 * messages record the physical model and thinking level the router picked.
1906 *
1907 * `provider` may be any provider id, including one with physical models, and may list several
1908 * virtual models. Registering the same provider and id again replaces the virtual model. See
1909 * docs/virtual-models.md.
1910 */
1911 registerVirtualModel<TState = unknown>(model: ExtensionVirtualModel<TState>): void;
1912
1913 /** Remove a virtual model registered with `registerVirtualModel()`. */
1914 unregisterVirtualModel(provider: string, id: string): void;
1915
1916 /** Shared event bus for extension communication. */
1917 events: EventBus;
1918}
1919
1920// ============================================================================
1921// Provider Registration Types
1922// ============================================================================
1923
1924/** Virtual model registered via pi.registerVirtualModel(). */
1925export interface ExtensionVirtualModel<TState = unknown> extends Omit<VirtualModelDefinition<TState>, "route"> {
1926 /** Like `VirtualModelDefinition.route`, with an extension context. */
1927 route(request: ModelRouteRequest<TState>, ctx: ExtensionContext): ModelRoute<TState> | Promise<ModelRoute<TState>>;
1928}
1929
1930/** Configuration for registering a provider via pi.registerProvider(). */
1931export interface ProviderConfig {
1932 /** Display name for the provider in UI. */
1933 name?: string;
1934 /** Base URL for the API endpoint. Required when defining models. */
1935 baseUrl?: string;
1936 /** API key literal, env interpolation ($ENV_VAR or ${ENV_VAR}), or leading !command. Required when defining models (unless oauth provided). */
1937 apiKey?: string;
1938 /** API type. Required at provider or model level when defining models. */
1939 api?: Api;
1940 /**
1941 * Optional streamSimple handler for custom APIs.
1942 * The context is a normalized transcript: read the prompt and tools from its system messages
1943 * (`getCurrentSystemPrompt(context.messages)`, `getCurrentTools(context.messages)`).
1944 * Implementations must invoke `options.onPayload` before sending the provider request and use any
1945 * returned replacement payload. They must invoke `options.onResponse` after receiving the response
1946 * and before consuming its body, matching built-in providers. Implementations may invoke
1947 * `options.onProviderStreamEvent(data, model)` with parsed stream events before normalization.
1948 * Event data is adapter-owned and must be treated as read-only.
1949 */
1950 streamSimple?: (
1951 model: Model<Api>,
1952 context: TranscriptContext,
1953 options?: SimpleStreamOptions,
1954 ) => AssistantMessageEventStream;
1955 /** Image-generation implementations keyed by image API. */
1956 images?: Partial<Record<ImageApi, ProviderImages>>;
1957 /** Classifier implementations keyed by classifier API. */
1958 classifiers?: Partial<Record<ClassifierApi, ProviderClassifier>>;
1959 /** Custom headers to include in requests. */
1960 headers?: Record<string, string>;
1961 /** If true, adds Authorization: Bearer header with the resolved API key. */
1962 authHeader?: boolean;
1963 /** Models to register. If provided, replaces all existing models for this provider. */
1964 models?: ProviderModelConfig[];
1965 /**
1966 * Refresh this provider's model list. The returned list replaces extension-provided models.
1967 * Use context.publish({ persist: entry }) when the catalog should persist across sessions.
1968 */
1969 refreshModels?(context: RefreshModelsContext): Promise<ProviderModelConfig[]>;
1970 /** OAuth provider for /login support. The `id` is set automatically from the provider name. */
1971 oauth?: {
1972 /** Display name for the provider in login UI. */
1973 name: string;
1974 /** Whether access through this auth method is backed by a provider subscription. */
1975 isSubscription?: boolean;
1976 /** @deprecated Retained for source compatibility; canonical auth flows ignore it. */
1977 usesCallbackServer?: boolean;
1978 /** Run the login flow, return credentials to persist. */
1979 login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials>;
1980 /** Refresh expired credentials, return updated credentials to persist. */
1981 refreshToken(credentials: OAuthCredentials, signal: AbortSignal): Promise<OAuthCredentials>;
1982 /** Convert credentials to API key string for the provider. */
1983 getApiKey(credentials: OAuthCredentials): string;
1984 /** Legacy synchronous credential-dependent model projection. */
1985 modifyModels?(models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[];
1986 };
1987}
1988
1989interface ProviderModelConfigBase {
1990 /** Model ID. */
1991 id: string;
1992 /** Display name. */
1993 name: string;
1994 /** API type override for this model. */
1995 api?: string;
1996 /** API endpoint URL override for this model. */
1997 baseUrl?: string;
1998 /** Supported input types. */
1999 input: ("text" | "image")[];
2000 /** Provider input limits and cache-safe image preprocessing metadata. */
2001 inputLimits?: AnyModel["inputLimits"];
2002 /** Per-million-token cost rates and optional request-wide input pricing tiers. */
2003 cost: AnyModel["cost"];
2004 /** Custom headers for this model. */
2005 headers?: Record<string, string>;
2006}
2007
2008/** Chat model configuration. Omitted `type` is normalized to `"chat"`. */
2009export interface ProviderChatModelConfig extends ProviderModelConfigBase {
2010 type?: "chat";
2011 api?: Api;
2012 /** Whether the model supports extended thinking. */
2013 reasoning: boolean;
2014 /** Maps pi thinking levels to provider/model-specific values; null marks a level unsupported. */
2015 thinkingLevelMap?: Model<Api>["thinkingLevelMap"];
2016 /** Best-effort prompt cache lifetime in seconds per retention tier. Unset disables cache warming. */
2017 promptCache?: Model<Api>["promptCache"];
2018 /** Maximum context window size in tokens. */
2019 contextWindow: number;
2020 /** Maximum output tokens. */
2021 maxTokens: number;
2022 samplingParams?: Record<string, unknown>;
2023 /** OpenAI compatibility settings. */
2024 compat?: Model<Api>["compat"];
2025}
2026
2027/** Image-generation model configuration. */
2028export interface ProviderImageModelConfig extends ProviderModelConfigBase {
2029 type: "image";
2030 api?: ImageApi;
2031 output: ("text" | "image")[];
2032}
2033
2034/** Structured classifier model configuration. */
2035export interface ProviderClassifierModelConfig extends ProviderModelConfigBase {
2036 type: "classifier";
2037 api?: ClassifierApi;
2038 contextWindow: number;
2039}
2040
2041/** Configuration for a model within a provider. */
2042export type ProviderModelConfig = ProviderChatModelConfig | ProviderImageModelConfig | ProviderClassifierModelConfig;
2043
2044/** Extension factory function type. Supports both sync and async initialization. */
2045export type ExtensionFactory = (pi: ExtensionAPI) => void | Promise<void>;
2046
2047export type InlineExtension =
2048 | ExtensionFactory
2049 | {
2050 /**
2051 * Display name shown as `<inline:name>` in the startup Extensions list and errors. With
2052 * `builtin`, the extension is named `builtin:name` in errors and diagnostics.
2053 */
2054 name: string;
2055 factory: ExtensionFactory;
2056 /** Omit this extension from the startup Extensions list. */
2057 hidden?: boolean;
2058 /**
2059 * Leave this extension out when another extension registers a tool, command, or flag with a
2060 * name it registers during loading, instead of reporting a conflict. The CLI's built-in MCP,
2061 * codemode, and tool search extensions use it, so for example an MCP extension that registers
2062 * `/mcp` replaces the built-in MCP support. The factory still runs, so it should only register
2063 * tools, commands, flags, and event handlers.
2064 */
2065 replaceable?: boolean;
2066 /**
2067 * Supply the code of the `builtin:<name>` extension instead of loading as an inline extension.
2068 * `builtin:<name>` is an extension resource like a file: it loads by default, `pi config` lists
2069 * it, `-builtin:<name>` in the `extensions` setting and `--no-extensions` disable it, and
2070 * `-e builtin:<name>` loads it explicitly. It is hidden from the startup Extensions list and
2071 * loads after project trust is resolved, so it cannot handle `project_trust`. The CLI's built-in
2072 * extensions use it.
2073 */
2074 builtin?: boolean;
2075 };
2076
2077// ============================================================================
2078// Loaded Extension Types
2079// ============================================================================
2080
2081export interface RegisteredTool {
2082 definition: ToolDefinition;
2083 sourceInfo: SourceInfo;
2084}
2085
2086export interface ExtensionFlag {
2087 name: string;
2088 description?: string;
2089 type: "boolean" | "string";
2090 default?: boolean | string;
2091 extensionPath: string;
2092}
2093
2094export interface ExtensionShortcut {
2095 shortcut: KeyId;
2096 description?: string;
2097 handler: (ctx: ExtensionContext) => Promise<void> | void;
2098 extensionPath: string;
2099}
2100
2101type HandlerFn = (...args: unknown[]) => Promise<unknown>;
2102
2103export type SendMessageHandler = <T = unknown>(
2104 message: Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">,
2105 options?: { triggerTurn?: boolean; deliverAs?: "steer" | "followUp" | "nextTurn" },
2106) => void;
2107
2108export type SendUserMessageHandler = (
2109 content: string | (TextContent | ImageContent)[],
2110 options?: { deliverAs?: "steer" | "followUp"; expandPromptTemplates?: boolean },
2111) => void;
2112
2113export type AppendEntryHandler = <T = unknown>(customType: string, data?: T) => void;
2114
2115export type SetSessionNameHandler = (name: string) => void;
2116
2117export type GetSessionNameHandler = () => string | undefined;
2118
2119export type GetActiveToolsHandler = () => string[];
2120
2121/** Tool info with name, description, parameter schema, prompt guidelines, and source metadata. */
2122export type ToolInfo = Pick<
2123 ToolDefinition,
2124 "name" | "description" | "parameters" | "promptGuidelines" | "reachesTools"
2125> & {
2126 exposure: ToolExposure;
2127 namespace?: ToolNamespace;
2128 annotations?: ToolAnnotations;
2129 sourceInfo: SourceInfo;
2130};
2131
2132export type GetAllToolsHandler = () => ToolInfo[];
2133
2134export type GetSettingsHandler = () => Settings;
2135
2136export type GetCommandsHandler = () => SlashCommandInfo[];
2137
2138export type SetActiveToolsHandler = (toolNames: string[]) => void;
2139
2140export type RefreshToolsHandler = () => void;
2141
2142export type SetModelHandler = (model: Model<any>) => Promise<boolean>;
2143
2144export type GetThinkingLevelHandler = () => ThinkingLevel;
2145
2146export type SetThinkingLevelHandler = (level: ThinkingLevel) => void;
2147
2148export type SetLabelHandler = (entryId: string, label: string | undefined) => void;
2149
2150/**
2151 * Shared state created by loader, used during registration and runtime.
2152 * Contains flag values (defaults set during registration, CLI values set after).
2153 */
2154export interface ExtensionRuntimeState {
2155 flagValues: Map<string, boolean | string>;
2156 /** Legacy provider-config registrations queued during extension loading, processed when runner binds. */
2157 pendingProviderRegistrations: Array<{ name: string; config: ProviderConfig; extensionPath: string }>;
2158 /** Native pi-ai provider registrations queued during extension loading, processed when runner binds. */
2159 pendingNativeProviderRegistrations: Array<{ provider: Provider; extensionPath: string }>;
2160 /** Virtual model registrations queued during extension loading, processed when runner binds. */
2161 pendingVirtualModelRegistrations: Array<{ definition: VirtualModelDefinition; extensionPath: string }>;
2162 /** Create an extension context. Throws before the runner binds. */
2163 createContext: () => ExtensionContext;
2164 /** Throws when this extension instance is stale after runtime replacement. */
2165 assertActive: () => void;
2166 /** Marks this extension instance as stale after runtime replacement or reload. */
2167 invalidate: (message?: string) => void;
2168 /** Retain an event-bus subscription until this runtime is invalidated. */
2169 trackEventBusSubscription: (unsubscribe: () => void) => () => void;
2170 /**
2171 * Register or unregister a provider.
2172 *
2173 * Before bindCore(): queues registrations / removes from queue.
2174 * After bindCore(): calls ModelRegistry directly for immediate effect.
2175 */
2176 registerProvider: (name: string, config: ProviderConfig, extensionPath?: string) => void;
2177 registerNativeProvider: (provider: Provider, extensionPath?: string) => void;
2178 unregisterProvider: (name: string, extensionPath?: string) => void;
2179 /** Servers registered with `pi.registerMcpServer()`. */
2180 mcpServers: McpServerRegistry;
2181 registerVirtualModel: (definition: VirtualModelDefinition, extensionPath?: string) => void;
2182 unregisterVirtualModel: (provider: string, id: string) => void;
2183}
2184
2185/**
2186 * Action implementations for pi.* API methods.
2187 * Provided to runner.initialize(), copied into the shared runtime.
2188 */
2189export interface ExtensionActions {
2190 sendMessage: SendMessageHandler;
2191 sendUserMessage: SendUserMessageHandler;
2192 appendEntry: AppendEntryHandler;
2193 setSessionName: SetSessionNameHandler;
2194 getSessionName: GetSessionNameHandler;
2195 setLabel: SetLabelHandler;
2196 getActiveTools: GetActiveToolsHandler;
2197 getAllTools: GetAllToolsHandler;
2198 getSettings: GetSettingsHandler;
2199 setActiveTools: SetActiveToolsHandler;
2200 refreshTools: RefreshToolsHandler;
2201 getCommands: GetCommandsHandler;
2202 setModel: SetModelHandler;
2203 getThinkingLevel: GetThinkingLevelHandler;
2204 setThinkingLevel: SetThinkingLevelHandler;
2205}
2206
2207/**
2208 * Actions for ExtensionContext (ctx.* in event handlers).
2209 * Required by all modes.
2210 */
2211export interface ExtensionContextActions {
2212 getModel: () => Model<any> | undefined;
2213 getScopedModels: () => readonly ScopedModel[];
2214 isIdle: () => boolean;
2215 isProjectTrusted: () => boolean;
2216 getSignal: () => AbortSignal | undefined;
2217 abort: () => void;
2218 hasPendingMessages: () => boolean;
2219 shutdown: () => void;
2220 getContextUsage: () => ContextUsage | undefined;
2221 compact: (options?: CompactOptions) => void;
2222 getSystemPrompt: () => string;
2223 getSystemPromptOptions?: () => BuildSystemPromptOptions;
2224 /** Backs `ExtensionToolContext.executeTool()`. Without it, nested calls fail. */
2225 executeTool?: (
2226 callerId: string,
2227 name: string,
2228 args: unknown,
2229 options: ExecuteToolOptions,
2230 ) => Promise<AgentToolCallOutcome>;
2231 /** Backs `ExtensionToolContext.tools`. */
2232 getCallableTools?: () => readonly AgentTool[];
2233}
2234
2235/**
2236 * Actions for ExtensionCommandContext (ctx.* in command handlers).
2237 * Only needed for interactive mode where extension commands are invokable.
2238 */
2239export interface ExtensionCommandContextActions {
2240 waitForIdle: () => Promise<void>;
2241 newSession: (options?: {
2242 parentSession?: string;
2243 setup?: (sessionManager: SessionManager) => Promise<void>;
2244 withSession?: (ctx: ReplacedSessionContext) => Promise<void>;
2245 }) => Promise<{ cancelled: boolean }>;
2246 fork: (
2247 entryId: string,
2248 options?: { position?: "before" | "at"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },
2249 ) => Promise<{ cancelled: boolean }>;
2250 navigateTree: (
2251 targetId: string,
2252 options?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },
2253 ) => Promise<{ cancelled: boolean }>;
2254 switchSession: (
2255 sessionPath: string,
2256 options?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },
2257 ) => Promise<{ cancelled: boolean }>;
2258 reload: () => Promise<void>;
2259}
2260
2261/**
2262 * Full runtime = state + actions.
2263 * Created by loader with throwing action stubs, completed by runner.initialize().
2264 */
2265export interface ExtensionRuntime extends ExtensionRuntimeState, ExtensionActions {}
2266
2267/** Loaded extension with all registered items. */
2268export interface Extension {
2269 path: string;
2270 resolvedPath: string;
2271 hidden?: boolean;
2272 /** See {@link InlineExtension}. */
2273 replaceable?: boolean;
2274 sourceInfo: SourceInfo;
2275 handlers: Map<string, HandlerFn[]>;
2276 tools: Map<string, RegisteredTool>;
2277 messageRenderers: Map<string, MessageRenderer>;
2278 toolRenderers?: ToolRendererResolver[];
2279 markdownTransformer?: MarkdownTransformer;
2280 entryRenderers?: Map<string, EntryRenderer>;
2281 commands: Map<string, RegisteredCommand>;
2282 flags: Map<string, ExtensionFlag>;
2283 shortcuts: Map<KeyId, ExtensionShortcut>;
2284}
2285
2286/** Result of loading extensions. */
2287export interface LoadExtensionsResult {
2288 extensions: Extension[];
2289 errors: Array<{ path: string; error: string }>;
2290 warnings?: Array<{ path: string; warning: string }>;
2291 /** Shared runtime - actions are throwing stubs until runner.initialize() */
2292 runtime: ExtensionRuntime;
2293}
2294
2295// ============================================================================
2296// Extension Error
2297// ============================================================================
2298
2299export interface ExtensionError {
2300 extensionPath: string;
2301 event: string;
2302 error: string;
2303 stack?: string;
2304}