返回源码地图

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

v1.3.0 · 71023aec1546 · 08/12:nested executeTool context及信号继承;非全部事件分支审计

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

1/**
2 * Extension runner - executes extensions and manages their lifecycle.
3 */
4
5import type { AgentMessage, AgentTool } from "@earendil-works/pi-agent-core";
6import {
7 getCurrentSystemMessage,
8 type ImageContent,
9 type Model,
10 type Provider,
11 type ProviderHeaders,
12} from "@earendil-works/pi-ai";
13import type { KeyId } from "@earendil-works/pi-tui";
14import { type Theme, theme } from "../../modes/interactive/theme/theme.ts";
15import type { CacheWarmingAction } from "../cache-warmer.ts";
16import type { ResourceDiagnostic } from "../diagnostics.ts";
17import type { KeybindingsConfig } from "../keybindings.ts";
18import type { ModelRegistry } from "../model-registry.ts";
19import type { ScopedModel } from "../model-resolver.ts";
20import type { SessionManager } from "../session-manager.ts";
21import {
22 type BuildSystemPromptOptions,
23 buildSystemPrompt,
24 type NormalizedBuildSystemPromptOptions,
25 normalizeBuildSystemPromptOptions,
26} from "../system-prompt.ts";
27import type { VirtualModelDefinition } from "../virtual-models.ts";
28import type {
29 AgentBeforeSettleEvent,
30 BeforeAgentStartCustomEvent,
31 BeforeAgentStartEvent,
32 BeforeAgentStartEventResult,
33 BeforeAgentStartUserEvent,
34 BeforeProviderHeadersEvent,
35 BeforeProviderRequestEvent,
36 BoundaryContextPreview,
37 BoundaryResult,
38 CacheWarmingDecisionEvent,
39 CacheWarmingDecisionEventResult,
40 CompactOptions,
41 ContextEvent,
42 ContextEventResult,
43 ContextUsage,
44 ContextWithSystemEvent,
45 EntryRenderer,
46 ExecuteToolOptions,
47 Extension,
48 ExtensionActions,
49 ExtensionCommandContext,
50 ExtensionCommandContextActions,
51 ExtensionContext,
52 ExtensionContextActions,
53 ExtensionError,
54 ExtensionEvent,
55 ExtensionFlag,
56 ExtensionMode,
57 ExtensionRuntime,
58 ExtensionShortcut,
59 ExtensionToolContext,
60 ExtensionUIContext,
61 InputEvent,
62 InputEventResult,
63 InputSource,
64 LoadExtensionsResult,
65 MarkdownTransformer,
66 MessageEndEvent,
67 MessageEndEventResult,
68 MessageRenderer,
69 ProjectTrustContext,
70 ProjectTrustEvent,
71 ProjectTrustEventResult,
72 ProviderConfig,
73 RegisteredCommand,
74 RegisteredTool,
75 ReplacedSessionContext,
76 ResolvedCommand,
77 ResourcesDiscoverEvent,
78 ResourcesDiscoverResult,
79 SessionBeforeCompactResult,
80 SessionBeforeForkResult,
81 SessionBeforeSwitchResult,
82 SessionBeforeTreeResult,
83 SessionBoundaryDraft,
84 SessionShutdownEvent,
85 ToolCallEvent,
86 ToolCallEventResult,
87 ToolRenderers,
88 ToolResultEvent,
89 ToolResultEventResult,
90 TurnEndEvent,
91 UIPromptKind,
92 UserBashEvent,
93 UserBashEventResult,
94} from "./types.ts";
95
96// Extension shortcuts compete with canonical keybinding ids from keybindings.json.
97// Only editor-global shortcuts are reserved here. Picker-specific bindings are not.
98const RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS = [
99 "app.interrupt",
100 "app.clear",
101 "app.exit",
102 "app.suspend",
103 "app.thinking.cycle",
104 "app.model.cycleForward",
105 "app.model.cycleBackward",
106 "app.model.select",
107 "app.tools.expand",
108 "app.thinking.toggle",
109 "app.editor.external",
110 "app.message.copy",
111 "app.message.followUp",
112 "tui.input.submit",
113 "tui.select.confirm",
114 "tui.select.cancel",
115 "tui.input.copy",
116 "tui.editor.deleteToLineEnd",
117] as const;
118
119type BuiltInKeyBindings = Partial<Record<KeyId, { keybinding: string; restrictOverride: boolean }>>;
120
121const buildBuiltinKeybindings = (resolvedKeybindings: KeybindingsConfig): BuiltInKeyBindings => {
122 const builtinKeybindings = {} as BuiltInKeyBindings;
123 for (const [keybinding, keys] of Object.entries(resolvedKeybindings)) {
124 if (keys === undefined) continue;
125 const keyList = Array.isArray(keys) ? keys : [keys];
126 const restrictOverride = (RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS as readonly string[]).includes(keybinding);
127 for (const key of keyList) {
128 const normalizedKey = key.toLowerCase() as KeyId;
129 // If multiple actions bind the same key, the reserved action wins so extensions
130 // remain blocked by reserved shortcuts regardless of iteration order.
131 const existing = builtinKeybindings[normalizedKey];
132 if (existing?.restrictOverride && !restrictOverride) continue;
133 builtinKeybindings[normalizedKey] = {
134 keybinding,
135 restrictOverride,
136 };
137 }
138 }
139 return builtinKeybindings;
140};
141
142function isUserBashEventResult(value: unknown): value is UserBashEventResult {
143 if (typeof value !== "object" || value === null) return false;
144 const candidate = value as Record<string, unknown>;
145 const hasOperations = candidate.operations !== undefined;
146 const hasResult = candidate.result !== undefined;
147 if (hasOperations === hasResult) return false;
148
149 if (hasOperations) {
150 const operations = candidate.operations;
151 if (typeof operations !== "object" || operations === null) return false;
152 return typeof (operations as Record<string, unknown>).exec === "function";
153 }
154
155 const result = candidate.result;
156 if (typeof result !== "object" || result === null) return false;
157 const resultRecord = result as Record<string, unknown>;
158 return (
159 typeof resultRecord.output === "string" &&
160 "exitCode" in resultRecord &&
161 (resultRecord.exitCode === undefined || typeof resultRecord.exitCode === "number") &&
162 typeof resultRecord.cancelled === "boolean" &&
163 typeof resultRecord.truncated === "boolean" &&
164 (resultRecord.fullOutputPath === undefined || typeof resultRecord.fullOutputPath === "string")
165 );
166}
167
168/** The message that starts a run: the before_agent_start event without its prompt fields. */
169export type BeforeAgentStartTrigger =
170 | Pick<BeforeAgentStartUserEvent, "messageType" | "prompt" | "images">
171 | Pick<BeforeAgentStartCustomEvent, "messageType" | "message">;
172
173/** Combined result from all before_agent_start handlers. */
174interface BeforeAgentStartCombinedResult {
175 messages: NonNullable<BeforeAgentStartEventResult["message"]>[];
176 systemPromptOptions: NormalizedBuildSystemPromptOptions;
177}
178
179/**
180 * Events handled by the generic emit() method.
181 * Events with dedicated emitXxx() methods are excluded for stronger type safety.
182 */
183type RunnerEmitEvent = Exclude<
184 ExtensionEvent,
185 | ToolCallEvent
186 | ProjectTrustEvent
187 | ToolResultEvent
188 | UserBashEvent
189 | ContextEvent
190 | ContextWithSystemEvent
191 | CacheWarmingDecisionEvent
192 | BeforeProviderRequestEvent
193 | BeforeProviderHeadersEvent
194 | BeforeAgentStartEvent
195 | MessageEndEvent
196 | ResourcesDiscoverEvent
197 | InputEvent
198 | TurnEndEvent
199 | AgentBeforeSettleEvent
200>;
201
202type SessionBeforeEvent = Extract<
203 RunnerEmitEvent,
204 { type: "session_before_switch" | "session_before_fork" | "session_before_compact" | "session_before_tree" }
205>;
206
207type SessionBeforeEventResult =
208 | SessionBeforeSwitchResult
209 | SessionBeforeForkResult
210 | SessionBeforeCompactResult
211 | SessionBeforeTreeResult;
212
213type RunnerEmitResult<TEvent extends RunnerEmitEvent> = TEvent extends { type: "session_before_switch" }
214 ? SessionBeforeSwitchResult | undefined
215 : TEvent extends { type: "session_before_fork" }
216 ? SessionBeforeForkResult | undefined
217 : TEvent extends { type: "session_before_compact" }
218 ? SessionBeforeCompactResult | undefined
219 : TEvent extends { type: "session_before_tree" }
220 ? SessionBeforeTreeResult | undefined
221 : undefined;
222
223export type ExtensionErrorListener = (error: ExtensionError) => void;
224
225type BoundaryBaseEvent =
226 | Omit<TurnEndEvent, "entries" | "continue" | "context">
227 | Omit<AgentBeforeSettleEvent, "entries" | "continue" | "context">;
228
229interface BoundaryDispatchResult {
230 entries: SessionBoundaryDraft[];
231 continue: boolean;
232 context: BoundaryContextPreview;
233 valid: boolean;
234}
235
236export type NewSessionHandler = (options?: {
237 parentSession?: string;
238 setup?: (sessionManager: SessionManager) => Promise<void>;
239 withSession?: (ctx: ReplacedSessionContext) => Promise<void>;
240}) => Promise<{ cancelled: boolean }>;
241
242export type ForkHandler = (
243 entryId: string,
244 options?: { position?: "before" | "at"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },
245) => Promise<{ cancelled: boolean }>;
246
247export type NavigateTreeHandler = (
248 targetId: string,
249 options?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },
250) => Promise<{ cancelled: boolean }>;
251
252export type SwitchSessionHandler = (
253 sessionPath: string,
254 options?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },
255) => Promise<{ cancelled: boolean }>;
256
257export type ReloadHandler = () => Promise<void>;
258
259export type ShutdownHandler = () => void;
260
261/**
262 * Helper function to emit session_shutdown event to extensions.
263 * Returns true if the event was emitted, false if there were no handlers.
264 */
265export async function emitSessionShutdownEvent(
266 extensionRunner: ExtensionRunner,
267 event: SessionShutdownEvent,
268): Promise<boolean> {
269 if (extensionRunner.hasHandlers("session_shutdown")) {
270 await extensionRunner.emit(event);
271 return true;
272 }
273 return false;
274}
275
276function snapshotEventHandlers(extensions: Extension[], event: ExtensionEvent["type"]) {
277 return extensions.map((ext) => ({ ext, handlers: ext.handlers.get(event)?.slice() ?? [] }));
278}
279
280function sameMessages(left: AgentMessage[], right: AgentMessage[]): boolean {
281 return left.length === right.length && left.every((message, index) => message === right[index]);
282}
283
284/**
285 * Re-attach the prompt and tool state after a `context` handler. Handlers only see the
286 * conversation; the system messages belong to Pi. An unchanged conversation keeps every
287 * system message in place, so models with mid-conversation support keep their cached
288 * prefix. A changed one gets the replayed prompt sections and tool declarations as one
289 * leading system message, so pruning, windowing, or slicing from a compaction summary
290 * cannot drop them.
291 */
292function restoreSystemMessages(
293 current: AgentMessage[],
294 visible: AgentMessage[],
295 returned: AgentMessage[],
296): AgentMessage[] {
297 if (sameMessages(returned, visible)) return current;
298 const head = getCurrentSystemMessage(current);
299 return head ? [head, ...returned] : returned;
300}
301
302export async function emitProjectTrustEvent(
303 extensionsResult: LoadExtensionsResult,
304 event: ProjectTrustEvent,
305 ctx: ProjectTrustContext,
306): Promise<{ result?: ProjectTrustEventResult; errors: ExtensionError[] }> {
307 const errors: ExtensionError[] = [];
308 for (const { ext, handlers } of snapshotEventHandlers(extensionsResult.extensions, "project_trust")) {
309 // A single extension may register multiple handlers for the same event.
310 // The first project_trust handler that returns yes/no wins; undecided falls through.
311 for (const handler of handlers) {
312 try {
313 const handlerResult = (await handler(event, ctx)) as ProjectTrustEventResult;
314 if (handlerResult.trusted === "undecided") {
315 continue;
316 }
317 return { result: handlerResult, errors };
318 } catch (error) {
319 errors.push({
320 extensionPath: ext.path,
321 event: event.type,
322 error: error instanceof Error ? error.message : String(error),
323 stack: error instanceof Error ? error.stack : undefined,
324 });
325 }
326 }
327 }
328 return { errors };
329}
330
331const noOpUIContext: ExtensionUIContext = {
332 select: async () => undefined,
333 confirm: async () => false,
334 input: async () => undefined,
335 notify: () => {},
336 onTerminalInput: () => () => {},
337 setStatus: () => {},
338 setWorkingMessage: () => {},
339 setWorkingVisible: () => {},
340 setWorkingIndicator: () => {},
341 setHiddenThinkingLabel: () => {},
342 setWidget: () => {},
343 setFooter: () => {},
344 setHeader: () => {},
345 setTitle: () => {},
346 custom: async () => undefined as never,
347 pasteToEditor: () => {},
348 setEditorText: () => {},
349 getEditorText: () => "",
350 editor: async () => undefined,
351 addAutocompleteProvider: () => {},
352 setEditorComponent: () => {},
353 getEditorComponent: () => undefined,
354 get theme() {
355 return theme;
356 },
357 getAllThemes: () => [],
358 getTheme: () => undefined,
359 setTheme: (_theme: string | Theme) => ({ success: false, error: "UI not available" }),
360 getToolsExpanded: () => false,
361 setToolsExpanded: () => {},
362};
363
364export class ExtensionRunner {
365 private extensions: Extension[];
366 private runtime: ExtensionRuntime;
367 private uiContext: ExtensionUIContext;
368 private mode: ExtensionMode = "print";
369 private cwd: string;
370 private sessionManager: SessionManager;
371 private modelRegistry: ModelRegistry;
372 private errorListeners: Set<ExtensionErrorListener> = new Set();
373 private getModel: () => Model<any> | undefined = () => undefined;
374 private getScopedModels: () => readonly ScopedModel[] = () => [];
375 private isIdleFn: () => boolean = () => true;
376 private isProjectTrustedFn: () => boolean = () => true;
377 private getSignalFn: () => AbortSignal | undefined = () => undefined;
378 private waitForIdleFn: () => Promise<void> = async () => {};
379 private abortFn: () => void = () => {};
380 private hasPendingMessagesFn: () => boolean = () => false;
381 private getContextUsageFn: () => ContextUsage | undefined = () => undefined;
382 private compactFn: (options?: CompactOptions) => void = () => {};
383 private getSystemPromptFn: () => string = () => "";
384 private getSystemPromptOptionsFn: () => BuildSystemPromptOptions = () =>
385 normalizeBuildSystemPromptOptions({ cwd: this.cwd });
386 private executeToolFn: ExtensionContextActions["executeTool"];
387 private getCallableToolsFn: () => readonly AgentTool[] = () => [];
388 /** Registered MCP servers already reported as unhandled. */
389 private readonly reportedMcpServers = new Set<string>();
390 private newSessionHandler: NewSessionHandler = async () => ({ cancelled: false });
391 private forkHandler: ForkHandler = async () => ({ cancelled: false });
392 private navigateTreeHandler: NavigateTreeHandler = async () => ({ cancelled: false });
393 private switchSessionHandler: SwitchSessionHandler = async () => ({ cancelled: false });
394 private reloadHandler: ReloadHandler = async () => {};
395 private shutdownHandler: ShutdownHandler = () => {};
396 private shortcutDiagnostics: ResourceDiagnostic[] = [];
397 private commandDiagnostics: ResourceDiagnostic[] = [];
398 private staleMessage: string | undefined;
399 private uiPromptDepth = 0;
400 private activeUIPrompt: { kind: UIPromptKind; title?: string } | undefined;
401
402 constructor(
403 extensions: Extension[],
404 runtime: ExtensionRuntime,
405 cwd: string,
406 sessionManager: SessionManager,
407 modelRegistry: ModelRegistry,
408 ) {
409 this.extensions = extensions;
410 this.runtime = runtime;
411 this.uiContext = noOpUIContext;
412 this.cwd = cwd;
413 this.sessionManager = sessionManager;
414 this.modelRegistry = modelRegistry;
415 }
416
417 bindCore(
418 actions: ExtensionActions,
419 contextActions: ExtensionContextActions,
420 providerActions?: {
421 registerProvider?: (name: string, config: ProviderConfig) => void;
422 registerNativeProvider?: (provider: Provider) => void;
423 unregisterProvider?: (name: string) => void;
424 registerVirtualModel?: (definition: VirtualModelDefinition) => void;
425 unregisterVirtualModel?: (provider: string, id: string) => void;
426 },
427 ): void {
428 // Copy actions into the shared runtime (all extension APIs reference this)
429 this.runtime.sendMessage = actions.sendMessage;
430 this.runtime.sendUserMessage = actions.sendUserMessage;
431 this.runtime.appendEntry = actions.appendEntry;
432 this.runtime.setSessionName = actions.setSessionName;
433 this.runtime.getSessionName = actions.getSessionName;
434 this.runtime.setLabel = actions.setLabel;
435 this.runtime.getActiveTools = actions.getActiveTools;
436 this.runtime.getAllTools = actions.getAllTools;
437 this.runtime.getSettings = actions.getSettings;
438 this.runtime.setActiveTools = actions.setActiveTools;
439 this.runtime.refreshTools = actions.refreshTools;
440 this.runtime.getCommands = actions.getCommands;
441 this.runtime.setModel = actions.setModel;
442 this.runtime.getThinkingLevel = actions.getThinkingLevel;
443 this.runtime.setThinkingLevel = actions.setThinkingLevel;
444 this.runtime.createContext = () => this.createContext();
445
446 // Context actions (required)
447 this.getModel = contextActions.getModel;
448 this.getScopedModels = contextActions.getScopedModels;
449 this.isIdleFn = contextActions.isIdle;
450 this.isProjectTrustedFn = contextActions.isProjectTrusted;
451 this.getSignalFn = contextActions.getSignal;
452 this.abortFn = contextActions.abort;
453 this.hasPendingMessagesFn = contextActions.hasPendingMessages;
454 this.shutdownHandler = contextActions.shutdown;
455 this.getContextUsageFn = contextActions.getContextUsage;
456 this.compactFn = contextActions.compact;
457 this.getSystemPromptFn = contextActions.getSystemPrompt;
458 this.getSystemPromptOptionsFn =
459 contextActions.getSystemPromptOptions ?? (() => normalizeBuildSystemPromptOptions({ cwd: this.cwd }));
460 this.executeToolFn = contextActions.executeTool;
461 this.getCallableToolsFn = contextActions.getCallableTools ?? (() => []);
462
463 // Servers registered from now on reach the extension that connects them right away. Servers
464 // registered during loading are read on session_start.
465 this.runtime.mcpServers.setChangeListener(() => {
466 void this.emit({ type: "mcp_servers_change", servers: this.runtime.mcpServers.list() });
467 this.reportUnhandledMcpServers();
468 });
469
470 // Flush provider registrations queued during extension loading
471 for (const { name, config, extensionPath } of this.runtime.pendingProviderRegistrations) {
472 try {
473 if (providerActions?.registerProvider) {
474 providerActions.registerProvider(name, config);
475 } else {
476 this.modelRegistry.registerProvider(name, config);
477 }
478 } catch (err) {
479 this.emitError({
480 extensionPath,
481 event: "register_provider",
482 error: err instanceof Error ? err.message : String(err),
483 stack: err instanceof Error ? err.stack : undefined,
484 });
485 }
486 }
487 this.runtime.pendingProviderRegistrations = [];
488 for (const { provider, extensionPath } of this.runtime.pendingNativeProviderRegistrations) {
489 try {
490 if (providerActions?.registerNativeProvider) {
491 providerActions.registerNativeProvider(provider);
492 } else {
493 this.modelRegistry.registerProvider(provider);
494 }
495 } catch (err) {
496 this.emitError({
497 extensionPath,
498 event: "register_provider",
499 error: err instanceof Error ? err.message : String(err),
500 stack: err instanceof Error ? err.stack : undefined,
501 });
502 }
503 }
504 this.runtime.pendingNativeProviderRegistrations = [];
505 const registerVirtualModel = (definition: VirtualModelDefinition) => {
506 if (providerActions?.registerVirtualModel) providerActions.registerVirtualModel(definition);
507 else this.modelRegistry.registerVirtualModel(definition);
508 };
509 for (const { definition, extensionPath } of this.runtime.pendingVirtualModelRegistrations) {
510 try {
511 registerVirtualModel(definition);
512 } catch (err) {
513 this.emitError({
514 extensionPath,
515 event: "register_virtual_model",
516 error: err instanceof Error ? err.message : String(err),
517 stack: err instanceof Error ? err.stack : undefined,
518 });
519 }
520 }
521 this.runtime.pendingVirtualModelRegistrations = [];
522
523 // From this point on, provider registration/unregistration takes effect immediately
524 // without requiring a /reload.
525 this.runtime.registerProvider = (name, config) => {
526 if (providerActions?.registerProvider) {
527 providerActions.registerProvider(name, config);
528 return;
529 }
530 this.modelRegistry.registerProvider(name, config);
531 };
532 this.runtime.registerNativeProvider = (provider) => {
533 if (providerActions?.registerNativeProvider) {
534 providerActions.registerNativeProvider(provider);
535 return;
536 }
537 this.modelRegistry.registerProvider(provider);
538 };
539 this.runtime.unregisterProvider = (name) => {
540 if (providerActions?.unregisterProvider) {
541 providerActions.unregisterProvider(name);
542 return;
543 }
544 this.modelRegistry.unregisterProvider(name);
545 };
546 this.runtime.registerVirtualModel = registerVirtualModel;
547 this.runtime.unregisterVirtualModel = (provider, id) => {
548 if (providerActions?.unregisterVirtualModel) providerActions.unregisterVirtualModel(provider, id);
549 else this.modelRegistry.unregisterVirtualModel(provider, id);
550 };
551 }
552
553 bindCommandContext(actions?: ExtensionCommandContextActions): void {
554 if (actions) {
555 this.waitForIdleFn = actions.waitForIdle;
556 this.newSessionHandler = actions.newSession;
557 this.forkHandler = actions.fork;
558 this.navigateTreeHandler = actions.navigateTree;
559 this.switchSessionHandler = actions.switchSession;
560 this.reloadHandler = actions.reload;
561 return;
562 }
563
564 this.waitForIdleFn = async () => {};
565 this.newSessionHandler = async () => ({ cancelled: false });
566 this.forkHandler = async () => ({ cancelled: false });
567 this.navigateTreeHandler = async () => ({ cancelled: false });
568 this.switchSessionHandler = async () => ({ cancelled: false });
569 this.reloadHandler = async () => {};
570 }
571
572 setUIContext(uiContext?: ExtensionUIContext, mode: ExtensionMode = "print"): void {
573 this.uiContext = uiContext ? this.wrapUIPromptContext(uiContext) : noOpUIContext;
574 this.mode = mode;
575 }
576
577 private wrapUIPromptContext(ui: ExtensionUIContext): ExtensionUIContext {
578 return {
579 ...ui,
580 select: (title, options, opts) => this.withUIPrompt("select", title, () => ui.select(title, options, opts)),
581 confirm: (title, message, opts) => this.withUIPrompt("confirm", title, () => ui.confirm(title, message, opts)),
582 input: (title, placeholder, opts) =>
583 this.withUIPrompt("input", title, () => ui.input(title, placeholder, opts)),
584 editor: (title, prefill) => this.withUIPrompt("editor", title, () => ui.editor(title, prefill)),
585 custom: (factory, options) => this.withUIPrompt("custom", undefined, () => ui.custom(factory, options)),
586 };
587 }
588
589 private withUIPrompt<T>(kind: UIPromptKind, title: string | undefined, run: () => Promise<T>): Promise<T> {
590 const outerPrompt = this.uiPromptDepth++ === 0;
591 if (outerPrompt) {
592 this.activeUIPrompt = { kind, title };
593 this.emitUIPromptEvent({ type: "ui_prompt_start", reason: "ui_prompt", kind, ...(title ? { title } : {}) });
594 }
595
596 const finish = () => {
597 if (--this.uiPromptDepth > 0) return;
598 this.uiPromptDepth = 0;
599
600 const prompt = this.activeUIPrompt ?? { kind, title };
601 this.activeUIPrompt = undefined;
602 this.emitUIPromptEvent({
603 type: "ui_prompt_end",
604 reason: "ui_prompt",
605 kind: prompt.kind,
606 ...(prompt.title ? { title: prompt.title } : {}),
607 });
608 };
609
610 try {
611 return run().finally(finish);
612 } catch (err) {
613 finish();
614 throw err;
615 }
616 }
617
618 private emitUIPromptEvent(event: Extract<RunnerEmitEvent, { type: "ui_prompt_start" | "ui_prompt_end" }>): void {
619 queueMicrotask(() => {
620 void this.emit(event);
621 });
622 }
623
624 getUIContext(): ExtensionUIContext {
625 return this.uiContext;
626 }
627
628 hasUI(): boolean {
629 return this.uiContext !== noOpUIContext;
630 }
631
632 getExtensionPaths(): string[] {
633 return this.extensions.map((e) => e.path);
634 }
635
636 /** Get all registered tools from all extensions (first registration per name wins). */
637 getAllRegisteredTools(): RegisteredTool[] {
638 const toolsByName = new Map<string, RegisteredTool>();
639 for (const ext of this.extensions) {
640 for (const tool of ext.tools.values()) {
641 if (!toolsByName.has(tool.definition.name)) {
642 toolsByName.set(tool.definition.name, tool);
643 }
644 }
645 }
646 return Array.from(toolsByName.values());
647 }
648
649 /** Get a tool definition by name. Returns undefined if not found. */
650 getToolDefinition(toolName: string): RegisteredTool["definition"] | undefined {
651 for (const ext of this.extensions) {
652 const tool = ext.tools.get(toolName);
653 if (tool) {
654 return tool.definition;
655 }
656 }
657 return undefined;
658 }
659
660 getFlags(): Map<string, ExtensionFlag> {
661 const allFlags = new Map<string, ExtensionFlag>();
662 for (const ext of this.extensions) {
663 for (const [name, flag] of ext.flags) {
664 if (!allFlags.has(name)) {
665 allFlags.set(name, flag);
666 }
667 }
668 }
669 return allFlags;
670 }
671
672 setFlagValue(name: string, value: boolean | string): void {
673 this.runtime.flagValues.set(name, value);
674 }
675
676 getFlagValues(): Map<string, boolean | string> {
677 return new Map(this.runtime.flagValues);
678 }
679
680 getShortcuts(resolvedKeybindings: KeybindingsConfig): Map<KeyId, ExtensionShortcut> {
681 this.shortcutDiagnostics = [];
682 const builtinKeybindings = buildBuiltinKeybindings(resolvedKeybindings);
683 const extensionShortcuts = new Map<KeyId, ExtensionShortcut>();
684
685 const addDiagnostic = (message: string, extensionPath: string) => {
686 this.shortcutDiagnostics.push({ type: "warning", message, path: extensionPath });
687 if (!this.hasUI()) {
688 console.warn(message);
689 }
690 };
691
692 for (const ext of this.extensions) {
693 for (const [key, shortcut] of ext.shortcuts) {
694 const normalizedKey = key.toLowerCase() as KeyId;
695
696 const builtInKeybinding = builtinKeybindings[normalizedKey];
697 if (builtInKeybinding?.restrictOverride === true) {
698 addDiagnostic(
699 `Extension shortcut '${key}' from ${shortcut.extensionPath} conflicts with built-in shortcut. Skipping.`,
700 shortcut.extensionPath,
701 );
702 continue;
703 }
704
705 if (builtInKeybinding?.restrictOverride === false) {
706 addDiagnostic(
707 `Extension shortcut conflict: '${key}' is built-in shortcut for ${builtInKeybinding.keybinding} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,
708 shortcut.extensionPath,
709 );
710 }
711
712 const existingExtensionShortcut = extensionShortcuts.get(normalizedKey);
713 if (existingExtensionShortcut) {
714 addDiagnostic(
715 `Extension shortcut conflict: '${key}' registered by both ${existingExtensionShortcut.extensionPath} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,
716 shortcut.extensionPath,
717 );
718 }
719 extensionShortcuts.set(normalizedKey, shortcut);
720 }
721 }
722 return extensionShortcuts;
723 }
724
725 getShortcutDiagnostics(): ResourceDiagnostic[] {
726 return this.shortcutDiagnostics;
727 }
728
729 invalidate(
730 message = "This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().",
731 ): void {
732 if (!this.staleMessage) {
733 this.staleMessage = message;
734 this.runtime.invalidate(message);
735 }
736 }
737
738 private assertActive(): void {
739 if (this.staleMessage) {
740 throw new Error(this.staleMessage);
741 }
742 }
743
744 onError(listener: ExtensionErrorListener): () => void {
745 this.errorListeners.add(listener);
746 return () => this.errorListeners.delete(listener);
747 }
748
749 emitError(error: ExtensionError): void {
750 for (const listener of this.errorListeners) {
751 listener(error);
752 }
753 }
754
755 /**
756 * Report registered MCP servers when no extension handles `mcp_servers_change`, which means
757 * nothing connects them (for example when another MCP extension replaced the built-in one).
758 */
759 reportUnhandledMcpServers(): void {
760 if (this.hasHandlers("mcp_servers_change")) return;
761 for (const server of this.runtime.mcpServers.list()) {
762 if (this.reportedMcpServers.has(server.name)) continue;
763 this.reportedMcpServers.add(server.name);
764 this.emitError({
765 extensionPath: server.extensionPath,
766 event: "register_mcp_server",
767 error: `MCP server "${server.name}" is registered, but no loaded extension connects MCP servers; another extension may have replaced the built-in MCP support`,
768 });
769 }
770 }
771
772 hasHandlers(eventType: string): boolean {
773 for (const ext of this.extensions) {
774 const handlers = ext.handlers.get(eventType);
775 if (handlers && handlers.length > 0) {
776 return true;
777 }
778 }
779 return false;
780 }
781
782 getMessageRenderer(customType: string): MessageRenderer | undefined {
783 for (const ext of this.extensions) {
784 const renderer = ext.messageRenderers.get(customType);
785 if (renderer) {
786 return renderer;
787 }
788 }
789 return undefined;
790 }
791
792 getMarkdownTransformers(): MarkdownTransformer[] {
793 return this.extensions.flatMap((ext) => (ext.markdownTransformer ? [ext.markdownTransformer] : []));
794 }
795
796 /** Renderers of calls to `toolName`: extension resolvers in load order, then `base`. */
797 resolveToolRenderers(toolName: string, base: () => ToolRenderers | undefined): ToolRenderers | undefined {
798 const resolvers = this.extensions.flatMap((ext) => ext.toolRenderers ?? []);
799 const resolve = (index: number): ToolRenderers | undefined =>
800 index < resolvers.length ? resolvers[index](toolName, () => resolve(index + 1)) : base();
801 return resolve(0);
802 }
803
804 getEntryRenderer(customType: string): EntryRenderer | undefined {
805 for (const ext of this.extensions) {
806 const renderer = ext.entryRenderers?.get(customType);
807 if (renderer) {
808 return renderer;
809 }
810 }
811 return undefined;
812 }
813
814 private resolveRegisteredCommands(): ResolvedCommand[] {
815 const commands: RegisteredCommand[] = [];
816 const counts = new Map<string, number>();
817
818 for (const ext of this.extensions) {
819 for (const command of ext.commands.values()) {
820 commands.push(command);
821 counts.set(command.name, (counts.get(command.name) ?? 0) + 1);
822 }
823 }
824
825 const seen = new Map<string, number>();
826 const takenInvocationNames = new Set<string>();
827
828 return commands.map((command) => {
829 const occurrence = (seen.get(command.name) ?? 0) + 1;
830 seen.set(command.name, occurrence);
831
832 let invocationName = (counts.get(command.name) ?? 0) > 1 ? `${command.name}:${occurrence}` : command.name;
833
834 if (takenInvocationNames.has(invocationName)) {
835 let suffix = occurrence;
836 do {
837 suffix++;
838 invocationName = `${command.name}:${suffix}`;
839 } while (takenInvocationNames.has(invocationName));
840 }
841
842 takenInvocationNames.add(invocationName);
843 return {
844 ...command,
845 invocationName,
846 };
847 });
848 }
849
850 getModelRegistry(): ModelRegistry {
851 return this.modelRegistry;
852 }
853
854 getRegisteredCommands(): ResolvedCommand[] {
855 this.commandDiagnostics = [];
856 return this.resolveRegisteredCommands();
857 }
858
859 getCommandDiagnostics(): ResourceDiagnostic[] {
860 return this.commandDiagnostics;
861 }
862
863 getCommand(name: string): ResolvedCommand | undefined {
864 return this.resolveRegisteredCommands().find((command) => command.invocationName === name);
865 }
866
867 /**
868 * Request a graceful shutdown. Called by extension tools and event handlers.
869 * The actual shutdown behavior is provided by the mode via bindExtensions().
870 */
871 shutdown(): void {
872 this.shutdownHandler();
873 }
874
875 getActiveTools(): string[] {
876 this.assertActive();
877 return this.runtime.getActiveTools();
878 }
879
880 /**
881 * Create an ExtensionContext for use in event handlers and tool execution.
882 * Context values are resolved at call time, so changes via bindCore/bindUI are reflected.
883 */
884 createContext(): ExtensionContext {
885 const runner = this;
886 const getModel = this.getModel;
887 const getScopedModels = this.getScopedModels;
888 return {
889 get ui() {
890 runner.assertActive();
891 return runner.uiContext;
892 },
893 get mode() {
894 runner.assertActive();
895 return runner.mode;
896 },
897 get hasUI() {
898 runner.assertActive();
899 return runner.hasUI();
900 },
901 get cwd() {
902 runner.assertActive();
903 return runner.cwd;
904 },
905 get sessionManager() {
906 runner.assertActive();
907 return runner.sessionManager;
908 },
909 get modelRegistry() {
910 runner.assertActive();
911 return runner.modelRegistry;
912 },
913 get model() {
914 runner.assertActive();
915 return getModel();
916 },
917 get scopedModels() {
918 runner.assertActive();
919 return getScopedModels();
920 },
921 get thinkingLevel() {
922 runner.assertActive();
923 return runner.runtime.getThinkingLevel();
924 },
925 isIdle: () => {
926 runner.assertActive();
927 return runner.isIdleFn();
928 },
929 isProjectTrusted: () => {
930 runner.assertActive();
931 return runner.isProjectTrustedFn();
932 },
933 get signal() {
934 runner.assertActive();
935 return runner.getSignalFn();
936 },
937 abort: () => {
938 runner.assertActive();
939 runner.abortFn();
940 },
941 hasPendingMessages: () => {
942 runner.assertActive();
943 return runner.hasPendingMessagesFn();
944 },
945 shutdown: () => {
946 runner.assertActive();
947 runner.shutdownHandler();
948 },
949 getContextUsage: () => {
950 runner.assertActive();
951 return runner.getContextUsageFn();
952 },
953 compact: (options) => {
954 runner.assertActive();
955 runner.compactFn(options);
956 },
957 getSystemPrompt: () => {
958 runner.assertActive();
959 return runner.getSystemPromptFn();
960 },
961 };
962 }
963
964 /**
965 * Create the context for executing the tool call `toolCallId`: the extension context plus
966 * `tools` and `executeTool()`. `signal` is the default signal of nested calls.
967 */
968 createToolContext(toolCallId: string, signal: AbortSignal | undefined): ExtensionToolContext {
969 const runner = this;
970 // createContext() returns a fresh object, so adding properties does not affect other contexts.
971 return Object.defineProperties(this.createContext() as ExtensionToolContext, {
972 tools: {
973 get() {
974 runner.assertActive();
975 return runner.getCallableToolsFn();
976 },
977 },
978 executeTool: {
979 value: async (name: string, args: unknown, options: ExecuteToolOptions = {}) => {
980 runner.assertActive();
981 if (!runner.executeToolFn) {
982 return {
983 toolCall: { type: "toolCall", id: `${toolCallId}/0`, name, arguments: {} },
984 result: {
985 content: [{ type: "text", text: "Nested tool calls are not available in this context" }],
986 details: {},
987 },
988 isError: true,
989 };
990 }
991 return runner.executeToolFn(toolCallId, name, args, { ...options, signal: options.signal ?? signal });
992 },
993 },
994 });
995 }
996
997 createCommandContext(): ExtensionCommandContext {
998 // Use property descriptors instead of object spread so the guarded getters from
999 // createContext() stay lazy. A spread would eagerly read them once and freeze the
1000 // old values into the returned object, bypassing stale-instance checks.
1001 const context = Object.defineProperties(
1002 {},
1003 Object.getOwnPropertyDescriptors(this.createContext()),
1004 ) as ExtensionCommandContext;
1005 context.getSystemPromptOptions = () => {
1006 this.assertActive();
1007 return this.getSystemPromptOptionsFn();
1008 };
1009 context.waitForIdle = () => {
1010 this.assertActive();
1011 return this.waitForIdleFn();
1012 };
1013 context.newSession = (options) => {
1014 this.assertActive();
1015 return this.newSessionHandler(options);
1016 };
1017 context.fork = (entryId, options) => {
1018 this.assertActive();
1019 return this.forkHandler(entryId, options);
1020 };
1021 context.navigateTree = (targetId, options) => {
1022 this.assertActive();
1023 return this.navigateTreeHandler(targetId, options);
1024 };
1025 context.switchSession = (sessionPath, options) => {
1026 this.assertActive();
1027 return this.switchSessionHandler(sessionPath, options);
1028 };
1029 context.reload = () => {
1030 this.assertActive();
1031 return this.reloadHandler();
1032 };
1033 return context;
1034 }
1035
1036 async emitBoundary(
1037 baseEvent: BoundaryBaseEvent,
1038 buildContext: (entries: SessionBoundaryDraft[]) => BoundaryContextPreview | Promise<BoundaryContextPreview>,
1039 ): Promise<BoundaryDispatchResult> {
1040 const ctx = this.createContext();
1041 let entries: SessionBoundaryDraft[] = [];
1042 let shouldContinue = false;
1043 let context = await buildContext(entries);
1044 let valid = true;
1045
1046 for (const { ext, handlers } of snapshotEventHandlers(this.extensions, baseEvent.type)) {
1047 for (const handler of handlers) {
1048 const event = {
1049 ...baseEvent,
1050 entries,
1051 continue: shouldContinue,
1052 context,
1053 } as TurnEndEvent | AgentBeforeSettleEvent;
1054 try {
1055 const handlerResult = (await handler(event, ctx)) as BoundaryResult | undefined;
1056 if (handlerResult?.entries !== undefined) entries = handlerResult.entries;
1057 if (handlerResult?.continue !== undefined) shouldContinue = handlerResult.continue;
1058 } catch (err) {
1059 this.emitError({
1060 extensionPath: ext.path,
1061 event: baseEvent.type,
1062 error: err instanceof Error ? err.message : String(err),
1063 stack: err instanceof Error ? err.stack : undefined,
1064 });
1065 }
1066
1067 try {
1068 context = await buildContext(entries);
1069 valid = true;
1070 } catch (err) {
1071 valid = false;
1072 this.emitError({
1073 extensionPath: ext.path,
1074 event: baseEvent.type,
1075 error: `Invalid boundary entries: ${err instanceof Error ? err.message : String(err)}`,
1076 stack: err instanceof Error ? err.stack : undefined,
1077 });
1078 }
1079 }
1080 }
1081
1082 return valid
1083 ? { entries, continue: shouldContinue, context, valid: true }
1084 : { entries: [], continue: false, context, valid: false };
1085 }
1086
1087 private isSessionBeforeEvent(event: RunnerEmitEvent): event is SessionBeforeEvent {
1088 return (
1089 event.type === "session_before_switch" ||
1090 event.type === "session_before_fork" ||
1091 event.type === "session_before_compact" ||
1092 event.type === "session_before_tree"
1093 );
1094 }
1095
1096 async emit<TEvent extends RunnerEmitEvent>(event: TEvent): Promise<RunnerEmitResult<TEvent>> {
1097 const ctx = this.createContext();
1098 let result: SessionBeforeEventResult | undefined;
1099
1100 for (const { ext, handlers } of snapshotEventHandlers(this.extensions, event.type)) {
1101 for (const handler of handlers) {
1102 try {
1103 const handlerResult = await handler(event, ctx);
1104
1105 if (this.isSessionBeforeEvent(event) && handlerResult) {
1106 result = handlerResult as SessionBeforeEventResult;
1107 if (result.cancel) {
1108 return result as RunnerEmitResult<TEvent>;
1109 }
1110 }
1111 } catch (err) {
1112 const message = err instanceof Error ? err.message : String(err);
1113 const stack = err instanceof Error ? err.stack : undefined;
1114 this.emitError({
1115 extensionPath: ext.path,
1116 event: event.type,
1117 error: message,
1118 stack,
1119 });
1120 }
1121 }
1122 }
1123
1124 return result as RunnerEmitResult<TEvent>;
1125 }
1126
1127 /** Returns the event's own action unless a handler overrides it; the last override wins. */
1128 async emitCacheWarmingDecision(event: CacheWarmingDecisionEvent): Promise<CacheWarmingAction> {
1129 const ctx = this.createContext();
1130 let action = event.action;
1131
1132 for (const { ext, handlers } of snapshotEventHandlers(this.extensions, event.type)) {
1133 for (const handler of handlers) {
1134 try {
1135 const result = (await handler(event, ctx)) as CacheWarmingDecisionEventResult | undefined;
1136 if (result?.action !== undefined) action = result.action;
1137 } catch (err) {
1138 this.emitError({
1139 extensionPath: ext.path,
1140 event: event.type,
1141 error: err instanceof Error ? err.message : String(err),
1142 stack: err instanceof Error ? err.stack : undefined,
1143 });
1144 }
1145 }
1146 }
1147
1148 return action;
1149 }
1150
1151 async emitMessageEnd(event: MessageEndEvent): Promise<AgentMessage | undefined> {
1152 const ctx = this.createContext();
1153 let currentMessage = event.message;
1154 let modified = false;
1155
1156 for (const { ext, handlers } of snapshotEventHandlers(this.extensions, "message_end")) {
1157 for (const handler of handlers) {
1158 try {
1159 const currentEvent: MessageEndEvent = { ...event, message: currentMessage };
1160 const handlerResult = (await handler(currentEvent, ctx)) as MessageEndEventResult | undefined;
1161 if (!handlerResult?.message) continue;
1162
1163 if (handlerResult.message.role !== currentMessage.role) {
1164 this.emitError({
1165 extensionPath: ext.path,
1166 event: "message_end",
1167 error: "message_end handlers must return a message with the same role",
1168 });
1169 continue;
1170 }
1171
1172 currentMessage = handlerResult.message;
1173 modified = true;
1174 } catch (err) {
1175 const message = err instanceof Error ? err.message : String(err);
1176 const stack = err instanceof Error ? err.stack : undefined;
1177 this.emitError({
1178 extensionPath: ext.path,
1179 event: "message_end",
1180 error: message,
1181 stack,
1182 });
1183 }
1184 }
1185 }
1186
1187 return modified ? currentMessage : undefined;
1188 }
1189
1190 async emitToolResult(event: ToolResultEvent): Promise<ToolResultEventResult | undefined> {
1191 const ctx = this.createContext();
1192 const currentEvent: ToolResultEvent = { ...event };
1193 let modified = false;
1194
1195 for (const { ext, handlers } of snapshotEventHandlers(this.extensions, "tool_result")) {
1196 for (const handler of handlers) {
1197 try {
1198 const handlerResult = (await handler(currentEvent, ctx)) as ToolResultEventResult | undefined;
1199 if (!handlerResult) continue;
1200
1201 if (handlerResult.content !== undefined) {
1202 currentEvent.content = handlerResult.content;
1203 // Structured content that is not replaced along with the content may no longer match it.
1204 if (handlerResult.structuredContent === undefined) delete currentEvent.structuredContent;
1205 modified = true;
1206 }
1207 if (handlerResult.details !== undefined) {
1208 currentEvent.details = handlerResult.details;
1209 modified = true;
1210 }
1211 if (handlerResult.structuredContent !== undefined) {
1212 currentEvent.structuredContent = handlerResult.structuredContent;
1213 modified = true;
1214 }
1215 if (handlerResult.isError !== undefined) {
1216 currentEvent.isError = handlerResult.isError;
1217 modified = true;
1218 }
1219 if (handlerResult.usage !== undefined) {
1220 currentEvent.usage = handlerResult.usage;
1221 modified = true;
1222 }
1223 } catch (err) {
1224 const message = err instanceof Error ? err.message : String(err);
1225 const stack = err instanceof Error ? err.stack : undefined;
1226 this.emitError({
1227 extensionPath: ext.path,
1228 event: "tool_result",
1229 error: message,
1230 stack,
1231 });
1232 }
1233 }
1234 }
1235
1236 if (!modified) {
1237 return undefined;
1238 }
1239
1240 return {
1241 content: currentEvent.content,
1242 details: currentEvent.details,
1243 structuredContent: currentEvent.structuredContent,
1244 isError: currentEvent.isError,
1245 usage: currentEvent.usage,
1246 };
1247 }
1248
1249 async emitToolCall(event: ToolCallEvent): Promise<ToolCallEventResult | undefined> {
1250 const ctx = this.createContext();
1251 let result: ToolCallEventResult | undefined;
1252
1253 for (const { handlers } of snapshotEventHandlers(this.extensions, "tool_call")) {
1254 for (const handler of handlers) {
1255 const handlerResult = await handler(event, ctx);
1256
1257 if (handlerResult) {
1258 result = handlerResult as ToolCallEventResult;
1259 if (result.block) {
1260 return result;
1261 }
1262 }
1263 }
1264 }
1265
1266 return result;
1267 }
1268
1269 async emitUserBash(event: UserBashEvent): Promise<UserBashEventResult | undefined> {
1270 const ctx = this.createContext();
1271
1272 for (const { ext, handlers } of snapshotEventHandlers(this.extensions, "user_bash")) {
1273 for (const handler of handlers) {
1274 try {
1275 const handlerResult = await handler(event, ctx);
1276 if (handlerResult === undefined) continue;
1277 if (!isUserBashEventResult(handlerResult)) {
1278 throw new Error(
1279 "Invalid user_bash handler result: return undefined for local execution or exactly one valid { operations } or { result } object",
1280 );
1281 }
1282 return handlerResult;
1283 } catch (err) {
1284 const message = err instanceof Error ? err.message : String(err);
1285 const stack = err instanceof Error ? err.stack : undefined;
1286 this.emitError({
1287 extensionPath: ext.path,
1288 event: "user_bash",
1289 error: message,
1290 stack,
1291 });
1292 throw err;
1293 }
1294 }
1295 }
1296
1297 return undefined;
1298 }
1299
1300 /**
1301 * Run the request-time transforms in two phases. `context` handlers see the conversation
1302 * only and Pi restores the prompt and tool state after each; `context_with_system`
1303 * handlers then see the full transcript and their output is used as returned.
1304 */
1305 async emitContext(messages: AgentMessage[]): Promise<AgentMessage[]> {
1306 const ctx = this.createContext();
1307 let currentMessages = structuredClone(messages);
1308
1309 for (const { ext, handlers } of snapshotEventHandlers(this.extensions, "context")) {
1310 for (const handler of handlers) {
1311 try {
1312 const visibleMessages = currentMessages.filter((message) => message.role !== "system");
1313 const visibleSnapshot = visibleMessages.slice();
1314 const event: ContextEvent = { type: "context", messages: visibleMessages };
1315 const handlerResult = (await handler(event, ctx)) as ContextEventResult | undefined;
1316
1317 // Handlers may return a new list or edit event.messages in place.
1318 const returned =
1319 handlerResult?.messages ??
1320 (sameMessages(visibleMessages, visibleSnapshot) ? undefined : visibleMessages);
1321 if (!returned) continue;
1322 currentMessages = restoreSystemMessages(currentMessages, visibleSnapshot, returned);
1323 } catch (err) {
1324 const message = err instanceof Error ? err.message : String(err);
1325 const stack = err instanceof Error ? err.stack : undefined;
1326 this.emitError({
1327 extensionPath: ext.path,
1328 event: "context",
1329 error: message,
1330 stack,
1331 });
1332 }
1333 }
1334 }
1335
1336 for (const { ext, handlers } of snapshotEventHandlers(this.extensions, "context_with_system")) {
1337 for (const handler of handlers) {
1338 try {
1339 const hadLeadingSystemMessage = currentMessages[0]?.role === "system";
1340 const event: ContextWithSystemEvent = { type: "context_with_system", messages: currentMessages };
1341 const handlerResult = (await handler(event, ctx)) as ContextEventResult | undefined;
1342 currentMessages = handlerResult?.messages ?? currentMessages;
1343 // Providers read the prompt and initial tools from the leading system message.
1344 // Losing it is never intended; report it but honor the handler's output.
1345 if (hadLeadingSystemMessage && currentMessages[0]?.role !== "system") {
1346 this.emitError({
1347 extensionPath: ext.path,
1348 event: "context_with_system",
1349 error: "Handler removed the leading system message; the request has no prompt or initial tool declarations. Keep it at index 0 or replace a dropped prefix with getCurrentSystemMessage().",
1350 });
1351 }
1352 } catch (err) {
1353 const message = err instanceof Error ? err.message : String(err);
1354 const stack = err instanceof Error ? err.stack : undefined;
1355 this.emitError({
1356 extensionPath: ext.path,
1357 event: "context_with_system",
1358 error: message,
1359 stack,
1360 });
1361 }
1362 }
1363 }
1364
1365 return currentMessages;
1366 }
1367
1368 async emitBeforeProviderRequest(payload: unknown): Promise<unknown> {
1369 const ctx = this.createContext();
1370 let currentPayload = payload;
1371
1372 for (const { ext, handlers } of snapshotEventHandlers(this.extensions, "before_provider_request")) {
1373 for (const handler of handlers) {
1374 try {
1375 const event: BeforeProviderRequestEvent = {
1376 type: "before_provider_request",
1377 payload: currentPayload,
1378 };
1379 const handlerResult = await handler(event, ctx);
1380 if (handlerResult !== undefined) {
1381 currentPayload = handlerResult;
1382 }
1383 } catch (err) {
1384 const message = err instanceof Error ? err.message : String(err);
1385 const stack = err instanceof Error ? err.stack : undefined;
1386 this.emitError({
1387 extensionPath: ext.path,
1388 event: "before_provider_request",
1389 error: message,
1390 stack,
1391 });
1392 }
1393 }
1394 }
1395
1396 return currentPayload;
1397 }
1398
1399 async emitBeforeProviderHeaders(headers: ProviderHeaders): Promise<ProviderHeaders> {
1400 const ctx = this.createContext();
1401
1402 for (const { ext, handlers } of snapshotEventHandlers(this.extensions, "before_provider_headers")) {
1403 for (const handler of handlers) {
1404 try {
1405 // Handlers mutate `headers` in place; the return value is ignored.
1406 const event: BeforeProviderHeadersEvent = {
1407 type: "before_provider_headers",
1408 headers,
1409 };
1410 await handler(event, ctx);
1411 } catch (err) {
1412 const message = err instanceof Error ? err.message : String(err);
1413 const stack = err instanceof Error ? err.stack : undefined;
1414 this.emitError({
1415 extensionPath: ext.path,
1416 event: "before_provider_headers",
1417 error: message,
1418 stack,
1419 });
1420 }
1421 }
1422 }
1423
1424 return headers;
1425 }
1426
1427 async emitBeforeAgentStart(
1428 trigger: BeforeAgentStartTrigger,
1429 systemPromptOptions: BuildSystemPromptOptions,
1430 ): Promise<BeforeAgentStartCombinedResult> {
1431 const currentOptions = normalizeBuildSystemPromptOptions(systemPromptOptions);
1432 const renderCurrentSystemPrompt = (): string => buildSystemPrompt(currentOptions);
1433 const ctx = Object.defineProperties(
1434 {},
1435 Object.getOwnPropertyDescriptors(this.createContext()),
1436 ) as ExtensionContext;
1437 ctx.getSystemPrompt = () => {
1438 this.assertActive();
1439 return renderCurrentSystemPrompt();
1440 };
1441 const messages: NonNullable<BeforeAgentStartEventResult["message"]>[] = [];
1442
1443 for (const { ext, handlers } of snapshotEventHandlers(this.extensions, "before_agent_start")) {
1444 for (const handler of handlers) {
1445 try {
1446 const event: BeforeAgentStartEvent = {
1447 ...trigger,
1448 type: "before_agent_start",
1449 get systemPrompt() {
1450 return renderCurrentSystemPrompt();
1451 },
1452 systemPromptOptions: currentOptions,
1453 };
1454 const handlerResult = await handler(event, ctx);
1455
1456 if (handlerResult) {
1457 const result = handlerResult as BeforeAgentStartEventResult;
1458 if (result.message) messages.push(result.message);
1459 if (result.systemPrompt !== undefined) {
1460 currentOptions.forceSystemPrompt = result.systemPrompt;
1461 }
1462 }
1463 } catch (err) {
1464 const message = err instanceof Error ? err.message : String(err);
1465 const stack = err instanceof Error ? err.stack : undefined;
1466 this.emitError({
1467 extensionPath: ext.path,
1468 event: "before_agent_start",
1469 error: message,
1470 stack,
1471 });
1472 }
1473 }
1474 }
1475
1476 return { messages, systemPromptOptions: currentOptions };
1477 }
1478
1479 async emitResourcesDiscover(
1480 cwd: string,
1481 reason: ResourcesDiscoverEvent["reason"],
1482 ): Promise<{
1483 skillPaths: Array<{ path: string; extensionPath: string }>;
1484 promptPaths: Array<{ path: string; extensionPath: string }>;
1485 themePaths: Array<{ path: string; extensionPath: string }>;
1486 }> {
1487 const ctx = this.createContext();
1488 const skillPaths: Array<{ path: string; extensionPath: string }> = [];
1489 const promptPaths: Array<{ path: string; extensionPath: string }> = [];
1490 const themePaths: Array<{ path: string; extensionPath: string }> = [];
1491
1492 for (const { ext, handlers } of snapshotEventHandlers(this.extensions, "resources_discover")) {
1493 for (const handler of handlers) {
1494 try {
1495 const event: ResourcesDiscoverEvent = { type: "resources_discover", cwd, reason };
1496 const handlerResult = await handler(event, ctx);
1497 const result = handlerResult as ResourcesDiscoverResult | undefined;
1498
1499 if (result?.skillPaths?.length) {
1500 skillPaths.push(...result.skillPaths.map((path) => ({ path, extensionPath: ext.path })));
1501 }
1502 if (result?.promptPaths?.length) {
1503 promptPaths.push(...result.promptPaths.map((path) => ({ path, extensionPath: ext.path })));
1504 }
1505 if (result?.themePaths?.length) {
1506 themePaths.push(...result.themePaths.map((path) => ({ path, extensionPath: ext.path })));
1507 }
1508 } catch (err) {
1509 const message = err instanceof Error ? err.message : String(err);
1510 const stack = err instanceof Error ? err.stack : undefined;
1511 this.emitError({
1512 extensionPath: ext.path,
1513 event: "resources_discover",
1514 error: message,
1515 stack,
1516 });
1517 }
1518 }
1519 }
1520
1521 return { skillPaths, promptPaths, themePaths };
1522 }
1523
1524 /** Emit input event. Transforms chain, "handled" short-circuits. */
1525 async emitInput(
1526 text: string,
1527 images: ImageContent[] | undefined,
1528 source: InputSource,
1529 streamingBehavior?: "steer" | "followUp",
1530 ): Promise<InputEventResult> {
1531 const ctx = this.createContext();
1532 let currentText = text;
1533 let currentImages = images;
1534
1535 for (const { ext, handlers } of snapshotEventHandlers(this.extensions, "input")) {
1536 for (const handler of handlers) {
1537 try {
1538 const event: InputEvent = {
1539 type: "input",
1540 text: currentText,
1541 images: currentImages,
1542 source,
1543 streamingBehavior,
1544 };
1545 const result = (await handler(event, ctx)) as InputEventResult | undefined;
1546 if (result?.action === "handled") return result;
1547 if (result?.action === "transform") {
1548 currentText = result.text;
1549 currentImages = result.images ?? currentImages;
1550 }
1551 } catch (err) {
1552 this.emitError({
1553 extensionPath: ext.path,
1554 event: "input",
1555 error: err instanceof Error ? err.message : String(err),
1556 stack: err instanceof Error ? err.stack : undefined,
1557 });
1558 }
1559 }
1560 }
1561 return currentText !== text || currentImages !== images
1562 ? { action: "transform", text: currentText, images: currentImages }
1563 : { action: "continue" };
1564 }
1565}