返回源码地图

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

v1.0.1 · a7229ddc2181 · 08:事件边界与mutable input;非全部公开类型逐句分析

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。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
494/**
495 * How the model reaches a tool. "Callable" means callable from other tools through
496 * `ctx.executeTool()`, as the `codemode` tool does.
497 *
498 * - `direct`: declared to the model while active, and callable while active.
499 * - `model-only`: declared to the model while active, never callable. Use it for orchestrating or
500 * interactive tools.
501 * - `codemode`: callable whenever registered. Not declared to the model unless explicitly
502 * activated. Codemode tools list it in their description.
503 * - `deferred`: like `codemode`, but codemode tools do not list it; tool search can find it.
504 * - `hidden`: registered but unreachable. Activating it has no effect.
505 *
506 * `direct` and `model-only` tools are activated when they are registered; the others are not.
507 * The active tool set (`getActiveTools`/`setActiveTools`) is the set declared to the model.
508 */
509export type ToolExposure = "direct" | "model-only" | "codemode" | "deferred" | "hidden";
510
511/**
512 * Hints about what a tool does, with the meaning of MCP tool annotations. They come from the tool's
513 * author and are not verified; permission extensions can use them to decide which calls to confirm.
514 */
515export interface ToolAnnotations {
516 /** The tool does not modify its environment. */
517 readOnlyHint?: boolean;
518 /** The tool may delete or overwrite data, rather than only add to it. Meaningful when not read-only. */
519 destructiveHint?: boolean;
520 /** Repeating a call with the same arguments has no further effect. Meaningful when not read-only. */
521 idempotentHint?: boolean;
522 /** The tool reaches an open world of external entities, such as the web, rather than a closed domain. */
523 openWorldHint?: boolean;
524}
525
526/** A group of related tools, such as the tools of one MCP server. Codemode tools list them together. */
527export interface ToolNamespace {
528 /** For example `mcp__docs`. */
529 name: string;
530 /** Short summary shown once with the group in model-facing tool listings. */
531 description?: string;
532 /**
533 * Longer usage guidance, such as MCP server instructions. Not part of tool listings; tools that
534 * describe the namespace on request (codemode's `describeNamespace()`) return it.
535 */
536 instructions?: string;
537}
538
539/** The tools of a session as {@link ToolDefinition.prepareLoadout} sees them. */
540export interface ToolLoadout {
541 /** Tools declared to the model (the active tools), in order, with their original descriptions. */
542 readonly declared: readonly AgentTool[];
543 /** Tools callable through `ctx.executeTool()`. */
544 readonly callable: readonly AgentTool[];
545 /** Every registered tool. */
546 readonly registered: readonly AgentTool[];
547 getExposure(name: string): ToolExposure;
548 getNamespace(name: string): ToolNamespace | undefined;
549}
550
551/** Changes {@link ToolDefinition.prepareLoadout} makes to what the model sees. */
552export interface ToolLoadoutChanges {
553 /** Model-facing descriptions of declared tools, by tool name. */
554 descriptions?: Readonly<Record<string, string>>;
555 /**
556 * Declared tools whose declarations requests leave out. They stay active and callable, and the
557 * transcript still declares them, so the active set survives `/tree` and resume.
558 */
559 hiddenDeclarations?: readonly string[];
560}
561
562/**
563 * Tool definition for registerTool().
564 */
565export interface ToolDefinition<TParams extends TSchema = TSchema, TDetails = unknown, TState = any> {
566 /** Tool name (used in LLM tool calls) */
567 name: string;
568 /** Human-readable label for UI */
569 label: string;
570 /** Description for LLM */
571 description: string;
572 /** 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. */
573 promptSnippet?: string;
574 /** Optional guideline bullets appended to the default system prompt Guidelines section when this tool is active. */
575 promptGuidelines?: string[];
576 /** Parameter schema (TypeBox) */
577 parameters: TParams;
578 /** Optional provider-side constrained sampling request for this tool. Set false to explicitly disable it, equivalent to leaving it undefined. */
579 constrainedSampling?: false | ConstrainedSamplingConfig;
580 /** Controls whether ToolExecutionComponent renders the standard colored shell or the tool renders its own framing. */
581 renderShell?: "default" | "self";
582
583 /** Optional compatibility shim to prepare raw tool call arguments before schema validation. Must return an object conforming to TParams. */
584 prepareArguments?: (args: unknown) => Static<TParams>;
585
586 /**
587 * JSON Schema of `structuredContent` in successful results. Tools that declare it should always
588 * set `structuredContent`; codemode scripts then receive it instead of the text content.
589 */
590 outputSchema?: TSchema;
591
592 /**
593 * How the model reaches the tool. Default: `"direct"`. See {@link ToolExposure}.
594 */
595 exposure?: ToolExposure;
596
597 /** Group the tool belongs to, for example its MCP server. */
598 namespace?: ToolNamespace;
599
600 /** Hints about what the tool does, for example from an MCP server. */
601 annotations?: ToolAnnotations;
602
603 /**
604 * Whether registering the tool activates it. Default: `true` for `direct` and `model-only` tools;
605 * other exposures are never activated on registration. A tool with `defaultActive: false` is
606 * activated by naming it in `--tools` or the `defaultTools` setting, or with `setActiveTools()`.
607 */
608 defaultActive?: boolean;
609
610 /**
611 * Adjust how the loadout is presented to the model while this tool is active. Called whenever
612 * the active tools change. Tools that orchestrate other tools use it, for example to list the
613 * callable tools in their own description.
614 */
615 prepareLoadout?: (loadout: ToolLoadout) => ToolLoadoutChanges | undefined;
616
617 /**
618 * Per-tool execution mode override.
619 * - "sequential": this tool must execute one at a time with other tool calls.
620 * - "parallel": this tool can execute concurrently with other tool calls.
621 *
622 * If omitted, the default execution mode applies.
623 */
624 executionMode?: ToolExecutionMode;
625
626 /** Execute the tool. */
627 execute(
628 toolCallId: string,
629 params: Static<TParams>,
630 signal: AbortSignal | undefined,
631 onUpdate: AgentToolUpdateCallback<TDetails> | undefined,
632 ctx: ExtensionToolContext,
633 ): Promise<AgentToolResult<TDetails>>;
634
635 /** Custom rendering for tool call display */
636 renderCall?: (args: Static<TParams>, theme: Theme, context: ToolRenderContext<TState, Static<TParams>>) => Component;
637
638 /** Custom rendering for tool result display */
639 renderResult?: (
640 result: AgentToolResult<TDetails>,
641 options: ToolRenderResultOptions,
642 theme: Theme,
643 context: ToolRenderContext<TState, Static<TParams>>,
644 ) => Component;
645}
646
647type AnyToolDefinition = ToolDefinition<any, any, any>;
648
649export type ToolRenderers = Pick<AnyToolDefinition, "renderShell" | "renderCall" | "renderResult">;
650
651/**
652 * Chooses how calls to a tool are drawn, including tools that are not registered. `next()` returns
653 * the renderers the remaining resolvers, then the registered tool, would use.
654 */
655export type ToolRendererResolver = (
656 toolName: string,
657 next: () => ToolRenderers | undefined,
658) => ToolRenderers | undefined;
659
660/**
661 * Preserve parameter inference for standalone tool definitions.
662 *
663 * Use this when assigning a tool to a variable or passing it through arrays such
664 * as `customTools`, where contextual typing would otherwise widen params to
665 * `unknown`.
666 */
667export function defineTool<TParams extends TSchema, TDetails = unknown, TState = any>(
668 tool: ToolDefinition<TParams, TDetails, TState>,
669): ToolDefinition<TParams, TDetails, TState> & AnyToolDefinition {
670 return tool as ToolDefinition<TParams, TDetails, TState> & AnyToolDefinition;
671}
672
673// ============================================================================
674// Startup/Resource Events
675// ============================================================================
676
677export interface ProjectTrustEvent {
678 type: "project_trust";
679 cwd: string;
680}
681
682export type ProjectTrustEventDecision = "yes" | "no" | "undecided";
683
684export interface ProjectTrustEventResult {
685 trusted: ProjectTrustEventDecision;
686 remember?: boolean;
687}
688
689export interface ProjectTrustContext {
690 cwd: string;
691 mode: ExtensionMode;
692 hasUI: boolean;
693 ui: Pick<ExtensionUIContext, "select" | "confirm" | "input" | "notify">;
694}
695
696export type ProjectTrustHandler = (
697 event: ProjectTrustEvent,
698 ctx: ProjectTrustContext,
699) => Promise<ProjectTrustEventResult> | ProjectTrustEventResult;
700
701/** Fired after session_start to allow extensions to provide additional resource paths. */
702export interface ResourcesDiscoverEvent {
703 type: "resources_discover";
704 cwd: string;
705 reason: "startup" | "reload";
706}
707
708/** Result from resources_discover event handler */
709export interface ResourcesDiscoverResult {
710 skillPaths?: string[];
711 promptPaths?: string[];
712 themePaths?: string[];
713}
714
715/**
716 * Fired when an extension registers or unregisters an MCP server after the extensions are bound
717 * (see {@link ExtensionAPI.registerMcpServer}). Servers registered while extensions load are read
718 * with `pi.getMcpServers()` on `session_start`. Handling this event marks an extension as the one
719 * that connects registered servers.
720 */
721export interface McpServersChangeEvent {
722 type: "mcp_servers_change";
723 /** Every registered server after the change. */
724 servers: RegisteredMcpServer[];
725}
726
727// ============================================================================
728// Session Events
729// ============================================================================
730
731/** Fired when a session is started, loaded, or reloaded */
732export interface SessionStartEvent {
733 type: "session_start";
734 /** Why this session start happened. */
735 reason: "startup" | "reload" | "new" | "resume" | "fork";
736 /** Previously active session file. Present for "new", "resume", and "fork". */
737 previousSessionFile?: string;
738}
739
740/** Fired when the current session metadata changes. */
741export interface SessionInfoChangedEvent {
742 type: "session_info_changed";
743 /** Current normalized session name. Undefined when the name is cleared. */
744 name: string | undefined;
745}
746
747/** Fired before switching to another session (can be cancelled) */
748export interface SessionBeforeSwitchEvent {
749 type: "session_before_switch";
750 reason: "new" | "resume";
751 targetSessionFile?: string;
752}
753
754/** Fired before forking a session (can be cancelled) */
755export interface SessionBeforeForkEvent {
756 type: "session_before_fork";
757 entryId: string;
758 position: "before" | "at";
759}
760
761/** Fired before context compaction (can be cancelled or customized) */
762export interface SessionBeforeCompactEvent {
763 type: "session_before_compact";
764 preparation: CompactionPreparation;
765 branchEntries: SessionEntry[];
766 customInstructions?: string;
767 /** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */
768 reason: "manual" | "threshold" | "overflow";
769 /** True when the aborted turn is retried after this compaction (overflow recovery) */
770 willRetry: boolean;
771 signal: AbortSignal;
772}
773
774/** Fired after context compaction succeeds */
775export interface SessionCompactEvent {
776 type: "session_compact";
777 compactionEntry: CompactionEntry;
778 fromExtension: boolean;
779 /** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */
780 reason: "manual" | "threshold" | "overflow";
781 /** True when the aborted turn is retried after this compaction (overflow recovery) */
782 willRetry: boolean;
783}
784
785/** Fired after context compaction fails or is aborted */
786export interface SessionCompactFailedEvent {
787 type: "session_compact_failed";
788 /** What triggered the compaction: manual /compact, the context threshold, or context overflow recovery */
789 reason: "manual" | "threshold" | "overflow";
790 /** Error text when compaction failed for a non-abort reason. */
791 errorMessage?: string;
792 /** True when compaction was cancelled or aborted. */
793 aborted: boolean;
794 /** True when the aborted turn would have been retried after this compaction (overflow recovery) */
795 willRetry: boolean;
796 /** True when the failing compaction content came from a session_before_compact handler. */
797 fromExtension: boolean;
798}
799
800/** Fired before an extension runtime is torn down due to quit, reload, or session replacement. */
801export interface SessionShutdownEvent {
802 type: "session_shutdown";
803 reason: "quit" | "reload" | "new" | "resume" | "fork";
804 /** Destination session file when shutting down due to session replacement. */
805 targetSessionFile?: string;
806}
807
808/** Preparation data for tree navigation */
809export interface TreePreparation {
810 targetId: string;
811 oldLeafId: string | null;
812 commonAncestorId: string | null;
813 entriesToSummarize: SessionEntry[];
814 userWantsSummary: boolean;
815 /** Custom instructions for summarization */
816 customInstructions?: string;
817 /** If true, customInstructions replaces the default prompt instead of being appended */
818 replaceInstructions?: boolean;
819 /** Label to attach to the branch summary entry */
820 label?: string;
821}
822
823/** Fired before navigating in the session tree (can be cancelled) */
824export interface SessionBeforeTreeEvent {
825 type: "session_before_tree";
826 preparation: TreePreparation;
827 signal: AbortSignal;
828}
829
830/** Fired after navigating in the session tree */
831export interface SessionTreeEvent {
832 type: "session_tree";
833 newLeafId: string | null;
834 oldLeafId: string | null;
835 summaryEntry?: BranchSummaryEntry;
836 fromExtension?: boolean;
837}
838
839export type SessionEvent =
840 | SessionStartEvent
841 | SessionInfoChangedEvent
842 | SessionBeforeSwitchEvent
843 | SessionBeforeForkEvent
844 | SessionBeforeCompactEvent
845 | SessionCompactEvent
846 | SessionCompactFailedEvent
847 | SessionShutdownEvent
848 | SessionBeforeTreeEvent
849 | SessionTreeEvent;
850
851// ============================================================================
852// Agent Events
853// ============================================================================
854
855/**
856 * Fired before each LLM call. Can modify messages.
857 *
858 * `messages` holds the conversation without system messages. The prompt and tool state
859 * belong to Pi: it restores them after the handler returns, so a handler cannot drop
860 * them and does not need to preserve them.
861 */
862export interface ContextEvent {
863 type: "context";
864 messages: AgentMessage[];
865}
866
867/**
868 * Fired before each LLM call, after every `context` handler has run and Pi has restored
869 * the prompt and tool state. `messages` is the full transcript including system messages,
870 * and the result is sent as returned: the handler owns the prompt and tool declarations.
871 */
872export interface ContextWithSystemEvent {
873 type: "context_with_system";
874 messages: AgentMessage[];
875}
876
877/** Fired before a provider request is sent. Can replace the payload. */
878export interface BeforeProviderRequestEvent {
879 type: "before_provider_request";
880 payload: unknown;
881}
882
883/**
884 * Fired after request headers are assembled, before the provider HTTP call.
885 * Handlers mutate `headers` in place (e.g. to inject tracing/session headers);
886 * the return value is ignored. A `null` value deletes that header.
887 */
888export interface BeforeProviderHeadersEvent {
889 type: "before_provider_headers";
890 headers: ProviderHeaders;
891}
892
893/** Fired after a provider response is received and before the response stream is consumed. */
894export interface AfterProviderResponseEvent {
895 type: "after_provider_response";
896 status: number;
897 headers: Record<string, string>;
898}
899
900/** Fired for a parsed provider stream event before Pi normalizes it. */
901export interface ProviderStreamEvent {
902 type: "provider_stream_event";
903 provider: ProviderId;
904 api: Api;
905 model: string;
906 data: unknown;
907}
908
909/** Fired after user submits prompt but before agent loop. */
910export interface BeforeAgentStartEvent {
911 type: "before_agent_start";
912 /** The raw user prompt text (after expansion). */
913 prompt: string;
914 /** Images attached to the user prompt, if any. */
915 images?: ImageContent[];
916 /** The current system prompt, rendered from systemPromptOptions and earlier handler changes. */
917 readonly systemPrompt: string;
918 /** Mutable prompt sections. Later handlers observe mutations made by earlier handlers. */
919 systemPromptOptions: NormalizedBuildSystemPromptOptions;
920}
921
922/** Fired when an agent loop starts */
923export interface AgentStartEvent {
924 type: "agent_start";
925}
926
927/** Fired when an agent loop ends */
928export interface AgentEndEvent {
929 type: "agent_end";
930 messages: AgentMessage[];
931}
932
933export type AgentActivityOutcome = "completed" | "aborted" | "error";
934
935export interface CustomEntryDraft {
936 type: "custom";
937 customType: string;
938 data?: unknown;
939}
940
941export interface CustomMessageEntryDraft {
942 type: "custom_message";
943 customType: string;
944 content: string | (TextContent | ImageContent)[];
945 display: boolean;
946 details?: unknown;
947}
948
949export interface ContextEditEntryDraft {
950 type: "context_edit";
951 targetId: string;
952 replacement: ContextEditEntry["replacement"];
953}
954
955export interface CompactionEntryDraft {
956 type: "compaction";
957 summary: string;
958 /** Null creates a self-retaining compaction that keeps no preceding entries. */
959 firstKeptEntryId: string | null;
960 details?: unknown;
961 usage?: Usage;
962}
963
964export type SessionBoundaryDraft =
965 | CustomEntryDraft
966 | CustomMessageEntryDraft
967 | ContextEditEntryDraft
968 | CompactionEntryDraft;
969
970export interface BoundaryContextPreview {
971 contextEntries: ProjectedSessionEntry[];
972 contextMessages: AgentMessage[];
973 llmMessages: Message[];
974 pendingMessages: AgentMessage[];
975 canContinue: boolean;
976}
977
978export interface BoundaryState {
979 entries: SessionBoundaryDraft[];
980 continue: boolean;
981 context: BoundaryContextPreview;
982 outcome: AgentActivityOutcome;
983}
984
985export interface BoundaryResult {
986 entries?: SessionBoundaryDraft[];
987 continue?: boolean;
988}
989
990/** Fired before final settlement. May append entries and ensure one next provider request. */
991export interface AgentBeforeSettleEvent extends BoundaryState {
992 type: "agent_before_settle";
993}
994
995/** Fired after an agent run has fully settled and no automatic retry, compaction, or queued continuation will run. */
996export interface AgentSettledEvent {
997 type: "agent_settled";
998}
999
1000export type UIPromptKind = "select" | "confirm" | "input" | "editor" | "custom";
1001
1002/** Fired when Pi starts waiting on a blocking user-facing extension UI prompt. */
1003export interface UIPromptStartEvent {
1004 type: "ui_prompt_start";
1005 reason: "ui_prompt";
1006 kind: UIPromptKind;
1007 title?: string;
1008}
1009
1010/** Fired when Pi is no longer waiting on a blocking user-facing extension UI prompt. */
1011export interface UIPromptEndEvent {
1012 type: "ui_prompt_end";
1013 reason: "ui_prompt";
1014 kind: UIPromptKind;
1015 title?: string;
1016}
1017
1018/** Fired at the start of each turn */
1019export interface TurnStartEvent {
1020 type: "turn_start";
1021 turnIndex: number;
1022 timestamp: number;
1023}
1024
1025/** Fired at the end of each turn */
1026export interface TurnEndEvent extends BoundaryState {
1027 type: "turn_end";
1028 turnIndex: number;
1029 message: AgentMessage;
1030 toolResults: ToolResultMessage[];
1031 messageEntryId: string;
1032 toolResultEntryIds: string[];
1033}
1034
1035/** Fired when a message starts (user, assistant, or toolResult) */
1036export interface MessageStartEvent {
1037 type: "message_start";
1038 message: AgentMessage;
1039}
1040
1041/** Fired during assistant message streaming with token-by-token updates */
1042export interface MessageUpdateEvent {
1043 type: "message_update";
1044 message: AgentMessage;
1045 assistantMessageEvent: AssistantMessageEvent;
1046}
1047
1048/** Fired when a message ends */
1049export interface MessageEndEvent {
1050 type: "message_end";
1051 message: AgentMessage;
1052}
1053
1054/** Fired when a tool starts executing */
1055export interface ToolExecutionStartEvent {
1056 type: "tool_execution_start";
1057 toolCallId: string;
1058 toolName: string;
1059 args: any;
1060 /** Set when another tool (for example a codemode script) made this call. */
1061 parentToolCallId?: string;
1062}
1063
1064/** Fired during tool execution with partial/streaming output */
1065export interface ToolExecutionUpdateEvent {
1066 type: "tool_execution_update";
1067 toolCallId: string;
1068 toolName: string;
1069 args: any;
1070 partialResult: any;
1071 /** Set when another tool (for example a codemode script) made this call. */
1072 parentToolCallId?: string;
1073}
1074
1075/** Fired when a tool finishes executing */
1076export interface ToolExecutionEndEvent {
1077 type: "tool_execution_end";
1078 toolCallId: string;
1079 toolName: string;
1080 result: any;
1081 isError: boolean;
1082 /** Set when another tool (for example a codemode script) made this call. */
1083 parentToolCallId?: string;
1084}
1085
1086// ============================================================================
1087// Model Events
1088// ============================================================================
1089
1090export type ModelSelectSource = "set" | "cycle" | "restore";
1091
1092/** Fired when a new model is selected */
1093export interface ModelSelectEvent {
1094 type: "model_select";
1095 model: Model<any>;
1096 previousModel: Model<any> | undefined;
1097 source: ModelSelectSource;
1098}
1099
1100/** Fired when a new thinking level is selected */
1101export interface ThinkingLevelSelectEvent {
1102 type: "thinking_level_select";
1103 level: ThinkingLevel;
1104 previousLevel: ThinkingLevel;
1105}
1106
1107// ============================================================================
1108// User Bash Events
1109// ============================================================================
1110
1111/** Fired when user executes a bash command via ! or !! prefix */
1112export interface UserBashEvent {
1113 type: "user_bash";
1114 /** The command to execute */
1115 command: string;
1116 /** True if !! prefix was used (excluded from LLM context) */
1117 excludeFromContext: boolean;
1118 /** Current working directory */
1119 cwd: string;
1120}
1121
1122// ============================================================================
1123// Input Events
1124// ============================================================================
1125
1126/** Source of user input */
1127export type InputSource = "interactive" | "rpc" | "extension";
1128
1129/** Fired when user input is received, before agent processing */
1130export interface InputEvent {
1131 type: "input";
1132 /** The input text */
1133 text: string;
1134 /** Attached images, if any */
1135 images?: ImageContent[];
1136 /** Where the input came from */
1137 source: InputSource;
1138 /** How the input will be delivered during streaming, or undefined when idle */
1139 streamingBehavior?: "steer" | "followUp";
1140}
1141
1142/** Result from input event handler */
1143export type InputEventResult =
1144 | { action: "continue" }
1145 | { action: "transform"; text: string; images?: ImageContent[] }
1146 | { action: "handled" };
1147
1148// ============================================================================
1149// Tool Events
1150// ============================================================================
1151
1152interface ToolCallEventBase {
1153 type: "tool_call";
1154 /**
1155 * The call's id. For calls another tool made (with `parentToolCallId` set), pi assigns
1156 * `<parent id>/<n>`; such ids never appear as tool calls or tool results in the transcript, only
1157 * in the parent result's `nestedCalls` record.
1158 */
1159 toolCallId: string;
1160 /** Set when another tool (for example a codemode script) issued this call. */
1161 parentToolCallId?: string;
1162}
1163
1164export interface BashToolCallEvent extends ToolCallEventBase {
1165 toolName: "bash";
1166 input: BashToolInput;
1167}
1168
1169export interface PowerShellToolCallEvent extends ToolCallEventBase {
1170 toolName: "powershell";
1171 input: PowerShellToolInput;
1172}
1173
1174export interface ReadToolCallEvent extends ToolCallEventBase {
1175 toolName: "read";
1176 input: ReadToolInput;
1177}
1178
1179export interface EditToolCallEvent extends ToolCallEventBase {
1180 toolName: "edit";
1181 input: EditToolInput;
1182}
1183
1184export interface WriteToolCallEvent extends ToolCallEventBase {
1185 toolName: "write";
1186 input: WriteToolInput;
1187}
1188
1189export interface GrepToolCallEvent extends ToolCallEventBase {
1190 toolName: "grep";
1191 input: GrepToolInput;
1192}
1193
1194export interface FindToolCallEvent extends ToolCallEventBase {
1195 toolName: "find";
1196 input: FindToolInput;
1197}
1198
1199export interface LsToolCallEvent extends ToolCallEventBase {
1200 toolName: "ls";
1201 input: LsToolInput;
1202}
1203
1204export interface CustomToolCallEvent extends ToolCallEventBase {
1205 toolName: string;
1206 input: Record<string, unknown>;
1207}
1208
1209/**
1210 * Fired before a tool executes. Can block.
1211 *
1212 * `event.input` is mutable. Mutate it in place to patch tool arguments before execution.
1213 * Later `tool_call` handlers see earlier mutations. No re-validation is performed after mutation.
1214 */
1215export type ToolCallEvent =
1216 | BashToolCallEvent
1217 | PowerShellToolCallEvent
1218 | ReadToolCallEvent
1219 | EditToolCallEvent
1220 | WriteToolCallEvent
1221 | GrepToolCallEvent
1222 | FindToolCallEvent
1223 | LsToolCallEvent
1224 | CustomToolCallEvent;
1225
1226interface ToolResultEventBase {
1227 type: "tool_result";
1228 /** The call's id; `<parent id>/<n>` for nested calls, see `ToolCallEvent`. */
1229 toolCallId: string;
1230 /** Set when another tool (for example a codemode script) issued this call. */
1231 parentToolCallId?: string;
1232 input: Record<string, unknown>;
1233 content: (TextContent | ImageContent)[];
1234 /**
1235 * Machine-readable result for tools that declare an `outputSchema`. Handlers that redact
1236 * `content` should also replace this; replacing `content` alone drops it.
1237 */
1238 structuredContent?: JsonValue;
1239 isError: boolean;
1240 /** Usage from the tool execution itself, if available. */
1241 usage?: Usage;
1242}
1243
1244export interface BashToolResultEvent extends ToolResultEventBase {
1245 toolName: "bash";
1246 details: BashToolDetails | undefined;
1247}
1248
1249export interface PowerShellToolResultEvent extends ToolResultEventBase {
1250 toolName: "powershell";
1251 details: PowerShellToolDetails | undefined;
1252}
1253
1254export interface ReadToolResultEvent extends ToolResultEventBase {
1255 toolName: "read";
1256 details: ReadToolDetails | undefined;
1257}
1258
1259export interface EditToolResultEvent extends ToolResultEventBase {
1260 toolName: "edit";
1261 details: EditToolDetails | undefined;
1262}
1263
1264export interface WriteToolResultEvent extends ToolResultEventBase {
1265 toolName: "write";
1266 details: undefined;
1267}
1268
1269export interface GrepToolResultEvent extends ToolResultEventBase {
1270 toolName: "grep";
1271 details: GrepToolDetails | undefined;
1272}
1273
1274export interface FindToolResultEvent extends ToolResultEventBase {
1275 toolName: "find";
1276 details: FindToolDetails | undefined;
1277}
1278
1279export interface LsToolResultEvent extends ToolResultEventBase {
1280 toolName: "ls";
1281 details: LsToolDetails | undefined;
1282}
1283
1284export interface CustomToolResultEvent extends ToolResultEventBase {
1285 toolName: string;
1286 details: unknown;
1287}
1288
1289/** Fired after a tool executes. Can modify result. */
1290export type ToolResultEvent =
1291 | BashToolResultEvent
1292 | PowerShellToolResultEvent
1293 | ReadToolResultEvent
1294 | EditToolResultEvent
1295 | WriteToolResultEvent
1296 | GrepToolResultEvent
1297 | FindToolResultEvent
1298 | LsToolResultEvent
1299 | CustomToolResultEvent;
1300
1301// Type guards for ToolResultEvent
1302export function isBashToolResult(e: ToolResultEvent): e is BashToolResultEvent {
1303 return e.toolName === "bash";
1304}
1305export function isPowerShellToolResult(e: ToolResultEvent): e is PowerShellToolResultEvent {
1306 return e.toolName === "powershell";
1307}
1308export function isReadToolResult(e: ToolResultEvent): e is ReadToolResultEvent {
1309 return e.toolName === "read";
1310}
1311export function isEditToolResult(e: ToolResultEvent): e is EditToolResultEvent {
1312 return e.toolName === "edit";
1313}
1314export function isWriteToolResult(e: ToolResultEvent): e is WriteToolResultEvent {
1315 return e.toolName === "write";
1316}
1317export function isGrepToolResult(e: ToolResultEvent): e is GrepToolResultEvent {
1318 return e.toolName === "grep";
1319}
1320export function isFindToolResult(e: ToolResultEvent): e is FindToolResultEvent {
1321 return e.toolName === "find";
1322}
1323export function isLsToolResult(e: ToolResultEvent): e is LsToolResultEvent {
1324 return e.toolName === "ls";
1325}
1326
1327/**
1328 * Type guard for narrowing ToolCallEvent by tool name.
1329 *
1330 * Built-in tools narrow automatically (no type params needed):
1331 * ```ts
1332 * if (isToolCallEventType("bash", event)) {
1333 * event.input.command; // string
1334 * }
1335 * ```
1336 *
1337 * Custom tools require explicit type parameters:
1338 * ```ts
1339 * if (isToolCallEventType<"my_tool", MyToolInput>("my_tool", event)) {
1340 * event.input.action; // typed
1341 * }
1342 * ```
1343 *
1344 * Note: Direct narrowing via `event.toolName === "bash"` doesn't work because
1345 * CustomToolCallEvent.toolName is `string` which overlaps with all literals.
1346 */
1347export function isToolCallEventType(toolName: "bash", event: ToolCallEvent): event is BashToolCallEvent;
1348export function isToolCallEventType(toolName: "powershell", event: ToolCallEvent): event is PowerShellToolCallEvent;
1349export function isToolCallEventType(toolName: "read", event: ToolCallEvent): event is ReadToolCallEvent;
1350export function isToolCallEventType(toolName: "edit", event: ToolCallEvent): event is EditToolCallEvent;
1351export function isToolCallEventType(toolName: "write", event: ToolCallEvent): event is WriteToolCallEvent;
1352export function isToolCallEventType(toolName: "grep", event: ToolCallEvent): event is GrepToolCallEvent;
1353export function isToolCallEventType(toolName: "find", event: ToolCallEvent): event is FindToolCallEvent;
1354export function isToolCallEventType(toolName: "ls", event: ToolCallEvent): event is LsToolCallEvent;
1355export function isToolCallEventType<TName extends string, TInput extends Record<string, unknown>>(
1356 toolName: TName,
1357 event: ToolCallEvent,
1358): event is ToolCallEvent & { toolName: TName; input: TInput };
1359export function isToolCallEventType(toolName: string, event: ToolCallEvent): boolean {
1360 return event.toolName === toolName;
1361}
1362
1363/** Union of all event types */
1364export type ExtensionEvent =
1365 | ProjectTrustEvent
1366 | ResourcesDiscoverEvent
1367 | McpServersChangeEvent
1368 | SessionEvent
1369 | ContextEvent
1370 | ContextWithSystemEvent
1371 | CacheWarmingDecisionEvent
1372 | BeforeProviderRequestEvent
1373 | BeforeProviderHeadersEvent
1374 | AfterProviderResponseEvent
1375 | ProviderStreamEvent
1376 | BeforeAgentStartEvent
1377 | AgentStartEvent
1378 | AgentEndEvent
1379 | AgentBeforeSettleEvent
1380 | AgentSettledEvent
1381 | UIPromptStartEvent
1382 | UIPromptEndEvent
1383 | TurnStartEvent
1384 | TurnEndEvent
1385 | MessageStartEvent
1386 | MessageUpdateEvent
1387 | MessageEndEvent
1388 | ToolExecutionStartEvent
1389 | ToolExecutionUpdateEvent
1390 | ToolExecutionEndEvent
1391 | ModelSelectEvent
1392 | ThinkingLevelSelectEvent
1393 | UserBashEvent
1394 | InputEvent
1395 | ToolCallEvent
1396 | ToolResultEvent;
1397
1398// ============================================================================
1399// Event Results
1400// ============================================================================
1401
1402export interface ContextEventResult {
1403 messages?: AgentMessage[];
1404}
1405
1406export type TurnEndEventResult = BoundaryResult;
1407export type AgentBeforeSettleEventResult = BoundaryResult;
1408
1409export type BeforeProviderRequestEventResult = unknown;
1410
1411export type { CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult } from "../cache-warmer.ts";
1412
1413export interface ToolCallEventResult {
1414 /** Block tool execution. To modify arguments, mutate `event.input` in place instead. */
1415 block?: boolean;
1416 reason?: string;
1417 /**
1418 * Hint that the agent should stop after the current tool batch when this call is blocked.
1419 * Early termination only happens when every finalized tool result in the batch sets this to true.
1420 */
1421 terminate?: boolean;
1422}
1423
1424/** Result from user_bash event handler */
1425export type UserBashEventResult =
1426 | {
1427 /** Custom operations to use for execution */
1428 operations: BashOperations;
1429 result?: never;
1430 }
1431 | {
1432 operations?: never;
1433 /** Full replacement: extension handled execution, use this result */
1434 result: BashResult;
1435 };
1436
1437/**
1438 * Changes a `tool_result` handler makes. Omitted fields stay as they are, except that replacing
1439 * `content` without returning `structuredContent` drops the structured content, because it may no
1440 * longer match. Return it along with `content` to keep it.
1441 */
1442export interface ToolResultEventResult {
1443 content?: (TextContent | ImageContent)[];
1444 details?: unknown;
1445 structuredContent?: JsonValue;
1446 isError?: boolean;
1447 usage?: Usage;
1448}
1449
1450export interface MessageEndEventResult {
1451 /** Replace the finalized message. The replacement must keep the original message role. */
1452 message?: AgentMessage;
1453}
1454
1455export interface BeforeAgentStartEventResult {
1456 message?: Pick<CustomMessage, "customType" | "content" | "display" | "details">;
1457 /** Replace the complete system prompt for this turn. Later handlers observe this exact override. */
1458 systemPrompt?: string;
1459}
1460
1461export interface SessionBeforeSwitchResult {
1462 cancel?: boolean;
1463}
1464
1465export interface SessionBeforeForkResult {
1466 cancel?: boolean;
1467 skipConversationRestore?: boolean;
1468}
1469
1470export interface SessionBeforeCompactResult {
1471 cancel?: boolean;
1472 compaction?: CompactionResult;
1473}
1474
1475export interface SessionBeforeTreeResult {
1476 cancel?: boolean;
1477 summary?: {
1478 summary: string;
1479 details?: unknown;
1480 usage?: Usage;
1481 };
1482 /** Override custom instructions for summarization */
1483 customInstructions?: string;
1484 /** Override whether customInstructions replaces the default prompt */
1485 replaceInstructions?: boolean;
1486 /** Override label to attach to the branch summary entry */
1487 label?: string;
1488}
1489
1490// ============================================================================
1491// Message and Entry Rendering
1492// ============================================================================
1493
1494export interface MessageRenderOptions {
1495 expanded: boolean;
1496 /** Horizontal padding configured by the outputPad setting. */
1497 outputPad: number;
1498}
1499
1500export interface MarkdownTransformContext {
1501 messageType: "user" | "assistant" | "assistant-thinking";
1502 isStreaming: boolean;
1503 availableWidth: number;
1504}
1505
1506export type MarkdownTransformer = (markdown: string, context: MarkdownTransformContext) => string;
1507
1508export interface EntryRenderOptions {
1509 expanded: boolean;
1510}
1511
1512export type MessageRenderer<T = unknown> = (
1513 message: CustomMessage<T>,
1514 options: MessageRenderOptions,
1515 theme: Theme,
1516) => Component | undefined;
1517
1518export type EntryRenderer<T = unknown> = (
1519 entry: CustomEntry<T>,
1520 options: EntryRenderOptions,
1521 theme: Theme,
1522) => Component | undefined;
1523
1524// ============================================================================
1525// Command Registration
1526// ============================================================================
1527
1528export interface RegisteredCommand {
1529 name: string;
1530 sourceInfo: SourceInfo;
1531 description?: string;
1532 getArgumentCompletions?: (argumentPrefix: string) => AutocompleteItem[] | null | Promise<AutocompleteItem[] | null>;
1533 handler: (args: string, ctx: ExtensionCommandContext) => Promise<void>;
1534}
1535
1536export interface ResolvedCommand extends RegisteredCommand {
1537 invocationName: string;
1538}
1539
1540// ============================================================================
1541// Extension API
1542// ============================================================================
1543
1544/** Handler function type for events */
1545// biome-ignore lint/suspicious/noConfusingVoidType: void allows bare return statements
1546export type ExtensionHandler<E, R = undefined> = (event: E, ctx: ExtensionContext) => Promise<R | void> | R | void;
1547
1548/**
1549 * ExtensionAPI passed to extension factory functions.
1550 */
1551export interface ExtensionAPI {
1552 // =========================================================================
1553 // Event Subscription
1554 // =========================================================================
1555
1556 on(event: "project_trust", handler: ProjectTrustHandler): () => void;
1557 on(
1558 event: "resources_discover",
1559 handler: ExtensionHandler<ResourcesDiscoverEvent, ResourcesDiscoverResult>,
1560 ): () => void;
1561 on(event: "session_start", handler: ExtensionHandler<SessionStartEvent>): () => void;
1562 on(event: "session_info_changed", handler: ExtensionHandler<SessionInfoChangedEvent>): () => void;
1563 on(
1564 event: "session_before_switch",
1565 handler: ExtensionHandler<SessionBeforeSwitchEvent, SessionBeforeSwitchResult>,
1566 ): () => void;
1567 on(
1568 event: "session_before_fork",
1569 handler: ExtensionHandler<SessionBeforeForkEvent, SessionBeforeForkResult>,
1570 ): () => void;
1571 on(
1572 event: "session_before_compact",
1573 handler: ExtensionHandler<SessionBeforeCompactEvent, SessionBeforeCompactResult>,
1574 ): () => void;
1575 on(event: "session_compact", handler: ExtensionHandler<SessionCompactEvent>): () => void;
1576 on(event: "session_compact_failed", handler: ExtensionHandler<SessionCompactFailedEvent>): () => void;
1577 on(event: "session_shutdown", handler: ExtensionHandler<SessionShutdownEvent>): () => void;
1578 on(event: "mcp_servers_change", handler: ExtensionHandler<McpServersChangeEvent>): () => void;
1579 on(
1580 event: "session_before_tree",
1581 handler: ExtensionHandler<SessionBeforeTreeEvent, SessionBeforeTreeResult>,
1582 ): () => void;
1583 on(event: "session_tree", handler: ExtensionHandler<SessionTreeEvent>): () => void;
1584 on(event: "context", handler: ExtensionHandler<ContextEvent, ContextEventResult>): () => void;
1585 on(event: "context_with_system", handler: ExtensionHandler<ContextWithSystemEvent, ContextEventResult>): () => void;
1586 on(
1587 event: "cache_warming_decision",
1588 handler: ExtensionHandler<CacheWarmingDecisionEvent, CacheWarmingDecisionEventResult>,
1589 ): () => void;
1590 on(
1591 event: "before_provider_request",
1592 handler: ExtensionHandler<BeforeProviderRequestEvent, BeforeProviderRequestEventResult>,
1593 ): () => void;
1594 on(event: "before_provider_headers", handler: ExtensionHandler<BeforeProviderHeadersEvent>): () => void;
1595 on(event: "after_provider_response", handler: ExtensionHandler<AfterProviderResponseEvent>): () => void;
1596 on(event: "provider_stream_event", handler: ExtensionHandler<ProviderStreamEvent>): () => void;
1597 on(
1598 event: "before_agent_start",
1599 handler: ExtensionHandler<BeforeAgentStartEvent, BeforeAgentStartEventResult>,
1600 ): () => void;
1601 on(event: "agent_start", handler: ExtensionHandler<AgentStartEvent>): () => void;
1602 on(event: "agent_end", handler: ExtensionHandler<AgentEndEvent>): () => void;
1603 on(
1604 event: "agent_before_settle",
1605 handler: ExtensionHandler<AgentBeforeSettleEvent, AgentBeforeSettleEventResult>,
1606 ): () => void;
1607 on(event: "agent_settled", handler: ExtensionHandler<AgentSettledEvent>): () => void;
1608 on(event: "ui_prompt_start", handler: ExtensionHandler<UIPromptStartEvent>): () => void;
1609 on(event: "ui_prompt_end", handler: ExtensionHandler<UIPromptEndEvent>): () => void;
1610 on(event: "turn_start", handler: ExtensionHandler<TurnStartEvent>): () => void;
1611 on(event: "turn_end", handler: ExtensionHandler<TurnEndEvent, TurnEndEventResult>): () => void;
1612 on(event: "message_start", handler: ExtensionHandler<MessageStartEvent>): () => void;
1613 on(event: "message_update", handler: ExtensionHandler<MessageUpdateEvent>): () => void;
1614 on(event: "message_end", handler: ExtensionHandler<MessageEndEvent, MessageEndEventResult>): () => void;
1615 on(event: "tool_execution_start", handler: ExtensionHandler<ToolExecutionStartEvent>): () => void;
1616 on(event: "tool_execution_update", handler: ExtensionHandler<ToolExecutionUpdateEvent>): () => void;
1617 on(event: "tool_execution_end", handler: ExtensionHandler<ToolExecutionEndEvent>): () => void;
1618 on(event: "model_select", handler: ExtensionHandler<ModelSelectEvent>): () => void;
1619 on(event: "thinking_level_select", handler: ExtensionHandler<ThinkingLevelSelectEvent>): () => void;
1620 on(event: "tool_call", handler: ExtensionHandler<ToolCallEvent, ToolCallEventResult>): () => void;
1621 on(event: "tool_result", handler: ExtensionHandler<ToolResultEvent, ToolResultEventResult>): () => void;
1622 on(event: "user_bash", handler: ExtensionHandler<UserBashEvent, UserBashEventResult>): () => void;
1623 on(event: "input", handler: ExtensionHandler<InputEvent, InputEventResult>): () => void;
1624
1625 // =========================================================================
1626 // Tool Registration
1627 // =========================================================================
1628
1629 /** Register a tool that the LLM can call. */
1630 registerTool<TParams extends TSchema = TSchema, TDetails = unknown, TState = any>(
1631 tool: ToolDefinition<TParams, TDetails, TState>,
1632 ): void;
1633
1634 // =========================================================================
1635 // Command, Shortcut, Flag Registration
1636 // =========================================================================
1637
1638 /** Register a custom command. */
1639 registerCommand(name: string, options: Omit<RegisteredCommand, "name" | "sourceInfo">): void;
1640
1641 /** Register a keyboard shortcut. */
1642 registerShortcut(
1643 shortcut: KeyId,
1644 options: {
1645 description?: string;
1646 handler: (ctx: ExtensionContext) => Promise<void> | void;
1647 },
1648 ): void;
1649
1650 /** Register a CLI flag. */
1651 registerFlag(
1652 name: string,
1653 options:
1654 | {
1655 description?: string;
1656 type: "boolean";
1657 default?: boolean;
1658 }
1659 | {
1660 description?: string;
1661 type: "string";
1662 default?: string;
1663 },
1664 ): void;
1665
1666 /** Get the value of a registered CLI flag. */
1667 getFlag(name: string): boolean | string | undefined;
1668
1669 // =========================================================================
1670 // Message Rendering
1671 // =========================================================================
1672
1673 /** Register a custom renderer for CustomMessageEntry. */
1674 registerMessageRenderer<T = unknown>(customType: string, renderer: MessageRenderer<T>): void;
1675
1676 /** Register a transformer for user and assistant Markdown before Pi renders it in the interactive transcript. */
1677 registerMarkdownTransformer(transformer: MarkdownTransformer): void;
1678
1679 /** Register a custom renderer for CustomEntry. Custom entries do not participate in LLM context. */
1680 registerEntryRenderer<T = unknown>(customType: string, renderer: EntryRenderer<T>): void;
1681
1682 /** Choose how tool calls are drawn. Resolvers run in extension load order. */
1683 registerToolRenderer(resolver: ToolRendererResolver): void;
1684
1685 // =========================================================================
1686 // Actions
1687 // =========================================================================
1688
1689 /** Send a custom message to the session. */
1690 sendMessage<T = unknown>(
1691 message: Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">,
1692 options?: { triggerTurn?: boolean; deliverAs?: "steer" | "followUp" | "nextTurn" },
1693 ): void;
1694
1695 /**
1696 * Send a user message to the agent. Always triggers a turn.
1697 * When the agent is streaming, use deliverAs to specify how to queue the message.
1698 * Set expandPromptTemplates to dispatch extension commands and expand skill commands and prompt templates.
1699 */
1700 sendUserMessage(
1701 content: string | (TextContent | ImageContent)[],
1702 options?: { deliverAs?: "steer" | "followUp"; expandPromptTemplates?: boolean },
1703 ): void;
1704
1705 /** Append a custom entry to the session for state persistence (not sent to LLM). */
1706 appendEntry<T = unknown>(customType: string, data?: T): void;
1707
1708 // =========================================================================
1709 // Session Metadata
1710 // =========================================================================
1711
1712 /** Set the session display name (shown in session selector). */
1713 setSessionName(name: string): void;
1714
1715 /** Get the current session name, if set. */
1716 getSessionName(): string | undefined;
1717
1718 /** Set or clear a label on an entry. Labels are user-defined markers for bookmarking/navigation. */
1719 setLabel(entryId: string, label: string | undefined): void;
1720
1721 /** Execute a shell command. */
1722 exec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;
1723
1724 /** Get the names of the active tools, which are the tools declared to the model. */
1725 getActiveTools(): string[];
1726
1727 /** Get all configured tools with parameter schema, prompt guidelines, exposure, and source metadata. */
1728 getAllTools(): ToolInfo[];
1729
1730 /** Get a copy of the effective settings (global and project settings merged, with overrides). */
1731 getSettings(): Settings;
1732
1733 /**
1734 * Set the active tools by name. Unknown and `hidden` tools are ignored. Tools with `codemode` or
1735 * `deferred` exposure stay callable from codemode scripts whether active or not.
1736 */
1737 setActiveTools(toolNames: string[]): void;
1738
1739 /** Get available slash commands in the current session. */
1740 getCommands(): SlashCommandInfo[];
1741
1742 // =========================================================================
1743 // Model and Thinking Level
1744 // =========================================================================
1745
1746 /**
1747 * Set the model for the current session without changing the configured default for new sessions.
1748 * Returns false if authentication is not configured for the model's provider.
1749 */
1750 setModel(model: Model<any>): Promise<boolean>;
1751
1752 /** Get current thinking level. */
1753 getThinkingLevel(): ThinkingLevel;
1754
1755 /**
1756 * Set the thinking level (clamped to model capabilities) for the current session without changing the configured default
1757 * for new sessions.
1758 */
1759 setThinkingLevel(level: ThinkingLevel): void;
1760
1761 // =========================================================================
1762 // Provider Registration
1763 // =========================================================================
1764
1765 /**
1766 * Register or override a model provider.
1767 *
1768 * If `models` is provided: replaces all existing models for this provider.
1769 * If only `baseUrl` is provided: overrides the URL for existing models.
1770 * If `oauth` is provided: registers OAuth provider for /login support.
1771 * If `streamSimple` is provided: registers a custom API stream handler.
1772 *
1773 * During initial extension load this call is queued and applied once the
1774 * runner has bound its context. After that it takes effect immediately, so
1775 * it is safe to call from command handlers or event callbacks without
1776 * requiring a `/reload`.
1777 *
1778 * @example
1779 * // Register a new provider with custom models
1780 * pi.registerProvider("my-proxy", {
1781 * baseUrl: "https://proxy.example.com",
1782 * apiKey: "$PROXY_API_KEY",
1783 * api: "anthropic-messages",
1784 * models: [
1785 * {
1786 * id: "claude-sonnet-4-20250514",
1787 * name: "Claude 4 Sonnet (proxy)",
1788 * reasoning: false,
1789 * input: ["text", "image"],
1790 * cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1791 * contextWindow: 200000,
1792 * maxTokens: 16384
1793 * }
1794 * ]
1795 * });
1796 *
1797 * @example
1798 * // Override baseUrl for an existing provider
1799 * pi.registerProvider("anthropic", {
1800 * baseUrl: "https://proxy.example.com"
1801 * });
1802 *
1803 * @example
1804 * // Register provider with OAuth support
1805 * pi.registerProvider("corporate-ai", {
1806 * baseUrl: "https://ai.corp.com",
1807 * api: "openai-responses",
1808 * models: [...],
1809 * oauth: {
1810 * name: "Corporate AI (SSO)",
1811 * async login(callbacks) { ... },
1812 * async refreshToken(credentials) { ... },
1813 * getApiKey(credentials) { return credentials.access; }
1814 * }
1815 * });
1816 */
1817 registerProvider(provider: Provider): void;
1818 registerProvider(name: string, config: ProviderConfig): void;
1819
1820 /**
1821 * Unregister a previously registered provider.
1822 *
1823 * Removes all models belonging to the named provider and restores any
1824 * built-in models that were overridden by it. Has no effect if the provider
1825 * is not currently registered.
1826 *
1827 * Like `registerProvider`, this takes effect immediately when called after
1828 * the initial load phase.
1829 *
1830 * @example
1831 * pi.unregisterProvider("my-proxy");
1832 */
1833 unregisterProvider(name: string): void;
1834
1835 // =========================================================================
1836 // MCP Servers
1837 // =========================================================================
1838
1839 /**
1840 * Register an MCP server for this session, with the same config as an `mcpServers` entry in
1841 * `mcp.json`. The server connects next to the configured servers: on `session_start` when
1842 * registered during extension load, right away when registered later. Registering a name again
1843 * replaces the extension's earlier registration.
1844 *
1845 * The registration is not saved; register again on every load. A server of the same name in
1846 * `mcp.json` takes precedence. Throws for invalid configs and for names another extension
1847 * registered. When no loaded extension handles MCP servers (for example because another MCP
1848 * extension replaced the built-in one), the registration is reported as an extension error.
1849 *
1850 * @example
1851 * pi.registerMcpServer("jira", { url: "https://mcp.example.com/jira" });
1852 */
1853 registerMcpServer(name: string, config: McpServerConfig): void;
1854
1855 /** Remove an MCP server this extension registered and close its connection. */
1856 unregisterMcpServer(name: string): void;
1857
1858 /** Every MCP server registered by extensions. For extensions that connect MCP servers. */
1859 getMcpServers(): RegisteredMcpServer[];
1860
1861 /**
1862 * Register a virtual model: a selectable catalog entry that routes each request to a physical
1863 * model. The selection (`ctx.model`, `model_change` entries) names the virtual model; assistant
1864 * messages record the physical model and thinking level the router picked.
1865 *
1866 * `provider` may be any provider id, including one with physical models, and may list several
1867 * virtual models. Registering the same provider and id again replaces the virtual model. See
1868 * docs/virtual-models.md.
1869 */
1870 registerVirtualModel<TState = unknown>(model: ExtensionVirtualModel<TState>): void;
1871
1872 /** Remove a virtual model registered with `registerVirtualModel()`. */
1873 unregisterVirtualModel(provider: string, id: string): void;
1874
1875 /** Shared event bus for extension communication. */
1876 events: EventBus;
1877}
1878
1879// ============================================================================
1880// Provider Registration Types
1881// ============================================================================
1882
1883/** Virtual model registered via pi.registerVirtualModel(). */
1884export interface ExtensionVirtualModel<TState = unknown> extends Omit<VirtualModelDefinition<TState>, "route"> {
1885 /** Like `VirtualModelDefinition.route`, with an extension context. */
1886 route(request: ModelRouteRequest<TState>, ctx: ExtensionContext): ModelRoute<TState> | Promise<ModelRoute<TState>>;
1887}
1888
1889/** Configuration for registering a provider via pi.registerProvider(). */
1890export interface ProviderConfig {
1891 /** Display name for the provider in UI. */
1892 name?: string;
1893 /** Base URL for the API endpoint. Required when defining models. */
1894 baseUrl?: string;
1895 /** API key literal, env interpolation ($ENV_VAR or ${ENV_VAR}), or leading !command. Required when defining models (unless oauth provided). */
1896 apiKey?: string;
1897 /** API type. Required at provider or model level when defining models. */
1898 api?: Api;
1899 /**
1900 * Optional streamSimple handler for custom APIs.
1901 * The context is a normalized transcript: read the prompt and tools from its system messages
1902 * (`getCurrentSystemPrompt(context.messages)`, `getCurrentTools(context.messages)`).
1903 * Implementations must invoke `options.onPayload` before sending the provider request and use any
1904 * returned replacement payload. They must invoke `options.onResponse` after receiving the response
1905 * and before consuming its body, matching built-in providers. Implementations may invoke
1906 * `options.onProviderStreamEvent(data, model)` with parsed stream events before normalization.
1907 * Event data is adapter-owned and must be treated as read-only.
1908 */
1909 streamSimple?: (
1910 model: Model<Api>,
1911 context: TranscriptContext,
1912 options?: SimpleStreamOptions,
1913 ) => AssistantMessageEventStream;
1914 /** Image-generation implementations keyed by image API. */
1915 images?: Partial<Record<ImageApi, ProviderImages>>;
1916 /** Classifier implementations keyed by classifier API. */
1917 classifiers?: Partial<Record<ClassifierApi, ProviderClassifier>>;
1918 /** Custom headers to include in requests. */
1919 headers?: Record<string, string>;
1920 /** If true, adds Authorization: Bearer header with the resolved API key. */
1921 authHeader?: boolean;
1922 /** Models to register. If provided, replaces all existing models for this provider. */
1923 models?: ProviderModelConfig[];
1924 /**
1925 * Refresh this provider's model list. The returned list replaces extension-provided models.
1926 * Use context.publish({ persist: entry }) when the catalog should persist across sessions.
1927 */
1928 refreshModels?(context: RefreshModelsContext): Promise<ProviderModelConfig[]>;
1929 /** OAuth provider for /login support. The `id` is set automatically from the provider name. */
1930 oauth?: {
1931 /** Display name for the provider in login UI. */
1932 name: string;
1933 /** Whether access through this auth method is backed by a provider subscription. */
1934 isSubscription?: boolean;
1935 /** @deprecated Retained for source compatibility; canonical auth flows ignore it. */
1936 usesCallbackServer?: boolean;
1937 /** Run the login flow, return credentials to persist. */
1938 login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials>;
1939 /** Refresh expired credentials, return updated credentials to persist. */
1940 refreshToken(credentials: OAuthCredentials, signal: AbortSignal): Promise<OAuthCredentials>;
1941 /** Convert credentials to API key string for the provider. */
1942 getApiKey(credentials: OAuthCredentials): string;
1943 /** Legacy synchronous credential-dependent model projection. */
1944 modifyModels?(models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[];
1945 };
1946}
1947
1948interface ProviderModelConfigBase {
1949 /** Model ID. */
1950 id: string;
1951 /** Display name. */
1952 name: string;
1953 /** API type override for this model. */
1954 api?: string;
1955 /** API endpoint URL override for this model. */
1956 baseUrl?: string;
1957 /** Supported input types. */
1958 input: ("text" | "image")[];
1959 /** Provider input limits and cache-safe image preprocessing metadata. */
1960 inputLimits?: AnyModel["inputLimits"];
1961 /** Per-million-token cost rates and optional request-wide input pricing tiers. */
1962 cost: AnyModel["cost"];
1963 /** Custom headers for this model. */
1964 headers?: Record<string, string>;
1965}
1966
1967/** Chat model configuration. Omitted `type` is normalized to `"chat"`. */
1968export interface ProviderChatModelConfig extends ProviderModelConfigBase {
1969 type?: "chat";
1970 api?: Api;
1971 /** Whether the model supports extended thinking. */
1972 reasoning: boolean;
1973 /** Maps pi thinking levels to provider/model-specific values; null marks a level unsupported. */
1974 thinkingLevelMap?: Model<Api>["thinkingLevelMap"];
1975 /** Best-effort prompt cache lifetime in seconds per retention tier. Unset disables cache warming. */
1976 promptCache?: Model<Api>["promptCache"];
1977 /** Maximum context window size in tokens. */
1978 contextWindow: number;
1979 /** Maximum output tokens. */
1980 maxTokens: number;
1981 samplingParams?: Record<string, unknown>;
1982 /** OpenAI compatibility settings. */
1983 compat?: Model<Api>["compat"];
1984}
1985
1986/** Image-generation model configuration. */
1987export interface ProviderImageModelConfig extends ProviderModelConfigBase {
1988 type: "image";
1989 api?: ImageApi;
1990 output: ("text" | "image")[];
1991}
1992
1993/** Structured classifier model configuration. */
1994export interface ProviderClassifierModelConfig extends ProviderModelConfigBase {
1995 type: "classifier";
1996 api?: ClassifierApi;
1997 contextWindow: number;
1998}
1999
2000/** Configuration for a model within a provider. */
2001export type ProviderModelConfig = ProviderChatModelConfig | ProviderImageModelConfig | ProviderClassifierModelConfig;
2002
2003/** Extension factory function type. Supports both sync and async initialization. */
2004export type ExtensionFactory = (pi: ExtensionAPI) => void | Promise<void>;
2005
2006export type InlineExtension =
2007 | ExtensionFactory
2008 | {
2009 /**
2010 * Display name shown as `<inline:name>` in the startup Extensions list and errors. With
2011 * `builtin`, the extension is named `builtin:name` in errors and diagnostics.
2012 */
2013 name: string;
2014 factory: ExtensionFactory;
2015 /** Omit this extension from the startup Extensions list. */
2016 hidden?: boolean;
2017 /**
2018 * Leave this extension out when another extension registers a tool, command, or flag with a
2019 * name it registers during loading, instead of reporting a conflict. The CLI's built-in MCP,
2020 * codemode, and tool search extensions use it, so for example an MCP extension that registers
2021 * `/mcp` replaces the built-in MCP support. The factory still runs, so it should only register
2022 * tools, commands, flags, and event handlers.
2023 */
2024 replaceable?: boolean;
2025 /**
2026 * Supply the code of the `builtin:<name>` extension instead of loading as an inline extension.
2027 * `builtin:<name>` is an extension resource like a file: it loads by default, `pi config` lists
2028 * it, `-builtin:<name>` in the `extensions` setting and `--no-extensions` disable it, and
2029 * `-e builtin:<name>` loads it explicitly. It is hidden from the startup Extensions list and
2030 * loads after project trust is resolved, so it cannot handle `project_trust`. The CLI's built-in
2031 * extensions use it.
2032 */
2033 builtin?: boolean;
2034 };
2035
2036// ============================================================================
2037// Loaded Extension Types
2038// ============================================================================
2039
2040export interface RegisteredTool {
2041 definition: ToolDefinition;
2042 sourceInfo: SourceInfo;
2043}
2044
2045export interface ExtensionFlag {
2046 name: string;
2047 description?: string;
2048 type: "boolean" | "string";
2049 default?: boolean | string;
2050 extensionPath: string;
2051}
2052
2053export interface ExtensionShortcut {
2054 shortcut: KeyId;
2055 description?: string;
2056 handler: (ctx: ExtensionContext) => Promise<void> | void;
2057 extensionPath: string;
2058}
2059
2060type HandlerFn = (...args: unknown[]) => Promise<unknown>;
2061
2062export type SendMessageHandler = <T = unknown>(
2063 message: Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">,
2064 options?: { triggerTurn?: boolean; deliverAs?: "steer" | "followUp" | "nextTurn" },
2065) => void;
2066
2067export type SendUserMessageHandler = (
2068 content: string | (TextContent | ImageContent)[],
2069 options?: { deliverAs?: "steer" | "followUp"; expandPromptTemplates?: boolean },
2070) => void;
2071
2072export type AppendEntryHandler = <T = unknown>(customType: string, data?: T) => void;
2073
2074export type SetSessionNameHandler = (name: string) => void;
2075
2076export type GetSessionNameHandler = () => string | undefined;
2077
2078export type GetActiveToolsHandler = () => string[];
2079
2080/** Tool info with name, description, parameter schema, prompt guidelines, and source metadata. */
2081export type ToolInfo = Pick<ToolDefinition, "name" | "description" | "parameters" | "promptGuidelines"> & {
2082 exposure: ToolExposure;
2083 namespace?: ToolNamespace;
2084 annotations?: ToolAnnotations;
2085 sourceInfo: SourceInfo;
2086};
2087
2088export type GetAllToolsHandler = () => ToolInfo[];
2089
2090export type GetSettingsHandler = () => Settings;
2091
2092export type GetCommandsHandler = () => SlashCommandInfo[];
2093
2094export type SetActiveToolsHandler = (toolNames: string[]) => void;
2095
2096export type RefreshToolsHandler = () => void;
2097
2098export type SetModelHandler = (model: Model<any>) => Promise<boolean>;
2099
2100export type GetThinkingLevelHandler = () => ThinkingLevel;
2101
2102export type SetThinkingLevelHandler = (level: ThinkingLevel) => void;
2103
2104export type SetLabelHandler = (entryId: string, label: string | undefined) => void;
2105
2106/**
2107 * Shared state created by loader, used during registration and runtime.
2108 * Contains flag values (defaults set during registration, CLI values set after).
2109 */
2110export interface ExtensionRuntimeState {
2111 flagValues: Map<string, boolean | string>;
2112 /** Legacy provider-config registrations queued during extension loading, processed when runner binds. */
2113 pendingProviderRegistrations: Array<{ name: string; config: ProviderConfig; extensionPath: string }>;
2114 /** Native pi-ai provider registrations queued during extension loading, processed when runner binds. */
2115 pendingNativeProviderRegistrations: Array<{ provider: Provider; extensionPath: string }>;
2116 /** Virtual model registrations queued during extension loading, processed when runner binds. */
2117 pendingVirtualModelRegistrations: Array<{ definition: VirtualModelDefinition; extensionPath: string }>;
2118 /** Create an extension context. Throws before the runner binds. */
2119 createContext: () => ExtensionContext;
2120 /** Throws when this extension instance is stale after runtime replacement. */
2121 assertActive: () => void;
2122 /** Marks this extension instance as stale after runtime replacement or reload. */
2123 invalidate: (message?: string) => void;
2124 /** Retain an event-bus subscription until this runtime is invalidated. */
2125 trackEventBusSubscription: (unsubscribe: () => void) => () => void;
2126 /**
2127 * Register or unregister a provider.
2128 *
2129 * Before bindCore(): queues registrations / removes from queue.
2130 * After bindCore(): calls ModelRegistry directly for immediate effect.
2131 */
2132 registerProvider: (name: string, config: ProviderConfig, extensionPath?: string) => void;
2133 registerNativeProvider: (provider: Provider, extensionPath?: string) => void;
2134 unregisterProvider: (name: string, extensionPath?: string) => void;
2135 /** Servers registered with `pi.registerMcpServer()`. */
2136 mcpServers: McpServerRegistry;
2137 registerVirtualModel: (definition: VirtualModelDefinition, extensionPath?: string) => void;
2138 unregisterVirtualModel: (provider: string, id: string) => void;
2139}
2140
2141/**
2142 * Action implementations for pi.* API methods.
2143 * Provided to runner.initialize(), copied into the shared runtime.
2144 */
2145export interface ExtensionActions {
2146 sendMessage: SendMessageHandler;
2147 sendUserMessage: SendUserMessageHandler;
2148 appendEntry: AppendEntryHandler;
2149 setSessionName: SetSessionNameHandler;
2150 getSessionName: GetSessionNameHandler;
2151 setLabel: SetLabelHandler;
2152 getActiveTools: GetActiveToolsHandler;
2153 getAllTools: GetAllToolsHandler;
2154 getSettings: GetSettingsHandler;
2155 setActiveTools: SetActiveToolsHandler;
2156 refreshTools: RefreshToolsHandler;
2157 getCommands: GetCommandsHandler;
2158 setModel: SetModelHandler;
2159 getThinkingLevel: GetThinkingLevelHandler;
2160 setThinkingLevel: SetThinkingLevelHandler;
2161}
2162
2163/**
2164 * Actions for ExtensionContext (ctx.* in event handlers).
2165 * Required by all modes.
2166 */
2167export interface ExtensionContextActions {
2168 getModel: () => Model<any> | undefined;
2169 getScopedModels: () => readonly ScopedModel[];
2170 isIdle: () => boolean;
2171 isProjectTrusted: () => boolean;
2172 getSignal: () => AbortSignal | undefined;
2173 abort: () => void;
2174 hasPendingMessages: () => boolean;
2175 shutdown: () => void;
2176 getContextUsage: () => ContextUsage | undefined;
2177 compact: (options?: CompactOptions) => void;
2178 getSystemPrompt: () => string;
2179 getSystemPromptOptions?: () => BuildSystemPromptOptions;
2180 /** Backs `ExtensionToolContext.executeTool()`. Without it, nested calls fail. */
2181 executeTool?: (
2182 callerId: string,
2183 name: string,
2184 args: unknown,
2185 options: ExecuteToolOptions,
2186 ) => Promise<AgentToolCallOutcome>;
2187 /** Backs `ExtensionToolContext.tools`. */
2188 getCallableTools?: () => readonly AgentTool[];
2189}
2190
2191/**
2192 * Actions for ExtensionCommandContext (ctx.* in command handlers).
2193 * Only needed for interactive mode where extension commands are invokable.
2194 */
2195export interface ExtensionCommandContextActions {
2196 waitForIdle: () => Promise<void>;
2197 newSession: (options?: {
2198 parentSession?: string;
2199 setup?: (sessionManager: SessionManager) => Promise<void>;
2200 withSession?: (ctx: ReplacedSessionContext) => Promise<void>;
2201 }) => Promise<{ cancelled: boolean }>;
2202 fork: (
2203 entryId: string,
2204 options?: { position?: "before" | "at"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },
2205 ) => Promise<{ cancelled: boolean }>;
2206 navigateTree: (
2207 targetId: string,
2208 options?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },
2209 ) => Promise<{ cancelled: boolean }>;
2210 switchSession: (
2211 sessionPath: string,
2212 options?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },
2213 ) => Promise<{ cancelled: boolean }>;
2214 reload: () => Promise<void>;
2215}
2216
2217/**
2218 * Full runtime = state + actions.
2219 * Created by loader with throwing action stubs, completed by runner.initialize().
2220 */
2221export interface ExtensionRuntime extends ExtensionRuntimeState, ExtensionActions {}
2222
2223/** Loaded extension with all registered items. */
2224export interface Extension {
2225 path: string;
2226 resolvedPath: string;
2227 hidden?: boolean;
2228 /** See {@link InlineExtension}. */
2229 replaceable?: boolean;
2230 sourceInfo: SourceInfo;
2231 handlers: Map<string, HandlerFn[]>;
2232 tools: Map<string, RegisteredTool>;
2233 messageRenderers: Map<string, MessageRenderer>;
2234 toolRenderers?: ToolRendererResolver[];
2235 markdownTransformer?: MarkdownTransformer;
2236 entryRenderers?: Map<string, EntryRenderer>;
2237 commands: Map<string, RegisteredCommand>;
2238 flags: Map<string, ExtensionFlag>;
2239 shortcuts: Map<KeyId, ExtensionShortcut>;
2240}
2241
2242/** Result of loading extensions. */
2243export interface LoadExtensionsResult {
2244 extensions: Extension[];
2245 errors: Array<{ path: string; error: string }>;
2246 warnings?: Array<{ path: string; warning: string }>;
2247 /** Shared runtime - actions are throwing stubs until runner.initialize() */
2248 runtime: ExtensionRuntime;
2249}
2250
2251// ============================================================================
2252// Extension Error
2253// ============================================================================
2254
2255export interface ExtensionError {
2256 extensionPath: string;
2257 event: string;
2258 error: string;
2259 stack?: string;
2260}