Repository navigation
Expand file tree
/
Copy pathrunner.ts
More file actions
2608 lines (2439 loc) · 91.2 KB
/
Copy pathrunner.ts
File metadata and controls
2608 lines (2439 loc) · 91.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Extension runner - executes extensions and manages their lifecycle.
*/
import { basename } from "node:path";
import type { AgentMessage, AgentTool } from "@earendil-works/pi-agent-core";
import type { Api, ImageContent, Model, Provider, ProviderHeaders } from "@earendil-works/pi-ai";
import type { KeyId } from "@earendil-works/pi-tui";
import { getAgentDir } from "../../config.ts";
import { type Theme, theme } from "../../modes/interactive/theme/theme.ts";
import { stripAnsi } from "../../utils/ansi.ts";
import type { ResourceDiagnostic } from "../diagnostics.ts";
import type { DiscoveredResourceEntry } from "../discovered-resource-scope.ts";
import type { DynamicSystemPromptPart } from "../dynamic-prompt/build.ts";
import { createEventBus, type EventBus, EXTENSION_RPC_EVENT_CHANNEL, type ExtensionRpcEvent } from "../event-bus.ts";
import type { InputOrigin } from "../input-origin.ts";
import type { KeybindingsConfig } from "../keybindings.ts";
import { inheritMcpMrtrPresentation } from "../mcp-mrtr-presentations.ts";
import type { NamedMemoryReporter } from "../memory-report/memory-report-registry.ts";
import type { ModelRegistry } from "../model-registry.ts";
import type { ScopedModel } from "../model-resolver.ts";
import { bindQuestionInput } from "../question-input.ts";
import type { SessionManager } from "../session-manager.ts";
import {
DEFAULT_EXTENSION_EVENT_HANDLER_TIMEOUT_MS,
DEFAULT_EXTENSION_EVENT_HANDLER_WARN_MS,
DEFAULT_SESSION_SHUTDOWN_HANDLER_TIMEOUT_MS,
DEFAULT_SESSION_SHUTDOWN_HANDLER_WARN_MS,
DEFAULT_SESSION_SHUTDOWN_QUIT_BUDGET_MS,
SettingsManager,
} from "../settings-manager.ts";
import type { BuildSystemPromptOptions } from "../system-prompt.ts";
import type { VirtualModelDefinition } from "../virtual-models.ts";
import { goalFilePath } from "./builtin/goal/persistence.ts";
import { goalStoreRef } from "./builtin/goal/store-ref.ts";
import { disableServerSearch } from "./builtin/server-search-fallback.ts";
import { dispatchContextMessages } from "./context-dispatch.ts";
import { reclaimRunnerHandles, registerRunnerExtensions } from "./extension-handle-ledger.ts";
import {
type BudgetedSequence,
type ExtensionHandlerBudget,
type ExtensionHandlerStall,
type HandlerStopVerdict,
HeldHandlerWaits,
runBudgetedHandler,
runBudgetedSequence,
} from "./handler-budget.ts";
import { kernelToolsStorage } from "./kernel-tools-context.ts";
import { drainPendingProviderRegistrations } from "./loader.ts";
import { runSessionMoveHandlers, type SessionMoveEmission, type SessionMoveFailure } from "./session-move-emit.ts";
import { SessionStartTurnGate } from "./session-start-turn-gate.ts";
import { QuitDeadline, type QuitHandlerBudget, type SessionShutdownBudget } from "./shutdown-quit-budget.ts";
import { StaleExtensionContextError } from "./stale-context-error.ts";
import type {
AgentBeforeSettleEvent,
BeforeAgentStartEvent,
BeforeAgentStartEventResult,
BeforeProviderHeadersEvent,
BeforeProviderRequestEvent,
BoundaryContextPreview,
BoundaryResult,
CompactOptions,
ContextEvent,
ContextUsage,
ContextWithSystemEvent,
EntryRenderer,
EntryRendererOptions,
ExecuteToolOptions,
Extension,
ExtensionActions,
ExtensionCommandContext,
ExtensionCommandContextActions,
ExtensionContext,
ExtensionContextActions,
ExtensionError,
ExtensionEvent,
ExtensionFlag,
ExtensionMode,
ExtensionRuntime,
ExtensionShortcut,
ExtensionToolContext,
ExtensionUIContext,
InputEvent,
InputEventResult,
InputSource,
LoadExtensionsResult,
MarkdownTransformer,
MessageEndEvent,
MessageEndEventResult,
MessageRenderer,
ModelSelectEvent,
ModelSelectEventResult,
OffloadOptions,
ProjectTrustContext,
ProjectTrustEvent,
ProjectTrustEventResult,
ProviderConfig,
ProviderRequestPreparation,
RegisteredChildModule,
RegisteredCommand,
RegisteredMcpServerDeclaration,
RegisteredTool,
ReplacedSessionContext,
ResolvedCommand,
ResourceDiscoverEntry,
ResourcesDiscoverEvent,
ResourcesDiscoverResult,
SendMessageReceipt,
ServiceTier,
SessionBeforeCompactResult,
SessionBeforeForkResult,
SessionBeforeReloadResult,
SessionBeforeSwitchResult,
SessionBeforeTreeResult,
SessionBoundaryDraft,
SessionShutdownEvent,
ToolCallEvent,
ToolCallEventResult,
ToolResultEvent,
ToolResultEventResult,
TurnEndEvent,
UIPromptKind,
UserBashEvent,
UserBashEventResult,
} from "./types.ts";
import { RUNTIME_EXTENSION_PATH } from "./types.ts";
export class ExtensionRpcRequestNotFoundError extends Error {
constructor(name: string) {
super(`Unknown extension RPC request: ${name}`);
this.name = "ExtensionRpcRequestNotFoundError";
}
}
// Extension shortcuts compete with canonical keybinding ids from keybindings.json.
// Only editor-global shortcuts are reserved here. Picker-specific bindings are not.
const RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS = [
"app.interrupt",
"app.clear",
"app.exit",
"app.suspend",
"app.thinking.cycle",
"app.model.cycleForward",
"app.model.cycleBackward",
"app.model.select",
"app.tools.expand",
"app.thinking.toggle",
"app.editor.external",
"app.message.copy",
"app.message.followUp",
"tui.input.submit",
"tui.select.confirm",
"tui.select.cancel",
"tui.input.copy",
"tui.editor.deleteToLineEnd",
] as const;
type BuiltInKeyBindings = Partial<Record<KeyId, { keybinding: string; restrictOverride: boolean }>>;
const buildBuiltinKeybindings = (resolvedKeybindings: KeybindingsConfig): BuiltInKeyBindings => {
const builtinKeybindings = {} as BuiltInKeyBindings;
for (const [keybinding, keys] of Object.entries(resolvedKeybindings)) {
if (keys === undefined) continue;
const keyList = Array.isArray(keys) ? keys : [keys];
const restrictOverride = (RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS as readonly string[]).includes(keybinding);
for (const key of keyList) {
const normalizedKey = key.toLowerCase() as KeyId;
// If multiple actions bind the same key, the reserved action wins so extensions
// remain blocked by reserved shortcuts regardless of iteration order.
const existing = builtinKeybindings[normalizedKey];
if (existing?.restrictOverride && !restrictOverride) continue;
builtinKeybindings[normalizedKey] = {
keybinding,
restrictOverride,
};
}
}
return builtinKeybindings;
};
function isUserBashEventResult(value: unknown): value is UserBashEventResult {
if (typeof value !== "object" || value === null) return false;
const candidate = value as Record<string, unknown>;
const hasOperations = candidate.operations !== undefined;
const hasResult = candidate.result !== undefined;
if (hasOperations === hasResult) return false;
if (hasOperations) {
const operations = candidate.operations;
if (typeof operations !== "object" || operations === null) return false;
return typeof (operations as Record<string, unknown>).exec === "function";
}
const result = candidate.result;
if (typeof result !== "object" || result === null) return false;
const resultRecord = result as Record<string, unknown>;
return (
typeof resultRecord.output === "string" &&
"exitCode" in resultRecord &&
(resultRecord.exitCode === undefined || typeof resultRecord.exitCode === "number") &&
typeof resultRecord.cancelled === "boolean" &&
typeof resultRecord.truncated === "boolean" &&
(resultRecord.fullOutputPath === undefined || typeof resultRecord.fullOutputPath === "string")
);
}
/** Combined result from all before_agent_start handlers */
interface BeforeAgentStartCombinedResult {
messages?: NonNullable<BeforeAgentStartEventResult["message"]>[];
systemPrompt?: string;
}
/**
* Events handled by the generic emit() method.
* Events with dedicated emitXxx() methods are excluded for stronger type safety.
*/
type RunnerEmitEvent = Exclude<
ExtensionEvent,
| ToolCallEvent
| ProjectTrustEvent
| ToolResultEvent
| UserBashEvent
| ContextEvent
| ContextWithSystemEvent
| BeforeProviderRequestEvent
| BeforeProviderHeadersEvent
| BeforeAgentStartEvent
| ModelSelectEvent
| MessageEndEvent
| ResourcesDiscoverEvent
| InputEvent
| TurnEndEvent
| AgentBeforeSettleEvent
>;
type SessionBeforeEvent = Extract<
RunnerEmitEvent,
{
type:
| "session_before_switch"
| "session_before_fork"
| "session_before_reload"
| "session_before_compact"
| "session_before_tree";
}
>;
type SessionBeforeEventResult =
| SessionBeforeSwitchResult
| SessionBeforeForkResult
| SessionBeforeReloadResult
| SessionBeforeCompactResult
| SessionBeforeTreeResult;
type RunnerEmitResult<TEvent extends RunnerEmitEvent> = TEvent extends { type: "session_before_switch" }
? SessionBeforeSwitchResult | undefined
: TEvent extends { type: "session_before_fork" }
? SessionBeforeForkResult | undefined
: TEvent extends { type: "session_before_reload" }
? SessionBeforeReloadResult | undefined
: TEvent extends { type: "session_before_compact" }
? SessionBeforeCompactResult | undefined
: TEvent extends { type: "session_before_tree" }
? SessionBeforeTreeResult | undefined
: undefined;
export type ExtensionErrorListener = (error: ExtensionError) => void;
function boundedToolHookStatusMessage(message: string): string {
return message.length <= 79 ? message : `${message.slice(0, 76)}...`;
}
function sanitizedToolHookStatusMessage(message: string): string {
return boundedToolHookStatusMessage(
stripAnsi(message)
.replace(/[\r\n\t]+/g, " ")
.replace(/[\u0000-\u001f\u007f]+/g, "")
.replace(/\s+/g, " ")
.trim(),
);
}
export type ExtensionToolHookName = "PreToolUse" | "PostToolUse";
export type ExtensionToolHookLifecycleStatus = "completed" | "blocked" | "failed";
type ExtensionToolHookLifecycleEventBase = {
type: "tool_hook_status";
hookRunId: string;
hookName: ExtensionToolHookName;
toolName: string;
toolCallId: string;
extensionPath: string;
statusMessage: string;
startedAt: number;
};
export type ExtensionToolHookLifecycleEvent =
| (ExtensionToolHookLifecycleEventBase & {
phase: "start";
})
| (ExtensionToolHookLifecycleEventBase & {
phase: "update";
})
| (ExtensionToolHookLifecycleEventBase & {
phase: "end";
completedAt: number;
status: ExtensionToolHookLifecycleStatus;
errorMessage?: string;
});
export type ExtensionToolHookLifecycleObserver = (event: ExtensionToolHookLifecycleEvent) => void;
type BoundaryBaseEvent =
| Omit<TurnEndEvent, "entries" | "continue" | "context">
| Omit<AgentBeforeSettleEvent, "entries" | "continue" | "context">;
interface BoundaryDispatchResult {
entries: SessionBoundaryDraft[];
continue: boolean;
context: BoundaryContextPreview;
valid: boolean;
}
export type NewSessionHandler = (options?: {
parentSession?: string;
setup?: (sessionManager: SessionManager) => Promise<void>;
withSession?: (ctx: ReplacedSessionContext) => Promise<void>;
}) => Promise<{ cancelled: boolean }>;
export type ForkHandler = (
entryId: string,
options?: { position?: "before" | "at"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },
) => Promise<{ cancelled: boolean }>;
export type NavigateTreeHandler = ExtensionCommandContextActions["navigateTree"];
export type EditUserMessageHandler = ExtensionCommandContextActions["editUserMessage"];
export type EditAssistantMessageHandler = (
entryId: string,
text: string,
options?: { summarize?: boolean; customInstructions?: string; expectedLeafId?: string },
) => Promise<{ cancelled: boolean; unchanged?: boolean; entryId?: string }>;
export type SwitchSessionHandler = (
sessionPath: string,
options?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },
) => Promise<{ cancelled: boolean }>;
export type ReloadHandler = () => Promise<void>;
export type ShutdownHandler = () => void;
/**
* Agent lifecycle events the session awaits on its serial event queue before it persists a turn (senpi#3650).
* Their handlers observe; none may hold the queue indefinitely, so each runs under the host's event handler budget.
*/
const QUEUED_LIFECYCLE_EVENTS: ReadonlySet<string> = new Set([
"agent_start",
"agent_end",
"agent_settled",
"turn_start",
"message_start",
"message_update",
"message_end",
"tool_execution_start",
"tool_execution_update",
"tool_execution_end",
]);
const UNBOUNDED_HANDLER_BUDGET: ExtensionHandlerBudget = { warnMs: 0, timeoutMs: 0 };
/**
* Helper function to emit session_shutdown event to extensions.
* Returns true if the event was emitted, false if there were no handlers.
*
* Each handler runs under the host's shutdown budget (see
* `ExtensionRunner.emit`), so a hung extension cannot hold teardown hostage.
* Afterwards senpi closes the servers, sockets and timers an extension instance
* still holds open (senpi#2292), with or without handlers.
*/
export async function emitSessionShutdownEvent(
extensionRunner: ExtensionRunner,
event: SessionShutdownEvent,
options: { readonly processExit?: boolean } = {},
): Promise<boolean> {
if (options.processExit && event.reason === "quit") extensionRunner.armProcessExitBudget();
const emitted = extensionRunner.hasHandlers("session_shutdown");
if (emitted) await extensionRunner.emit(event);
reclaimRunnerHandles(extensionRunner);
return emitted;
}
function snapshotEventHandlers(extensions: Extension[], event: ExtensionEvent["type"]) {
return extensions.map((ext) => ({ ext, handlers: ext.handlers.get(event)?.slice() ?? [] }));
}
type EventHandlerFn = NonNullable<ReturnType<Extension["handlers"]["get"]>>[number];
interface HandlerEntry {
readonly path: string;
readonly handler: EventHandlerFn;
}
/** The same snapshot as `snapshotEventHandlers`, in dispatch order, one entry per handler. */
function flattenHandlers(extensions: Extension[], event: ExtensionEvent["type"]): readonly HandlerEntry[] {
return snapshotEventHandlers(extensions, event).flatMap(({ ext, handlers }) =>
handlers.map((handler) => ({ path: ext.path, handler })),
);
}
function entryAt(entries: readonly HandlerEntry[], index: number): HandlerEntry {
const entry = entries[index];
if (entry === undefined) throw new RangeError(`no extension handler at index ${index}`);
return entry;
}
export async function emitProjectTrustEvent(
extensionsResult: LoadExtensionsResult,
event: ProjectTrustEvent,
ctx: ProjectTrustContext,
): Promise<{ result?: ProjectTrustEventResult; errors: ExtensionError[] }> {
const errors: ExtensionError[] = [];
for (const { ext, handlers } of snapshotEventHandlers(extensionsResult.extensions, "project_trust")) {
// A single extension may register multiple handlers for the same event.
// The first project_trust handler that returns yes/no wins; undecided falls through.
for (const handler of handlers) {
try {
const handlerResult = (await handler(event, ctx)) as ProjectTrustEventResult;
if (handlerResult.trusted === "undecided") {
continue;
}
return { result: handlerResult, errors };
} catch (error) {
errors.push({
extensionPath: ext.path,
event: event.type,
error: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
});
}
}
}
return { errors };
}
function createNoOpSessionSettings(): ExtensionContextActions["sessionSettings"] {
const settings = SettingsManager.inMemory();
return {
getRetryFallbackSettings: () => settings.getRetryFallbackSettings(),
setFallbackChain: async (key, entries) => {
settings.setFallbackChain(key, [...entries]);
await settings.flush();
},
removeFallbackChain: async (key) => {
settings.removeFallbackChain(key);
await settings.flush();
},
setModelFallbackEnabled: async (enabled) => {
settings.setModelFallbackEnabled(enabled);
await settings.flush();
},
setFallbackRevertPolicy: async (policy) => {
settings.setFallbackRevertPolicy(policy);
await settings.flush();
},
reload: () => settings.reload(),
getFallbackStatus: () => undefined,
};
}
const noOpUIContext: ExtensionUIContext = {
select: async () => undefined,
confirm: async () => false,
input: async () => undefined,
notify: () => {},
onTerminalInput: () => () => {},
setStatus: () => {},
setSubagentCost: () => {},
setWorkingMessage: () => {},
setWorkingVisible: () => {},
setWorkingIndicator: () => {},
setHiddenThinkingLabel: () => {},
setWidget: () => {},
setFooter: () => {},
setHeader: () => {},
setTitle: () => {},
custom: async () => undefined as never,
pasteToEditor: () => {},
setEditorText: () => {},
getEditorText: () => "",
editor: async () => undefined,
addAutocompleteProvider: () => {},
setEditorComponent: () => {},
getEditorComponent: () => undefined,
get theme() {
return theme;
},
getAllThemes: () => [],
getTheme: () => undefined,
setTheme: (_theme: string | Theme) => ({ success: false, error: "UI not available" }),
getToolsExpanded: () => false,
setToolsExpanded: () => {},
};
export class ExtensionRunner {
private extensions: Extension[];
private runtime: ExtensionRuntime;
private uiContext: ExtensionUIContext;
private mode: ExtensionMode = "print";
private cwd: string;
private sessionManager: SessionManager;
private modelRegistry: ModelRegistry;
private eventBus: EventBus;
private errorListeners: Set<ExtensionErrorListener> = new Set();
private eventHandlerBudget: () => ExtensionHandlerBudget = () => UNBOUNDED_HANDLER_BUDGET;
private handlerStallListener: ((stall: ExtensionHandlerStall) => void) | undefined;
private handlerTurnScope: () => number = () => 0;
private reportedInvalidHandlerBudget = false;
private processExitRequestedAt: number | undefined;
private readonly heldHandlerWaits = new HeldHandlerWaits();
private getModel: () => Model<any> | undefined = () => undefined;
private getServiceTier: () => ServiceTier | undefined = () => undefined;
private getEffectiveServiceTier: () => ServiceTier | undefined = () => this.getServiceTier();
private getScopedModels: () => readonly ScopedModel[] = () => [];
private isIdleFn: () => boolean = () => true;
private engineTurnsHeldFn: () => boolean = () => false;
private noteHeldWakeFn: (source: string) => void = () => {};
private pauseActions: Pick<ExtensionContextActions, "getPauseState" | "fenceRun" | "releaseRunFence"> = {};
private questionInput: ExtensionContextActions["questionInput"];
private personAnswerPending = false;
private isProjectTrustedFn: () => boolean = () => true;
private getSignalFn: () => AbortSignal | undefined = () => undefined;
private waitForIdleFn: () => Promise<void> = async () => {};
private abortFn: ExtensionContextActions["abort"] = () => {};
private hasPendingMessagesFn: () => boolean = () => false;
private hasQueuedPersonInputFn: () => boolean = () => false;
private isCompactingFn: () => boolean = () => false;
private checkReloadVetoFn: ExtensionContextActions["checkReloadVeto"];
private getContextUsageFn: () => ContextUsage | undefined = () => undefined;
private getCompactionModelFn: ExtensionContextActions["getCompactionModel"];
private getCompactionSettingsFn: ExtensionContextActions["getCompactionSettings"] = () => ({
enabled: true,
reserveTokens: 16384,
keepRecentTokens: 20000,
});
private getPromptCacheSafeWaitSecondsFn: () => number | undefined = () => undefined;
private getPromptCacheGoalBackstopMaxSecondsFn: () => number = () => 270;
private getPromptCacheKeepAliveSettingsFn: NonNullable<ExtensionContextActions["getPromptCacheKeepAliveSettings"]> =
() => ({ enabled: false, maxRequestsPerSession: 3, maxCostUsdPerSession: 0.05, marginSeconds: 60 });
private getLookAtSettingsFn: ExtensionContextActions["getLookAtSettings"] = () => ({
enabled: true,
models: undefined,
});
private getAskUserSettingsFn: () => { enabled: boolean; timeoutMinutes: number } = () => ({
enabled: true,
timeoutMinutes: 30,
});
private getBrowserEngineFn: NonNullable<ExtensionContextActions["getBrowserEngine"]> = () => undefined;
private getImageSettingsFn: ExtensionContextActions["getImageSettings"] = () => ({
autoResize: true,
blockImages: false,
});
private sessionSettingsFn: ExtensionContextActions["sessionSettings"] = createNoOpSessionSettings();
private compactFn: (options?: CompactOptions) => void = () => {};
private beginCompactionFn: ExtensionContextActions["beginCompaction"] = undefined;
private updateCompactionFn: ExtensionContextActions["updateCompaction"] = undefined;
private endCompactionFn: ExtensionContextActions["endCompaction"] = undefined;
private getMessageRevisionFn: () => number = () => 0;
private applyCompactionFn: ExtensionContextActions["applyCompaction"] = async () => ({
applied: false,
reason: "rejected",
});
private getSystemPromptFn: () => string = () => "";
private getLoadedHookSourcesFn: ExtensionContextActions["getLoadedHookSources"] = () => ({
agentDir: "",
cwd: this.cwd,
globalHookSourcePaths: [],
globalHooksPath: "",
preSessionHookSourcePaths: [],
projectHookSourcePaths: [],
projectHooksPath: "",
runtimeHookSourcePaths: [],
});
private getSystemPromptOptionsFn: () => BuildSystemPromptOptions = () => ({ cwd: this.cwd });
private getPromptCachePrefixRequestFn: ExtensionContextActions["getPromptCachePrefixRequest"] = undefined;
private onUserActivityFn: ExtensionContextActions["onUserActivity"];
private getAgentDirFn: () => string = () => getAgentDir();
private executeToolFn: ExtensionContextActions["executeTool"];
private offloadFn: ExtensionContextActions["offload"];
private getCallableToolsFn: () => readonly AgentTool[] = () => [];
private newSessionHandler: NewSessionHandler = async () => ({ cancelled: false });
private forkHandler: ForkHandler = async () => ({ cancelled: false });
private navigateTreeHandler: NavigateTreeHandler = async () => ({ cancelled: false });
private editAssistantMessageHandler: EditAssistantMessageHandler = async () => ({ cancelled: false });
private editUserMessageHandler: EditUserMessageHandler = async () => ({ cancelled: false });
private switchSessionHandler: SwitchSessionHandler = async () => ({ cancelled: false });
private reloadHandler: ReloadHandler | undefined;
private reloadRequestPromise: Promise<void> | undefined;
private shutdownHandler: ShutdownHandler = () => {};
private readonly sessionStartTurns = new SessionStartTurnGate((error) =>
this.emitError({
extensionPath: RUNTIME_EXTENSION_PATH,
event: "session_start",
error: error instanceof Error ? error.message : String(error),
}),
);
private shortcutDiagnostics: ResourceDiagnostic[] = [];
private commandDiagnostics: ResourceDiagnostic[] = [];
private staleMessage: string | undefined;
private toolHookLifecycleObserver: ExtensionToolHookLifecycleObserver | undefined;
private nextToolHookRunIndex = 0;
private uiPromptDepth = 0;
private activeUIPrompt: { kind: UIPromptKind; title?: string; requestId: string; since: string } | undefined;
private lifecycleAttentionObserver: (() => void) | undefined;
constructor(
extensions: Extension[],
runtime: ExtensionRuntime,
cwd: string,
sessionManager: SessionManager,
modelRegistry: ModelRegistry,
eventBus: EventBus = createEventBus(),
) {
this.extensions = extensions;
registerRunnerExtensions(this, extensions);
this.runtime = runtime;
this.uiContext = noOpUIContext;
this.cwd = cwd;
this.sessionManager = sessionManager;
this.modelRegistry = modelRegistry;
this.eventBus = eventBus;
}
bindCore(
actions: ExtensionActions,
contextActions: ExtensionContextActions,
providerActions?: {
registerProvider?: (name: string, config: ProviderConfig) => void;
registerNativeProvider?: (provider: Provider) => void;
unregisterProvider?: (name: string) => void;
registerVirtualModel?: (definition: VirtualModelDefinition) => void;
unregisterVirtualModel?: (provider: string, id: string) => void;
},
): void {
// Copy actions into the shared runtime (all extension APIs reference this)
if (actions.lifecycle) this.runtime.lifecycle = actions.lifecycle;
this.runtime.sendMessage = (message, options) => {
if (options?.triggerTurn === true) this.sessionStartTurns.admit(() => actions.sendMessage(message, options));
else actions.sendMessage(message, options);
};
// An itemized send answers its receipts from wherever its admission ends up running (senpi#3811).
this.runtime.sendItemizedMessage = (message, options) => {
const receipts = Promise.withResolvers<readonly SendMessageReceipt[] | undefined>();
const send = () => {
const itemized = actions.sendItemizedMessage;
if (itemized === undefined) {
actions.sendMessage(message, options);
receipts.resolve(undefined);
} else itemized(message, options).then(receipts.resolve, receipts.reject);
};
if (options.triggerTurn === true) this.sessionStartTurns.admit(send);
else send();
return receipts.promise;
};
this.runtime.sendUserMessage = (content, options) => {
// Captured at admission: a deferred answer keeps the origin it was delivered with.
const inputOrigin: InputOrigin = this.personAnswerPending ? "person" : "extension";
this.personAnswerPending = false;
this.sessionStartTurns.admit(() => actions.sendUserMessage(content, options, inputOrigin));
};
this.runtime.appendEntry = actions.appendEntry;
this.runtime.setSessionName = actions.setSessionName;
this.runtime.getSessionName = actions.getSessionName;
this.runtime.setLabel = actions.setLabel;
this.runtime.executeTool = actions.executeTool;
this.runtime.getActiveTools = actions.getActiveTools;
this.runtime.getAllTools = actions.getAllTools;
this.runtime.getSettings = actions.getSettings;
this.runtime.setActiveTools = actions.setActiveTools;
this.runtime.refreshTools = actions.refreshTools;
this.runtime.registerRemovedToolHint = actions.registerRemovedToolHint;
this.runtime.registerLazyToolActivator = actions.registerLazyToolActivator;
this.runtime.getCommands = actions.getCommands;
this.runtime.setModel = actions.setModel;
this.runtime.getThinkingLevel = actions.getThinkingLevel;
this.runtime.setThinkingLevel = actions.setThinkingLevel;
this.runtime.setSessionModel = actions.setSessionModel;
this.runtime.setSessionThinkingLevel = actions.setSessionThinkingLevel;
this.runtime.setSessionFastMode = actions.setSessionFastMode;
if (actions.sessionControl) this.runtime.sessionControl = actions.sessionControl;
if (actions.armToolBarrier) this.runtime.armToolBarrier = actions.armToolBarrier;
if (actions.releaseToolBarrier) this.runtime.releaseToolBarrier = actions.releaseToolBarrier;
this.runtime.createContext = () => this.createContext();
this.offloadFn = contextActions.offload;
// Context actions (required)
this.getModel = contextActions.getModel;
this.getServiceTier = contextActions.getServiceTier;
this.getEffectiveServiceTier = contextActions.getEffectiveServiceTier ?? contextActions.getServiceTier;
this.getScopedModels = contextActions.getScopedModels;
this.isIdleFn = contextActions.isIdle;
this.engineTurnsHeldFn = contextActions.engineTurnsHeld ?? (() => false);
this.noteHeldWakeFn = contextActions.noteHeldWake ?? (() => {});
this.pauseActions = {
getPauseState: contextActions.getPauseState,
fenceRun: contextActions.fenceRun,
releaseRunFence: contextActions.releaseRunFence,
};
this.questionInput = contextActions.questionInput;
this.isProjectTrustedFn = contextActions.isProjectTrusted;
this.getSignalFn = contextActions.getSignal;
this.abortFn = contextActions.abort;
this.hasPendingMessagesFn = contextActions.hasPendingMessages;
this.hasQueuedPersonInputFn = contextActions.hasQueuedPersonInput ?? (() => false);
this.isCompactingFn = contextActions.isCompacting;
this.checkReloadVetoFn = contextActions.checkReloadVeto;
this.shutdownHandler = contextActions.shutdown;
this.getContextUsageFn = contextActions.getContextUsage;
this.getCompactionSettingsFn = contextActions.getCompactionSettings;
this.getCompactionModelFn = contextActions.getCompactionModel;
if (contextActions.getPromptCacheSafeWaitSeconds)
this.getPromptCacheSafeWaitSecondsFn = contextActions.getPromptCacheSafeWaitSeconds;
if (contextActions.getPromptCacheGoalBackstopMaxSeconds)
this.getPromptCacheGoalBackstopMaxSecondsFn = contextActions.getPromptCacheGoalBackstopMaxSeconds;
if (contextActions.getPromptCacheKeepAliveSettings)
this.getPromptCacheKeepAliveSettingsFn = contextActions.getPromptCacheKeepAliveSettings;
this.getLookAtSettingsFn = contextActions.getLookAtSettings;
if (contextActions.getAskUserSettings) this.getAskUserSettingsFn = contextActions.getAskUserSettings;
if (contextActions.getBrowserEngine) this.getBrowserEngineFn = contextActions.getBrowserEngine;
this.getImageSettingsFn = contextActions.getImageSettings;
this.sessionSettingsFn = contextActions.sessionSettings;
this.compactFn = contextActions.compact;
this.beginCompactionFn = contextActions.beginCompaction;
this.updateCompactionFn = contextActions.updateCompaction;
this.endCompactionFn = contextActions.endCompaction;
this.getMessageRevisionFn = contextActions.getMessageRevision;
this.applyCompactionFn = contextActions.applyCompaction;
this.getSystemPromptFn = contextActions.getSystemPrompt;
this.getLoadedHookSourcesFn = contextActions.getLoadedHookSources;
if (contextActions.getAgentDir) this.getAgentDirFn = contextActions.getAgentDir;
this.getSystemPromptOptionsFn = contextActions.getSystemPromptOptions ?? (() => ({ cwd: this.cwd }));
this.getPromptCachePrefixRequestFn = contextActions.getPromptCachePrefixRequest;
this.onUserActivityFn = contextActions.onUserActivity;
this.executeToolFn = contextActions.executeTool;
this.getCallableToolsFn = contextActions.getCallableTools ?? (() => []);
for (const extension of this.extensions) {
for (const [name, hint] of extension.removedToolHints ?? []) {
actions.registerRemovedToolHint(name, hint);
}
for (const activator of extension.lazyToolActivators ?? []) {
actions.registerLazyToolActivator(activator);
}
}
// Flush provider registrations queued during extension loading, replaying the
// original call order so last-registration-wins holds across mixed
// legacy (name/config) and native registrations.
for (const registration of drainPendingProviderRegistrations(this.runtime)) {
try {
if (registration.kind === "config") {
if (providerActions?.registerProvider) {
providerActions.registerProvider(registration.name, registration.config);
} else {
this.modelRegistry.registerProvider(registration.name, registration.config);
}
} else if (providerActions?.registerNativeProvider) {
providerActions.registerNativeProvider(registration.provider);
} else {
this.modelRegistry.registerProvider(registration.provider);
}
} catch (err) {
this.emitError({
extensionPath: registration.extensionPath,
event: "register_provider",
error: err instanceof Error ? err.message : String(err),
stack: err instanceof Error ? err.stack : undefined,
});
}
}
const registerVirtualModel = (definition: VirtualModelDefinition) => {
if (providerActions?.registerVirtualModel) providerActions.registerVirtualModel(definition);
else this.modelRegistry.registerVirtualModel(definition);
};
for (const { definition, extensionPath } of this.runtime.pendingVirtualModelRegistrations) {
try {
registerVirtualModel(definition);
} catch (err) {
this.emitError({
extensionPath,
event: "register_virtual_model",
error: err instanceof Error ? err.message : String(err),
stack: err instanceof Error ? err.stack : undefined,
});
}
}
this.runtime.pendingVirtualModelRegistrations = [];
// From this point on, provider registration/unregistration takes effect immediately
// without requiring a /reload.
this.runtime.registerProvider = (name, config) => {
if (providerActions?.registerProvider) {
providerActions.registerProvider(name, config);
return;
}
this.modelRegistry.registerProvider(name, config);
};
this.runtime.registerNativeProvider = (provider) => {
if (providerActions?.registerNativeProvider) {
providerActions.registerNativeProvider(provider);
return;
}
this.modelRegistry.registerProvider(provider);
};
this.runtime.unregisterProvider = (name) => {
if (providerActions?.unregisterProvider) {
providerActions.unregisterProvider(name);
return;
}
this.modelRegistry.unregisterProvider(name);
};
this.runtime.registerVirtualModel = registerVirtualModel;
this.runtime.unregisterVirtualModel = (provider, id) => {
if (providerActions?.unregisterVirtualModel) providerActions.unregisterVirtualModel(provider, id);
else this.modelRegistry.unregisterVirtualModel(provider, id);
};
}
bindCommandContext(actions?: ExtensionCommandContextActions): void {
if (actions) {
this.waitForIdleFn = actions.waitForIdle;
this.newSessionHandler = actions.newSession;
this.forkHandler = actions.fork;
this.navigateTreeHandler = actions.navigateTree;
this.editAssistantMessageHandler = actions.editAssistantMessage;
this.editUserMessageHandler = actions.editUserMessage;
this.switchSessionHandler = actions.switchSession;
this.reloadHandler = actions.reload;
return;
}
this.waitForIdleFn = async () => {};
this.newSessionHandler = async () => ({ cancelled: false });
this.forkHandler = async () => ({ cancelled: false });
this.navigateTreeHandler = async () => ({ cancelled: false });
this.editAssistantMessageHandler = async () => ({ cancelled: false });
this.editUserMessageHandler = async () => ({ cancelled: false });
this.switchSessionHandler = async () => ({ cancelled: false });
this.reloadHandler = undefined;
}
private requestReload(): Promise<void> {
if (!this.reloadHandler) return Promise.resolve();
if (!this.reloadRequestPromise) {
this.reloadRequestPromise = this.reloadHandler().finally(() => {
this.reloadRequestPromise = undefined;
});
}
return this.reloadRequestPromise;
}
setUIContext(uiContext?: ExtensionUIContext, mode: ExtensionMode = "print"): void {
this.uiContext = uiContext ? this.wrapUIPromptContext(uiContext) : noOpUIContext;
this.mode = mode;
}
setToolHookLifecycleObserver(observer?: ExtensionToolHookLifecycleObserver): void {
this.toolHookLifecycleObserver = observer;
}
setLifecycleAttentionObserver(observer: () => void): void {
this.lifecycleAttentionObserver = observer;
}
getLifecycleHumanWait(): Omit<import("../session-lifecycle-types.ts").HumanWait, "originSessionId"> | undefined {
const prompt = this.activeUIPrompt;
if (this.mode === "rpc" || !prompt) return undefined;
return {
kind: prompt.kind === "confirm" ? "approval" : "question",
requestId: prompt.requestId,
revision: 1,
since: prompt.since,
};
}
private wrapUIPromptContext(ui: ExtensionUIContext): ExtensionUIContext {
const questionFn = ui.question;
return inheritMcpMrtrPresentation(ui, {
...ui,
select: (title, options, opts) => this.withUIPrompt("select", title, () => ui.select(title, options, opts)),
confirm: (title, message, opts) => this.withUIPrompt("confirm", title, () => ui.confirm(title, message, opts)),
input: (title, placeholder, opts) =>
this.withUIPrompt("input", title, () => ui.input(title, placeholder, opts)),
editor: (title, prefill) => this.withUIPrompt("editor", title, () => ui.editor(title, prefill)),
custom: (factory, options) => this.withUIPrompt("custom", undefined, () => ui.custom(factory, options)),
...(questionFn
? {
question: (request, opts) =>
this.withUIPrompt(
"question",
request.questions[0]?.header,
() => questionFn(request, opts),
request.requestId,
),
}
: {}),
});
}
private withUIPrompt<T>(
kind: UIPromptKind,
title: string | undefined,
run: () => Promise<T>,
requestId: string = crypto.randomUUID(),
): Promise<T> {
const outerPrompt = this.uiPromptDepth++ === 0;
if (outerPrompt) {
this.activeUIPrompt = { kind, title, requestId, since: new Date().toISOString() };
this.lifecycleAttentionObserver?.();
this.emitUIPromptEvent({ type: "ui_prompt_start", reason: "ui_prompt", kind, ...(title ? { title } : {}) });
}
const finish = () => {
if (--this.uiPromptDepth > 0) return;
this.uiPromptDepth = 0;
const prompt = this.activeUIPrompt ?? { kind, title };
this.activeUIPrompt = undefined;
this.lifecycleAttentionObserver?.();
this.emitUIPromptEvent({
type: "ui_prompt_end",
reason: "ui_prompt",
kind: prompt.kind,
...(prompt.title ? { title: prompt.title } : {}),
});
};
try {
return run().finally(finish);
} catch (err) {
finish();
throw err;
}
}
private emitUIPromptEvent(event: Extract<RunnerEmitEvent, { type: "ui_prompt_start" | "ui_prompt_end" }>): void {
queueMicrotask(() => {
void this.emit(event);
});
}
getUIContext(): ExtensionUIContext {
return this.uiContext;
}
/** True while session_start handlers run and the turns they trigger are still held. */
sessionStartTurnsHeld(): boolean {
return this.sessionStartTurns.holding;
}
hasUI(): boolean {
return this.uiContext !== noOpUIContext;
}
getExtensionPaths(): string[] {
return this.extensions.map((e) => e.path);
}
getExtensionIdentities(): Array<{ path: string; resolvedPath: string }> {
return this.extensions.map(({ path, resolvedPath }) => ({ path, resolvedPath }));
}
readonly #reportedChildModuleReplacements = new Set<string>();
/**
* Every registered child module by id. Unlike tools, the last extension to register an id wins, in load order; the
* replacement is logged once, so a module that shadows another (a builtin's included) is never silent.
*/
getAllChildModules(): Map<string, RegisteredChildModule> {
const modules = new Map<string, RegisteredChildModule>();
for (const ext of this.extensions)
for (const [id, entry] of ext.childModules ?? []) {
const earlier = modules.get(id);
const replacement = `${id}\0${earlier?.sourceInfo.path}\0${entry.sourceInfo.path}`;
if (
earlier !== undefined &&
earlier.sourceInfo.path !== entry.sourceInfo.path &&
!this.#reportedChildModuleReplacements.has(replacement)
) {
this.#reportedChildModuleReplacements.add(replacement);
console.warn(
`Child module "${id}" from ${entry.sourceInfo.path} replaces the one from ${earlier.sourceInfo.path}`,
);
}
modules.set(id, entry);
}
return modules;
}
/**
* Get all registered tools from all extensions. The first registration within a source tier
* wins, while a non-builtin extension may override a builtin extension tool.
*/