forked from PrimeIntellect-ai/prime-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent-session.ts
More file actions
12628 lines (11810 loc) · 443 KB
/
Copy pathagent-session.ts
File metadata and controls
12628 lines (11810 loc) · 443 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
import { AsyncLocalStorage } from "node:async_hooks";
import { randomUUID } from "node:crypto";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, dirname, join, resolve } from "node:path";
import {
Agent,
type AgentContext,
AgentContinueError,
type AgentEvent,
type AgentMessage,
type AgentState,
type AgentTool,
type GetContinuationMessagesContext,
type ShouldStopAfterTurnContext,
type ThinkingLevel,
} from "@earendil-works/pi-agent-core";
import type {
Api,
AssistantMessage,
ImageContent,
Model,
ServiceTier,
TextContent,
Usage,
UserMessage,
} from "@earendil-works/pi-ai";
import {
clampThinkingLevel,
cleanupSessionResources,
getSupportedThinkingLevels,
isContextOverflow,
modelsAreEqual,
resetApiProviders,
supportsFastMode,
} from "@earendil-works/pi-ai";
import { theme } from "../modes/interactive/theme/theme.js";
import { stripFrontmatter } from "../utils/frontmatter.js";
import { sleep } from "../utils/sleep.js";
import {
AGENT_MESSAGE_CUSTOM_TYPE,
AGENT_MESSAGE_RECEIVED_PREVIEW_LABEL,
AGENT_MESSAGE_SKILL_NAME,
type AgentFamilyCatalogEntry,
type AgentFamilyRosterResult,
type AgentSessionMessage,
type AgentSessionMessageAgentSummary,
type AgentSessionMessageController,
type AgentSessionMessageListResult,
type AgentSessionMessageReceipt,
assertAgentMessageQueueCapacity,
assertAgentSessionNameAvailable,
assertDirectAgentMessageTarget,
createAgentMessageHostHandlers,
DEFAULT_AGENT_MESSAGE_MAX_PENDING_PER_SESSION,
formatAgentSessionNameUnavailable,
isAgentSessionMessage,
isAgentSessionMessagePrompt,
normalizeAgentSessionMessage,
parseAgentSessionMessagePromptId,
startsAgentRun,
} from "./agent-messages.js";
import {
AGENT_OBSERVE_SKILL_NAME,
type AgentObserveAgentSnapshot,
type AgentObserveController,
type AgentObserveListResult,
type AgentObserveRecentMessagesResult,
createAgentObserveHostHandlers,
normalizeObserveLimit,
normalizeObserveMaxChars,
ORCHESTRATION_HEARTBEAT_SKILL_NAME,
} from "./agent-observe.js";
import { flushAgentTraceUpload } from "./agent-traces.js";
import {
addLoginGuidanceToAuthError,
formatAuthenticationFailedMessage,
formatNoApiKeyFoundMessage,
formatNoModelSelectedMessage,
isLikelyAuthenticationError,
} from "./auth-guidance.js";
import type { AuthSourceToken } from "./auth-storage.js";
import {
type AgentAutonomousConfig,
type AgentAutonomousStatus,
type AutonomousRuntimeState,
addAutonomousContinuation,
addAutonomousUsage,
autonomousStatus,
createAutonomousRuntimeState,
nextAutonomousContinuation,
refreshAutonomousQualityGates,
setAutonomousEnabled,
} from "./autonomous.js";
import { type BashResult, executeBashWithOperations } from "./bash-executor.js";
import {
COMPACT_SKILL_NAME,
type CompactionResult,
calculateContextTokens,
collectEntriesForBranchSummary,
compact,
estimateContextTokens,
generateBranchSummary,
prepareCompaction,
serializeConversation,
shouldCompact,
} from "./compaction/index.js";
import {
type ContextTreeNode,
type ContextWindowResolver,
computeOwnAndTotalUsage,
loadContextTreeChildFromDisk,
loadContextTreeChildrenFromDisk,
} from "./context-tree.js";
import type { AgentCronJob, AgentRlmHeartbeatController, AgentRlmHeartbeatStatusUpdate } from "./cron-jobs.js";
import { normalizeHeartbeatDeliveryMode } from "./cron-jobs.js";
import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
import { exportSessionToHtml, type ToolHtmlRenderer } from "./export-html/index.js";
import { createToolHtmlRenderer } from "./export-html/tool-renderer.js";
import { createExtensionProviderHooks, type ExtensionProviderHooks } from "./extension-provider-hooks.js";
import {
type ContextUsage,
type ExtensionCommandContextActions,
type ExtensionErrorListener,
ExtensionRunner,
type ExtensionUIContext,
type InputSource,
type MessageEndEvent,
type MessageStartEvent,
type MessageUpdateEvent,
type ReplacedSessionContext,
type SessionBeforeCompactResult,
type SessionBeforeRefineResult,
type SessionBeforeTreeResult,
type SessionStartEvent,
type ShutdownHandler,
type ToolDefinition,
type ToolExecutionEndEvent,
type ToolExecutionStartEvent,
type ToolExecutionUpdateEvent,
type ToolInfo,
type TreePreparation,
type TurnEndEvent,
type TurnStartEvent,
wrapRegisteredTools,
} from "./extensions/index.js";
import { emitSessionShutdownEvent } from "./extensions/runner.js";
import {
createGoalContextMessage,
emptyGoalState,
GOAL_CONTEXT_CUSTOM_TYPE,
GOAL_CONTEXT_PREVIEW_LABEL,
GOAL_SKILL_NAME,
GOAL_STATE_CUSTOM_TYPE,
type GoalHostResponse,
type GoalState,
type GoalStatus,
goalHostResponse,
goalTokenDeltaForUsage,
isPersistedGoalState,
normalizeGoalState,
validateGoalBudget,
validateGoalObjective,
} from "./goals.js";
import type { HostRequestHandlers, KernelSentAgentMessage } from "./kernel/index.js";
import { type RestoreResult, snapshotPathIn } from "./kernel/state-snapshot.js";
import type { AcpMcpServerConfig } from "./mcp/acp-mcp-types.js";
import type { AcpMcpOwnerTransferProof, McpManager } from "./mcp/mcp-manager.js";
import {
type BashExecutionMessage,
type CompactionOutcome,
type CompactionOutcomeReason,
type CustomMessage,
convertToLlm,
createCompactionOutcomeMessage,
createHeartbeatPromptMessage,
createRefinementOutcomeMessage,
createRlmChildFailureMessage,
createRlmChildTerminalNoticeMessage,
createSessionSlashCommandMessage,
createSessionSlashCommandResultMessage,
HEARTBEAT_PROMPT_CUSTOM_TYPE,
HEARTBEAT_PROMPT_PREVIEW_LABEL,
IPYTHON_STATE_RESTORED_CUSTOM_TYPE,
isSessionSlashCommandMessage,
RLM_CHILD_FAILURE_CUSTOM_TYPE,
RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE,
} from "./messages.js";
import type { ModelRegistry } from "./model-registry.js";
import { throwIfPromptAdmissionCancelled } from "./prompt-admission.js";
import {
createPromptRequestFingerprint,
isPromptLifecycleTerminal,
type PromptLifecycleCancellationResult,
type PromptLifecycleEvent,
type PromptLifecycleKind,
type PromptLifecyclePhase,
type PromptLifecycleRecoveryStateSnapshot,
type PromptLifecycleSnapshot,
type PromptLifecycleStateSnapshot,
PromptLifecycleStore,
} from "./prompt-lifecycle.js";
import { expandPromptTemplate, type PromptTemplate } from "./prompt-templates.js";
import {
type AutoRefineReason,
type AutoRefineReview,
appendGlobalRefinement,
applyRefinementProposal,
generateRefinementId,
getGlobalHarnessStateDir,
getLocalHarnessStateDir,
getRefinementHistory,
type HarnessState,
inferRefinementResultScope,
loadGlobalRefinementHistory,
loadHarnessState,
mergeHarnessStates,
mergeRefinementHistory,
normalizeRefinementProposal,
planRefinement,
REFINE_SKILL_NAME,
type RefinementPlan,
type RefinementResult,
reviewAutoRefine,
saveHarnessState,
} from "./refinement/index.js";
import { resolveConfigValue } from "./resolve-config-value.js";
import type { ResourceExtensionPaths, ResourceLoader } from "./resource-loader.js";
import { computeRetryBackoff } from "./retry-backoff.js";
import {
type CreateRlmSubagentRuntimeOptions,
createDefaultRlmSubagentSessionName,
createRlmDeleteSubagentHostHandler,
createRlmFindModelsHostHandler,
createRlmListSubagentsHostHandler,
createRlmRunHostHandler,
findRlmModelMatches,
normalizeRequestedRlmSubagentModel,
normalizeRequestedRlmSubagentSessionName,
normalizeRequestedRlmSubagentThinkingLevel,
type RlmDeleteSubagentResult,
type RlmFindModelsResult,
type RlmListSubagentsResult,
type RlmSpawnHandle,
type RlmSubagentRegistryEntry,
type RlmSubagentRuntime,
type SubagentRuntimeHost,
} from "./rlm-runtime.js";
import {
ActionStore,
type ActionTicket,
canSelectSessionAction,
type DeliveryPolicy,
type DeliveryRecord,
type QueuedMessageLane,
type QueuedMessageMutation,
type QueuedMessageMutationStatus,
queuedMessageLaneDeliveryPolicy,
type RuntimeActivity,
type SessionAction,
type SessionActionSnapshot,
type SessionCommandPayload,
type SessionTurnPayload,
transitionSessionAction,
type WakePolicy,
} from "./session-action-store.js";
import type { BranchSummaryEntry, CompactionEntry, SessionContext, SessionMessageEntry } from "./session-manager.js";
import {
CURRENT_SESSION_VERSION,
getLatestCompactionEntry,
type SessionHeader,
SessionManager,
} from "./session-manager.js";
import type { SessionStats } from "./session-stats.js";
import type { SettingsManager } from "./settings-manager.js";
import { getPythonSkillRuntimeInfo, type Skill } from "./skills.js";
import {
parseRefineCommandOptions,
parseSessionSlashCommand,
parseSlashCommand,
type SessionSlashCommand,
type SlashCommandInfo,
} from "./slash-commands.js";
import { createSyntheticSourceInfo, type SourceInfo } from "./source-info.js";
import { type BuildSystemPromptOptions, buildSystemPrompt, buildVolatileContext } from "./system-prompt.js";
import { THINKING_LEVELS } from "./thinking-levels.js";
import { type BashOperations, createLocalBashOperations } from "./tools/bash.js";
import { createAllToolDefinitions } from "./tools/index.js";
import { IpythonKernelProvisioner } from "./tools/ipython.js";
import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";
import { addAssistantUsage, emptyUsage } from "./usage.js";
import { SERPER_CREDENTIAL_ID, SERPER_ENV_VAR, WEBSEARCH_SKILL_NAME } from "./websearch-credential.js";
export type { GoalState, GoalStatus } from "./goals.js";
export type { SessionStats } from "./session-stats.js";
export { type ParsedSkillBlock, parseSkillBlock } from "./skill-blocks.js";
export type RlmChildAgentStatus = "queued" | "running" | "done" | "error" | "cancelled";
export interface RlmChildAgentActivity {
kind: "waiting" | "writing" | "executing";
toolName?: string;
}
export interface RlmChildAgentSnapshot {
id: string;
parentId?: string;
activeSessionId?: string;
sessionName?: string;
model?: string;
label: string;
status: RlmChildAgentStatus;
durationMs?: number;
answerPreview?: string;
toolUseCount?: number;
tokenCount?: number;
recap?: string;
sessionDir: string;
activity?: RlmChildAgentActivity;
repliedSinceTask?: boolean;
error?: string;
}
export type CompactionReason = "manual" | "threshold" | "overflow" | "requested";
type AgentSessionEventBody =
| AgentEvent
| {
type: "ipython_sent_agent_message";
toolCallId: string;
message: KernelSentAgentMessage;
}
| { type: "session_action_update"; actions: SessionActionSnapshot }
| {
type: "compaction_start";
reason: CompactionReason;
customInstructions?: string;
}
| { type: "session_info_changed"; name: string | undefined }
| { type: "thinking_level_changed"; level: ThinkingLevel }
| { type: "service_tier_changed"; serviceTier: ServiceTier }
| {
type: "compaction_end";
reason: CompactionReason;
result: CompactionResult | undefined;
aborted: boolean;
willRetry: boolean;
errorMessage?: string;
errorSeverity?: "warning" | "error";
customInstructions?: string;
}
| {
type: "auto_retry_start";
attempt: number;
maxAttempts: number;
delayMs: number;
errorMessage: string;
}
| {
type: "auto_retry_end";
success: boolean;
attempt: number;
finalError?: string;
}
| {
type: "auth_stale";
provider: string;
sourceTokens?: readonly AuthSourceToken[];
}
| { type: "rlm_child_update"; child: RlmChildAgentSnapshot }
| { type: "recap_update"; recap: string | undefined }
| { type: "goal_update"; goal: GoalState }
| {
type: "bash_start";
command: string;
excludeFromContext: boolean;
transient?: boolean;
runId?: string;
}
| { type: "bash_output"; chunk: string }
| {
type: "bash_end";
exitCode: number | undefined;
cancelled: boolean;
truncated: boolean;
fullOutputPath?: string;
errorMessage?: string;
transient?: boolean;
runId?: string;
}
| { type: "refine_complete"; result: RefinementResult }
| { type: "refine_failed"; error: string }
| PromptLifecycleEvent;
export type AgentSessionEvent = AgentSessionEventBody & { promptCorrelationId?: string | null };
export type AgentSessionEventListener = (event: AgentSessionEvent) => void;
type UserBashEndDetails = {
exitCode: number | undefined;
cancelled: boolean;
truncated: boolean;
fullOutputPath?: string;
errorMessage?: string;
};
export class CompactionSkippedError extends Error {}
/** Thrown when a session_before_refine extension skips the refinement round. */
export class RefineSkippedError extends Error {}
export interface AgentSessionConfig {
agent: Agent;
sessionManager: SessionManager;
settingsManager: SettingsManager;
serviceTierPreference?: ServiceTier;
cwd: string;
agentDir?: string;
scopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;
resourceLoader: ResourceLoader;
customTools?: ToolDefinition[];
modelRegistry: ModelRegistry;
initialActiveToolNames?: string[];
allowedToolNames?: string[];
/**
* Whether the built-in long-running goals feature is available: the bundled
* goal skill in the Python kernel, its goal.* host handlers, and /goal.
* Default: true.
*/
includeGoals?: boolean;
agentMessageController?: AgentSessionMessageController;
agentObserveController?: AgentObserveController;
/**
* Whether the bundled compact skill and its compact.* host handlers are
* available to the model. Default: the compaction.agentCallable setting.
*/
includeCompactSkill?: boolean;
/**
* Optional host-side controller for the bundled rlm-heartbeat Python skill.
* When omitted, rlm_heartbeat.* host requests are unavailable.
*/
rlmHeartbeatController?: AgentRlmHeartbeatController;
/**
* Optional MCP integration manager. When present, its mcp.* host requests
* (refresh, begin_login) are exposed to the kernel.
*/
mcpManager?: McpManager;
/**
* 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>;
extensionRunnerRef?: { current?: ExtensionRunner };
sessionStartEvent?: SessionStartEvent;
rlmDepth?: number;
rlmMaxDepth?: number;
rlmSessionDir?: string;
rlmParentNodeId?: string;
rlmParentAgent?: string;
subagentRuntimeHost?: SubagentRuntimeHost;
autonomous?: AgentAutonomousConfig;
prewarmIpythonKernel?: boolean;
autoRefineReviewer?: AutoRefineReviewer;
/**
* When true, auto-refine runs synchronously between turns at the
* shouldStopAfterTurn boundary instead of in the background after
* agent_end. Used for print/headless autonomous runs so refinement
* never overlaps the primary model request. Default: false.
*/
serializedRefine?: boolean;
/**
* Initial goal to seed at session creation. Only applied when rlmDepth
* is 0 and no persisted thread_goal_state entry exists in the branch.
*/
initialGoal?: { objective: string; tokenBudget?: number };
}
export interface ExtensionBindings {
uiContext?: ExtensionUIContext;
commandContextActions?: ExtensionCommandContextActions;
shutdownHandler?: ShutdownHandler;
onError?: ExtensionErrorListener;
}
export interface AutoRefineReviewRequest {
reason: AutoRefineReason;
turnsSinceLastReview: number;
}
/**
* Discriminated result from a serialized-mode background planning pass.
* - "plan": review approved and planning succeeded; carry the exact plan,
* options, and abort controller so the boundary can apply directly
* without a second planning request.
* - "skip": reviewer declined; no refine needed.
* - "failure": review or planning threw; boundary should not retry.
*/
export type SerializedBackgroundPlanResult =
| {
status: "plan";
plan: RefinementPlan;
options: { instructions?: string; rollbackId?: string; global?: boolean };
abort: AbortController;
branchVersion: number;
}
| { status: "skip"; explicit?: boolean }
| { status: "invalidated"; branchVersion: number }
| {
status: "failure";
explicit: boolean;
options: { instructions?: string; rollbackId?: string; global?: boolean };
branchVersion: number;
};
export type AutoRefineReviewer = (request: AutoRefineReviewRequest, signal?: AbortSignal) => Promise<AutoRefineReview>;
export interface PromptOptions {
expandPromptTemplates?: boolean;
images?: ImageContent[];
streamingBehavior?: "steer" | "followUp";
followUpQueueKey?: string;
source?: InputSource;
preflightResult?: (success: boolean, queued?: boolean) => void;
queueIfBusy?: boolean;
resumeIfIdle?: boolean;
internalPrompt?: boolean;
suppressAutonomousContinuation?: boolean;
skipInputHandlers?: boolean;
signal?: AbortSignal;
admissionCommitted?: () => void;
promptCorrelationId?: string;
agentMessageId?: string;
content?: (TextContent | ImageContent)[];
customMessage?: CustomMessage;
}
interface InternalPromptOptions extends PromptOptions {
skipPrePromptWork?: boolean;
returnAfterAccepted?: boolean;
agentMessageId?: string;
}
type SubmissionExtensionCommandPolicy = "execute" | "reject" | "ignore";
interface SubmissionNormalizationPolicy {
parseSessionCommands: boolean;
extensionCommands: SubmissionExtensionCommandPolicy;
inputSource?: InputSource;
expandSkills: boolean;
expandPromptTemplates: boolean;
}
type NormalizedSubmission =
| { kind: "prompt"; text: string; images?: ImageContent[] }
| {
kind: "sessionCommand";
text: string;
images?: ImageContent[];
command: SessionSlashCommand;
}
| { kind: "extensionCommand"; completion: Promise<void> }
| { kind: "handled" };
type PreTurnCompactionTiming = "beforeModelSelection" | "afterModelSelection" | "skip";
type RefineBarrierPolicy = "always" | "ifInFlight" | "skip";
interface CommitPreparationPolicy {
initialRefineBarrier: RefineBarrierPolicy;
flushPendingBashBeforeValidation: boolean;
validateModelAndAuth: boolean;
awaitPendingModelSelection: boolean;
preTurnCompaction: PreTurnCompactionTiming;
finalRefineBarrier: RefineBarrierPolicy;
}
interface CommitPreparationSteps<TPrepared, TCommitted> {
afterValidation?: () => void;
prepare: () => Promise<TPrepared>;
shouldCommit?: (prepared: TPrepared) => boolean;
beforeFinalRefineBarrier?: (prepared: TPrepared) => void;
commit: (prepared: TPrepared, passedFinalRefineBarrier: boolean) => TCommitted;
}
type QueuedAgentMessage = UserMessage | CustomMessage;
type SessionInputSchedule = "steer" | "followUp";
export interface TurnExecutionPolicy {
preparation: CommitPreparationPolicy;
runBeforeAgentStart: boolean;
nextTurnContextTiming: "preparation" | "commit" | "skip";
preserveEmptyExtensionPrompt: boolean;
completionIncludesRetryChain: boolean;
}
function turnExecutionPoliciesEqual(left: TurnExecutionPolicy, right: TurnExecutionPolicy): boolean {
return (
left.preparation.initialRefineBarrier === right.preparation.initialRefineBarrier &&
left.preparation.flushPendingBashBeforeValidation === right.preparation.flushPendingBashBeforeValidation &&
left.preparation.validateModelAndAuth === right.preparation.validateModelAndAuth &&
left.preparation.awaitPendingModelSelection === right.preparation.awaitPendingModelSelection &&
left.preparation.preTurnCompaction === right.preparation.preTurnCompaction &&
left.preparation.finalRefineBarrier === right.preparation.finalRefineBarrier &&
left.runBeforeAgentStart === right.runBeforeAgentStart &&
left.nextTurnContextTiming === right.nextTurnContextTiming &&
left.preserveEmptyExtensionPrompt === right.preserveEmptyExtensionPrompt &&
left.completionIncludesRetryChain === right.completionIncludesRetryChain
);
}
interface PreparedTurnPayload extends SessionTurnPayload {
images?: ImageContent[];
content?: (TextContent | ImageContent)[];
customMessage?: CustomMessage;
prepared?: PreparedPromptPreparation;
executionPolicy: TurnExecutionPolicy;
queueVisible: boolean;
acceptedAgentMessage: boolean;
acceptedBeforeCompletion: boolean;
captureRunMessages?: Set<AgentMessage>;
cancelledDispatchEnded?: boolean;
}
interface PreparedCommandPayload extends SessionCommandPayload {
images?: ImageContent[];
}
type QueuedSessionAction = SessionAction<PreparedTurnPayload | PreparedCommandPayload>;
interface PreparedPromptPreparation {
result: Awaited<ReturnType<ExtensionRunner["emitBeforeAgentStart"]>>;
basePromptSnapshot: string;
}
class DeferredSessionInputError extends Error {}
function oncePreflight(
preflightResult: ((success: boolean, queued?: boolean) => void) | undefined,
): (success: boolean, queued?: boolean) => void {
let settled = false;
return (success, queued = false) => {
if (!settled) {
settled = true;
preflightResult?.(success, queued);
}
};
}
interface RestoredPromptInput {
text: string;
content?: (TextContent | ImageContent)[];
images?: ImageContent[];
queueKey?: string;
agentMessageId?: string;
customMessage?: CustomMessage;
prefixMessages?: CustomMessage[];
}
export const SESSION_ACTION_RECOVERY_FORMAT_VERSION = 1;
export interface SessionActionRecoveryRecord {
id: string;
role: DeliveryRecord["role"];
message: QueuedAgentMessage;
ownerActionId: string;
}
export type SessionActionRecoveryPayload =
| {
kind: "turn";
text: string;
preview?: string;
records: SessionActionRecoveryRecord[];
images?: ImageContent[];
content?: (TextContent | ImageContent)[];
customMessage?: CustomMessage;
executionPolicy: TurnExecutionPolicy;
queueVisible: boolean;
acceptedAgentMessage: boolean;
acceptedBeforeCompletion: boolean;
}
| {
kind: "session_command";
text: string;
command: SessionSlashCommand;
images?: ImageContent[];
};
export interface SessionActionRecoveryAction {
id: string;
source: InputSource | "internal";
delivery: DeliveryPolicy;
wake: WakePolicy;
payload: SessionActionRecoveryPayload;
queueKey?: string;
agentMessageId?: string;
promptCorrelationId?: string;
suppressAutonomousContinuation?: boolean;
}
export interface SessionActionRecoverySnapshot {
formatVersion: typeof SESSION_ACTION_RECOVERY_FORMAT_VERSION;
actions: SessionActionRecoveryAction[];
promptLifecycles?: PromptLifecycleRecoveryStateSnapshot;
}
function cloneCustomMessage(message: CustomMessage): CustomMessage {
return {
...message,
content: Array.isArray(message.content) ? message.content.map((block) => ({ ...block })) : message.content,
};
}
function cloneQueuedAgentMessage(message: QueuedAgentMessage): QueuedAgentMessage {
if (message.role === "custom") return cloneCustomMessage(message);
return {
...message,
content: Array.isArray(message.content) ? message.content.map((block) => ({ ...block })) : message.content,
};
}
function primaryDeliveryRecord(action: QueuedSessionAction): DeliveryRecord {
if (action.payload.kind !== "turn") throw new Error(`Session action ${action.id} is not a turn`);
const record = action.payload.records.find((candidate) => candidate.role === "primary");
if (!record) throw new Error(`Turn action ${action.id} has no primary delivery record`);
return record;
}
function normalizeMessageContent(content: string | (TextContent | ImageContent)[]): {
text: string;
images?: ImageContent[];
} {
if (typeof content === "string") return { text: content };
const text = content
.filter((part): part is TextContent => part.type === "text")
.map((part) => part.text)
.join("\n");
const images = content.filter((part): part is ImageContent => part.type === "image");
return { text, ...(images.length > 0 ? { images } : {}) };
}
function queuedAgentMessagePreview(action: QueuedSessionAction): string {
const payload = action.payload;
if (payload.kind === "session_command") return payload.text;
if (payload.customMessage && isAgentSessionMessage(payload.customMessage)) {
return `${AGENT_MESSAGE_RECEIVED_PREVIEW_LABEL}: ${payload.customMessage.details.message}`;
}
return payload.preview ?? payload.text;
}
function visibleSessionActionProjection(actions: readonly QueuedSessionAction[]): readonly QueuedSessionAction[] {
return actions.filter(
(action) =>
action.payload.kind === "session_command" ||
action.payload.queueVisible ||
action.payload.acceptedAgentMessage,
);
}
const IPYTHON_SENT_AGENT_MESSAGE_CUSTOM_ENTRY = "ipython_sent_agent_message";
interface PersistedIpythonSentAgentMessage {
toolCallId: string;
message: KernelSentAgentMessage;
}
function isObjectRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function parsePersistedIpythonSentAgentMessage(value: unknown): PersistedIpythonSentAgentMessage | undefined {
if (!isObjectRecord(value) || typeof value.toolCallId !== "string" || !isObjectRecord(value.message)) {
return undefined;
}
const { id, message, deliveryStatus, target } = value.message;
if (
typeof id !== "string" ||
typeof message !== "string" ||
(deliveryStatus !== "delivered" && deliveryStatus !== "queued") ||
!isObjectRecord(target) ||
typeof target.activeSessionId !== "string" ||
typeof target.sessionId !== "string"
) {
return undefined;
}
return {
toolCallId: value.toolCallId,
message: {
id,
message,
deliveryStatus,
target: {
activeSessionId: target.activeSessionId,
sessionId: target.sessionId,
...(typeof target.sessionName === "string" ? { sessionName: target.sessionName } : {}),
},
},
};
}
function appendSentAgentMessageToToolResult(
message: AgentMessage,
toolCallId: string,
sentMessage: KernelSentAgentMessage,
): boolean {
if (message.role !== "toolResult" || message.toolName !== "ipython" || message.toolCallId !== toolCallId) {
return false;
}
const details = isObjectRecord(message.details) ? message.details : {};
const current = Array.isArray(details.sentAgentMessages) ? details.sentAgentMessages : [];
if (current.some((entry) => isObjectRecord(entry) && entry.id === sentMessage.id)) {
return true;
}
message.details = {
...details,
sentAgentMessages: [...current, sentMessage],
};
return true;
}
function injectedMessagePreviewLabel(message: CustomMessage): string | undefined {
switch (message.customType) {
case HEARTBEAT_PROMPT_CUSTOM_TYPE:
return HEARTBEAT_PROMPT_PREVIEW_LABEL;
case GOAL_CONTEXT_CUSTOM_TYPE:
return GOAL_CONTEXT_PREVIEW_LABEL;
default:
return undefined;
}
}
interface AgentMessageDeferred {
promise: Promise<void>;
resolve: () => void;
reject: (error: Error) => void;
}
interface AgentMessageOutcome {
delivery?: AgentMessageDeferred;
completion?: AgentMessageDeferred;
}
function createAgentMessageDeferred(): AgentMessageDeferred {
const deferred = {} as AgentMessageDeferred;
deferred.promise = new Promise<void>((resolve, reject) => {
deferred.resolve = resolve;
deferred.reject = reject;
});
deferred.promise.catch(() => undefined);
return deferred;
}
/** One-shot settlement for a scheduled post-compaction continuation; a settled failure is never re-exposed to later waiters. */
interface PostCompactionContinuationSettlement extends AgentMessageDeferred {
continueAfterSessionInput: boolean;
settled: boolean;
}
function createPostCompactionContinuationSettlement(): PostCompactionContinuationSettlement {
return { ...createAgentMessageDeferred(), continueAfterSessionInput: false, settled: false };
}
export interface ModelCycleResult {
model: Model<any>;
thinkingLevel: ThinkingLevel;
serviceTier: ServiceTier;
isScoped: boolean;
}
interface ModelSelectOptions {
waitForExtensions?: boolean;
}
interface ToolDefinitionEntry {
definition: ToolDefinition;
sourceInfo: SourceInfo;
}
type GoalSlashCommand =
| { kind: "status" }
| { kind: "clear" }
| { kind: "pause" }
| { kind: "resume" }
| { kind: "start"; objective: string; tokenBudget?: number };
type AutonomousSlashCommand = { kind: "status" } | { kind: "on" } | { kind: "off" };
import type { RlmMaxDepthSource, RlmMaxDepthStatus, SetRlmMaxDepthResult } from "./rlm-max-depth.js";
export type { RlmMaxDepthSource, RlmMaxDepthStatus, SetRlmMaxDepthResult } from "./rlm-max-depth.js";
interface PersistedRlmMaxDepthState {
maxDepth: number;
}
type AutonomousRuntimeSnapshot = Pick<
AutonomousRuntimeState,
"continuationsUsed" | "gateAttempts" | "lastGateFailure" | "lastGateFailureSnapshot"
>;
interface RlmChildRun {
id: string;
prompt: string;
sessionName: string;
sessionDir: string;
model: Model<Api>;
status: RlmChildAgentStatus;
durationMs?: number;
answerPreview?: string;
toolUseCount: number;
activity?: RlmChildAgentActivity;
error?: string;
abort: () => void;
publication: AgentMessageDeferred;
/** Resolves after terminal result publication and detached-run cleanup finish. */
settlement: AgentMessageDeferred;
/** Child session, once its runtime exists. Used to cancel nested child runs. */
session?: AgentSession;
settled: boolean;
/** Do not inject a late terminal notice after the parent session is aborted. */
suppressTerminalNotice?: boolean;
/** Excluded from future strong barriers after an authoritative cancellation cut. */
abandonedForQuiescence?: boolean;
/** Selector snapshot for an admitted explicit delete. */
detachedDeletion?: RlmSubagentRegistryEntry;
/** Shared physical runtime cleanup owned by the explicit-delete path. */
deletionCleanup?: Promise<void>;
deletionCleanupObserver?: Promise<boolean>;
/** Resolves when a deletion may release its selector reservation. */
deletionReservation: AgentMessageDeferred;
deletionCleanupFailed?: boolean;
deletionRunFinished?: boolean;
deletionNotice?: Promise<void>;
deletionNeedsCompletionNotice?: boolean;
completeDeletion?: () => Promise<void>;
reportDeletionCleanupFailure?: (error: unknown) => Promise<void>;
emitUpdate?: () => void;
unsubscribe?: () => void;
}
interface RetainedRlmChild {
session: AgentSession;
run?: RlmChildRun;
/** Durable terminal status for a rehydrated child that has no in-memory run. */
terminalStatus?: "done" | "error";
}
interface RlmSubagentModelSelection {
model: Model<Api>;
}
const KERNEL_STATE_LISTING_TIMEOUT_MS = 5000;
const RLM_MAX_DEPTH_STATE_CUSTOM_TYPE = "rlm_max_depth_state";
function noopRlmChildAbort(): void {}
function noopRlmChildEventUnsubscribe(): void {}
function autoRefineInstructions(reason: AutoRefineReason, review: AutoRefineReview): string {
const detail = review.instructions
? `
Reviewer instructions: ${review.instructions}`
: "";
return `Automatic refine review triggered by ${reason}. Only create/update/delete local harness entries if there is clear evidence that should help this session continue. Prefer an empty edits array over speculative or one-off memories. Do not promote anything global unless explicitly requested. Reviewer rationale: ${review.rationale}${detail}`;
}
function isNonNegativeInteger(value: unknown): value is number {
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
}
function parseDepth(value: string | undefined, fallback: number, name: string): number {
if (value === undefined || value === "") {
return fallback;
}
if (!/^\d+$/.test(value)) {
throw new Error(`${name} must be a non-negative integer`);
}
const parsed = Number(value);
if (!isNonNegativeInteger(parsed)) {
throw new Error(`${name} must be a non-negative integer`);
}
return parsed;
}
function isPersistedRlmMaxDepthState(value: unknown): value is PersistedRlmMaxDepthState {
return (
typeof value === "object" && value !== null && isNonNegativeInteger((value as PersistedRlmMaxDepthState).maxDepth)
);
}
function parseGoalBudgetValue(value: string): number {
if (!/^[1-9]\d*$/.test(value)) {
throw new Error("Goal token budget must be a positive integer.");
}
const budget = validateGoalBudget(Number(value));
if (budget === undefined) {
throw new Error("Goal token budget must be a positive integer.");
}
return budget;
}