-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathagent-session.ts
More file actions
6788 lines (6240 loc) · 239 KB
/
Copy pathagent-session.ts
File metadata and controls
6788 lines (6240 loc) · 239 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 { randomUUID } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { basename, dirname } from "node:path";
import type {
Agent,
AgentContinuationOptions,
AgentEvent,
AgentMessage,
AgentState,
AgentTool,
AgentToolCall,
AgentToolResult,
AgentToolUpdateCallback,
PreparedAgentToolCall,
PrepareNextTurnContext,
ThinkingLevel,
} from "@earendil-works/pi-agent-core";
import { prepareAgentToolCall } from "@earendil-works/pi-agent-core";
import { contentText, SERVER_FALLBACK_ABORTED_DIAGNOSTIC } from "@earendil-works/pi-ai";
import type {
Api,
AssistantMessage,
AuthResult,
ImageContent,
Model,
ProviderHeaders,
SimpleStreamOptions,
TextContent,
Usage,
} from "@earendil-works/pi-ai/compat";
import {
cleanupSessionResources,
isClassifierRefusal,
isContextOverflow,
isProviderStreamStallError,
isProviderTimeoutError,
isRetryableAssistantError,
modelsAreEqual,
type RetryCallbacks,
resetApiProviders,
streamSimple,
} from "@earendil-works/pi-ai/compat";
import { extract429RetryAfterMs, parseRetryAfterMsMarker } from "@earendil-works/pi-ai/utils/retry-hint";
import { getAgentDir } from "../config.ts";
import { getThemeByName, theme } from "../modes/interactive/theme/theme.ts";
import { stripFrontmatter } from "../utils/frontmatter.ts";
import { resolvePath } from "../utils/paths.ts";
import { sleep } from "../utils/sleep.ts";
import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.ts";
import { type BashResult, executeBashWithOperations } from "./bash-executor.ts";
import {
type CompactionResult,
calculateContextTokens,
collectEntriesForBranchSummary,
compact,
estimateContextTokens,
estimateTokens,
generateBranchSummary,
prepareCompaction,
shouldCompact,
} from "./compaction/index.ts";
import { CompactionLifecycleCoordinator, type CompactionLifecycleState } from "./compaction/lifecycle.ts";
import { DEFAULT_THINKING_LEVEL } from "./defaults.ts";
import { type BuildDynamicSystemPromptOptions, buildDynamicSystemPrompt } from "./dynamic-prompt/index.ts";
import { exportSessionToHtml, type ToolHtmlRenderer } from "./export-html/index.ts";
import { createToolHtmlRenderer } from "./export-html/tool-renderer.ts";
import type { ServiceTier } from "./extensions/builtin/service-tier.ts";
import {
type ContextUsage,
ExecuteToolError,
type ExecuteToolOptions,
type ExtensionCommandContextActions,
type ExtensionErrorListener,
type ExtensionMode,
ExtensionRunner,
type ExtensionToolHookLifecycleEvent,
type ExtensionUIContext,
type InputSource,
type MessageEndEvent,
type MessageStartEvent,
type MessageUpdateEvent,
type ReplacedSessionContext,
type SessionBeforeCompactResult,
type SessionBeforeTreeResult,
type SessionStartEvent,
type ShutdownHandler,
type SystemPromptChangeEvent,
type ToolDefinition,
type ToolExecutionEndEvent,
type ToolExecutionStartEvent,
type ToolExecutionUpdateEvent,
type ToolInfo,
type TreePreparation,
type TurnEndEvent,
type TurnStartEvent,
wrapRegisteredTools,
} from "./extensions/index.ts";
import { emitSessionShutdownEvent } from "./extensions/runner.ts";
import type {
ApplyCompactionOptions,
ApplyCompactionResult,
CompactionReason,
CompactionRejectionCause,
LazyToolActivator,
ModelSelectSource,
} from "./extensions/types.ts";
import { RUNTIME_EXTENSION_PATH } from "./extensions/types.ts";
import { shouldWarnHighReasoning } from "./high-reasoning-warning.ts";
import { type BashExecutionMessage, type CustomMessage, filterContextExcludedMessages } from "./messages.ts";
import { ModelRegistry } from "./model-registry.ts";
import { type AvailableModelsSource, getModelNarrowingPatterns, resolveModelScope } from "./model-resolver.ts";
import type { ModelRuntime } from "./model-runtime.ts";
import { PROMPT_CACHE_SAFE_WAIT_ENV, resolvePromptCacheSafeWaitSeconds } from "./prompt-cache-budget.ts";
import { expandPromptTemplate, type PromptTemplate } from "./prompt-templates.ts";
import type { ResourceExtensionPaths, ResourceLoader } from "./resource-loader.ts";
import { isBillingErrorMessage } from "./retry-fallback/billing.ts";
import { formatSelector } from "./retry-fallback/chains.ts";
import { RetryFallbackController } from "./retry-fallback/controller.ts";
import { SelectorCooldowns } from "./retry-fallback/cooldown.ts";
import {
classifyRateLimitedWait,
nextInTurnDelayMs,
type ProbePhase,
probeBackSchedule,
} from "./retry-fallback/hint-policy.ts";
import { createFallbackLogger } from "./retry-fallback/log.ts";
import { ProbeBackScheduler } from "./retry-fallback/probe-scheduler.ts";
import { validateFallbackChains } from "./retry-fallback/validate.ts";
import { createSessionLogger, type SessionLogger } from "./session-log.ts";
import type { BranchSummaryEntry, CompactionEntry, SessionEntry, SessionManager } from "./session-manager.ts";
import {
buildSessionContext,
CURRENT_SESSION_VERSION,
getLatestCompactionEntry,
type SessionHeader,
} from "./session-manager.ts";
import { generateSessionTitle, sessionTitleRetryPolicy, shouldSkipSessionTitle } from "./session-title-generator.ts";
import { SessionWorkBarrier } from "./session-work-barrier.ts";
import type { SettingsManager } from "./settings-manager.ts";
import type { SlashCommandInfo } from "./slash-commands.ts";
import { createSyntheticSourceInfo, type SourceInfo } from "./source-info.ts";
import { getSupportedThinkingLevels, supportsMax, supportsXhigh } from "./thinking-levels.ts";
import { resetTimings, time } from "./timings.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, createUsageTotals } from "./usage-totals.ts";
const TURN_RETRY_SUPPRESSION_PREFIX = "senpi:no-turn-retry:";
// ============================================================================
// 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,
};
}
/** Session-specific events that extend the core AgentEvent */
type AgentSessionAgentEndEvent = Extract<AgentEvent, { type: "agent_end" }> & { willRetry: boolean };
export type AgentSessionEvent =
| Exclude<AgentEvent, { type: "agent_end" }>
| AgentSessionAgentEndEvent
| { type: "agent_settled" }
| { type: "session_abort" }
| { type: "continuation_error"; errorMessage: string }
| {
type: "queue_update";
steering: readonly string[];
followUp: readonly string[];
}
| { type: "compaction_start"; reason: CompactionReason; requestId?: string }
| { type: "compaction_progress"; reason: CompactionReason; delta?: string; text?: string }
| { type: "entry_appended"; entry: SessionEntry }
| { type: "session_info_changed"; name: string | undefined }
| ExtensionToolHookLifecycleEvent
| SystemPromptChangeEvent
| { type: "thinking_level_changed"; level: ThinkingLevel }
| { type: "high_reasoning_warning"; modelId: string; provider: string; thinkingLevel: ThinkingLevel }
| {
type: "compaction_end";
reason: CompactionReason;
result: CompactionResult | undefined;
aborted: boolean;
willRetry: boolean;
requestId?: string;
accepted?: boolean;
rejectionCause?: CompactionRejectionCause;
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: "retry_fallback_applied";
from: string;
to: string;
chainKey: string;
reason: "transient" | "refusal" | "hard-error" | "billing";
}
| { type: "retry_fallback_succeeded"; model: string; chainKey: string }
| { type: "retry_fallback_reverted"; from: string; to: string }
| { type: "retry_fallback_exhausted"; chainKey: string; lastError: string }
| { type: "server_fallback_aborted"; from: string; to: string; chainConfigured: boolean }
// Auth login flow (task 13) is additive with event-only completion. The
// login_start command responds immediately, then the OAuth URL and the
// terminal result arrive here, because an interactive browser round-trip
// cannot fit inside the request timeout.
| { type: "auth_login_url"; provider: string; url: string }
| { type: "auth_login_end"; provider: string; success: boolean; error?: 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: CompactionReason;
}
| { type: "summarization_retry_finished" }
| { type: "retry_probe_scheduled"; selector: string; atMs: number; probeIndex: 1 | 2 }
| { type: "retry_probe_result"; selector: string; ok: boolean; errorMessage?: string }
| { 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;
/** Directory containing runtime logs and global agent configuration. */
agentDir?: string;
/** Clock override for fallback selector cooldowns (tests only). */
fallbackNow?: () => number;
/** Global model narrowing for selectors and startup model choice (from --models / enabledModels) */
scopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel; serviceTier?: ServiceTier }>;
/** Favorite models to cycle through with Ctrl+P */
favoriteModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel; serviceTier?: ServiceTier }>;
/** 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;
/** Legacy model facade retained for extensions and SDK consumers. */
modelRegistry?: ModelRegistry;
/** Initial active built-in tool names. Default: [read, bash, edit, write] */
initialActiveToolNames?: string[];
/** 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;
autoTitleSessions?: boolean;
}
type SessionModelEntry = { model: Model<any>; thinkingLevel?: ThinkingLevel; serviceTier?: ServiceTier };
interface CompactionExecutionRequest {
controller: AbortController;
owner: "auto" | "compaction";
reason: CompactionReason;
requestId?: string;
customInstructions?: string;
willRetry: boolean;
skipAbortedCheck?: boolean;
lastAssistantMessage?: AgentMessage;
precomputed?: CompactionResult;
allowSummaryOnly?: boolean;
agentMessagesAtStart?: readonly AgentMessage[];
}
type CompactionExecutionResult =
| {
accepted: true;
requestId: string;
result: CompactionResult;
compactionEntry: CompactionEntry;
fromExtension: boolean;
}
| {
accepted: false;
requestId: string;
rejectionCause: CompactionRejectionCause;
};
type PendingCompactionAdmission = {
readonly controller: AbortController;
readonly finishSessionWork: () => void;
outcome?: "completed" | "failed" | "aborted";
};
function isCompactionOwnedPreCompactDiagnostic(message: AgentMessage, requestId: string): boolean {
if (message.role !== "custom" || message.customType !== "senpi.hook") return false;
const details = message.details;
if (!details || typeof details !== "object") return false;
const diagnostic = details as { event?: unknown; compactionRequestId?: unknown };
return diagnostic.event === "PreCompact" && diagnostic.compactionRequestId === requestId;
}
/**
* Human-readable rejection message paired with a `CompactionRejectionCause`.
*
* Kept exhaustive over the union so the compiler flags any new cause that would
* otherwise reintroduce silent failures at the `compaction_end` UI seam.
*/
function describeCompactionRejection(cause: CompactionRejectionCause): string {
switch (cause) {
case "would-overflow":
return "Compaction rejected: the produced summary would still overflow the model context window. Reduce context (e.g. /new, drop attachments) or switch to a larger-context model.";
case "cancelled-by-extension":
return "Compaction rejected: cancelled by an extension.";
case "circuit-breaker":
return "Compaction rejected: the compaction circuit breaker is open after repeated failures. Wait for the cooldown and retry.";
case "per-turn-cap":
return "Compaction rejected: per-turn compaction cap reached for this turn.";
case "stale-revision":
return "Compaction rejected: the session changed while the summary was being prepared. Retry compaction against the latest context.";
}
}
class CompactionRejectedError extends Error {
readonly rejectionCause: CompactionRejectionCause;
constructor(rejectionCause: CompactionRejectionCause) {
super(
rejectionCause === "cancelled-by-extension"
? "Compaction cancelled"
: describeCompactionRejection(rejectionCause),
);
this.name = "CompactionRejectedError";
this.rejectionCause = rejectionCause;
}
}
class CompactionCancelledError extends Error {
constructor() {
super("Compaction cancelled");
this.name = "CompactionCancelledError";
}
}
/**
* An execution failure annotated with whether this operation still owns its
* terminal transition. Callers must not publish a terminal event for an
* operation that a newer compaction generation has superseded.
*/
class CompactionExecutionError extends Error {
readonly ownsTerminalTransition: boolean;
readonly aborted: boolean;
constructor(error: unknown, ownsTerminalTransition: boolean, aborted: boolean) {
super(error instanceof Error ? error.message : String(error));
this.name = "CompactionExecutionError";
this.ownsTerminalTransition = ownsTerminalTransition;
this.aborted = aborted;
}
}
function compactionExecutionOwnsTerminalTransition(error: unknown): boolean {
return !(error instanceof CompactionExecutionError) || error.ownsTerminalTransition;
}
function isCompactionExecutionAborted(error: unknown): boolean {
return (
(error instanceof CompactionExecutionError && error.aborted) ||
error instanceof CompactionCancelledError ||
(error instanceof Error && error.name === "AbortError")
);
}
class RequiredCompactionError extends Error {
constructor() {
super("Context remains above the compaction threshold because compaction did not complete");
this.name = "RequiredCompactionError";
}
}
class MissingModelAccessError extends Error {
constructor() {
super("AgentSession requires modelRuntime or modelRegistry");
this.name = "MissingModelAccessError";
}
}
export interface ExtensionBindings {
uiContext?: ExtensionUIContext;
mode?: ExtensionMode;
commandContextActions?: ExtensionCommandContextActions;
abortHandler?: () => void;
shutdownHandler?: ShutdownHandler;
onError?: ExtensionErrorListener;
}
/** Options for AgentSession.prompt() */
export type PromptDisposition = "handled" | "queued" | "started";
export type QueuedInput = {
readonly text: string;
readonly mode: "steer" | "followUp";
readonly enqueueOrder: number;
};
export type ClearedQueue = {
steering: string[];
followUp: string[];
/** Global enqueue order, independent of native delivery priority. */
readonly ordered: readonly QueuedInput[];
};
export interface PromptOptions {
/** Whether to expand file-based 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";
/** Session-only thinking level applied before starting this prompt. */
thinkingLevel?: ThinkingLevel;
/** Source of input for extension input event handlers. Defaults to "interactive". */
source?: InputSource;
/** Internal hook used by RPC mode to observe prompt preflight acceptance or rejection. */
preflightResult?: (success: boolean) => void;
/** Internal hook used by the TUI to distinguish handled input from owned prompt work. */
promptDisposition?: (disposition: PromptDisposition) => void;
/** Internal cancellation signal for a prompt that has not acquired session-work ownership yet. */
signal?: AbortSignal;
/** Internal callback used by fire-and-forget extension input to retain session-work ownership after its barrier wait. */
onSessionWorkReady?: () => void;
sessionTitlePrompt?: string | false;
}
/** Result from cycleModel() */
export interface ModelCycleResult {
model: Model<any>;
thinkingLevel: ThinkingLevel;
/** Whether cycling used the configured favorite model list */
isScoped: boolean;
/** Present when the model switch also changed the active system prompt. */
systemPromptChange?: SystemPromptChangeEvent;
}
/** 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;
}
function isSameOverflowSource(
message: AssistantMessage,
model: Model<Api>,
upstreamModelId: string | undefined,
): boolean {
if (message.provider !== model.provider) return false;
if (message.model === model.id) return true;
return message.model === upstreamModelId;
}
// ============================================================================
// Constants
// ============================================================================
/** Thinking levels including native max (Opus 4.6 legacy / Opus 4.7 native). */
const THINKING_LEVELS_WITH_MAX: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
/** Caps explicit skill expansion so one prompt cannot consume unbounded context. */
export const MAX_SKILL_EXPANSIONS_PER_PROMPT = 5;
// ============================================================================
// AgentSession Class
// ============================================================================
export class AgentSession {
readonly agent: Agent;
readonly sessionManager: SessionManager;
readonly settingsManager: SettingsManager;
private _scopedModels: SessionModelEntry[];
private _favoriteModels: SessionModelEntry[];
// Event subscription state
private _unsubscribeAgent?: () => void;
private _eventListeners: AgentSessionEventListener[] = [];
private _agentEventQueue: Promise<void> = Promise.resolve();
/**
* Exact message objects whose message_end persistence is still queued.
* Agent core appends messages to agent.state.messages before emitting
* message_end; until that event settles on _agentEventQueue, compaction must
* treat these identities as pending persistence, never as stale or droppable.
*/
private readonly _messageEndsAwaitingPersistence = new Set<AgentMessage>();
private _isAgentRunActive = false;
private _toolExecutionDepth = 0;
private _promptStartPending = false;
private _nextInputId = 0;
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[] = [];
/** Recovery-only order across both native queue modes and TUI compaction ownership. */
private _queuedInputOrder: QueuedInput[] = [];
private _nextQueuedInputOrder = 0;
private _sessionLogger: SessionLogger;
private _activeCompactionLogAttempt:
| { id: string; reason: CompactionReason; tokensBefore: number | undefined }
| undefined;
private readonly _supersededCompactionLogAttemptIds = new Set<string>();
/** Messages queued to be included with the next user prompt as context ("asides"). */
private _pendingNextTurnMessages: CustomMessage[] = [];
// Queues held while the first post-compaction response is classified. Agent
// core otherwise drains steering immediately before AgentSession can consume
// the stale-usage exemption and schedule the continuation itself.
private _postCompactionDeferredSteeringMessages: AgentMessage[] = [];
private _postCompactionDeferredFollowUpMessages: AgentMessage[] = [];
// Compaction state
private _compactionAbortController: AbortController | undefined = undefined;
private _autoCompactionAbortController: AbortController | undefined = undefined;
private _pendingCompactionAdmission: PendingCompactionAdmission | undefined = undefined;
private readonly _compactionLifecycle = new CompactionLifecycleCoordinator();
private readonly _sessionWorkBarrier = new SessionWorkBarrier();
private _overflowRecoveryAttempted = false;
private _requiredCompactionAdmissionError: RequiredCompactionError | undefined;
// Preserve provenance across agent-core's conversion of our admission error
// into an assistant error message. Matching provider text alone is not proof
// that AgentSession initiated required-compaction recovery.
private _requiredCompactionTurnError: RequiredCompactionError | undefined;
// A retry continuation immediately follows an accepted compaction. Its first
// response must not retrigger threshold compaction from stale provider usage.
private _skipNextPostRetryCompactionCheck = false;
private _blockedPostCompactionAssistant: { assistant: AssistantMessage; revision: number } | undefined;
private _skipNextPostCompactionAssistantCheck = false;
private _scheduledContinuationRecompacted = false;
private readonly _assistantsPendingAtCompaction = new WeakSet<AssistantMessage>();
private readonly _postCompactionUsageExemptAssistants = new WeakSet<AssistantMessage>();
private _messageRevision = 0;
// Branch summarization state
private _branchSummaryAbortController: AbortController | undefined = undefined;
private _sessionTitleAbortController: AbortController | undefined = undefined;
private _sessionTitlePromise: Promise<void> | undefined = undefined;
private readonly _autoTitleSessions: boolean;
// Retry state
private _retryAbortController: AbortController | undefined = undefined;
private _retryAttempt = 0;
private _consecutiveProviderStreamStalls = 0;
private _probePhase: ProbePhase = "idle";
private _hintDeadlineMs: number | undefined = undefined;
private _cumulativeHintedWaitMs = 0;
private _retryPromise: Promise<void> | undefined = undefined;
private _retryResolve: (() => void) | undefined = undefined;
private _userAbortPromise: Promise<void> | undefined = undefined;
private _agentAbortSource: "user" | "system" | undefined = undefined;
private _suppressQueuedContinuationAfterUserAbort = false;
/** Set when clearQueue({ abortWillFollow: true }) drains queues immediately before abort(). */
private _hadClearedQueuedMessages = false;
private _extensionEventSignal: AbortSignal | undefined = undefined;
// Bash execution state
private readonly _bashAbortControllers = new Set<AbortController>();
private _pendingBashMessages: BashExecutionMessage[] = [];
// Extension system
private _extensionRunner!: ExtensionRunner;
private _turnIndex = 0;
private _resourceLoader: ResourceLoader;
private _customTools: ToolDefinition[];
private _baseToolDefinitions: Map<string, ToolDefinition> = new Map();
private _cwd: string;
private _agentDir: string;
private _extensionRunnerRef?: { current?: ExtensionRunner };
private _initialActiveToolNames?: string[];
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 _extensionBindingPromptReadiness: Set<Promise<void>> | undefined;
private _modelRuntime: ModelRuntime;
private _modelRegistry: ModelRegistry;
private readonly _fallbackValidationWarnings: readonly string[];
private readonly _retryFallback: RetryFallbackController;
private readonly _selectorCooldowns: SelectorCooldowns;
private readonly _probeBackScheduler: ProbeBackScheduler;
private readonly _fallbackNow: () => number;
// Tool registry for extension getTools/setTools
private _toolRegistry: Map<string, AgentTool> = new Map();
private _lazyToolActivators: LazyToolActivator[] = [];
private _toolDefinitions: Map<string, ToolDefinitionEntry> = new Map();
private _toolPromptSnippets: Map<string, string> = new Map();
private _toolPromptGuidelines: Map<string, string[]> = new Map();
// Base system prompt (without extension appends) - used to apply fresh appends each turn
private _baseSystemPrompt = "";
private _currentServiceTier: ServiceTier | undefined = undefined;
private _sessionFastMode = false;
private readonly _shownHighReasoningWarningKeys = new Set<string>();
private _baseSystemPromptOptions!: BuildDynamicSystemPromptOptions;
private _systemPromptOverride?: string;
constructor(config: AgentSessionConfig) {
this.agent = config.agent;
this.sessionManager = config.sessionManager;
this.settingsManager = config.settingsManager;
const noModelFallback =
config.resourceLoader.getExtensions().runtime.flagValues.get("no-model-fallback") === true ||
process.env.SENPI_NO_FALLBACK === "1";
if (noModelFallback) {
this.settingsManager.applyOverrides({ retry: { modelFallback: false } });
}
this._scopedModels = config.scopedModels ?? [];
this._favoriteModels = config.favoriteModels ?? [];
this._resourceLoader = config.resourceLoader;
this._customTools = config.customTools ?? [];
this._cwd = config.cwd;
const modelRuntime = config.modelRuntime ?? config.modelRegistry?.modelRuntime;
if (!modelRuntime) {
throw new MissingModelAccessError();
}
this._modelRuntime = modelRuntime;
this._modelRegistry = config.modelRegistry ?? new ModelRegistry(modelRuntime);
this._agentDir = config.agentDir ?? getAgentDir();
const fallbackLogger = createFallbackLogger(this._agentDir);
this._sessionLogger = createSessionLogger(this._agentDir);
this._fallbackValidationWarnings = validateFallbackChains(
this.settingsManager.getRawFallbackChains(),
this._modelRegistry,
);
for (const warning of this._fallbackValidationWarnings) {
fallbackLogger.warn("validation_warning", { warning });
}
this._selectorCooldowns = new SelectorCooldowns(config.fallbackNow ?? (() => Date.now()));
this._fallbackNow = config.fallbackNow ?? (() => Date.now());
this._retryFallback = new RetryFallbackController({
getSettings: () => this.settingsManager.getRetryFallbackSettings(),
registry: this._modelRegistry,
cooldowns: this._selectorCooldowns,
logger: fallbackLogger,
switchModel: async (model, thinking, reason) => {
await this._switchActiveModel(model, {
persistDefault: false,
appendSessionEntry: true,
entryReason: reason,
emitModelSelect: true,
modelSelectSource: reason,
invalidateCompaction: true,
ephemeralThinkingLevel: thinking,
});
},
emit: (event) => this._emit(event),
getCurrentSelector: () => (this.model ? { model: this.model, thinkingLevel: this.thinkingLevel } : undefined),
isAuthAvailable: (provider) => this._modelRuntime.hasConfiguredAuth(provider),
});
this._probeBackScheduler = new ProbeBackScheduler({
now: this._fallbackNow,
});
this._extensionRunnerRef = config.extensionRunnerRef;
this._initialActiveToolNames = config.initialActiveToolNames;
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" };
this._autoTitleSessions = config.autoTitleSessions ?? false;
const initialModel = this.agent.state.model;
if (initialModel) {
const scopedMatch = this._scopedModels.find((sm) => modelsAreEqual(sm.model, initialModel));
this._currentServiceTier = this._resolveServiceTier(initialModel, scopedMatch?.serviceTier);
}
this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
this._installAgentToolHooks();
this._installAgentNextTurnRefresh();
this._buildRuntime({
activeToolNames: this._initialActiveToolNames,
includeAllExtensionTools: true,
});
}
get modelRuntime(): ModelRuntime {
return this._modelRuntime;
}
get modelRegistry(): ModelRegistry {
return this._modelRegistry;
}
private async _getRequiredRequestAuth(model: Model<any>): Promise<{
apiKey?: string;
headers?: Record<string, string>;
extraBody?: Record<string, unknown>;
env?: Record<string, string>;
}> {
let result: AuthResult | undefined;
try {
result = await this._modelRuntime.getAuth(model);
} 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)) {
return {
apiKey: result.auth.apiKey,
headers: withoutDeletedHeaders(result.auth.headers),
extraBody: this._modelRuntime.getCompatibilityRequestConfig(model).extraBody,
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));
}
/**
* Resolve optional auth for a summarization stream. Native/custom stream
* functions may provide ambient credentials, unlike streamSimple.
*/
private async _getSummarizationRequestAuth(model: Model<any>): Promise<{
apiKey?: string;
headers?: Record<string, string>;
env?: Record<string, string>;
}> {
if (this.agent.streamFunction === streamSimple) {
return this._getRequiredRequestAuth(model);
}
try {
const apiKey = await this.agent.getApiKey?.(model.provider);
const result = await this._modelRuntime.getAuth(model, { apiKey });
return result
? {
apiKey: apiKey ?? result.auth.apiKey,
headers: withoutDeletedHeaders(result.auth.headers),
env: result.env,
}
: {};
} catch {
return {};
}
}
private async _getCompactionRequestAuth(model: Model<any>): Promise<{
apiKey?: string;
headers?: Record<string, string>;
extraBody?: Record<string, unknown>;
env?: Record<string, string>;
}> {
const auth = await this._getSummarizationRequestAuth(model);
return {
...auth,
extraBody: this._modelRuntime.getCompatibilityRequestConfig(model).extraBody,
};
}
/**
* 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.
*/
/**
* Surface a provider-level server-fallback abort before retry handling runs so
* the UI can explain the switch. Emitted synchronously here because retry work
* for the following agent_end starts before queued message_end processing
* drains. `chainConfigured` is required because the no-chain refusal path
* emits no retry_fallback_exhausted, leaving the UI no other signal.
*/
private _emitServerFallbackAborted(message: AssistantMessage): void {
const details = message.diagnostics?.find((entry) => entry.type === SERVER_FALLBACK_ABORTED_DIAGNOSTIC)?.details;
if (details === undefined) return;
this._emit({
type: "server_fallback_aborted",
from: typeof details.from === "string" ? details.from : message.model,
to: typeof details.to === "string" ? details.to : message.model,
chainConfigured: this._retryFallback.hasConfiguredChain(),
});
}
private _installAgentToolHooks(): void {
this.agent.beforeToolCall = async ({ toolCall, args }) => {
this._toolExecutionDepth++;
try {
const result = await this._emitBeforeToolCallHooks(toolCall, args);
if (result?.block) {
this._toolExecutionDepth--;
}
return result;
} catch (err) {
this._toolExecutionDepth--;
throw err;
}
};
this.agent.afterToolCall = async ({ toolCall, args, result, isError }) => {
try {
return await this._emitAfterToolCallHooks(toolCall, args, result, isError);
} finally {
this._toolExecutionDepth--;
}
};
}
private async _emitBeforeToolCallHooks(
toolCall: AgentToolCall,
args: unknown,
options: { waitForEventQueue?: boolean } = {},
) {
if (options.waitForEventQueue !== false) {
await this._agentEventQueue;
}
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,
input: args as Record<string, unknown>,
});
} catch (err) {
if (err instanceof Error) {
throw err;
}
throw new Error(`Extension failed, blocking execution: ${String(err)}`);
}
}
private async _emitAfterToolCallHooks(
toolCall: AgentToolCall,
args: unknown,
result: AgentToolResult<unknown>,
isError: boolean,
) {
const runner = this._extensionRunner;
if (!runner.hasHandlers("tool_result")) {
return undefined;
}
const hookResult = await runner.emitToolResult({
type: "tool_result",
toolName: toolCall.name,
toolCallId: toolCall.id,
input: args as Record<string, unknown>,
content: result.content,
details: result.details,
isError,
usage: result.usage,
});
if (!hookResult) {
return undefined;
}
return {
content: hookResult.content,
details: hookResult.details,
isError: hookResult.isError ?? isError,
usage: hookResult.usage,
};
}
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) => {
// Enforce compaction only when this prepare precedes an actual provider
// admission: a tool continuation or queued steer/follow-up messages. A
// completed turn with no continuation keeps pre-PR timing, while the
// prior prepare callback and context refresh below still run every turn.
const compactBeforeNextAdmission = async (): Promise<boolean> => {
if (turn.toolResults.length === 0 && !this.agent.hasQueuedMessages()) {
return false;
}
await this._agentEventQueue;
// A queue can be cleared while waiting for persistence. Re-sample it
// immediately before compaction so a completed turn never compacts
// merely because it once had a possible continuation.
if (turn.toolResults.length === 0 && !this.agent.hasQueuedMessages()) {
return false;
}