Repository navigation
Expand file tree
/
Copy pathsession.ts
More file actions
4024 lines (3824 loc) · 177 KB
/
Copy pathsession.ts
File metadata and controls
4024 lines (3824 loc) · 177 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 { parseOutputLimitDetails, type OutputLimitDetails } from '@cindy/maker-shared';
/**
* Session — 单次 agent 会话的上层包装。
*
* 职责:
* - 统一暴露能力(capabilities)+ runtime 切换接口
* - 把 BaseAgent 的事件流转发给订阅者
* - 提供 UI 友好的事件订阅 API(不强迫 UI 自己消费 AsyncIterable)
* - 管理 InteractionResolver 注入(permission / ask_user_question / plan_review 三合一)
*
* 不持有 LLM client、不做决策、不存任何业务记忆 —— 这些是未来 MetaAgent 的事。
*/
import { appendAutoReviewUserIntent, type AutoReviewUserIntent } from './agents/shared/auto-review-decision.js';
import { bindSessionSendOwner, readSessionSendTerminalOwner } from './session-send-terminal.js';
export { markSessionSendTerminal, readSessionSendTerminalStatus } from './session-send-terminal.js';
import { randomUUID } from 'node:crypto';
import { ToolLoopGuard } from './agents/shared/loop-guard.js';
import { AsyncUserQuestions } from './agents/shared/async-user-questions.js';
import {
ToolLoopMonitor,
type HardToolLoopVerdict,
type ToolLoopReviewer,
} from './agents/shared/tool-loop-review.js';
import type { ReviewableAction } from './agents/shared/auto-review.js';
import type { AutoReviewDecision } from './agents/shared/auto-review-decision.js';
import {
extractNonSecretErrorSignals,
redactSensitiveText,
} from '@cindy/maker-shared/error-redaction';
import type { SessionGracefulStopState } from '@cindy/maker-shared/session-activity';
export type { SessionGracefulStopState } from '@cindy/maker-shared/session-activity';
import type {
Effort,
PermissionMode,
AgentKind,
EngineKind,
UserMessage,
} from './types/common.js';
import type {
Capabilities,
ManualCompactResult,
NavigateSessionTreeOptions,
NavigateSessionTreeResult,
SessionTreeSnapshot,
} from './types/capabilities.js';
import { NotSupportedError } from './types/capabilities.js';
import type {
AgentEvent,
AskUserQuestionItem,
InteractionRequest,
InteractionDecision,
RewindCommitOptions,
RewindCommitResult,
UsageSnapshot,
RewindFilesResult,
SendOrigin,
} from './types/events.js';
import {
isTerminalAgentErrorEvent,
isTerminalTurnEvent,
parseToolLoopErrorDetails,
isTurnWatchdogLivenessEvent,
} from './types/events.js';
import type { ContextUsageData } from './types/context-usage.js';
import type { PiRuntimeCapabilityManifest } from './types/pi-runtime-capabilities.js';
import type {
AgentMcpServerToolsReport,
AgentSessionHandle,
PiModelSwitchPreview,
AgentSessionTeardownOptions,
BackgroundTaskSnapshot,
SendOptions,
StartSessionOptions,
TurnContinuationState,
TurnContinuationCancellationReason,
} from './agents/base-agent.js';
import {
AUTO_REVIEW_SOURCE_CONTENT,
ASYNC_QUESTION_ANSWER,
SUPERSEDE_ASYNC_QUESTIONS,
AUTO_REVIEW_USER_INTENT,
TurnDispatchRejectedError,
TurnDispatchUnconfirmedError,
} from './agents/base-agent.js';
import type { Logger } from './interfaces/logger.js';
export type SessionStatus = 'active' | 'aborting' | 'closed' | 'error';
export interface PermissionModeState {
mode: PermissionMode | null;
generation: number;
}
export type SessionEventListener = (event: AgentEvent) => void;
export type SessionStatusListener = (status: SessionStatus) => void;
export type InteractionRequestListener = (req: InteractionRequest, signal?: AbortSignal) => Promise<InteractionDecision>;
/**
* turn 零事件看门狗阈值(ms)。turn 在跑、却连续这么久**没有产品进展**,视为整条
* 链路已死,中断本轮而不是永远转圈。env `XDT_SESSION_TURN_STALL_MS` 覆盖,0 关闭。
*
* 与 agent 层 watchdog 的分工:各 agent 内部的 upstream-idle watchdog 只盯"球在上游
* 却不回话"(claude-code 30min / codex 30min),它们在**工具执行期间刻意不计时** ——
* 因此工具自己 hang(MCP 卡住、SDK↔子进程 stdio 通道 wedge)时没有任何机制兜底,
* turn 可以永久挂着。这一层就是兜那个洞:不区分球在谁手里,只看有没有产品进展。
* `status` / `account_usage` 是传输层或用量心跳,不算进展(见 isTurnWatchdogLivenessEvent)。
*
* 45min 刻意大于 agent 层的 30min,保证正常情况下 agent 自己先自愈、不被抢跑;
* 只有 agent 层也失灵才轮到这里。
*
* 误杀防护(见 armTurnStallWatchdog):等用户回应交互(权限询问 / AskUserQuestion /
* plan review)期间、以及有后台任务在跑期间都不计时 —— 那些场景没有事件是正常的。
*/
const DEFAULT_TURN_STALL_MS = 45 * 60_000;
/**
* 看门狗 abort 之后复核"turn 真的停了吗"的宽限(ms)。
*
* 为什么必须复核:各 agent 的 abort 在中断失败时都只记日志、**不改** turn-in-flight
* 状态(claude-code 的 `q.interrupt()` 抛错、codex 的 app-server 两次 ack 超时都是
* 这样)。此时 handle.isTurnRunning() 恒 true,而终态 error 已经推给上层收口 ——
* 之后每一条 send 都被 in-flight guard 拒掉,会话彻底不可用,看门狗等于"报告已恢复
* 但什么都没恢复"(review #944 第三轮)。
*
* 复核发现 turn 仍在跑就关闭会话:下一次 send 由 Maker 的 lazy create 重建 handle
* (与 handle 自然死亡后的路径一致,见 runEventLoop 尾部注释),这是唯一不依赖各 agent
* 自己实现重建的通用出路。
*
* 10s 是给 abort 的正常收口留的余量:interrupt 成功后 turn 的终态事件要经 SDK drain
* → translator → 事件流才让 isTurnRunning 翻 false,abort() resolve 的那一刻通常还没到。
*/
export const STALL_ABORT_RECOVERY_GRACE_MS = 10_000;
/**
* 手动 abort(用户按 Stop)之后的复核宽限。
*
* agent 层的 abort() 已自带 interrupt 超时(10s) + turnInFlight 即刻清除;
* 超时后走 q.close() → U2 兜底收口。本宽限是最后的保险:只保 agent 层 timeout
* 和 q.close() 都失败(极度罕见)的极端情况。从 60s 缩到 15s, 与 agent 层互不叠加,
* 端到端最长不超过 15s(review #944 第十一轮末尾调优)。
*/
export const MANUAL_ABORT_RECOVERY_GRACE_MS = 15_000;
/**
* 宿主请求的事件流暂停(`holdEventStream`)最长等待。宿主交付生成图要落库、可能经中转
* 分块下载,这里给足余量;超时只是放行后续事件,宿主的后台交付照常完成。
* abort / close / detach 立即放行,不受这个上限约束(手动 Stop 的复核宽限更短)。
*/
export const EVENT_STREAM_HOLD_MS = 20_000;
/**
* The same Codex tool call starting again sooner than this cannot be a new model
* response (one sampling takes seconds): it is a script repeating it in a burst.
*/
const CODEX_BURST_REPEAT_GAP_MS = 2_000;
/** Shared confirmation budget for provider interrupt ACK and send acceptance. */
const GRACEFUL_STOP_CONFIRMATION_TIMEOUT_MS = 5_000;
/**
* Terminal error message when this host closes a session while its turn is still running.
* Hosts match it to tell a local close apart from the agent dying on its own.
*/
export const SESSION_CLOSED_MID_TURN_MESSAGE = 'Session closed before the current turn delivered a terminal event';
/**
* 运行时已经无法接收新输入。
*
* 与 `SESSION_RUNNING`(竞态,可排队重试)区分:这里代表这条运行时本身不可再用,宿主
* 只能重建会话或明说失败。放在 `code` 上而不是让宿主去解析 message —— 飞书等渠道会把
* 派发前失败的原因直接回给用户,解析人话文案既脆弱又会把内部措辞漏出去;固定标识符
* 既安全又能进日志。
*/
export const SESSION_UNAVAILABLE_CODES = [
/** 底层句柄已关闭。 */
'SESSION_CLOSED',
/** 拆除已开始(含 close 尚未确认完成、以及静默停止后的运行时退场)。 */
'SESSION_CLOSING',
/** 上一次 close/detach 失败,句柄停在 error 态。 */
'SESSION_ERROR',
] as const;
export type SessionUnavailableCode = (typeof SESSION_UNAVAILABLE_CODES)[number];
/** 带稳定 `code` 的不可用错误;message 保持原有措辞,供本地日志与人读。 */
export function createSessionUnavailableError(
code: SessionUnavailableCode,
message: string,
): Error & { code: SessionUnavailableCode } {
const err = new Error(message) as Error & { code: SessionUnavailableCode };
err.code = code;
return err;
}
/**
* turn 零事件看门狗的计时分片长度。额度按片累加,片尾核对真实经过时间,
* 借此把系统挂起(合盖睡眠)的那段排除掉 —— 见 armTurnStallSlice。
*/
const TURN_STALL_SLICE_MS = 60_000;
/**
* 一个计时分片的实际耗时超出片长这么多 → 判为进程被系统挂起过,该片不计入额度。
* 与 maker-scheduler 的 SUSPEND_GAP_MS 同量级:远大于正常的事件循环抖动。
*/
const TURN_STALL_SUSPEND_GAP_MS = 30_000;
/** Terminal error 的尾部 drain 宽限;超时后关闭句柄,下一次 send 由 Maker 重建。 */
const TERMINAL_ERROR_DRAIN_GRACE_MS = 250;
function parseTurnStallMs(raw: string | undefined): number {
if (raw === undefined || raw === '') return DEFAULT_TURN_STALL_MS;
const n = Number(raw);
if (!Number.isFinite(n) || n < 0) return DEFAULT_TURN_STALL_MS;
return Math.floor(n);
}
/** Launch-only caller preferences. Live controls and grants have separate authorities. */
export type SessionStartupPreferences = Readonly<Pick<StartSessionOptions,
'userPrompt' | 'makerMemoryEnabled' | 'displayReasoning'>>;
export interface SessionOptions {
beforeTurn?: (session: Session) => Promise<void>;
hostStartupPreferences?: SessionStartupPreferences;
id: string;
/** 与 Agent MCP context 同源的本次内存实例代号;省略时由 Session 自铸。 */
sessionInstanceId?: string;
agentKind: EngineKind;
workDir: string;
handle: AgentSessionHandle;
capabilities: Capabilities;
logger: Logger;
/** Runtime permission mode used to create/resume the underlying handle. */
permissionMode?: PermissionMode;
/**
* 远端 SSH 主机的 alias (来自 `@cindy/maker-remote-ssh` ConnectionPool)。
* 非空 → 这个 session 实际跑在远端机器上, workDir 是远端机器上的路径。
* 主进程的 send 路径用它判断 "local fs guard 应不应该跑" — 远端 workdir
* 是不可能存在于本地 fs 的, 没必要也不该 stat。
*/
remoteHostId?: string | null;
/**
* 同账号另一台电脑(或 `share:` 分享来源)上运行 Agent 时的设备 id,与 remoteHostId 互斥。
* 主进程的发送边界用它判断供应商目录在对端:本机目录不能裁决这类会话的显式来源。
*/
agentDeviceId?: string | null;
/**
* turn 零事件看门狗阈值(ms)。省略 = env / DEFAULT_TURN_STALL_MS;0 = 关闭。
* 主要供测试注入短阈值,宿主正常不传。
*/
turnStallMs?: number;
/** `holdEventStream` 的最长等待(ms)。省略 = EVENT_STREAM_HOLD_MS;主要供测试注入。 */
eventStreamHoldMs?: number;
/**
* 宿主整机拆除(Maker.shutdown / 应用退出 / 账号边界切换)是否已开始。
* 注入后,Session 用它识别「空闲会话的进程死亡终态错误」并抑制派发;
* 缺省 = 永不抑制,与旧行为一致。
*/
isHostShuttingDown?: () => boolean;
/**
* 可选:工具循环疑似命中时的辅助模型复核入口(host 注入)。缺省 = 疑似即中断,
* 与未接入复核前一致。
*/
toolLoopReviewer?: ToolLoopReviewer;
}
function redactEventForListeners(event: AgentEvent): AgentEvent {
if (!event.data || typeof event.data !== 'object') return event;
const data = event.data as Record<string, unknown>;
const safeData = { ...data };
let changed = false;
if (event.type === 'error' && typeof safeData.message === 'string') {
const signals = extractNonSecretErrorSignals(safeData.message);
if (safeData.errorStatus == null && signals.errorStatus !== undefined) {
safeData.errorStatus = signals.errorStatus;
changed = true;
}
if (safeData.usageLimit == null && signals.usageLimit) {
safeData.usageLimit = true;
changed = true;
}
}
const stringKeys = ['message', 'sdkError', 'summary'];
if (event.type === 'tool_result_full' && safeData.isError === true) {
stringKeys.push('fullText');
}
for (const key of stringKeys) {
if (typeof safeData[key] === 'string') {
const redacted = redactSensitiveText(safeData[key]);
if (redacted !== safeData[key]) {
safeData[key] = redacted;
changed = true;
}
}
}
if (
event.type === 'agent_task_update' &&
safeData.status === 'failed' &&
safeData.raw &&
typeof safeData.raw === 'object'
) {
safeData.raw = redactNestedStrings(safeData.raw, () => {
changed = true;
});
}
if (event.type === 'done' && safeData.raw && typeof safeData.raw === 'object') {
const raw = { ...(safeData.raw as Record<string, unknown>) };
if (raw.error && typeof raw.error === 'object') {
raw.error = redactNestedStrings(raw.error, () => {
changed = true;
});
}
if (raw.status === 'failed' && Array.isArray(raw.items)) {
raw.items = redactNestedStrings(raw.items, () => {
changed = true;
});
}
safeData.raw = raw;
}
return changed ? ({ ...event, data: safeData } as AgentEvent) : event;
}
function redactNestedStrings(value: unknown, onChange: () => void): unknown {
if (typeof value === 'string') {
const redacted = redactSensitiveText(value);
if (redacted !== value) onChange();
return redacted;
}
if (Array.isArray(value)) {
return value.map((item) => redactNestedStrings(item, onChange));
}
if (!value || typeof value !== 'object') return value;
const copy: Record<string, unknown> = {};
for (const [key, child] of Object.entries(value)) {
copy[key] = redactNestedStrings(child, onChange);
}
return copy;
}
export interface SessionSendOptions extends SendOptions {
/**
* Host-owned authorization refresh after all preparation, before vendor dispatch.
* Returning undefined preserves the existing intent; an empty intent still clears it.
*/
resolveAutoReviewUserIntent?: () => Promise<AutoReviewUserIntent | undefined>;
/**
* Turn reservation 建立后的原子准备钩子。
*
* Session 在 active/running 守卫通过并占住本轮之后、provider option preflight
* 之前调用。仅用于让 host 临时收紧 preflight 本身依赖的 live session 状态;
* 后续校验或派发仍可能失败,因此调用方必须在自己的终态路径恢复该状态。
*/
afterTurnReserved?: () => void | Promise<void>;
/**
* Provider 启动前的安全屏障。
*
* Session 在 active/running 守卫通过、turn reservation 建立后调用;只有该
* hook 成功完成,才会继续执行产品层 onAccepted 与 vendor handle.send。
* 适合 durable queue 用 CAS 把任务从 dispatching 标成 accepted_running:
* hook 失败时 provider/model/tool 均不会启动。
*/
beforeProviderStart?: () => void | Promise<void>;
/**
* 产品层 accepted hook。
* Session 在 active/running 守卫通过、turn reservation 建立后调用;
* hook 完成后才启动 vendor handle。
*/
// Reservation cancellation reaches host preparation (for example Git
// snapshots); returning from a cancelled hook never authorizes dispatch.
onAccepted?: (signal?: AbortSignal) => void | Promise<void>;
/** Reservation 建立后立刻回调本轮 turn generation;host 必须用它绑定 leftover,不能等 send 返回后再读最新 generation。 */
onTurnReserved?: (turnGeneration: number) => void;
/**
* vendor dispatch 前最后一个同步边界。用于让 host 在底层可能产生新 turn
* callback 之前,精确切换自己的 turn-scoped 状态。
*/
onDispatching?: () => void;
}
export interface SessionTurnLifecycleObserver {
/** A reservation precedes async preparation; it may never reach provider dispatch. */
onTurnReserved?(generation: number): ((dispatched: boolean) => void) | void;
/** Last synchronous authorization check; no asynchronous work may follow before handle.send. */
onDispatching?(): void;
/** Awaited after option validation and before any provider-owned start hook or send. */
beforeProviderStart(turnGeneration: number, signal?: AbortSignal): void | Promise<void>;
/** Called when a prepared generation never crosses the provider dispatch boundary. */
onUndispatched(turnGeneration: number): void | Promise<void>;
/** Called before event listeners for a foreground unclaimed done or terminal error. */
onTerminal(input: {
turnGeneration: number;
event: AgentEvent;
isCurrentGeneration: boolean;
}): void | Promise<void>;
/**
* Called synchronously, before event listeners see its first event, when the provider starts a
* turn on its own: top-level output after this generation's product terminal, with no
* `Session.send` reserved and no `Session.steer` carried over (e.g. Claude Code waking itself on a
* background task notification). The turn reuses the previous generation and has no turnOrigin.
* Claimed continuations never reach here: their `done` is not a product terminal.
*/
onProviderInitiatedTurn?(turnGeneration: number): void;
}
/**
* Session.send 的产品层结果。
* accepted=true 表示 vendor handle.send 已经跨过 dispatch 边界;onAccepted 只表示
* 产品层持久化 hook 执行过,不能单独当作 turn 已启动。
*/
export type SessionSendResult =
| { accepted: true }
| {
accepted: false;
reason: 'cancelled-before-dispatch' | 'provider-rejected-before-dispatch';
};
export interface SessionTurnControlSnapshot {
active: boolean;
turnGeneration: number | null;
activeToolCount: number;
pendingInteractionCount: number;
gracefulStopState: SessionGracefulStopState;
}
export type SessionGracefulStopResult =
| { status: 'no-active-turn' }
| { status: 'unsupported'; reason: 'provider-not-supported' }
| { status: 'waiting-for-safe-point'; turnGeneration: number }
| { status: 'requested'; turnGeneration: number }
| { status: 'unconfirmed'; turnGeneration: number; reason: string };
type TurnControlState = {
generation: number;
toolLoopMonitor: ToolLoopMonitor | null;
pendingToolLoop: { toolUseId: string; verdict: HardToolLoopVerdict } | null;
/** 已送达完整结果、尚未送达结果摘要的工具;终态错误必须排在它们的摘要之后。 */
awaitingToolResultSummaries: Set<string>;
activeToolIds: Set<string>;
anonymousActiveTools: number;
pendingInteractionToolIds: Map<string, number>;
gracefulStopState: SessionGracefulStopState;
gracefulStopPromise: Promise<SessionGracefulStopResult> | null;
};
type SendReservation = {
generation: number;
phase: 'accepting' | 'dispatching';
/** handle.send() has resolved as accepted. Until then, late N terminals stay off N+1. */
accepted: boolean;
cancelled: boolean;
abortController: AbortController;
settled: Promise<SendReservationOutcome>;
settle(outcome: SendReservationOutcome): void;
gracefulStopPromise: Promise<SessionGracefulStopResult> | null;
};
type SendReservationOutcome = 'accepted' | 'undispatched' | 'unconfirmed';
function createSendReservation(generation: number): SendReservation {
let resolveSettled!: (outcome: SendReservationOutcome) => void;
const settled = new Promise<SendReservationOutcome>((resolve) => {
resolveSettled = resolve;
});
return {
generation,
phase: 'accepting',
accepted: false,
cancelled: false,
abortController: new AbortController(),
settled,
settle: resolveSettled,
gracefulStopPromise: null,
};
}
export class Session {
/** Caller preferences before generated context; memory-only recovery input. */
readonly hostStartupPreferences?: SessionStartupPreferences;
readonly id: string;
/** business id 可复用;instanceId 精确标识本次内存 Session incarnation。 */
readonly instanceId: string;
readonly agentKind: EngineKind;
/** `AgentEvent.source` names built-in engines only; plugin engines leave it unset. */
private get eventSource(): AgentKind | undefined {
return this.agentKind === 'acp' ? undefined : this.agentKind;
}
readonly workDir: string;
private readonly initialCapabilities: Capabilities;
get capabilities(): Capabilities {
return this.agentKind === 'acp'
? this.handle.negotiatedCapabilities ?? this.initialCapabilities
: this.initialCapabilities;
}
/** 见 SessionOptions.remoteHostId。 */
readonly remoteHostId: string | null;
/** 见 SessionOptions.agentDeviceId。 */
readonly agentDeviceId: string | null;
private readonly handle: AgentSessionHandle;
private readonly logger: Logger;
private readonly toolLoopReviewer: ToolLoopReviewer | undefined;
private toolLoopUserIntent: AutoReviewUserIntent | undefined;
private permissionModeStateValue: PermissionModeState;
private permissionModeChangeChain: Promise<void> = Promise.resolve();
private permissionModeChangesInFlight = 0;
/** Invalidation only; the provider remains the sole owner of the live Plan flag. */
private planModeGeneration = 0;
private planModeChangesInFlight = 0;
/** User/API permission changes, serialized separately so host restores cannot deadlock. */
private externalPermissionModeChangeChain: Promise<void> = Promise.resolve();
private externalPermissionModeChangesInFlight = 0;
/** Host-owned logical turn leases that outlive a vendor's transient idle edge. */
private readonly hostTurnLeases = new Set<Promise<void>>();
private readonly eventListeners = new Set<SessionEventListener>();
private readonly runtimeRecoveryListeners = new Set<SessionEventListener>();
private readonly statusListeners = new Set<SessionStatusListener>();
private interactionListener: InteractionRequestListener | null = null;
private turnLifecycleObserver: SessionTurnLifecycleObserver | null = null;
/** Generation whose turn after the product terminal (no send) is currently open. */
private unsolicitedTurnGeneration: number | null = null;
/**
* Generation that accepted a steer. Claude may run a steer that missed the ending turn as a new
* SDK turn without a send; that turn belongs to the steering input, not to the provider.
*/
private steerAcceptedGeneration: number | null = null;
private status: SessionStatus = 'active';
/**
* 同一 Session 的并发 close 共享一次底层关闭过程。renderer 与 main 生命周期钩子可能
* 同时请求关闭;所有调用方都必须等到 transport / 子进程真正释放后才能继续回收 worktree。
*/
private closePromise: Promise<void> | null = null;
/** close/detach 一进入同步入口就置位,早于底层 handle 的异步关闭完成。 */
private terminationStarted = false;
/** 见 SessionOptions.isHostShuttingDown。 */
private readonly isHostShuttingDown: () => boolean;
/**
* The runtime itself began this teardown (dead handle, crashed loop, failed
* dispatch, abort / terminal-error recovery). External close()/closeIfIdle()/
* detach() callers never set it, so a direct product close is not mistaken
* for a self-close even when no Maker close reason was recorded.
*/
private runtimeInitiatedClose = false;
private eventLoopStarted = false;
/**
* 最近一次已观察到的终态事件属于哪个 turn generation;事件迭代器可能在上一轮
* 开始等待、下一轮 dispatch 后才返回旧事件,不能用一个 bool 判断是否已收口。
*/
private terminalEventObservedGeneration: number | null = null;
/** 与 terminalEventObservedGeneration 成对;同 generation 的 error 不被后续 done 尾巴改写。 */
private terminalEventObservedKind: 'done' | 'error' | null = null;
private terminalEventObservedErrorMessage: string | null = null;
private terminalEventObservedErrorSignals: {
reason?: string;
sdkError?: string;
errorStatus?: number;
toolLoop?: import('./types/events.js').ToolLoopErrorDetails;
outputLimit?: OutputLimitDetails;
/** Codex app-server 的结构化错误 tag(如 badRequest / cyberPolicy)。 */
codexErrorInfo?: string;
} | null = null;
/** Survives N+1 reservation clearing the current snapshot; leftover done must not adopt. */
private lastObservedTerminalGeneration: number | null = null;
private lastObservedTerminalKind: 'done' | 'error' | null = null;
/**
* N+1 reservation 窗口内观察到的前一轮前台终态。lost-callback 时 turn N 的
* done/error 可能在直接 N+1 `handle.send()` 待处理期间才 fan-out;当时
* `turnGeneration` 已是 N+1,不能写入当前 generation 快照。拒绝回滚时再提升
* 到 N,避免 leftover `activeTurn` 永久失去回收证据。
*/
private terminalObservedDuringReservation: {
kind: 'done' | 'error';
message: string | null;
signals: {
reason?: string;
sdkError?: string;
errorStatus?: number;
} | null;
} | null = null;
/** 终态 error 后等待 provider 尾部 done;避免旧尾事件冒领下一轮。 */
private terminalErrorDrainGeneration: number | null = null;
private terminalErrorDrainTimer: ReturnType<typeof setTimeout> | null = null;
private sendReservation: SendReservation | null = null;
/**
* N+1 send that has reserved a generation but not yet accepted.
* Survives `releaseSendReservationIfObserved()` clearing the reservation
* after the handle flips running; leftover N tails must not adopt as N+1.
*/
private unacceptedSendGeneration: number | null = null;
/**
* True while runEventLoop is blocked on the provider stream: iterator.next(),
* including a bounded listener-requested hold that precedes it.
*/
private eventLoopAwaiting = false;
/** The current-turn event runEventLoop is fanning out; only it may request a hold. */
private holdableFanOutEvent: AgentEvent | null = null;
/** A hold requested while fanning out `source`, drained before the next provider event. */
private pendingEventStreamHold: {
source: AgentEvent;
followUps: Promise<readonly AgentEvent[]>;
} | null = null;
/** Ends an in-progress hold early (stop / teardown) without fanning out its follow-ups. */
private releaseEventStreamHoldWait: (() => void) | null = null;
/**
* Fences send admission from the moment a hold is accepted until the loop has
* read the event that follows it. The provider may already have marked its
* handle idle with `done` queued; without the fence a send could start turn
* N+1 before N's terminal is consumed and steal its origin / generation.
*/
private eventStreamHoldFence = false;
private readonly eventStreamHoldMs: number;
/** The blocked next() that was pending when the current send entered handle.send. */
private inFlightSendOwnsBlockedWait = false;
/** Last resolve() returned the in-flight send generation. */
private lastResolvedInFlightSend = false;
/** True from handle.send() start until that send settles. */
private insideProviderSendSync = false;
/** Keep a leftover status/done tail on the generation that started it. */
private staleTerminalQueuedGeneration: number | null = null;
/** Previous turn generation, kept until leftover tail or new-turn progress. */
private pendingPriorGeneration: number | null = null;
/** Generation that already emitted foreground running. */
private sawCurrentTurnRunningGeneration: number | null = null;
/**
* 当前进行中 turn 的发起来源(来自 send 的 opts.origin)。事件 fan-out 前打到
* AgentEvent.turnOrigin 上,turn 终止(isTerminalTurnEvent)后清空 — 共享
* session(心跳 + 远程控制)下区分 per-turn 归属。null = 未标记来源(默认)。
*/
private currentTurnOrigin: SendOrigin | null = null;
/** Host-owned per-turn correlation, kept beside origin and cleared at the terminal boundary. */
private currentTurnAttemptToken: number | null = null;
// ── turn 零事件看门狗(见 DEFAULT_TURN_STALL_MS)────────────────────────
private readonly turnStallMs: number;
private turnStallTimer: ReturnType<typeof setTimeout> | null = null;
private turnStallDiagnosticState = 'idle';
private turnStallLastDiagnosticAt = 0;
/** 还需要"清醒地"静默多久才判卡死;按分片递减(见 armTurnStallSlice)。 */
private turnStallRemainingMs = 0;
/** 当前分片的起始壁钟时刻;片尾据此识别系统挂起。 */
private turnStallSliceStartedAt = 0;
/** 正在等用户回应的交互数;>0 期间不计 stall 额度(没事件是正常的)。 */
private pendingInteractions = 0;
/** 最近一次 fan-out 事件的时刻,仅用于日志诊断。 */
private lastEventAt = 0;
/**
* turn 代号:每次 send 建立 reservation 时 +1。看门狗的善后动作(尤其
* recoverIfTurnStillRunning 的"关掉会话")必须绑定到超时的那一个 turn,否则宽限期内
* 新起的健康 turn 会被误杀 —— `isTurnRunning()` 只回答"有 turn 在跑",不回答"是不是
* 那一个"(review #944 第七轮 P1)。
*
* 只在 reservation 创建处自增就够:send 入口有 `isTurnRunning()` 守卫,卡死的 turn
* 还在跑时新 send 会被 SESSION_RUNNING 拒掉、拿不到 reservation。换句话说代号变了
* 就一定意味着"卡死那个 turn 已经停了、这是新活儿"。
*/
private turnGeneration = 0;
/** 已为哪个 turn 代号排过 abort 复核;同一 turn 上重复 abort 不重复排。 */
private abortRecoveryScheduledFor: number | null = null;
/** Host operations can start new work without creating a user-turn generation. */
private abortRecoveryEpoch = 0;
private lastEventType: string | null = null;
/** 优雅停止所需的 turn 控制事实;不承担 UI/MCP 会话状态投影。 */
private turnControlState: TurnControlState | null = null;
private readonly asyncUserQuestions: AsyncUserQuestions;
private readonly beforeTurn?: (session: Session) => Promise<void>;
constructor(opts: SessionOptions) {
this.beforeTurn = opts.beforeTurn;
this.hostStartupPreferences = opts.hostStartupPreferences
? Object.freeze({ ...opts.hostStartupPreferences }) : undefined;
this.id = opts.id;
this.instanceId = opts.sessionInstanceId ?? generateSessionId();
this.agentKind = opts.agentKind;
this.workDir = opts.workDir;
this.handle = opts.handle;
this.initialCapabilities = opts.capabilities;
this.remoteHostId = opts.remoteHostId ?? null;
this.agentDeviceId = opts.agentDeviceId ?? null;
this.logger = opts.logger.child(`s:${this.id}`);
this.permissionModeStateValue = {
mode: opts.permissionMode ?? null,
generation: 0,
};
this.turnStallMs =
opts.turnStallMs ?? parseTurnStallMs(process.env.XDT_SESSION_TURN_STALL_MS);
this.eventStreamHoldMs = opts.eventStreamHoldMs ?? EVENT_STREAM_HOLD_MS;
this.isHostShuttingDown = opts.isHostShuttingDown ?? (() => false);
this.toolLoopReviewer = opts.toolLoopReviewer;
this.asyncUserQuestions = new AsyncUserQuestions({
currentOrigin: () => this.currentTurnOrigin,
isActive: (generation) => this.status === 'active' && !this.terminationStarted
&& generation === this.turnGeneration,
isLateAnswer: (generation) => generation !== this.turnGeneration || !this.handle.isTurnRunning?.(),
resolve: (request) => this.interactionListener!(request),
deliver: async (text, signal, requestId, displayText, origin) => {
if (this.asyncQuestionAnswerDispatcher) return this.asyncQuestionAnswerDispatcher(text, signal, requestId, displayText, origin);
const options = { signal, [ASYNC_QUESTION_ANSWER]: true as const };
if (this.handle.isTurnRunning?.()) {
try { await this.steer(text, options); return; } catch (error) {
// Only a definite idle rejection can start a new turn. Unknown delivery is never replayed.
if (!/has no active turn to steer/.test(String(error))) throw error;
}
}
if (signal.aborted) return;
const result = await this.send(text, options);
if (!result.accepted) throw new Error('Async question answer was not accepted');
},
dismiss: (requestId, reason, withdrawalReason) => this.fanOutEvent({
type: 'interaction_dismissed', data: { requestId, reason, resolvedAs: 'deny', ...(withdrawalReason ? { withdrawalReason } : {}) }, source: this.eventSource,
}),
reportError: () => this.fanOutEvent({ type: 'error', source: this.eventSource,
data: { message: 'Async question answer delivery failed.', isTerminal: false } }),
});
// 注入 InteractionResolver 到底层 handle, 转发到 host 维护的 listener。
// 没接 listener 时按 kind 给出安全默认: 都视作 deny(host 必须接 listener 才能交互)。
this.handle.setInteractionResolver((req, signal) => {
if (req.kind === 'ask_user_question' && req.delivery === 'async' && this.interactionListener) {
// Native Codex emits messages, not pending RPCs. The Session owns their UI lifetime,
// just as it owns Claude/Pi questions; do not leave a second adapter continuation.
this.asyncUserQuestions.ask(req.questions, this.turnGeneration, req.requestId);
return Promise.resolve({ kind: 'ask_user_question' as const, answers: {}, dismissed: true });
}
return this.runHostInteraction(req, async () => {
if (!this.interactionListener) {
this.logger.warn('interaction request received but no listener attached, denying', { kind: req.kind, requestId: req.requestId });
if (req.kind === 'ask_user_question') {
return { kind: 'ask_user_question', answers: {} };
}
if (req.kind === 'plan_review') {
return { kind: 'plan_review', behavior: 'deny', reason: 'no_listener_attached', dismissed: true };
}
return { kind: req.kind, behavior: 'deny', reason: 'no_listener_attached' } as InteractionDecision;
}
return await (signal ? this.interactionListener(req, signal) : this.interactionListener(req));
});
});
}
// ── 公开 API ─────────────────────────────────────────────────────────────
/** 当前/最近一次已建立 reservation 的 turn 代号;只用于跨 await 识别是否仍是同一轮。 */
getTurnGeneration(): number {
return this.turnGeneration;
}
/**
* 当前 turn generation 已 fan-out 的产品终态类型。
* none:PI prompt accepted → agent_start 空窗、continuation claim 挡住的 SDK done、
* 或尚无当前 generation 终态。Host 回收残留 activeTurn 必须认类型:done 才能当
* 成功结算,error 必须走 recovery,不能靠 live idle + tracker idle 的超时猜测。
*/
getObservedCurrentTurnTerminal(): {
kind: 'none' | 'done' | 'error';
generation?: number;
message?: string;
reason?: string;
sdkError?: string;
errorStatus?: number;
toolLoop?: import('./types/events.js').ToolLoopErrorDetails;
outputLimit?: OutputLimitDetails;
codexErrorInfo?: string;
} {
if (
this.turnGeneration <= 0 ||
this.terminalEventObservedGeneration !== this.turnGeneration ||
this.terminalEventObservedKind == null
) {
return { kind: 'none' };
}
if (this.terminalEventObservedKind === 'error') {
return {
kind: 'error',
generation: this.turnGeneration,
...(this.terminalEventObservedErrorMessage
? { message: redactSensitiveText(this.terminalEventObservedErrorMessage) }
: {}),
...(this.terminalEventObservedErrorSignals?.reason
? { reason: this.terminalEventObservedErrorSignals.reason }
: {}),
...(this.terminalEventObservedErrorSignals?.sdkError
? { sdkError: redactSensitiveText(this.terminalEventObservedErrorSignals.sdkError) }
: {}),
...(typeof this.terminalEventObservedErrorSignals?.errorStatus === 'number'
? { errorStatus: this.terminalEventObservedErrorSignals.errorStatus }
: {}),
...(this.terminalEventObservedErrorSignals?.toolLoop
? { toolLoop: this.terminalEventObservedErrorSignals.toolLoop }
: {}),
...(this.terminalEventObservedErrorSignals?.outputLimit
? { outputLimit: this.terminalEventObservedErrorSignals.outputLimit }
: {}),
...(this.terminalEventObservedErrorSignals?.codexErrorInfo
? { codexErrorInfo: this.terminalEventObservedErrorSignals.codexErrorInfo }
: {}),
};
}
return { kind: 'done', generation: this.turnGeneration };
}
private readRedactedTerminalErrorSnapshot(listenerEvent: AgentEvent): {
message: string | null;
signals: {
reason?: string;
sdkError?: string;
errorStatus?: number;
toolLoop?: import('./types/events.js').ToolLoopErrorDetails;
outputLimit?: OutputLimitDetails;
codexErrorInfo?: string;
} | null;
} {
const errorData = (listenerEvent.data ?? null) as {
message?: unknown;
reason?: unknown;
sdkError?: unknown;
errorStatus?: unknown;
toolLoop?: unknown;
outputLimit?: unknown;
codexErrorInfo?: unknown;
} | null;
const errorMessage = errorData?.message;
const signals: {
reason?: string;
sdkError?: string;
errorStatus?: number;
toolLoop?: import('./types/events.js').ToolLoopErrorDetails;
outputLimit?: OutputLimitDetails;
codexErrorInfo?: string;
} = {};
if (typeof errorData?.reason === 'string' && errorData.reason.length > 0) {
signals.reason = errorData.reason;
}
if (typeof errorData?.sdkError === 'string' && errorData.sdkError.length > 0) {
signals.sdkError = redactSensitiveText(errorData.sdkError);
}
if (typeof errorData?.errorStatus === 'number' && Number.isFinite(errorData.errorStatus)) {
signals.errorStatus = errorData.errorStatus;
}
const toolLoop = parseToolLoopErrorDetails(errorData?.toolLoop);
if (toolLoop) signals.toolLoop = toolLoop;
const outputLimit = parseOutputLimitDetails(errorData?.outputLimit);
if (outputLimit) signals.outputLimit = outputLimit;
// Codex 的结构化 tag 是有界枚举名(translator 只取 tag,不带原文),不需要脱敏。
if (typeof errorData?.codexErrorInfo === 'string' && /^[A-Za-z][A-Za-z0-9_]{0,63}$/u.test(errorData.codexErrorInfo)) {
signals.codexErrorInfo = errorData.codexErrorInfo;
}
return {
message: typeof errorMessage === 'string' && errorMessage.length > 0 ? errorMessage : null,
signals:
signals.reason ||
signals.sdkError ||
signals.errorStatus !== undefined ||
signals.toolLoop ||
signals.outputLimit ||
signals.codexErrorInfo
? signals
: null,
};
}
private rememberReservationWindowPriorTerminal(
event: AgentEvent,
listenerEvent: AgentEvent,
): void {
if (event.type === 'error') {
const snapshot = this.readRedactedTerminalErrorSnapshot(listenerEvent);
this.terminalObservedDuringReservation = {
kind: 'error',
message: snapshot.message,
signals: snapshot.signals,
};
return;
}
if (event.type !== 'done') return;
if (this.terminalObservedDuringReservation?.kind === 'error') return;
this.terminalObservedDuringReservation = {
kind: 'done',
message: null,
signals: null,
};
}
private consumeReservationWindowPriorTerminal(): {
kind: 'done' | 'error';
message: string | null;
signals: {
reason?: string;
sdkError?: string;
errorStatus?: number;
toolLoop?: import('./types/events.js').ToolLoopErrorDetails;
outputLimit?: OutputLimitDetails;
} | null;
} | null {
const snapshot = this.terminalObservedDuringReservation;
this.terminalObservedDuringReservation = null;
return snapshot;
}
private asyncQuestionAnswerDispatcher?: (text: string, signal: AbortSignal, requestId: string, displayText: string, origin: SendOrigin | null) => Promise<void>;
/**
* Hosts with a durable input queue own admission/persistence of question replies.
* `text` is the model's copy; `displayText` is what history and queues show.
*/
setAsyncQuestionAnswerDispatcher(dispatch: (text: string, signal: AbortSignal, requestId: string, displayText: string, origin: SendOrigin | null) => Promise<void>): void {
this.asyncQuestionAnswerDispatcher = dispatch;
}
submitAsyncQuestionAnswer(requestId: string, decision: InteractionDecision): Promise<boolean> {
return this.asyncUserQuestions.submit(requestId, decision);
}
/** Called only after an ordinary user input has been accepted by the host. */
dismissAsyncQuestionsForUserInput(): void { this.asyncUserQuestions.expire('superseded'); }
manageAsyncUserQuestions(input: { action: 'list' } | { action: 'withdraw'; request_ids: string[]; reason: string }) {
if (this.getStatus() !== 'active' || this.terminationStarted) throw new Error('No active question session');
return input.action === 'list'
? { questions: this.asyncUserQuestions.list() }
: { results: this.asyncUserQuestions.withdraw(input.request_ids, input.reason) };
}
async send(message: UserMessage | string, opts?: SessionSendOptions): Promise<SessionSendResult> {
const pending = this.asyncUserQuestions.snapshot();
const result = await this.dispatchSend(message, opts, false);
if (result.accepted && opts?.[SUPERSEDE_ASYNC_QUESTIONS] && !opts[ASYNC_QUESTION_ANSWER]) this.asyncUserQuestions.expire('superseded', pending);
return result;
}
/**
* Host-owned silent-stop continuation. This is the only send admitted while a
* retiring runtime has claimed the current generation; ordinary `send()` stays
* rejected so queued/user work cannot run on the snapshot being retired.
*/
async sendHostTurnContinuation(
message: UserMessage | string,
opts?: SessionSendOptions,
): Promise<SessionSendResult> {
return this.dispatchSend(message, opts, true);
}
private async dispatchSend(
message: UserMessage | string,
opts: SessionSendOptions | undefined,
allowRetirementContinuation: boolean,
): Promise<SessionSendResult> {
const {
afterTurnReserved,
beforeProviderStart,
onAccepted,
onDispatching,
onTurnReserved,
resolveAutoReviewUserIntent,
...handleOpts
} = opts ?? {};
const cancelledBeforeReservation = (): SessionSendResult | null =>
handleOpts.signal?.aborted === true
? { accepted: false, reason: 'cancelled-before-dispatch' }
: null;
const alreadyCancelled = cancelledBeforeReservation();
if (alreadyCancelled !== null) return alreadyCancelled;
// A host may need to keep a logical turn exclusive while the vendor briefly
// reports idle between a foreground result and background-task continuation.
// Wait instead of racing that continuation with a new Desktop turn.
while (this.hostTurnLeases.size > 0) {
if (await this.waitForGateOrAbort(Promise.all([...this.hostTurnLeases]), handleOpts.signal)) {
return { accepted: false, reason: 'cancelled-before-dispatch' };
}
}
// Preserve user/API permission change ordering before admitting the next turn.
while (this.externalPermissionModeChangesInFlight > 0) {
if (await this.waitForGateOrAbort(this.externalPermissionModeChangeChain, handleOpts.signal)) {
return { accepted: false, reason: 'cancelled-before-dispatch' };
}
}
// A temporary host permission lease may be restoring immediately after a
// terminal event. Do not let the next turn reserve the session until that
// live provider state is settled.
while (this.permissionModeChangesInFlight > 0) {
if (await this.waitForGateOrAbort(this.permissionModeChangeChain, handleOpts.signal)) {
return { accepted: false, reason: 'cancelled-before-dispatch' };
}
}
const msg: UserMessage = typeof message === 'string'
? { type: 'user', content: message }
: message;
this.logger.debug('send', summarizeUserMessage(msg));
this.ensureActive();
// A silent-stop claim keeps this generation alive for Host continuation only.
// Any other sender (user, queue, Goal, IM) must not start new work on a
// runtime that is already marked to retire after the current product turn.
if (this.retirementRequested
&& (this.retirementContinuationGeneration !== this.turnGeneration
|| !allowRetirementContinuation)) {
throw createSessionUnavailableError(
'SESSION_CLOSING', `Session ${this.id} is closing`,
);
}