dsh-client-auto-continue 0.11.8 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,6 +10,7 @@ const css = `
10
10
  --dsh-ac-violet: #8b7cff;
11
11
  --dsh-ac-cyan: #45cce5;
12
12
  --dsh-ac-mint: #46d69d;
13
+ --dsh-ac-red: #e5484d;
13
14
  --dsh-ac-amber: #f1b95c;
14
15
  isolation: isolate;
15
16
  position: relative;
@@ -232,6 +233,7 @@ const css = `
232
233
  background: color-mix(in srgb, var(--dsw-alias-bg-layer-3) 95%, var(--dsh-ac-section) 5%);
233
234
  }
234
235
  .dshAcFormSection-handoff { --dsh-ac-section: var(--dsh-ac-mint); }
236
+ .dshAcFormSection-autoloop { --dsh-ac-section: var(--dsh-ac-red); }
235
237
  .dshAcFormSection-safety { --dsh-ac-section: var(--dsh-ac-amber); }
236
238
  .dshAcFormSection-recovery { --dsh-ac-section: var(--dsh-ac-cyan); }
237
239
  .dshAcFormSection-loop { --dsh-ac-section: var(--dsh-ac-violet); }
@@ -6,10 +6,11 @@
6
6
  * bugs (issue #13) cannot exist by construction. Listens to the session event
7
7
  * firehose (`session/event`), sends through the agent registry
8
8
  * (`agent.followup`), cancels through `agent.cancel`, and reads configuration
9
- * from the settings service.
9
+ * injected by the entry (`apply`'s config argument, merged with schema
10
+ * defaults by `resolveConfig`).
10
11
  *
11
- * All behavior is driven by the `auto-continue` settings namespace (see the
12
- * plugin's settings card); every knob below is user-configurable there.
12
+ * All behavior is driven by the `auto-continue` entry config; every knob below
13
+ * is user-configurable there.
13
14
  */
14
15
 
15
16
  import type { Context } from '@deepseek-ai/cordis';
@@ -79,6 +80,21 @@ const LOOP_GUARD_CANCEL_CAUSE = {
79
80
  reason: 'dsh-auto-continue:loop-guard',
80
81
  } as const;
81
82
 
83
+ /**
84
+ * Autonomous-loop resume reasons.
85
+ * - `turn/end:completed` is a *successful* visible completion: the loop hands
86
+ * the thread back and the send is exempt from the failure budget.
87
+ * - `turn/end:loop-silent` is a loop-covered turn with no visible output. The
88
+ * loop still continues it, but it is a failure: it must consume the retry
89
+ * budget and obey backoff, or a stuck model retries forever.
90
+ * The silent reason must not end in `:silent` — `fire()` skips those when
91
+ * silent-turn resume is off, which would stall the loop (27j).
92
+ */
93
+ const LOOP_COMPLETED_REASON = 'turn/end:completed';
94
+ const LOOP_SILENT_REASON = 'turn/end:loop-silent';
95
+ const isLoopReason = (reason: string): boolean =>
96
+ reason === LOOP_COMPLETED_REASON || reason === LOOP_SILENT_REASON;
97
+
82
98
  /** Keep fuzzy matching off the unbounded host event path; exact repeats remain unlimited. */
83
99
  const STREAM_NEAR_DUPLICATE_MAX_CHARS = 2_048;
84
100
  /** Bound unfinished text copied between token chunks when a provider emits no paragraph break. */
@@ -201,10 +217,13 @@ export class AutoContinueRunner {
201
217
  private readonly disposeSessionEvents: () => void;
202
218
  private readonly disposeInboxEvents: () => void;
203
219
  private disposed = false;
220
+ private readonly bootScannedSessions = new WeakSet<Session>();
221
+ private bootScanTimer: ReturnType<typeof setTimeout> | undefined;
222
+ private wakeBootScan: (() => void) | undefined;
204
223
 
205
224
  /**
206
- * @param ctx - host plugin context (agents registry, session events, settings).
207
- * @param getConfig - read the current resolved configuration (settings service).
225
+ * @param ctx - host plugin context (agents registry, session events).
226
+ * @param getConfig - read the current resolved configuration (entry config).
208
227
  */
209
228
  constructor(
210
229
  private readonly ctx: Context,
@@ -326,12 +345,17 @@ export class AutoContinueRunner {
326
345
  dispose(): void {
327
346
  if (this.disposed) return;
328
347
  this.disposed = true;
348
+ if (this.bootScanTimer !== undefined) clearTimeout(this.bootScanTimer);
349
+ this.bootScanTimer = undefined;
350
+ this.wakeBootScan?.();
351
+ this.wakeBootScan = undefined;
329
352
  this.disposeSessionEvents();
330
353
  this.disposeInboxEvents();
331
354
  this.prioritizedFollowups.clear();
332
355
  for (const state of this.states.values()) {
333
356
  if (state.pendingTimer !== undefined) clearTimeout(state.pendingTimer);
334
357
  if (state.loopRetryTimer !== undefined) clearTimeout(state.loopRetryTimer);
358
+ if (state.cooldownRetryTimer !== undefined) clearTimeout(state.cooldownRetryTimer);
335
359
  }
336
360
  this.states.clear();
337
361
  }
@@ -363,24 +387,58 @@ export class AutoContinueRunner {
363
387
  if (event.type === 'tool/call') {
364
388
  const state = this.state(sessionId);
365
389
  // 任何新鲜调用都代表进展(即使缺关联 id);旧帧重放不能清短句 streak。
366
- if (state.tools.recordCall(event)) state.shortRun = 0;
390
+ if (state.tools.recordCall(event)) {
391
+ state.shortRun = 0;
392
+ if (this.tracksOutput(state, event)) state.turnOutput = 'visible';
393
+ }
367
394
  } else if (event.type === 'tool/result') {
368
395
  const state = this.state(sessionId);
369
396
  state.tools.recordResult(event);
370
397
  } else if (event.type === 'step/start') {
371
398
  const state = this.state(sessionId);
399
+ if (this.tracksOutput(state, event) && state.turnOutput === 'empty') state.turnOutput = 'silent';
372
400
  const repeat = state.tools.confirmRepeatAtStep(event.seq);
373
401
  if (repeat !== undefined) this.checkLoop(sessionId, state, repeat);
374
402
  } else if (event.type === 'assistant/chunk') {
375
403
  const state = this.state(sessionId);
404
+ if (this.tracksOutput(state, event)) {
405
+ const chunk = event.data.chunk;
406
+ const visible = (chunk.type === 'text-delta' && chunk.text.trim() !== '') ||
407
+ chunk.type === 'tool-call-delta' ||
408
+ (chunk.type === 'block-end' && this.hasVisibleContent([chunk.block])) ||
409
+ (chunk.type === 'block-start' && chunk.blockType !== 'reasoning' && chunk.blockType !== 'text');
410
+ if (visible) state.turnOutput = 'visible';
411
+ else if (state.turnOutput === 'empty' && chunk.type !== 'usage' && chunk.type !== 'finish') state.turnOutput = 'silent';
412
+ }
376
413
  this.onAssistantChunk(sessionId, state, event);
377
414
  } else if (event.type === 'assistant/message') {
378
415
  const state = this.state(sessionId);
416
+ if (this.tracksOutput(state, event)) {
417
+ if (this.hasVisibleContent(event.data.message.content)) state.turnOutput = 'visible';
418
+ else if (state.turnOutput === 'empty') state.turnOutput = 'silent';
419
+ }
379
420
  this.onAssistantMessage(sessionId, state, event);
380
421
  }
381
422
  this.onSessionEvent(sessionId, event);
382
423
  }
383
424
 
425
+ private tracksOutput(state: SessionState, event: SessionEvent): boolean {
426
+ return state.running === true && state.outputTurn === (event.data as { turn?: number }).turn &&
427
+ event.seq > state.outputStartSeq;
428
+ }
429
+
430
+ /** Treat unknown block kinds conservatively: only reasoning and blank text are silent. */
431
+ private hasVisibleContent(content: unknown): boolean {
432
+ if (!Array.isArray(content)) return false;
433
+ return content.some((part: unknown) => {
434
+ if (part === null || typeof part !== 'object') return true;
435
+ const block = part as { type?: unknown; text?: unknown };
436
+ if (block.type === 'reasoning') return false;
437
+ if (block.type === 'text') return typeof block.text !== 'string' || block.text.trim() !== '';
438
+ return true;
439
+ });
440
+ }
441
+
384
442
  /** 从 assistant/message 事件提取纯文本。 */
385
443
  private assistantText(event: SessionEvent<'assistant/message'>): string {
386
444
  const content = event.data.message.content;
@@ -601,6 +659,9 @@ export class AutoContinueRunner {
601
659
  state.streamLastSegment = '';
602
660
  state.streamRepeatRun = 0;
603
661
  state.loopFired = false;
662
+ state.turnOutput = 'empty';
663
+ state.outputTurn = event.data.turn;
664
+ state.outputStartSeq = event.seq;
604
665
  if (state.loopRetryTimer !== undefined) {
605
666
  clearTimeout(state.loopRetryTimer);
606
667
  state.loopRetryTimer = undefined;
@@ -612,17 +673,50 @@ export class AutoContinueRunner {
612
673
  const loopCancelPending = state.loopFired;
613
674
  state.loopFired = false;
614
675
  this.cancelPending(sessionId, '收到新的 turn/end');
676
+ const turnOutput = state.outputTurn === event.data.turn ? state.turnOutput : 'unknown';
677
+ state.turnOutput = 'unknown';
678
+ state.outputTurn = undefined;
615
679
  const reason = event.data.reason;
616
680
  const reasonKind = readReasonKind(reason);
617
681
  if (reasonKind === undefined) {
618
682
  console.error(`[auto-continue] 忽略畸形 turn/end ${sessionId}: reason 无法解释`);
619
683
  break;
620
684
  }
621
- if (reasonKind === 'completed') {
622
- // 成功回合: 恢复健康状态, 并确认上一次自动发送的效果
623
- state.consecutive = 0;
685
+ if (reasonKind === 'no-visible-output' || (reasonKind === 'completed' && turnOutput === 'silent')) {
686
+ // 已观察到模型活动但没有可见输出; 没有模型活动的空回合不属于此类。
687
+ // 不清零 consecutive: 每轮都卡住的模型仍受冷却与连续上限约束。
688
+ // `no-visible-output` 是 DSH 为同一种回合提议的结束原因, 按同样方式处理。
624
689
  state.lastFailure = undefined;
625
- this.noteRecovery(sessionId, 'completed');
690
+ state.lastTurn = event.data.turn;
691
+ state.lastFailureAt = Date.now();
692
+ this.noteRecovery(sessionId, 'error');
693
+ if (this.getConfig().resumeCompletedTurns) {
694
+ // 自主循环覆盖无可见输出的回合, 但这类回合是「失败」而非成功:
695
+ // 不 force, 否则会绕过连续上限与冷却, 让卡住的模型无限重试。
696
+ this.schedule(sessionId, LOOP_SILENT_REASON);
697
+ } else if (this.getConfig().resumeSilentTurns) {
698
+ this.schedule(sessionId, `turn/end:${reasonKind}:silent`);
699
+ }
700
+ break;
701
+ }
702
+ if (reasonKind === 'completed') {
703
+ // Only observed visible output proves recovery; no-op and unknown
704
+ // turns must not erase the retry budget or count as successful.
705
+ // 自主循环的例外只在于「是否续跑」, 不在于「是否清零预算」: 循环对每个
706
+ // completed 回合都强制续跑, 但失败预算依旧只在可见输出时清零, 否则
707
+ // 空回合/未观察到的回合会不断抹掉连续计数, 令连续上限永远无法生效。
708
+ if (this.getConfig().resumeCompletedTurns) {
709
+ if (turnOutput === 'visible') {
710
+ state.consecutive = 0;
711
+ state.lastFailure = undefined;
712
+ this.noteRecovery(sessionId, 'completed');
713
+ }
714
+ this.schedule(sessionId, LOOP_COMPLETED_REASON, true);
715
+ } else if (turnOutput === 'visible') {
716
+ state.consecutive = 0;
717
+ state.lastFailure = undefined;
718
+ this.noteRecovery(sessionId, 'completed');
719
+ }
626
720
  } else if (reasonKind === 'aborted') {
627
721
  if (isLoopGuardCancelReason((reason as { reason?: unknown }).reason)) {
628
722
  // 我们自己的 loop guard 打断: 视为可恢复中断, 用循环提示文本重启回合。
@@ -650,7 +744,7 @@ export class AutoContinueRunner {
650
744
  } catch (error) {
651
745
  console.error(`[auto-continue] loop 重启异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
652
746
  }
653
- }, remaining);
747
+ }, remaining + 10); // +10ms: the schedule re-check compares Date.now() against the cooldown; a 1ms wall-clock step can otherwise make it read just under, silently dropping the restart
654
748
  this.log(`loop 重启延迟 ${remaining}ms(冷却期) ${sessionId}`);
655
749
  } else {
656
750
  this.schedule(sessionId, 'loop:aborted');
@@ -767,6 +861,10 @@ export class AutoContinueRunner {
767
861
  if (delta.code !== undefined) {
768
862
  this.dayStats.byCode[delta.code] = (this.dayStats.byCode[delta.code] ?? 0) + 1;
769
863
  }
864
+ // Stats are only observable through the status bridge, so every bump must
865
+ // publish. Previously the panel only moved when a notification happened to
866
+ // fire (notify=false by default), leaving "Auto-continued" frozen at 0.
867
+ this.emitState();
770
868
  }
771
869
 
772
870
  /** 通知桥: 产生一条通知事件, SSE 端点推给 browser 侧展示。 */
@@ -831,7 +929,7 @@ export class AutoContinueRunner {
831
929
  );
832
930
  }
833
931
 
834
- private schedule(sessionId: SessionId, reason: string): void {
932
+ private schedule(sessionId: SessionId, reason: string, force = false): void {
835
933
  const state = this.state(sessionId);
836
934
  const config = this.getConfig();
837
935
  if (state.subagent) return; // 子代理会话由父代理处理, 不抢跑
@@ -844,46 +942,93 @@ export class AutoContinueRunner {
844
942
  return;
845
943
  }
846
944
  if (state.pendingTimer !== undefined) return; // 已有待发送
847
- if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) return; // 冷却期(含失败尝试, 自适应退避)
848
- if (state.consecutive >= config.maxConsecutive) {
945
+ // 连续上限优先于冷却: 已经放弃的会话不该再安排冷却后的重试。
946
+ // 自主循环的完成续跑(force)不受二者约束。
947
+ if (!force && state.consecutive >= config.maxConsecutive) {
849
948
  this.log(
850
949
  `跳过 ${sessionId}(${reason}): 已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`,
851
950
  );
852
951
  return;
853
952
  }
953
+ // 冷却(含失败尝试, 自适应退避): 不能直接丢弃这次恢复, 否则一次瞬时失败
954
+ // 会把会话搁置到用户手动介入为止。
955
+ if (!force) {
956
+ const remaining = this.cooldownFor(state) - (Date.now() - state.lastAttemptAt);
957
+ if (remaining > 0) {
958
+ this.deferCooldownRetry(sessionId, reason, remaining);
959
+ return;
960
+ }
961
+ }
854
962
  const timer = setTimeout(() => {
855
963
  if (state.pendingTimer !== timer) return;
856
964
  state.pendingTimer = undefined;
857
965
  // 保险丝: 定时器回调内任何异常(含 inactive context)都不得成为未捕获异常炸掉进程。
858
966
  try {
859
- void this.fire(sessionId, reason);
967
+ void this.fire(sessionId, reason, force);
860
968
  } catch (error) {
861
969
  console.error(`[auto-continue] 定时发送异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
862
970
  }
863
971
  }, config.graceMs);
864
972
  state.pendingTimer = timer;
865
- const template = reason.startsWith('loop:')
866
- ? config.loopText
867
- : reason.includes('max-tokens')
868
- ? config.continueTextMaxTokens
869
- : config.continueText;
973
+ const template = this.templateFor(config, reason);
870
974
  this.log(
871
975
  `检测到非人为中断 ${sessionId}(${reason}), ${config.graceMs}ms 后自动发送「${template}」`,
872
976
  );
873
977
  }
874
978
 
979
+ /**
980
+ * 冷却期内的恢复: 等到冷却结束再重新调度。
981
+ * 直接丢弃会让一次瞬时失败把会话搁置, 直到用户手动发消息才恢复。
982
+ */
983
+ private deferCooldownRetry(sessionId: SessionId, reason: string, remaining: number): void {
984
+ const state = this.state(sessionId);
985
+ if (state.cooldownRetryTimer !== undefined) clearTimeout(state.cooldownRetryTimer);
986
+ state.cooldownRetryTimer = setTimeout(() => {
987
+ state.cooldownRetryTimer = undefined;
988
+ try {
989
+ this.schedule(sessionId, reason);
990
+ } catch (error) {
991
+ console.error(`[auto-continue] 冷却后重试异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
992
+ }
993
+ }, remaining + 10); // +10ms: 同 loop 重启; 否则 1ms 抖动可能让重检仍判为冷却期而再次丢弃
994
+ this.log(`冷却中 ${sessionId}(${reason}), ${remaining}ms 后重试`);
995
+ }
996
+
997
+ /** 按调度原因选择续跑模板: loop 重启、无输出回合、max-tokens、自主循环, 其余用通用继续文本。 */
998
+ private templateFor(config: AutoContinueConfig, reason: string): string {
999
+ if (reason.startsWith('loop:')) return config.loopText;
1000
+ // 自主循环的两种原因都用循环文本(顺序在 `:silent` 之前: 循环模式决定文本)。
1001
+ if (isLoopReason(reason)) return config.continueTextLoop;
1002
+ if (reason.endsWith(':silent')) return config.continueTextSilent;
1003
+ if (reason.includes('max-tokens')) return config.continueTextMaxTokens;
1004
+ return config.continueText;
1005
+ }
1006
+
875
1007
  private cancelPending(sessionId: SessionId, why: string): void {
876
1008
  const state = this.state(sessionId);
877
- if (state.pendingTimer === undefined) return;
878
- clearTimeout(state.pendingTimer);
879
- state.pendingTimer = undefined;
880
- this.log(`取消 ${sessionId} 的自动继续(${why})`);
1009
+ let cancelled = false;
1010
+ if (state.pendingTimer !== undefined) {
1011
+ clearTimeout(state.pendingTimer);
1012
+ state.pendingTimer = undefined;
1013
+ cancelled = true;
1014
+ }
1015
+ // 冷却后的重试同样属于「待发送」: 新回合或用户介入必须让它作废。
1016
+ if (state.cooldownRetryTimer !== undefined) {
1017
+ clearTimeout(state.cooldownRetryTimer);
1018
+ state.cooldownRetryTimer = undefined;
1019
+ cancelled = true;
1020
+ }
1021
+ if (cancelled) this.log(`取消 ${sessionId} 的自动继续(${why})`);
881
1022
  }
882
1023
 
883
1024
  private fire(sessionId: SessionId, reason: string, force = false): void {
884
1025
  if (this.disposed) return;
885
1026
  const state = this.state(sessionId);
886
1027
  const config = this.getConfig();
1028
+ if (reason.endsWith(':silent') && !config.resumeSilentTurns) return;
1029
+ // 宽限期内循环被关闭: 发送前必须重新检查开关, 与 :silent 恢复同样处理。
1030
+ // 否则「关掉循环」后仍会多发出一次续跑。
1031
+ if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
887
1032
  if (state.subagent) return; // 子代理会话由父代理处理, 不抢跑
888
1033
  if (config.paused) {
889
1034
  this.log(`跳过 ${sessionId}(${reason}): 全局暂停中`);
@@ -903,11 +1048,7 @@ export class AutoContinueRunner {
903
1048
  return;
904
1049
  }
905
1050
  // 模板填充: continueText 可含 {code}/{message}/{status}/{tool}/{turn}/{errorCount}/{sessionTitle}/{elapsed} 占位符
906
- const template = reason.startsWith('loop:')
907
- ? config.loopText
908
- : reason.includes('max-tokens')
909
- ? config.continueTextMaxTokens
910
- : config.continueText;
1051
+ const template = this.templateFor(config, reason);
911
1052
  const text = this.buildContinueText(config, state, template);
912
1053
  // 发送: followup 负责唤醒; 同步 inbox 插入事件会在唤醒前把本消息移到已有队列之前。
913
1054
  const agent = this.ctx.agents.get(sessionId);
@@ -933,7 +1074,8 @@ export class AutoContinueRunner {
933
1074
  this.prioritizedFollowups.delete(message.id);
934
1075
  }
935
1076
  const now = Date.now();
936
- state.consecutive += 1;
1077
+ // 自主循环的成功续跑不计入连续上限: 上限只约束失败(网络中断等)。
1078
+ if (reason !== LOOP_COMPLETED_REASON) state.consecutive += 1;
937
1079
  state.pendingRecoveryAt = now; // 等待窗口内的下一个回合结束来判定恢复结果
938
1080
  this.bumpStat({ sent: 1, ...(state.lastFailure !== undefined ? { code: state.lastFailure.code } : {}) });
939
1081
  this.log(`已自动发送「${text}」到 ${sessionId}(${reason}), 第 ${state.consecutive} 次连续`);
@@ -1003,12 +1145,11 @@ export class AutoContinueRunner {
1003
1145
  }
1004
1146
 
1005
1147
  private async bootScanLoop(): Promise<void> {
1006
- await this.scanLoop(Infinity, 3000);
1007
- }
1008
-
1009
- /** 反复尝试扫描, 直到成功(宿主就绪)或达到次数上限。 */
1010
- private async scanLoop(attempts: number, delayMs: number): Promise<void> {
1011
- for (let attempt = 0; attempt < attempts && !this.disposed; attempt += 1) {
1148
+ // Sessions restored after this window are too old for startup recovery.
1149
+ // Keep polling only within that window, including while globally paused.
1150
+ const deadline = Date.now() + this.getConfig().freshMs;
1151
+ for (let attempt = 0; !this.disposed; attempt += 1) {
1152
+ if (attempt > 0 && Date.now() >= deadline) return;
1012
1153
  try {
1013
1154
  if (await this.scanInterrupted()) return;
1014
1155
  } catch (error) {
@@ -1016,100 +1157,110 @@ export class AutoContinueRunner {
1016
1157
  // 宿主未就绪时每 3s 重试; 只节流记录日志, 避免刷屏。
1017
1158
  if (attempt % 10 === 0) {
1018
1159
  this.log(
1019
- `扫描失败(${attempt + 1}/${attempts === Infinity ? '∞' : attempts}): ${
1160
+ `扫描失败(${attempt + 1}): ${
1020
1161
  error instanceof Error ? error.message : String(error)
1021
1162
  }`,
1022
1163
  );
1023
1164
  }
1024
1165
  }
1025
- if (attempt + 1 < attempts) await sleep(delayMs);
1166
+ const remaining = deadline - Date.now();
1167
+ if (this.disposed || remaining <= 0) return;
1168
+ await new Promise<void>((resolve) => {
1169
+ this.wakeBootScan = resolve;
1170
+ this.bootScanTimer = setTimeout(() => {
1171
+ this.bootScanTimer = undefined;
1172
+ this.wakeBootScan = undefined;
1173
+ resolve();
1174
+ }, Math.min(3000, remaining));
1175
+ });
1026
1176
  }
1027
1177
  }
1028
1178
 
1029
- /**
1030
- * 扫描最近中断过的会话: 最后回合以非人为原因结束, 且其后没有新回合或用户消息。
1031
- * @returns 是否成功完成一次扫描(宿主就绪)。
1032
- */
1179
+ /** Inspect newly available sessions; process each settled startup history once. */
1033
1180
  private async scanInterrupted(): Promise<boolean> {
1034
1181
  const config = this.getConfig();
1035
- if (config.paused) return true; // 全局暂停: 不做任何扫描
1036
- // 只扫 live agents(host 重启后 agent-loop 会 resume 崩溃会话, 冷会话无需处理)
1182
+ if (config.paused || !config.scanOnBoot) return false;
1037
1183
  const now = Date.now();
1038
1184
  const candidates: {
1039
- sessionId: SessionId;
1185
+ session: Session;
1040
1186
  events: readonly SessionEvent[];
1187
+ lastEnd: SessionEvent<'turn/end'>;
1188
+ reasonKind: string;
1189
+ failure?: FailureFacts;
1041
1190
  lastActivityAt: number;
1042
1191
  listIndex: number;
1043
1192
  }[] = [];
1044
1193
  for (const agent of this.ctx.agents.list()) {
1045
1194
  const session = agent.session;
1046
- if (session.header.origin === 'subagent') continue; // 子代理由父代理处理
1047
- const events = snapshotSessionEvents(session);
1048
- const lastActivityAt = events.reduce(
1049
- (latest, event) => Math.max(latest, event.time),
1050
- Number.isFinite(session.header.createdAt) ? session.header.createdAt : 0,
1051
- );
1052
- candidates.push({
1053
- sessionId: session.id,
1054
- events,
1055
- lastActivityAt,
1056
- listIndex: candidates.length,
1057
- });
1058
- }
1059
- candidates.sort(
1060
- (left, right) =>
1061
- right.lastActivityAt - left.lastActivityAt || left.listIndex - right.listIndex,
1062
- );
1063
- for (const candidate of candidates.slice(0, config.scanLimit)) {
1064
- if (this.disposed) return true;
1065
- const state = this.state(candidate.sessionId);
1066
- if (state.pendingTimer !== undefined) continue;
1067
- if (state.consecutive >= config.maxConsecutive) continue;
1195
+ if (session.header.origin === 'subagent' || this.bootScannedSessions.has(session)) continue;
1196
+ const state = this.state(session.id);
1197
+ if (state.pendingTimer !== undefined || state.consecutive >= config.maxConsecutive) continue;
1068
1198
  if (now - state.lastAttemptAt < this.cooldownFor(state)) continue;
1069
- if (now < (this.pauseUntil.get(candidate.sessionId) ?? 0)) continue; // 会话暂停中
1070
- const events = candidate.events;
1071
- // 从尾部找最后一个 turn/end
1199
+ if (now < (this.pauseUntil.get(session.id) ?? 0)) continue;
1200
+ const events = snapshotSessionEvents(session);
1201
+ // A published session may still be waiting for its first history snapshot.
1202
+ if (events.length === 0) continue;
1072
1203
  let lastEnd: SessionEvent<'turn/end'> | undefined;
1073
1204
  for (let i = events.length - 1; i >= 0; i -= 1) {
1074
1205
  const event = events[i];
1075
- if (event !== undefined && event.type === 'turn/end') {
1076
- lastEnd = event;
1077
- break;
1078
- }
1206
+ if (event?.type === 'turn/end') { lastEnd = event; break; }
1079
1207
  }
1080
- if (lastEnd === undefined) continue;
1081
- const reason = lastEnd.data.reason;
1082
- const reasonKind = readReasonKind(reason);
1083
- if (reasonKind === undefined || !isNonHumanReason(reasonKind)) continue;
1084
- if (lastEnd.time < now - config.freshMs) continue; // 太久远, 不翻旧账
1085
- // 该 turn/end 之后不能有新回合或用户消息(说明已被处理)
1086
- let superseded = false;
1087
- for (const event of events) {
1088
- if (event.seq <= lastEnd.seq) continue;
1089
- if (event.type === 'turn/start') superseded = true;
1090
- if (event.type === 'user/message' && event.data.source.kind === 'user') superseded = true;
1091
- if (superseded) break;
1208
+ const reasonKind = readReasonKind(lastEnd?.data.reason);
1209
+ const silent = reasonKind === 'no-visible-output' && config.resumeSilentTurns;
1210
+ const superseded = lastEnd !== undefined && events.some((event) =>
1211
+ event.seq > lastEnd!.seq && (event.type === 'turn/start' ||
1212
+ (event.type === 'user/message' && event.data.source.kind === 'user')),
1213
+ );
1214
+ if (lastEnd === undefined || reasonKind === undefined || (!isNonHumanReason(reasonKind) && !silent) ||
1215
+ lastEnd.time < now - config.freshMs || superseded) {
1216
+ this.bootScannedSessions.add(session);
1217
+ continue;
1092
1218
  }
1093
- if (superseded) continue;
1094
- // 幂等护栏: 从历史事件里重建上一步工具调用的执行状态
1095
- this.applyGuardFromEvents(state, events, lastEnd.seq);
1096
- const scanReason = `scan:turn/end:${reasonKind}`;
1097
- this.log(`扫描发现中断 ${candidate.sessionId}(turn/end:${reasonKind}), 交给恢复策略处理`);
1219
+ let failure: FailureFacts | undefined;
1098
1220
  if (reasonKind === 'error') {
1099
- const failure = parseFailureFacts((reason as { error?: unknown }).error);
1221
+ failure = parseFailureFacts((lastEnd.data.reason as { error?: unknown }).error);
1100
1222
  if (failure === undefined) {
1101
- console.error(`[auto-continue] 忽略畸形扫描 turn/end ${candidate.sessionId}: error details 无法解释`);
1223
+ this.bootScannedSessions.add(session);
1224
+ console.error(`[auto-continue] 忽略畸形扫描 turn/end ${session.id}: error details 无法解释`);
1225
+ continue;
1226
+ }
1227
+ if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
1228
+ this.bootScannedSessions.add(session);
1229
+ this.onTurnFailure(session.id, 'scan:turn/end:error', failure);
1102
1230
  continue;
1103
1231
  }
1232
+ }
1233
+ candidates.push({
1234
+ session, events, lastEnd, reasonKind, failure,
1235
+ lastActivityAt: events.reduce((latest, event) => Math.max(latest, event.time), 0),
1236
+ listIndex: candidates.length,
1237
+ });
1238
+ }
1239
+ // Limit recoveries, not healthy/permanent histories that cannot be resumed.
1240
+ candidates.sort((left, right) => right.lastActivityAt - left.lastActivityAt || left.listIndex - right.listIndex);
1241
+ for (const candidate of candidates.slice(0, config.scanLimit)) {
1242
+ if (this.disposed) return true;
1243
+ const { session, events, lastEnd, reasonKind, failure } = candidate;
1244
+ this.bootScannedSessions.add(session);
1245
+ const state = this.state(session.id);
1246
+ this.applyGuardFromEvents(state, events, lastEnd.seq);
1247
+ const scanReason = `scan:turn/end:${reasonKind}${reasonKind === 'no-visible-output' ? ':silent' : ''}`;
1248
+ this.log(`扫描发现中断 ${session.id}(turn/end:${reasonKind}), 交给恢复策略处理`);
1249
+ if (failure !== undefined) {
1104
1250
  state.lastFailure = failure;
1105
1251
  state.lastTurn = lastEnd.data.turn;
1106
1252
  state.lastFailureAt = lastEnd.time;
1107
- this.onTurnFailure(candidate.sessionId, scanReason, state.lastFailure);
1253
+ this.onTurnFailure(session.id, scanReason, failure);
1108
1254
  } else {
1109
- this.schedule(candidate.sessionId, scanReason);
1255
+ if (reasonKind === 'no-visible-output') {
1256
+ state.lastFailure = undefined;
1257
+ state.lastTurn = lastEnd.data.turn;
1258
+ state.lastFailureAt = lastEnd.time;
1259
+ }
1260
+ this.schedule(session.id, scanReason);
1110
1261
  }
1111
1262
  }
1112
- return true;
1263
+ return false;
1113
1264
  }
1114
1265
 
1115
1266
  /** 从历史事件恢复上一步工具调用状态(扫描路径的幂等护栏)。 */