Repository navigation
Expand file tree
/
Copy pathagent-session.ts
More file actions
4349 lines (3949 loc) · 154 KB
/
Copy pathagent-session.ts
File metadata and controls
4349 lines (3949 loc) · 154 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
/**
* AgentSession - Core abstraction for agent lifecycle and session management.
*
* This class is shared between all run modes (interactive, print, rpc).
* It encapsulates:
* - Agent state access
* - Event subscription with automatic session persistence
* - Model and thinking level management
* - Compaction (manual and auto)
* - Bash execution
* - Session switching and branching
*
* Modes use this class and add their own I/O layer on top.
*/
import { readFileSync } from "node:fs";
import { basename, dirname } from "node:path";
import {
type AfterToolCallContext,
type AfterToolCallResult,
type Agent,
type AgentContext,
type AgentEvent,
type AgentMessage,
type AgentState,
type AgentTool,
type AgentToolCallOutcome,
type BeforeToolCallContext,
type BeforeToolCallResult,
type PrepareNextTurnContext,
runToolCall,
type ThinkingLevel,
} from "@earendil-works/pi-agent-core";
import { contentText, getCurrentSystemMessage, retryDelayMs } from "@earendil-works/pi-ai";
import type {
AssistantMessage,
AuthResult,
ImageContent,
Model,
ProviderHeaders,
SystemMessage,
TextContent,
ToolResultMessage,
Usage,
} from "@earendil-works/pi-ai/compat";
import {
clampThinkingLevel,
cleanupSessionResources,
getSupportedThinkingLevels,
isContextOverflow,
isRecoverableLength,
isRetryableAssistantError,
modelsAreEqual,
type RetryCallbacks,
resetApiProviders,
streamSimple,
} from "@earendil-works/pi-ai/compat";
import { getThemeByName, theme } from "../modes/interactive/theme/theme.ts";
import { stripFrontmatter } from "../utils/frontmatter.ts";
import { processImage } from "../utils/image-process.ts";
import { sleep } from "../utils/sleep.ts";
import { normalizeToolResultImages } from "../utils/tool-result-images.ts";
import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.ts";
import { type BashResult, executeBashWithOperations } from "./bash-executor.ts";
import { generateBugReportSummary } from "./bug-report.ts";
import type { CacheWarmer, CacheWarmingStatus } from "./cache-warmer.ts";
import {
type CompactionPreparation,
type CompactionResult,
calculateContextTokens,
collectEntriesForBranchSummary,
compact,
estimateContextTokens,
estimateProjectedContextTokens,
estimateTokens,
generateBranchSummary,
prepareCompaction,
shouldCompact,
} from "./compaction/index.ts";
import { DEFAULT_THINKING_LEVEL, THINKING_LEVEL_OPTIONS } from "./defaults.ts";
import { exportSessionToHtml, type ToolHtmlRenderer } from "./export-html/index.ts";
import { createToolHtmlRenderer } from "./export-html/tool-renderer.ts";
import {
type AgentActivityOutcome,
type BoundaryContextPreview,
type ContextUsage,
type ExecuteToolOptions,
type ExtensionCommandContextActions,
type ExtensionErrorListener,
type ExtensionMode,
ExtensionRunner,
type ExtensionUIContext,
type InputSource,
type MessageEndEvent,
type MessageStartEvent,
type MessageUpdateEvent,
type ReplacedSessionContext,
type SessionBeforeCompactResult,
type SessionBeforeTreeResult,
type SessionBoundaryDraft,
type SessionCompactFailedEvent,
type SessionStartEvent,
type ShutdownHandler,
type ToolDefinition,
type ToolExecutionEndEvent,
type ToolExecutionStartEvent,
type ToolExecutionUpdateEvent,
type ToolExposure,
type ToolInfo,
type ToolLoadout,
type TreePreparation,
type TurnStartEvent,
wrapRegisteredTools,
} from "./extensions/index.ts";
import { emitSessionShutdownEvent } from "./extensions/runner.ts";
import { type BashExecutionMessage, type CustomMessage, convertToLlm } from "./messages.ts";
import { ModelRegistry } from "./model-registry.ts";
import type { ModelRuntime } from "./model-runtime.ts";
import { NestedToolCallRunner } from "./nested-tool-calls.ts";
import { expandPromptTemplate, type PromptTemplate } from "./prompt-templates.ts";
import type { ResourceExtensionPaths, ResourceLoader } from "./resource-loader.ts";
import { exportSessionToJsonl } from "./session-export.ts";
import {
type BranchSummaryEntry,
type CompactionEntry,
type ContextEditEntry,
getLatestCompactionEntry,
type SessionEntry,
SessionManager,
type SessionProjection,
} from "./session-manager.ts";
import { type CacheWarmingMode, DEFAULT_TOOL_NAMES, type SettingsManager } from "./settings-manager.ts";
import type { SlashCommandInfo } from "./slash-commands.ts";
import { BUILTIN_PATH_PREFIX, createSyntheticSourceInfo, isSyntheticPath, type SourceInfo } from "./source-info.ts";
import {
buildSystemPrompt,
buildSystemPromptSections,
diffSystemPromptSections,
type NormalizedBuildSystemPromptOptions,
normalizeBuildSystemPromptOptions,
} from "./system-prompt.ts";
import { type BashOperations, createLocalBashOperations } from "./tools/bash.ts";
import { createAllToolDefinitions } from "./tools/index.ts";
import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.ts";
import { addUsageToTotals, combineUsage, createUsageTotals } from "./usage-totals.ts";
import {
findLatestResponse,
getBranchSelection,
getVirtualModelState,
isVirtualModel,
VIRTUAL_MODEL_STATE_ENTRY,
type VirtualModelStateData,
} from "./virtual-models.ts";
// ============================================================================
// Skill Block Parsing
// ============================================================================
/** Parsed skill block from a user message */
export interface ParsedSkillBlock {
name: string;
location: string;
content: string;
userMessage: string | undefined;
}
/**
* Parse a skill block from message text.
* Returns null if the text doesn't contain a skill block.
*/
export function parseSkillBlock(text: string): ParsedSkillBlock | null {
const match = text.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);
if (!match) return null;
return {
name: match[1],
location: match[2],
content: match[3],
userMessage: match[4]?.trim() || undefined,
};
}
/** Tool execution events of calls a tool made through `ctx.executeTool()` carry `parentToolCallId`. */
type WithParentToolCallId<E> = E extends {
type: "tool_execution_start" | "tool_execution_update" | "tool_execution_end";
}
? E & { parentToolCallId?: string }
: E;
/** Session-specific events that extend the core AgentEvent */
export type AgentSessionEvent =
| WithParentToolCallId<Exclude<AgentEvent, { type: "agent_end" }>>
| {
type: "agent_end";
messages: AgentMessage[];
willRetry: boolean;
}
| { type: "agent_settled" }
| {
type: "queue_update";
steering: readonly string[];
followUp: readonly string[];
}
| { type: "compaction_start"; reason: "manual" | "threshold" | "overflow" }
| { type: "entry_appended"; entry: SessionEntry }
| { type: "session_info_changed"; name: string | undefined }
| { type: "thinking_level_changed"; level: ThinkingLevel }
| {
type: "compaction_end";
reason: "manual" | "threshold" | "overflow";
result: CompactionResult | undefined;
aborted: boolean;
willRetry: boolean;
errorMessage?: string;
}
| { type: "auto_retry_start"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }
| { type: "auto_retry_end"; success: boolean; attempt: number; finalError?: string }
| {
type: "summarization_retry_scheduled";
attempt: number;
maxAttempts: number;
delayMs: number;
errorMessage: string;
}
| { type: "summarization_retry_attempt_start"; source: "branchSummary" }
| {
type: "summarization_retry_attempt_start";
source: "compaction";
reason: "manual" | "threshold" | "overflow";
}
| { type: "summarization_retry_finished" }
| { type: "bash_execution_update"; id?: string; delta: string };
/** Listener function for agent session events */
export type AgentSessionEventListener = (event: AgentSessionEvent) => void;
// ============================================================================
// Types
// ============================================================================
function withoutDeletedHeaders(headers: ProviderHeaders | undefined): Record<string, string> | undefined {
return headers
? Object.fromEntries(Object.entries(headers).filter((entry): entry is [string, string] => entry[1] !== null))
: undefined;
}
export interface AgentSessionConfig {
agent: Agent;
sessionManager: SessionManager;
settingsManager: SettingsManager;
cwd: string;
/** Models to cycle through with Ctrl+P (from --models flag) */
scopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;
/** Resource loader for extensions, skills, prompts, themes, context files, and system prompt */
resourceLoader: ResourceLoader;
/** SDK custom tools registered outside extensions */
customTools?: ToolDefinition[];
/** Canonical model/auth runtime used by coding-agent internals. */
modelRuntime: ModelRuntime;
/** Keeps the prompt cache entry of the last session request warm. */
cacheWarmer?: Pick<CacheWarmer, "cancel" | "status" | "onAgentSettled" | "onModeChanged" | "onWarmed">;
/** Initial active built-in tool names. Default: [read, bash, edit, write] */
initialActiveToolNames?: string[];
/**
* Whether the initial tools come from the `defaultTools` setting. When true, reload activates
* tools newly added to the setting. Tools removed from it stay active.
*/
usesDefaultTools?: boolean;
/** Optional allowlist of tool names. When provided, only these tool names are exposed. */
allowedToolNames?: string[];
/** Optional denylist of tool names. When provided, these tool names are not exposed. */
excludedToolNames?: string[];
/**
* Override base tools (useful for custom runtimes).
*
* These are synthesized into minimal ToolDefinitions internally so AgentSession can keep
* a definition-first registry even when callers provide plain AgentTool instances.
*/
baseToolsOverride?: Record<string, AgentTool>;
/** Mutable ref used by Agent to access the current ExtensionRunner */
extensionRunnerRef?: { current?: ExtensionRunner };
/** Session start event metadata emitted when extensions bind to this runtime. */
sessionStartEvent?: SessionStartEvent;
}
export interface ExtensionBindings {
uiContext?: ExtensionUIContext;
mode?: ExtensionMode;
commandContextActions?: ExtensionCommandContextActions;
abortHandler?: () => void;
shutdownHandler?: ShutdownHandler;
onError?: ExtensionErrorListener;
}
export type QueuedInputDisposition = "handled" | "queued";
export type PromptDisposition = QueuedInputDisposition | "started";
/** Options for AgentSession.prompt() */
export interface PromptOptions {
/** Whether to dispatch extension commands and expand skill commands and prompt templates (default: true) */
expandPromptTemplates?: boolean;
/** Image attachments */
images?: ImageContent[];
/** When streaming, how to queue the message: "steer" (interrupt) or "followUp" (wait). Required if streaming. */
streamingBehavior?: "steer" | "followUp";
/** Source of input for extension input event handlers. Defaults to "interactive". */
source?: InputSource;
/** Internal hook used by RPC mode to observe how an accepted prompt was dispatched. Not called if the prompt is rejected. */
preflightResult?: (disposition: PromptDisposition) => void;
}
/** Options for model/thinking mutations. */
export interface ModelMutationOptions {
/** Persist the new value to global defaults. Defaults to session-only. */
persist?: boolean;
}
/** Result from cycleModel() */
export interface ModelCycleResult {
model: Model<any>;
thinkingLevel: ThinkingLevel;
/** Whether cycling through scoped models (--models flag) or all available */
isScoped: boolean;
}
/** Session statistics for /session command */
export interface SessionStats {
sessionFile: string | undefined;
sessionId: string;
userMessages: number;
assistantMessages: number;
toolCalls: number;
toolResults: number;
totalMessages: number;
tokens: {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
total: number;
};
cost: number;
contextUsage?: ContextUsage;
}
interface ToolDefinitionEntry {
definition: ToolDefinition;
sourceInfo: SourceInfo;
}
function estimateMessagesTokens(messages: AgentMessage[]): number {
let tokens = 0;
for (const message of messages) {
tokens += estimateTokens(message);
}
return tokens;
}
// ============================================================================
// AgentSession Class
// ============================================================================
export class AgentSession {
readonly agent: Agent;
readonly sessionManager: SessionManager;
readonly settingsManager: SettingsManager;
private _scopedModels: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;
// Event subscription state
private _unsubscribeAgent?: () => void;
private _eventListeners: AgentSessionEventListener[] = [];
private _isAgentRunActive = false;
private _agentRunAbortRequested = false;
private _idleWaitPromise: Promise<void> | undefined;
private _resolveIdleWait: (() => void) | undefined;
/** Tracks pending steering messages for UI display. Removed when delivered. */
private _steeringMessages: string[] = [];
/** Tracks pending follow-up messages for UI display. Removed when delivered. */
private _followUpMessages: string[] = [];
/** Messages queued to be included with the next user prompt as context ("asides"). */
private _pendingNextTurnMessages: CustomMessage[] = [];
/** Context-only custom messages queued during a run, flushed once the current turn's tool results are in. */
private _pendingCustomMessages: CustomMessage[] = [];
// Compaction state
private _compactionAbortController: AbortController | undefined = undefined;
private _autoCompactionAbortController: AbortController | undefined = undefined;
private _overflowRecoveryAttempted = false;
// Branch summarization state
private _branchSummaryAbortController: AbortController | undefined = undefined;
// Retry state
private _retryAbortController: AbortController | undefined = undefined;
private _retryAttempt = 0;
/**
* Failed response that the next request repeats, set by auto-retry and overflow recovery. The
* retry is routed with it as `failed`, since the context no longer contains it.
*/
private _failedResponse: AssistantMessage | undefined;
// Bash execution state
private readonly _bashAbortControllers = new Set<AbortController>();
private _pendingBashMessages: BashExecutionMessage[] = [];
// Extension system
private _extensionRunner!: ExtensionRunner;
private _turnIndex = 0;
private readonly _entryIdsByMessage = new WeakMap<object, string>();
private readonly _boundaryDispatchedMessages = new WeakSet<object>();
private _lastAssistantMessage: AssistantMessage | undefined;
private _lastAssistantToolResults: AgentMessage[] = [];
private _lastActivityOutcome: AgentActivityOutcome = "completed";
private _isBeforeSettle = false;
private _abortDuringBeforeSettle = false;
private _isEmittingAgentSettled = false;
private readonly _deferredSettledActions: Array<() => Promise<void>> = [];
private _resourceLoader: ResourceLoader;
private _customTools: ToolDefinition[];
private _baseToolDefinitions: Map<string, ToolDefinition> = new Map();
private _cwd: string;
private _extensionRunnerRef?: { current?: ExtensionRunner };
private _initialActiveToolNames?: string[];
/**
* Tools of the restored or reloaded loadout that are not registered yet, such as tools of MCP
* servers that are still connecting. They are activated when they are registered, and dropped when
* `setActiveToolsByName()` deactivates a tool or the next agent run starts.
*/
private _pendingToolNames = new Set<string>();
private _usesDefaultTools: boolean;
private _allowedToolNames?: Set<string>;
private _excludedToolNames?: Set<string>;
private _baseToolsOverride?: Record<string, AgentTool>;
private _sessionStartEvent: SessionStartEvent;
private _extensionUIContext?: ExtensionUIContext;
private _extensionMode: ExtensionMode = "print";
private _extensionCommandContextActions?: ExtensionCommandContextActions;
private _extensionAbortHandler?: () => void;
private _extensionShutdownHandler?: ShutdownHandler;
private _extensionErrorListener?: ExtensionErrorListener;
private _extensionErrorUnsubscriber?: () => void;
private _modelRuntime: ModelRuntime;
private _cacheWarmer?: Pick<CacheWarmer, "cancel" | "status" | "onAgentSettled" | "onModeChanged" | "onWarmed">;
// Tool registry for extension getTools/setTools
private _toolRegistry: Map<string, AgentTool> = new Map();
/** Created on the first `ctx.executeTool()` call. */
private _nestedToolCalls: NestedToolCallRunner | undefined;
/** Declared tools whose declarations requests leave out, from `prepareLoadout` hooks. */
private _hiddenDeclarations: ReadonlySet<string> = new Set();
private _toolDefinitions: Map<string, ToolDefinitionEntry> = new Map();
private _toolPromptSnippets: Map<string, string> = new Map();
private _toolPromptGuidelines: Map<string, string[]> = new Map();
private _baseSystemPromptOptions!: NormalizedBuildSystemPromptOptions;
/** Prompt options after before_agent_start mutations for the active run. */
private _runSystemPromptOptions?: NormalizedBuildSystemPromptOptions;
constructor(config: AgentSessionConfig) {
this.agent = config.agent;
this.sessionManager = config.sessionManager;
this.settingsManager = config.settingsManager;
this._scopedModels = config.scopedModels ?? [];
this._resourceLoader = config.resourceLoader;
this._customTools = config.customTools ?? [];
this._cwd = config.cwd;
this._modelRuntime = config.modelRuntime;
this._cacheWarmer = config.cacheWarmer;
if (this._cacheWarmer) {
this._cacheWarmer.onWarmed = (entry) => this._emit({ type: "entry_appended", entry });
}
this._extensionRunnerRef = config.extensionRunnerRef;
this._initialActiveToolNames = config.initialActiveToolNames;
this._usesDefaultTools = config.usesDefaultTools ?? false;
this._allowedToolNames = config.allowedToolNames ? new Set(config.allowedToolNames) : undefined;
this._excludedToolNames = config.excludedToolNames ? new Set(config.excludedToolNames) : undefined;
this._baseToolsOverride = config.baseToolsOverride;
this._sessionStartEvent = config.sessionStartEvent ?? { type: "session_start", reason: "startup" };
// Always subscribe to agent events for internal handling
// (session persistence, extensions, auto-compaction, retry logic)
this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
this._installAgentToolHooks();
this._installAgentNextTurnRefresh();
this._installAgentRequestProjection();
this._installAgentBoundaryHooks();
this._installHiddenDeclarationsProjection();
this._installAgentForcedPromptProjection();
this._buildRuntime({
activeToolNames: this._initialActiveToolNames,
includeAllExtensionTools: true,
});
if (this._initialActiveToolNames === undefined) this._restoreToolsFromTranscript();
}
get modelRuntime(): ModelRuntime {
return this._modelRuntime;
}
private async _getRequiredRequestAuth(
model: Model<any>,
signal?: AbortSignal,
): Promise<{
model: Model<any>;
apiKey?: string;
headers?: Record<string, string>;
env?: Record<string, string>;
}> {
let result: AuthResult | undefined;
try {
result = await this._modelRuntime.getAuth(model, { signal });
} catch (error) {
const cause = error instanceof Error ? error.cause : undefined;
if (cause instanceof Error && cause.message === "authHeader requires a resolved API key") {
throw new Error(formatNoApiKeyFoundMessage(model.provider));
}
throw error;
}
if (result && (result.auth.apiKey || result.auth.headers)) {
const requestModel = result.auth.baseUrl ? { ...model, baseUrl: result.auth.baseUrl } : model;
return {
model: requestModel,
apiKey: result.auth.apiKey,
headers: withoutDeletedHeaders(result.auth.headers),
env: result.env,
};
}
const isOAuth = this._modelRuntime.isUsingOAuth(model.provider);
if (isOAuth) {
throw new Error(
`Authentication failed for "${model.provider}". ` +
`Credentials may have expired or network is unavailable. ` +
`Run '/login ${model.provider}' to re-authenticate.`,
);
}
throw new Error(formatNoApiKeyFoundMessage(model.provider));
}
private async _getSummarizationRequestAuth(
selectedModel: Model<any>,
signal?: AbortSignal,
): Promise<{
model: Model<any>;
apiKey?: string;
headers?: Record<string, string>;
env?: Record<string, string>;
thinkingLevel: ThinkingLevel;
}> {
// Route a virtual model first: summaries size their input and output from the model they get.
const { model, thinkingLevel } = isVirtualModel(selectedModel)
? await this._modelRuntime.resolveModel(selectedModel, convertToLlm(this.messages), {
reason: "direct",
thinkingLevel: this.thinkingLevel,
signal,
})
: { model: selectedModel, thinkingLevel: this.thinkingLevel };
if (this.agent.streamFunction === streamSimple) {
return { ...(await this._getRequiredRequestAuth(model, signal)), thinkingLevel };
}
try {
const result = await this._modelRuntime.getAuth(model, { signal });
if (!result) return { model, thinkingLevel };
const requestModel = result.auth.baseUrl ? { ...model, baseUrl: result.auth.baseUrl } : model;
return {
model: requestModel,
apiKey: result.auth.apiKey,
headers: withoutDeletedHeaders(result.auth.headers),
env: result.env,
thinkingLevel,
};
} catch (error) {
if (signal?.aborted) throw error;
return { model, thinkingLevel };
}
}
/**
* The model whose limits apply to `message`, or undefined when the message came from another
* model. Under a virtual selection, that is the physical model that produced it.
*/
private _modelForMessage(message: AssistantMessage): Model<any> | undefined {
const model = this.model;
if (model && isVirtualModel(model)) return this._modelRuntime.getPhysicalModel(message.provider, message.model);
return model?.provider === message.provider && model.id === message.model ? model : undefined;
}
/**
* Record the selection on the current branch when the branch implies another one, so a resume
* restores it. Tree navigation can leave the latest `model_change` on another branch; responses
* cannot record a virtual selection because they name physical models. Responses do record a
* physical selection unless the branch holds a virtual one; checking a physical selection against
* responses would record it on every prompt while `prepareRequest` redirects to another model.
*/
private _recordSelection(): void {
const model = this.model;
if (!model) return;
const getModel = (provider: string, modelId: string) => this._modelRuntime.getModel(provider, modelId);
const recorded = getBranchSelection(this.sessionManager.getBranch(), getModel);
if (!recorded || (recorded.provider === model.provider && recorded.modelId === model.id)) return;
const recordedModel = getModel(recorded.provider, recorded.modelId);
if (!isVirtualModel(model) && !(recordedModel && isVirtualModel(recordedModel))) return;
this.sessionManager.appendModelChange(model.provider, model.id);
}
/** The model whose limits apply to the conversation. */
private _limitsModel(): Model<any> | undefined {
return this.routedModel?.model ?? this.model;
}
/**
* Install tool hooks once on the Agent instance.
*
* The callbacks read `this._extensionRunner` at execution time, so extension reload swaps in the
* new runner without reinstalling hooks. Extension-specific tool wrappers are still used to adapt
* registered tool execution to the extension context. Tool call and tool result interception now
* happens here instead of in wrappers.
*/
private _installAgentToolHooks(): void {
this.agent.beforeToolCall = (context) => this._beforeToolCall(context);
this.agent.afterToolCall = (context) => this._afterToolCall(context);
}
/** `tool_call` handlers. `parentToolCallId` is set for calls another tool made. */
private async _beforeToolCall(
{ toolCall, args }: BeforeToolCallContext,
parentToolCallId?: string,
): Promise<BeforeToolCallResult | undefined> {
const runner = this._extensionRunner;
if (!runner.hasHandlers("tool_call")) {
return undefined;
}
try {
return await runner.emitToolCall({
type: "tool_call",
toolName: toolCall.name,
toolCallId: toolCall.id,
...(parentToolCallId ? { parentToolCallId } : {}),
input: args as Record<string, unknown>,
});
} catch (err) {
if (err instanceof Error) {
throw err;
}
throw new Error(`Extension failed, blocking execution: ${String(err)}`);
}
}
/** `tool_result` handlers and image normalization. `parentToolCallId` is set for calls another tool made. */
private async _afterToolCall(
{ toolCall, args, result, isError }: AfterToolCallContext,
parentToolCallId?: string,
): Promise<AfterToolCallResult | undefined> {
const runner = this._extensionRunner;
const hookResult = runner.hasHandlers("tool_result")
? await runner.emitToolResult({
type: "tool_result",
toolName: toolCall.name,
toolCallId: toolCall.id,
...(parentToolCallId ? { parentToolCallId } : {}),
input: args as Record<string, unknown>,
content: result.content,
details: result.details,
...(result.structuredContent === undefined ? {} : { structuredContent: result.structuredContent }),
isError,
usage: result.usage,
})
: undefined;
const content = hookResult?.content ?? result.content ?? [];
// Runs after the extension hook so images injected or replaced by extensions are normalized too.
const resizeOptions = this._limitsModel()?.inputLimits?.images?.resize;
const normalizedContent = await normalizeToolResultImages(content, {
autoResizeImages: this.settingsManager.getImageAutoResize(),
...(resizeOptions ? { resizeOptions } : {}),
});
if (!hookResult && normalizedContent === content) {
return undefined;
}
// The hook result already dropped structured content that replaced content no longer matches.
return {
content: normalizedContent,
details: hookResult?.details,
structuredContent: hookResult ? hookResult.structuredContent : result.structuredContent,
isError: hookResult?.isError ?? isError,
usage: hookResult?.usage,
};
}
/**
* Run a call that the tool call `parentToolCallId` made through `ctx.executeTool()`. It goes
* through the agent's tool pipeline with the session's hooks, against the callable tools.
*/
private async _executeNestedToolCall(
parentToolCallId: string,
name: string,
args: unknown,
options: ExecuteToolOptions,
): Promise<AgentToolCallOutcome> {
this._nestedToolCalls ??= new NestedToolCallRunner({
getTools: () => this._getCallableTools(),
isSequential: () => this.agent.toolExecution === "sequential",
runToolCall: (toolCall, parentId, signal, onUpdate) => {
const assistantMessage = this._findLastAssistantMessage();
if (!assistantMessage) {
return Promise.resolve({
toolCall,
result: { content: [{ type: "text", text: "No assistant message issued this call" }], details: {} },
isError: true,
});
}
return runToolCall(toolCall, {
tools: this._getCallableTools(),
assistantMessage,
context: { messages: this.agent.state.messages, tools: this.agent.state.tools },
beforeToolCall: (context) => this._beforeToolCall(context, parentId),
afterToolCall: (context) => this._afterToolCall(context, parentId),
signal,
onUpdate,
});
},
emit: async (event) => {
await this._extensionRunner.emit(event);
this._emit(event);
},
});
return this._nestedToolCalls.execute(parentToolCallId, name, args, options);
}
/** Whether `projection`, the current session projection, exceeds the compaction threshold of `model`. */
private _exceedsCompactionThreshold(model: Model<any>, projection: SessionProjection): boolean {
if (model.contextWindow <= 0) return false;
return shouldCompact(
estimateProjectedContextTokens(projection, this.sessionManager.getBranch()).tokens,
model.contextWindow,
this.settingsManager.getCompactionSettings(this.model),
);
}
private async _compactBeforeNextAssistantResponse(context: AgentContext): Promise<AgentContext> {
const projection = this.sessionManager.buildSessionProjection();
// A virtual selection is checked in prepareRequest, against the model the request is routed to.
const model = this.model;
if (!model || isVirtualModel(model) || !this._exceedsCompactionThreshold(model, projection)) {
return { ...context, messages: projection.messages };
}
await this._runAutoCompaction("threshold", false);
return { ...context, messages: this.sessionManager.buildSessionProjection().messages };
}
private _installAgentRequestProjection(): void {
const previousPrepareRequest = this.agent.prepareRequest;
this.agent.prepareRequest = async (request, signal) => {
const failed = this._failedResponse;
this._failedResponse = undefined;
const prepare = async () => {
const projection = this.sessionManager.buildSessionProjection();
const canonicalContext = {
...request.context,
messages: projection.messages,
// Messages declare the provider-visible loadout; context.tools keeps executable implementations.
tools: this.agent.state.tools.slice(),
};
const previous = await previousPrepareRequest?.(
{
...request,
context: canonicalContext,
model: this.agent.state.model,
thinkingLevel: this.agent.state.thinkingLevel,
},
signal,
);
return { previous, context: previous?.context ?? canonicalContext, projection };
};
let { previous, context, projection } = await prepare();
const model = previous?.model ?? this.agent.state.model;
const thinkingLevel = previous?.thinkingLevel ?? this.agent.state.thinkingLevel;
if (!isVirtualModel(model)) return { ...previous, context, model, thinkingLevel };
// The selection stays in agent state; only this request uses the routed model. A routing
// failure rejects, which ends the run with an error response. Only messages the user wrote
// start a turn; extension messages can follow them, e.g. from before_agent_start.
const lastResponse = context.messages.findLastIndex((message) => message.role === "assistant");
const userTurn = context.messages.slice(lastResponse + 1).some((message) => message.role === "user");
const state = getVirtualModelState(this.sessionManager.getBranch(), model.provider, model.id);
const route = await this._modelRuntime.resolveModel(model, convertToLlm(context.messages), {
reason: failed ? "retry" : userTurn ? "user" : "continuation",
thinkingLevel,
signal,
failed,
state,
});
if (route.state !== undefined && route.state !== state) {
const data: VirtualModelStateData = { provider: model.provider, modelId: model.id, state: route.state };
const entry = this.sessionManager.getEntry(
this.sessionManager.appendCustomEntry(VIRTUAL_MODEL_STATE_ENTRY, data),
);
if (entry) this._emit({ type: "entry_appended", entry });
}
// The route stands: the router already decided this request. The state entry does not change
// the projection.
if (this._exceedsCompactionThreshold(route.model, projection)) {
await this._runAutoCompaction("threshold", false);
({ previous, context } = await prepare());
}
return { ...previous, context, model: route.model, thinkingLevel: route.thinkingLevel };
};
}
private async _dispatchTurnEndBoundary(
message: AssistantMessage,
toolResults: ToolResultMessage[],
): Promise<boolean> {
this._lastActivityOutcome =
message.stopReason === "aborted" ? "aborted" : message.stopReason === "error" ? "error" : "completed";
const messageEntryId = this._findPersistedMessageEntryId(message);
if (!this._extensionRunner.hasHandlers("turn_end")) return false;
if (!messageEntryId) {
this._extensionRunner.emitError({
extensionPath: "<boundary>",
event: "turn_end",
error: "turn_end could not resolve the persisted assistant entry ID",
});
return false;
}
const toolResultEntryIds = toolResults.flatMap((result) => {
const entryId = this._findPersistedMessageEntryId(result);
return entryId ? [entryId] : [];
});
const boundary = await this._extensionRunner.emitBoundary(
{
type: "turn_end",
turnIndex: this._turnIndex,
message,
toolResults,
messageEntryId,
toolResultEntryIds,
outcome: this._lastActivityOutcome,
},
(entries) => this._buildBoundaryContext(entries, "turn_end"),
);
this._commitBoundaryDrafts(boundary.entries);
if (boundary.continue && !this._buildBoundaryContext([], "turn_end").canContinue) {
this._reportInvalidBoundaryContinuation("turn_end");
return false;
}
return boundary.continue;
}
private _installAgentBoundaryHooks(): void {
const previousFinishTurn = this.agent.finishTurn;
this.agent.finishTurn = async (turn, signal) => {
this._boundaryDispatchedMessages.add(turn.message);
const extensionContinue = await this._dispatchTurnEndBoundary(turn.message, turn.toolResults);
const previousDecision = await previousFinishTurn?.(turn, signal);
if (previousDecision?.action === "end") return previousDecision;
if (extensionContinue || previousDecision?.action === "continue") return { action: "continue" };
return undefined;
};
}
private _installAgentNextTurnRefresh(): void {
const previousPrepareNextTurnWithContext =
this.agent.prepareNextTurnWithContext ??
(this.agent.prepareNextTurn
? async (_turn: PrepareNextTurnContext, signal?: AbortSignal) => await this.agent.prepareNextTurn?.(signal)
: undefined);
this.agent.prepareNextTurnWithContext = async (turn, signal) => {
const context = await this._compactBeforeNextAssistantResponse(turn.context);
const previousSnapshot = await previousPrepareNextTurnWithContext?.({ ...turn, context }, signal);
const nextContext = previousSnapshot?.context ?? context;
const runOptions = this._runSystemPromptOptions ?? this._baseSystemPromptOptions;
const options = normalizeBuildSystemPromptOptions({
...runOptions,
selectedTools: this.getActiveToolNames(),
toolSnippets: { ...this._baseSystemPromptOptions.toolSnippets, ...runOptions.toolSnippets },
toolGuidelines: { ...this._baseSystemPromptOptions.toolGuidelines, ...runOptions.toolGuidelines },
});
const updateMessage = this._preparePromptAndToolLoadout(options, nextContext.messages);
// Keep session.systemPrompt and ctx.getSystemPrompt() in step with what the provider sees.
this._runSystemPromptOptions = options;
return {
...previousSnapshot,
context: {
...nextContext,
tools: this.agent.state.tools.slice(),
},
messages: updateMessage
? [...(previousSnapshot?.messages ?? []), updateMessage]
: previousSnapshot?.messages,
model: this.agent.state.model,
thinkingLevel: this.agent.state.thinkingLevel,
};
};
}
// =========================================================================
// Event Subscription
// =========================================================================
private _refreshFinalizedContext(): void {
const projection = this.sessionManager.buildSessionProjection();
for (const entry of projection.entries) {
for (const message of entry.messages) this._entryIdsByMessage.set(message, entry.sourceEntry.id);
}
this.agent.state.messages = projection.messages;
}
private _applyBoundaryDrafts(manager: SessionManager, drafts: SessionBoundaryDraft[]): SessionEntry[] {
const appended: SessionEntry[] = [];
for (const draft of drafts) {
let entryId: string;
switch (draft.type) {
case "custom":
entryId = manager.appendCustomEntry(draft.customType, draft.data);
break;
case "custom_message":
entryId = manager.appendCustomMessageEntry(
draft.customType,
draft.content,
draft.display,
draft.details,
);
break;
case "context_edit":
entryId = manager.appendContextEdit(draft.targetId, draft.replacement);
break;
case "compaction": {
const tokensBefore = estimateProjectedContextTokens(
manager.buildSessionProjection(),
manager.getBranch(),
).tokens;
entryId = manager.appendCompaction(
draft.summary,
draft.firstKeptEntryId,
tokensBefore,
draft.details,
true,
draft.usage,
);
break;
}
}
const entry = manager.getEntry(entryId);
if (entry) appended.push(entry);
}
return appended;
}
private _createBoundaryPreviewManager(drafts: SessionBoundaryDraft[]): SessionManager {
const header = this.sessionManager.getHeader();
if (!header) throw new Error("Session header is missing");
const manager = SessionManager.inMemory(this._cwd, undefined, [header, ...this.sessionManager.getBranch()]);
this._applyBoundaryDrafts(manager, drafts);
return manager;
}
private _getPendingBoundaryMessages(): AgentMessage[] {
return [...this.agent.peekQueuedMessages(), ...this._pendingCustomMessages];
}
private _buildBoundaryContext(
drafts: SessionBoundaryDraft[],
boundary: "turn_end" | "agent_before_settle",
): BoundaryContextPreview {
const projection = this._createBoundaryPreviewManager(drafts).buildSessionProjection();
const pendingMessages = this._getPendingBoundaryMessages();
const llmMessages = convertToLlm(projection.messages);
const finalRole = llmMessages[llmMessages.length - 1]?.role;
const hasNonSystemContext = llmMessages.some((message) => message.role !== "system");
const contextCanContinue = hasNonSystemContext && finalRole !== "assistant";
const pendingCustomContext = this._pendingCustomMessages.length > 0;
return {
contextEntries: projection.entries,
contextMessages: projection.messages,
llmMessages,
pendingMessages,
canContinue:
contextCanContinue ||
pendingCustomContext ||
(boundary === "turn_end"
? this.agent.hasQueuedMessages()
: finalRole === "assistant" && this.agent.hasQueuedMessages()),
};
}
private _commitBoundaryDrafts(drafts: SessionBoundaryDraft[]): void {
const appended = this._applyBoundaryDrafts(this.sessionManager, drafts);
this._refreshFinalizedContext();
for (const entry of appended) this._emit({ type: "entry_appended", entry });
}