-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathagent-session.ts
More file actions
12962 lines (11922 loc) · 486 KB
/
Copy pathagent-session.ts
File metadata and controls
12962 lines (11922 loc) · 486 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 * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { scheduler } from "node:timers/promises";
import { isPromise } from "node:util/types";
import type { InMemorySnapshotStore } from "@oh-my-pi/hashline";
import {
type AfterToolCallContext,
type AfterToolCallResult,
Agent,
AgentBusyError,
type AgentEvent,
type AgentMessage,
type AgentState,
type AgentTool,
AppendOnlyContextManager,
type AsideMessage,
type CompactionSummaryMessage,
countTokens,
resolveTelemetry,
ThinkingLevel,
type ToolChoiceDirective,
} from "@oh-my-pi/pi-agent-core";
import {
AGGRESSIVE_SHAKE_CONFIG,
AUTO_HANDOFF_THRESHOLD_FOCUS,
applyShakeRegions,
CompactionCancelledError,
type CompactionPreparation,
type CompactionResult,
type CompactionSettings,
calculateContextTokens,
calculatePromptTokens,
collectEntriesForBranchSummary,
collectShakeRegions,
compact,
compactionContextTokens,
createCompactionSummaryMessage,
DEFAULT_SHAKE_CONFIG,
effectiveReserveTokens,
estimateTokens,
generateBranchSummary,
generateHandoff,
prepareCompaction,
resolveThresholdTokens,
type SessionEntry,
type SessionMessageEntry,
type ShakeConfig,
type ShakeRegion,
type SummaryOptions,
shouldCompact,
shouldUseOpenAiRemoteCompaction,
} from "@oh-my-pi/pi-agent-core/compaction";
import {
DEFAULT_PRUNE_CONFIG,
pruneSupersededToolResults,
pruneToolOutputs,
readToolSupersedeKey,
} from "@oh-my-pi/pi-agent-core/compaction/pruning";
import type { ProtectedToolMatcher } from "@oh-my-pi/pi-agent-core/compaction/tool-protection";
import type {
AssistantMessage,
ImageContent,
Message,
MessageAttribution,
Model,
ProviderResponseMetadata,
ProviderSessionState,
ResetCreditAccountStatus,
ResetCreditRedeemOutcome,
ResetCreditTarget,
ServiceTier,
SimpleStreamOptions,
TextContent,
ToolCall,
ToolChoice,
Usage,
UsageReport,
} from "@oh-my-pi/pi-ai";
import {
calculateRateLimitBackoffMs,
clearAnthropicFastModeFallback,
deriveClaudeDeviceId,
Effort,
isContextOverflow,
isUsageLimitError,
parseRateLimitReason,
resolveServiceTier,
streamSimple,
} from "@oh-my-pi/pi-ai";
import { stripToolDescriptions, toolWireSchema } from "@oh-my-pi/pi-ai/utils/schema";
import { THINKING_LOOP_ERROR_MARKER } from "@oh-my-pi/pi-ai/utils/thinking-loop";
import { isFireworksFastModelId, toFireworksBaseModelId } from "@oh-my-pi/pi-catalog/fireworks-model-id";
import { getSupportedEfforts } from "@oh-my-pi/pi-catalog/model-thinking";
import { modelsAreEqual } from "@oh-my-pi/pi-catalog/models";
import { MacOSPowerAssertion } from "@oh-my-pi/pi-natives";
import {
extractRetryHint,
formatDuration,
getAgentDbPath,
getInstallId,
isBunTestRuntime,
isEnoent,
isUnexpectedSocketCloseMessage,
logger,
prompt,
relativePathWithinRoot,
Snowflake,
withTimeout,
} from "@oh-my-pi/pi-utils";
import * as snapcompact from "@oh-my-pi/snapcompact";
import {
AdviseTool,
type AdvisorAgent,
type AdvisorMessageDetails,
type AdvisorNote,
AdvisorRuntime,
type AdvisorSeverity,
AdvisorTranscriptRecorder,
formatAdvisorBatchContent,
isAdvisorInterruptImmuneTurnActive,
isInterruptingSeverity,
resolveAdvisorDeliveryChannel,
} from "../advisor";
import { type AsyncJob, type AsyncJobDeliveryState, AsyncJobManager } from "../async";
import { classifyDifficulty } from "../auto-thinking/classifier";
import { reset as resetCapabilities } from "../capability";
import type { Rule } from "../capability/rule";
import { shouldEnableAppendOnlyContext } from "../config/append-only-context-mode";
import type { ModelRegistry } from "../config/model-registry";
import {
extractExplicitThinkingSelector,
filterAvailableModelsByEnabledPatterns,
formatModelSelectorValue,
formatModelString,
formatModelStringWithRouting,
getModelMatchPreferences,
parseModelString,
type ResolvedModelRoleValue,
resolveModelOverride,
resolveModelRoleValue,
resolveRoleSelection,
} from "../config/model-resolver";
import { MODEL_ROLE_IDS, MODEL_ROLES } from "../config/model-roles";
import { expandPromptTemplate, type PromptTemplate } from "../config/prompt-templates";
import type { Settings, SkillsSettings } from "../config/settings";
import { getDefault, onAppendOnlyModeChanged } from "../config/settings";
import { RawSseDebugBuffer } from "../debug/raw-sse-buffer";
import { loadCapability } from "../discovery";
import { expandApplyPatchToEntries, normalizeDiff, normalizeToLF, ParseError, previewPatch, stripBom } from "../edit";
import { getFileSnapshotStore } from "../edit/file-snapshot-store";
import { disposeJuliaKernelSessionsByOwner } from "../eval/jl/executor";
import { namespaceSessionId as namespacePythonSessionId } from "../eval/py";
import {
disposeKernelSessionsByOwner,
executePython as executePythonCommand,
type PythonResult,
} from "../eval/py/executor";
import { disposeRubyKernelSessionsByOwner } from "../eval/rb/executor";
import { defaultEvalSessionId } from "../eval/session-id";
import { type BashResult, executeBash as executeBashCommand } from "../exec/bash-executor";
import type { TtsrManager, TtsrMatchContext } from "../export/ttsr";
import type { LoadedCustomCommand } from "../extensibility/custom-commands";
import type { CustomTool, CustomToolContext } from "../extensibility/custom-tools/types";
import { CustomToolAdapter } from "../extensibility/custom-tools/wrapper";
import type {
ExtensionCommandContext,
ExtensionRunner,
ExtensionUIContext,
MessageEndEvent,
MessageStartEvent,
MessageUpdateEvent,
SessionBeforeBranchResult,
SessionBeforeCompactResult,
SessionBeforeSwitchResult,
SessionBeforeTreeResult,
SessionStopEventResult,
ToolExecutionEndEvent,
ToolExecutionStartEvent,
ToolExecutionUpdateEvent,
TreePreparation,
TurnEndEvent,
TurnStartEvent,
} from "../extensibility/extensions";
import { createExtensionModelQuery } from "../extensibility/extensions/model-api";
import type { CompactOptions, ContextUsage } from "../extensibility/extensions/types";
import { ExtensionToolWrapper } from "../extensibility/extensions/wrapper";
import type { HookCommandContext } from "../extensibility/hooks/types";
import type { Skill, SkillWarning } from "../extensibility/skills";
import { expandSlashCommand, type FileSlashCommand } from "../extensibility/slash-commands";
import { GoalRuntime } from "../goals/runtime";
import type { Goal, GoalModeState } from "../goals/state";
import type { HindsightSessionState } from "../hindsight/state";
import { type LocalProtocolOptions, resolveLocalUrlToPath } from "../internal-urls";
import { IrcBus, type IrcMessage } from "../irc/bus";
import { resolveMemoryBackend } from "../memory-backend";
import { shutdownMnemopiEmbedClient } from "../mnemopi/embed-client";
import { getMnemopiSessionState, type MnemopiSessionState, setMnemopiSessionState } from "../mnemopi/state";
import { containsOrchestrate, ORCHESTRATE_NOTICE } from "../modes/orchestrate";
import { theme } from "../modes/theme/theme";
import { parseTurnBudget } from "../modes/turn-budget";
import { containsUltrathink, ULTRATHINK_NOTICE } from "../modes/ultrathink";
import { computeNonMessageBreakdown, computeNonMessageTokens } from "../modes/utils/context-usage";
import { containsWorkflow, WORKFLOW_NOTICE } from "../modes/workflow";
import { createPlanReadMatcher } from "../plan-mode/plan-protection";
import type { PlanModeState } from "../plan-mode/state";
import advisorSystemPrompt from "../prompts/advisor/system.md" with { type: "text" };
import autoContinuePrompt from "../prompts/system/auto-continue.md" with { type: "text" };
import eagerTaskPrompt from "../prompts/system/eager-task.md" with { type: "text" };
import eagerTodoPrompt from "../prompts/system/eager-todo.md" with { type: "text" };
import emptyStopRetryTemplate from "../prompts/system/empty-stop-retry.md" with { type: "text" };
import ircAutoReplyTemplate from "../prompts/system/irc-autoreply.md" with { type: "text" };
import ircIncomingTemplate from "../prompts/system/irc-incoming.md" with { type: "text" };
import planModeActivePrompt from "../prompts/system/plan-mode-active.md" with { type: "text" };
import planModeReferencePrompt from "../prompts/system/plan-mode-reference.md" with { type: "text" };
import planModeToolDecisionReminderPrompt from "../prompts/system/plan-mode-tool-decision-reminder.md" with {
type: "text",
};
import sideChannelNoToolsReminder from "../prompts/system/side-channel-no-tools.md" with { type: "text" };
import ttsrInterruptTemplate from "../prompts/system/ttsr-interrupt.md" with { type: "text" };
import ttsrToolReminderTemplate from "../prompts/system/ttsr-tool-reminder.md" with { type: "text" };
import unexpectedStopRetryTemplate from "../prompts/system/unexpected-stop-retry.md" with { type: "text" };
import {
deobfuscateAssistantContent,
deobfuscateSessionContext,
obfuscateMessages,
obfuscateProviderContext,
type SecretObfuscator,
} from "../secrets/obfuscator";
import { invalidateHostMetadata } from "../ssh/connection-manager";
import {
AUTO_THINKING,
type ConfiguredThinkingLevel,
clampAutoThinkingEffort,
parseConfiguredThinkingLevel,
resolveProvisionalAutoLevel,
resolveThinkingLevelForModel,
shouldDisableReasoning,
toReasoningEffort,
} from "../thinking";
import { shutdownTinyTitleClient } from "../tiny/title-client";
import { countToolsForAutoDiscovery, resolveEffectiveToolDiscoveryMode } from "../tool-discovery/mode";
import {
buildDiscoverableToolSearchIndex,
collectDiscoverableTools,
type DiscoverableTool,
type DiscoverableToolSearchIndex,
filterBySource,
isMCPToolName,
selectDiscoverableToolNamesByServer,
} from "../tool-discovery/tool-index";
import { assertEditableFile } from "../tools/auto-generated-guard";
import type { CheckpointState } from "../tools/checkpoint";
import { outputMeta, wrapToolWithMetaNotice } from "../tools/output-meta";
import { normalizeLocalScheme, resolveToCwd } from "../tools/path-utils";
import { isAutoQaEnabled } from "../tools/report-tool-issue";
import { buildResolveReminderMessage } from "../tools/resolve";
import { getLatestTodoPhasesFromEntries, type TodoItem, type TodoPhase } from "../tools/todo";
import { ToolAbortError, ToolError } from "../tools/tool-errors";
import { clampTimeout } from "../tools/tool-timeouts";
import { parseCommandArgs } from "../utils/command-args";
import { type EditMode, resolveEditMode } from "../utils/edit-mode";
import { resolveFileDisplayMode } from "../utils/file-display-mode";
import { extractFileMentions, generateFileMentionMessages } from "../utils/file-mentions";
import { normalizeModelContextImages } from "../utils/image-loading";
import { describeAttachedImagesForTextModel } from "../utils/image-vision-fallback";
import { buildNamedToolChoice, isToolChoiceActive } from "../utils/tool-choice";
import type { AuthStorage } from "./auth-storage";
import type { ClientBridge, ClientBridgePermissionOption, ClientBridgePermissionOutcome } from "./client-bridge";
import {
type CodexAutoRedeemRedeemDecision,
defaultCodexAutoRedeemCoordinator,
evaluateCodexAutoRedeem,
shouldEvaluateCodexAutoRedeem,
shouldPromptCodexAutoRedeem,
} from "./codex-auto-reset";
import { findCompactMode } from "./compact-modes";
import {
type BashExecutionMessage,
type CustomMessage,
convertToLlm,
GENERIC_ABORT_SENTINEL,
type PythonExecutionMessage,
readQueueChipText,
SILENT_ABORT_MARKER,
SKILL_PROMPT_MESSAGE_TYPE,
stripImagesFromMessage,
USER_INTERRUPT_LABEL,
} from "./messages";
import type { SessionContext } from "./session-context";
import { getLatestCompactionEntry, getRestorableSessionModels } from "./session-context";
import { formatSessionDumpText } from "./session-dump-format";
import type { BranchSummaryEntry, CompactionEntry, NewSessionOptions } from "./session-entries";
import { EPHEMERAL_MODEL_CHANGE_ROLE } from "./session-entries";
import { formatSessionHistoryMarkdown } from "./session-history-format";
import type { SessionManager } from "./session-manager";
import type { ShakeMode, ShakeResult } from "./shake-types";
import { ToolChoiceQueue } from "./tool-choice-queue";
import { classifyUnexpectedStop, isUnexpectedStopCandidate } from "./unexpected-stop-classifier";
import { YieldQueue } from "./yield-queue";
const SESSION_STOP_CONTINUATION_CAP = 8;
// A side-channel assistant response is signed for the hidden prompt/history that
// produced it. If we persist that response under a different user turn, native
// replay anchors become invalid; keep only visible, non-cryptographic content.
function sanitizeAssistantForReparentedHistory(message: AssistantMessage): AssistantMessage {
const content: AssistantMessage["content"] = [];
for (const block of message.content) {
if (block.type === "redactedThinking") continue;
if (block.type === "thinking") {
content.push({ type: "thinking", thinking: block.thinking });
continue;
}
content.push(block);
}
return { ...message, content, providerPayload: undefined };
}
/** Session-specific events that extend the core AgentEvent */
export type AgentSessionEvent =
| AgentEvent
| {
type: "auto_compaction_start";
reason: "threshold" | "overflow" | "idle" | "incomplete";
action: "context-full" | "handoff" | "shake" | "snapcompact";
}
| {
type: "auto_compaction_end";
action: "context-full" | "handoff" | "shake" | "snapcompact";
result: CompactionResult | undefined;
aborted: boolean;
willRetry: boolean;
errorMessage?: string;
/** True when compaction was skipped for a benign reason (no model, no candidates, nothing to compact). */
skipped?: boolean;
}
| { 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; role: string }
| { type: "retry_fallback_succeeded"; model: string; role: string }
| { type: "ttsr_triggered"; rules: Rule[] }
| { type: "todo_reminder"; todos: TodoItem[]; attempt: number; maxAttempts: number }
| { type: "todo_auto_clear" }
| { type: "irc_message"; message: CustomMessage }
| { type: "notice"; level: "info" | "warning" | "error"; message: string; source?: string }
| {
type: "thinking_level_changed";
thinkingLevel: ThinkingLevel | undefined;
/** The user-configured selector when it differs from the effective level (e.g. `auto`). */
configured?: ConfiguredThinkingLevel;
/** The level `auto` resolved to this turn, once classified. */
resolved?: Effort;
}
| { type: "goal_updated"; goal: Goal | null; state?: GoalModeState };
/** Listener function for agent session events */
export type AgentSessionEventListener = (event: AgentSessionEvent) => void;
const UNEXPECTED_STOP_MAX_RETRIES = 3;
const UNEXPECTED_STOP_TIMEOUT_MS = 4000;
const EMPTY_STOP_MAX_RETRIES = 3;
const RETRY_BACKOFF_MAX_DELAY_MS = 8_000;
type CompactionCheckResult = Readonly<{
deferredHandoff: boolean;
continuationScheduled: boolean;
}>;
const COMPACTION_CHECK_NONE: CompactionCheckResult = {
deferredHandoff: false,
continuationScheduled: false,
};
const COMPACTION_CHECK_DEFERRED_HANDOFF: CompactionCheckResult = {
deferredHandoff: true,
continuationScheduled: true,
};
const COMPACTION_CHECK_CONTINUATION: CompactionCheckResult = {
deferredHandoff: false,
continuationScheduled: true,
};
/**
* Per-turn prune cache window. A tool result whose all-message suffix exceeds
* this is in the warm, already-sent prompt-cache prefix: re-writing it costs the
* cacheWrite premium on the whole suffix. Per-turn passes only reclaim inside
* this tail (matches the supersede pass's default `suffixTokenLimit`); deeper
* stale/age victims are left to compaction/shake, which rebuild the cache anyway.
*/
const PRUNE_CACHE_WARM_SUFFIX_TOKENS = 8_000;
/**
* Idle gap after which the supersede pass may flush the whole sent region (the
* provider cache is cold, so re-writing it is free). MUST exceed the maximum
* Anthropic prompt-cache TTL — "long" retention (the OAuth default) is 1h — or a
* still-warm prefix is busted by the flush. 90 min leaves margin over the 1h TTL.
*/
const PRUNE_IDLE_FLUSH_MS = 90 * 60_000;
export type CommandMetadataChangedListener = () => void | Promise<void>;
export type AsyncJobSnapshotItem = Pick<AsyncJob, "id" | "type" | "status" | "label" | "startTime">;
const RETRY_BACKOFF_JITTER_RATIO = 0.25;
/**
* Hysteresis band for the post-shake "did we actually create headroom?" check.
* Shake counts as having resolved threshold pressure only when residual context
* lands at or below `SHAKE_RECOVERY_BAND × threshold`. Re-checking against the
* raw threshold lets shake keep reclaiming a trickle of the previous turn's
* output and land just under the line every turn, sustaining the auto-continue
* dead loop reported in #2275.
*/
const SHAKE_RECOVERY_BAND = 0.8;
function calculateRetryBackoffDelayMs(baseDelayMs: number, attempt: number): number {
const cappedDelayMs = Math.min(Math.max(0, baseDelayMs) * 2 ** Math.max(0, attempt - 1), RETRY_BACKOFF_MAX_DELAY_MS);
const jitter = 1 - Math.random() * RETRY_BACKOFF_JITTER_RATIO;
return cappedDelayMs * jitter;
}
/**
* Slack added past a sibling credential's block expiry before retrying, so
* the next getApiKey lands after the block has actually lapsed.
*/
const SIBLING_UNBLOCK_BUFFER_MS = 1_000;
const NON_WHITESPACE_RE = /\S/;
function hasNonWhitespace(value: string): boolean {
return NON_WHITESPACE_RE.test(value);
}
export interface AsyncJobSnapshot {
running: AsyncJobSnapshotItem[];
recent: AsyncJobSnapshotItem[];
delivery: AsyncJobDeliveryState;
}
export type { ShakeMode, ShakeResult };
// ============================================================================
// Types
// ============================================================================
export interface AgentSessionConfig {
agent: Agent;
sessionManager: SessionManager;
settings: Settings;
/** Whether the caller explicitly requested yolo/auto-approve behavior for this session. */
autoApprove?: boolean;
/** Models to cycle through with Ctrl+P (from --models flag) */
scopedModels?: Array<{ model: Model; thinkingLevel?: ThinkingLevel }>;
/** Initial session thinking selector. */
thinkingLevel?: ConfiguredThinkingLevel;
/** Prompt templates for expansion */
promptTemplates?: PromptTemplate[];
/** File-based slash commands for expansion */
slashCommands?: FileSlashCommand[];
/** Extension runner (created in main.ts with wrapped tools) */
extensionRunner?: ExtensionRunner;
/** Loaded skills (already discovered by SDK) */
skills?: Skill[];
/** Skill loading warnings (already captured by SDK) */
skillWarnings?: SkillWarning[];
/** Custom commands (TypeScript slash commands) */
customCommands?: LoadedCustomCommand[];
skillsSettings?: SkillsSettings;
/** Model registry for API key resolution and model discovery */
modelRegistry: ModelRegistry;
/** Tool registry for LSP and settings */
toolRegistry?: Map<string, AgentTool>;
/** Tool names whose current registry entry is still the built-in implementation. */
builtInToolNames?: Iterable<string>;
/** Current session pre-LLM message transform pipeline */
transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => AgentMessage[] | Promise<AgentMessage[]>;
/** Provider payload hook used by the active session request path */
onPayload?: SimpleStreamOptions["onPayload"];
/** Provider response hook used by the active session request path */
onResponse?: SimpleStreamOptions["onResponse"];
/** Raw SSE hook used by the active session request path */
onSseEvent?: SimpleStreamOptions["onSseEvent"];
/** Per-session raw SSE diagnostic buffer */
rawSseDebugBuffer?: RawSseDebugBuffer;
/** Current session message-to-LLM conversion pipeline */
convertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
/** System prompt builder that can consider tool availability. Returns ordered provider-facing blocks. */
rebuildSystemPrompt?: (toolNames: string[], tools: Map<string, AgentTool>) => Promise<{ systemPrompt: string[] }>;
/** Rebuild the SSH tool from current capability discovery results. */
reloadSshTool?: () => Promise<AgentTool | null>;
requestedToolNames?: ReadonlySet<string>;
/**
* Optional accessor for live MCP server instructions. Read by the session's
* `rebuildSystemPrompt`-skip optimization to detect server-side instruction
* changes (e.g. an MCP server upgrade) that would otherwise pass the tool-set
* signature comparison and silently keep a stale prompt cached.
*/
getMcpServerInstructions?: () => Map<string, string> | undefined;
/** Enable hidden-by-default MCP tool discovery for this session. */
mcpDiscoveryEnabled?: boolean;
/** MCP tool names to activate for the current session when discovery mode is enabled. */
initialSelectedMCPToolNames?: string[];
/** Whether constructor-provided MCP defaults should be persisted immediately. */
persistInitialMCPToolSelection?: boolean;
/** MCP server names whose tools should seed discovery-mode sessions whenever those servers are connected. */
defaultSelectedMCPServerNames?: string[];
/** MCP tool names that should seed brand-new sessions created from this AgentSession. */
defaultSelectedMCPToolNames?: string[];
/** TTSR manager for time-traveling stream rules */
ttsrManager?: TtsrManager;
/** Secret obfuscator for deobfuscating streaming edit content */
obfuscator?: SecretObfuscator;
/** Inherited eval executor session id from a parent agent. */
parentEvalSessionId?: string;
/** Logical owner for retained eval kernels created by this session. */
evalKernelOwnerId?: string;
/**
* AsyncJobManager that this session installed as the process-global instance.
* Only set for top-level sessions; subagents inherit the parent's manager and
* **MUST NOT** dispose it on their own teardown.
*/
ownedAsyncJobManager?: AsyncJobManager;
/**
* AsyncJobManager reachable by this session for scoped job actions.
*
* Top-level owners receive their own manager, subagents receive the inherited
* parent manager, and secondary in-process top-level sessions receive
* `undefined` so job snapshots and ACP drains cannot observe the primary's
* state.
*/
asyncJobManager?: AsyncJobManager;
/** Agent identity (registry id like "Main" or "Alice") used for IRC routing. */
agentId?: string;
/** Whether this session is the top-level agent or a subagent. Drives eager-task
* prelude gating so a top-level session created with a custom `agentId` still
* receives the always-mode reminder. Defaults to "main". */
agentKind?: "main" | "sub";
/**
* Override the provider-facing session ID for all API requests from this session.
* When absent, `sessionManager.getSessionId()` is used. Needed when benchmark or
* SDK callers issue probes / prewarming with an explicit `--provider-session-id`
* so that credential sticky selection is consistent with the session's streaming calls.
*/
providerSessionId?: string;
/**
* Hard-isolated read-only tools (read/search/find) for the advisor agent,
* pre-built in `createAgentSession` against a distinct `ToolSession` so the
* advisor's reads never share the primary's snapshot/seen-lines/conflict
* caches. Undefined when the advisor is disabled.
*/
advisorReadOnlyTools?: AgentTool[];
/** Preloaded watchdog prompt content for the advisor. */
advisorWatchdogPrompt?: string;
/**
* Strip tool descriptions from provider-bound tool specs on side requests
* (handoff). Must match the session-start value used to build the system
* prompt so inline descriptors are not also sent through provider schemas.
*/
pruneToolDescriptions?: boolean;
/**
* Disconnect this session's OWNED MCP manager on dispose. Provided only when
* the session created the manager (top-level sessions); subagents reuse a
* parent's manager via `options.mcpManager` and omit this so a child's
* teardown never tears down the shared servers.
*/
disconnectOwnedMcpManager?: () => Promise<void>;
}
/** Options for AgentSession.prompt() */
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). */
streamingBehavior?: "steer" | "followUp";
/** Optional tool choice override for the next LLM call. */
toolChoice?: ToolChoice;
/** Send as developer/system message instead of user. Providers that support it use the developer role; others fall back to user. */
synthetic?: boolean;
/** Marks this prompt as a deliberate user action (typed message, `.`/`c`
* continue). Clears advisor auto-resume suppression that a user interrupt set.
* Defaults to `!synthetic`; manual-continue is synthetic yet user-initiated, so
* it sets this explicitly. Agent-initiated synthetic prompts (auto-continue,
* plan re-prime, reminders) leave it unset and keep suppression latched. */
userInitiated?: boolean;
/** Explicit billing/initiator attribution for the prompt. Defaults to user prompts as `user` and synthetic prompts as `agent`. */
attribution?: MessageAttribution;
/** Skip pre-send compaction checks for this prompt (internal use for maintenance flows). */
skipCompactionCheck?: boolean;
}
/** Result from a handoff operation. */
export interface HandoffResult {
document: string;
savedPath?: string;
}
export interface SessionHandoffOptions {
autoTriggered?: boolean;
signal?: AbortSignal;
}
/** Result from cycleModel() */
export interface ModelCycleResult {
model: Model;
thinkingLevel: ThinkingLevel | undefined;
/** Whether cycling through scoped models (--models flag) or all available */
isScoped: boolean;
}
/** Result from cycleRoleModels() */
export interface RoleModelCycleResult {
model: Model;
thinkingLevel: ThinkingLevel | undefined;
role: string;
}
/** A configured role resolved to a concrete model, used by role cycling and
* the plan-approval model slider. */
export interface ResolvedRoleModel {
role: string;
model: Model;
thinkingLevel?: ThinkingLevel;
explicitThinkingLevel: boolean;
}
/** The set of resolvable role models plus the index of the currently active
* one within {@link ResolvedRoleModel.role} order. */
export interface RoleModelCycle {
models: ResolvedRoleModel[];
currentIndex: number;
}
export interface ContextUsageBreakdown {
contextWindow: number;
anchored: boolean;
usedTokens: number;
systemPromptTokens: number;
systemToolsTokens: number;
systemContextTokens: number;
skillsTokens: number;
messagesTokens: number;
}
/** 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;
};
premiumRequests: number;
cost: number;
}
/** Advisor statistics for /advisor status command. */
export interface AdvisorStats {
configured: boolean;
active: boolean;
model?: Model;
contextWindow: number;
contextTokens: number;
tokens: {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
total: number;
};
cost: number;
messages: {
user: number;
assistant: number;
total: number;
};
}
export interface FreshSessionResult {
previousSessionId: string;
sessionId: string;
closedProviderSessions: number;
}
/** Internal marker for hook messages queued through the agent loop */
// ============================================================================
// Constants
// ============================================================================
/** Standard thinking levels */
type RetryFallbackChains = Record<string, string[]>;
type RetryFallbackRevertPolicy = "never" | "cooldown-expiry";
interface RetryFallbackSelector {
raw: string;
provider: string;
id: string;
thinkingLevel: ThinkingLevel | undefined;
}
interface ActiveRetryFallbackState {
role: string;
originalSelector: string;
originalThinkingLevel: ConfiguredThinkingLevel | undefined;
lastAppliedFallbackThinkingLevel: ConfiguredThinkingLevel | undefined;
pinned: boolean;
}
function parseRetryFallbackSelector(
selector: string,
modelLookup?: { find(provider: string, id: string): Model | undefined },
): RetryFallbackSelector | undefined {
const trimmed = selector.trim();
if (!trimmed) return undefined;
const parsed = parseModelString(trimmed, {
allowMaxAlias: true,
isLiteralModelId: (provider, id) => modelLookup?.find(provider, id) !== undefined,
});
if (!parsed) return undefined;
return {
raw: trimmed,
provider: parsed.provider,
id: parsed.id,
thinkingLevel: parsed.thinkingLevel,
};
}
function formatRetryFallbackSelector(model: Model, thinkingLevel: ThinkingLevel | undefined): string {
return formatModelSelectorValue(formatModelStringWithRouting(model), thinkingLevel);
}
function formatRetryFallbackBaseSelector(selector: RetryFallbackSelector): string {
return `${selector.provider}/${selector.id}`;
}
const EPHEMERAL_REPLY_MAX_BYTES = 4096;
/**
* Collapse degenerate ephemeral replies (/btw, /omfg side-channel turns).
* Models occasionally loop on a single line (~16 reports of N-times-repeated
* replies); compress runs longer than 3 down to one instance + `[…N×]`, then
* cap at 4 KiB so a runaway reply can't flood the channel.
*/
function dedupeEphemeralReply(text: string): string {
if (!text) return text;
const lines = text.split("\n");
const out: string[] = [];
let i = 0;
while (i < lines.length) {
let j = i + 1;
while (j < lines.length && lines[j] === lines[i]) j++;
const runLen = j - i;
if (runLen > 3) {
out.push(lines[i], `[…${runLen}×]`);
} else {
for (let k = 0; k < runLen; k++) out.push(lines[i]);
}
i = j;
}
let result = out.join("\n");
if (Buffer.byteLength(result, "utf8") > EPHEMERAL_REPLY_MAX_BYTES) {
// Trim by characters until we're under the byte budget — handles multi-byte
// glyphs at the boundary without splitting them.
const suffix = "\n[…truncated]";
const budget = EPHEMERAL_REPLY_MAX_BYTES - Buffer.byteLength(suffix, "utf8");
while (Buffer.byteLength(result, "utf8") > budget) {
result = result.slice(0, -1);
}
result += suffix;
}
return result;
}
/**
* Build the per-request `metadata` payload for the Anthropic provider, shaped
* like real Claude Code's `getAPIMetadata` output (`{ session_id, account_uuid,
* device_id }`) so the backend buckets requests under one session and attributes
* them to the authenticated OAuth account when available. Resolved at request
* time so token refreshes and login/logout transitions don't strand a stale
* account UUID in memory. `account_uuid` and `device_id` are omitted for
* non-Anthropic providers to avoid leaking the user's Claude identity to
* third-party APIs (including Anthropic-format-compatible proxies such as
* cloudflare-ai-gateway or gitlab-duo).
*
* `provider` is the target provider string (e.g. `"anthropic"`) and gates the
* `account_uuid` and `device_id` lookups — only `"anthropic"` requests carry them.
*
* `sessionId` is forwarded to the auth-storage session-sticky lookup so that
* multi-credential setups attribute to the same OAuth account used for the
* actual API request rather than always picking the first credential.
*
* `authStorage` is treated as optional so test fixtures that stub `modelRegistry`
* without a real storage layer still work; the resolver simply skips the lookup
* and emits `{ session_id }` alone, matching the no-OAuth-credential path.
*/
function buildSessionMetadata(
sessionId: string,
provider: string,
authStorage: AuthStorage | undefined,
): Record<string, unknown> {
const userId: Record<string, string> = { session_id: sessionId };
// Only look up account_uuid when the request is going to Anthropic. Injecting
// a Claude OAuth account_uuid into requests bound for other providers (including
// Anthropic-format-compatible proxies like cloudflare-ai-gateway or gitlab-duo)
// would leak the user's Anthropic identity to unrelated third-party APIs.
if (provider === "anthropic") {
const accountUuid = authStorage?.getOAuthAccountId("anthropic", sessionId);
if (typeof accountUuid === "string" && accountUuid.length > 0) {
userId.account_uuid = accountUuid;
// Claude Code's `device_id` is a stable 64-hex account-scoped install
// identifier. Include both omp's persistent install id and the Claude
// account UUID so two accounts on the same install do not share a device.
userId.device_id = deriveClaudeDeviceId(getInstallId(), accountUuid);
}
}
return { user_id: JSON.stringify(userId) };
}
const noOpUIContext: ExtensionUIContext = {
select: async (_title, _options, _dialogOptions) => undefined,
confirm: async (_title, _message, _dialogOptions) => false,
input: async (_title, _placeholder, _dialogOptions) => undefined,
notify: () => {},
onTerminalInput: () => () => {},
setStatus: () => {},
setWorkingMessage: () => {},
setWidget: () => {},
setTitle: () => {},
custom: async () => undefined as never,
setEditorText: () => {},
pasteToEditor: () => {},
getEditorText: () => "",
editor: async () => undefined,
get theme() {
return theme;
},
getAllThemes: () => Promise.resolve([]),
getTheme: () => Promise.resolve(undefined),
setTheme: _theme => Promise.resolve({ success: false, error: "UI not available" }),
setFooter: () => {},
setHeader: () => {},
setEditorComponent: () => {},
getToolsExpanded: () => false,
setToolsExpanded: () => {},
};
function createHandoffContext(document: string): string {
return `<handoff-context>\n${document}\n</handoff-context>\n\nThe above is a handoff document from a previous session. Use this context to continue the work seamlessly.`;
}
function createHandoffFileName(date = new Date()): string {
const fileTimestamp = date.toISOString().replace(/[:.]/g, "-");
return `handoff-${fileTimestamp}.md`;
}
// ============================================================================
// ACP Permission Gate
// ============================================================================
/** Tools that require user permission before execution when an ACP client is connected. */
const PERMISSION_REQUIRED_TOOLS = new Set(["bash", "edit", "delete", "move"]);
/** Permission options presented to the client on each gated tool call. */
const PERMISSION_OPTIONS: ClientBridgePermissionOption[] = [
{ optionId: "allow_once", name: "Allow once", kind: "allow_once" },
{ optionId: "allow_always", name: "Always allow", kind: "allow_always" },
{ optionId: "reject_once", name: "Reject", kind: "reject_once" },
{ optionId: "reject_always", name: "Always reject", kind: "reject_always" },
];
const PERMISSION_OPTIONS_BY_ID = new Map(PERMISSION_OPTIONS.map(option => [option.optionId, option]));
function getStringProperty(value: Record<string, unknown>, key: string): string | undefined {
const candidate = value[key];
return typeof candidate === "string" ? candidate : undefined;
}
function collectStringPaths(value: unknown): string[] {
return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];
}
function getEditDestructiveIntent(args: unknown): { kind: "delete" | "move"; paths: string[] } | undefined {
if (!args || typeof args !== "object" || Array.isArray(args)) return undefined;
const a = args as Record<string, unknown>;
const edits = Array.isArray(a.edits) ? a.edits : undefined;
if (edits) {
const path = getStringProperty(a, "path");
if (path) {
for (const edit of edits) {
if (!edit || typeof edit !== "object" || Array.isArray(edit)) continue;
const op = getStringProperty(edit as Record<string, unknown>, "op");
if (op === "delete") return { kind: "delete", paths: [path] };
}
}
for (const edit of edits) {
if (!edit || typeof edit !== "object" || Array.isArray(edit)) continue;
const entry = edit as Record<string, unknown>;
const op = getStringProperty(entry, "op");
const rename = getStringProperty(entry, "rename");
if (op !== "create" && rename) return { kind: "move", paths: path ? [path, rename] : [rename] };
}
}
const input = getStringProperty(a, "input");
if (input) {
try {
const entries = expandApplyPatchToEntries({ input });
const deleteEntry = entries.find(entry => entry.op === "delete");
if (deleteEntry) return { kind: "delete", paths: [deleteEntry.path] };
const moveEntry = entries.find(entry => entry.rename);
if (moveEntry?.rename) return { kind: "move", paths: [moveEntry.path, moveEntry.rename] };
} catch {
// If the edit input is not an apply_patch envelope, it is not a delete/move operation.
}
}
return undefined;
}
function getPermissionIntent(
toolName: string,
args: unknown,
): { toolName: string; title: string; paths?: string[]; cacheKey: string } | undefined {
const a = args && typeof args === "object" && !Array.isArray(args) ? (args as Record<string, unknown>) : {};
if (toolName === "bash") {
const cmd = getStringProperty(a, "command")?.slice(0, 80);
return { toolName, title: cmd || toolName, cacheKey: toolName };
}
if (toolName === "delete") {
const p = getStringProperty(a, "path");
return { toolName, title: p ? `Delete ${p}` : toolName, paths: p ? [p] : undefined, cacheKey: toolName };
}
if (toolName === "move") {
const from = getStringProperty(a, "oldPath") ?? getStringProperty(a, "path") ?? getStringProperty(a, "from");
const to = getStringProperty(a, "newPath") ?? getStringProperty(a, "to") ?? getStringProperty(a, "destination");
if (from && to) return { toolName, title: `Move ${from} to ${to}`, paths: [from, to], cacheKey: toolName };
return {
toolName,
title: from ? `Move ${from}` : toolName,
paths: from ? [from] : undefined,
cacheKey: toolName,
};
}
if (toolName === "edit") {
const intent = getEditDestructiveIntent(args);
if (!intent) return undefined;
if (intent.kind === "delete") {
return {
toolName,
title: `Delete ${intent.paths[0] ?? "edit target"}`,
paths: intent.paths,
cacheKey: "edit:delete",
};
}
const from = intent.paths[0];
const to = intent.paths[1];
return {
toolName,
title: from && to ? `Move ${from} to ${to}` : `Move ${from ?? to ?? "edit target"}`,
paths: intent.paths,
cacheKey: "edit:move",
};
}
return undefined;
}
function extractPermissionLocations(
args: unknown,
cwd: string,
explicitPaths?: string[],
): { path: string; line?: number }[] {
if (!args || typeof args !== "object") return [];
const a = args as Record<string, unknown>;
const out: { path: string; line?: number }[] = [];
const pushPath = (value: unknown) => {
if (typeof value !== "string" || value.length === 0) return;
// ACP locations carry file paths that the editor host will open or focus;