dsh-client-auto-continue 0.11.7 → 0.11.9

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.
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * The auto-continue settings card: edits the `auto-continue` namespace fields
3
- * from the plugin-configuration section (the `settings.plugin.item` seat).
3
+ * from the legacy settings section or the bundle's plugin-manager page.
4
4
  *
5
5
  * Self-contained card chrome (disclosure header, staged fields, save/discard
6
6
  * footer) following the plugin-card store pattern of the DSH plugin
@@ -8,7 +8,7 @@
8
8
  * tokens so the card follows the active theme.
9
9
  */
10
10
  import { useEffect, useState, type ReactNode } from 'react';
11
- import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots';
11
+ import type { InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots';
12
12
  import { type AutoContinueSettings } from './engine.ts';
13
13
  import { createSnapshotStore, type SettingsScope, type SnapshotStore } from './dsh-store-compat.ts';
14
14
  import {
@@ -39,6 +39,8 @@ export interface AutoContinueSettingsCardState extends CardShell {
39
39
  paused: CardFieldState;
40
40
  continueText: CardFieldState;
41
41
  continueTextMaxTokens: CardFieldState;
42
+ resumeSilentTurns: CardFieldState;
43
+ continueTextSilent: CardFieldState;
42
44
  guardTools: CardFieldState;
43
45
  guardPendingText: CardFieldState;
44
46
  guardDoneText: CardFieldState;
@@ -84,6 +86,8 @@ export class AutoContinueSettingsCardController {
84
86
  booleanField('paused'),
85
87
  textField('continueText'),
86
88
  textField('continueTextMaxTokens'),
89
+ booleanField('resumeSilentTurns'),
90
+ textField('continueTextSilent'),
87
91
  booleanField('guardTools'),
88
92
  textField('guardPendingText'),
89
93
  textField('guardDoneText'),
@@ -116,6 +120,8 @@ export class AutoContinueSettingsCardController {
116
120
  paused: this.form.field('paused'),
117
121
  continueText: this.form.field('continueText'),
118
122
  continueTextMaxTokens: this.form.field('continueTextMaxTokens'),
123
+ resumeSilentTurns: this.form.field('resumeSilentTurns'),
124
+ continueTextSilent: this.form.field('continueTextSilent'),
119
125
  guardTools: this.form.field('guardTools'),
120
126
  guardPendingText: this.form.field('guardPendingText'),
121
127
  guardDoneText: this.form.field('guardDoneText'),
@@ -148,11 +154,25 @@ export class AutoContinueSettingsCardController {
148
154
  inject(): AutoContinueSettingsCardFace {
149
155
  return { hooks: { autoContinueSettingsCard: this.store }, ...this.form.actions() };
150
156
  }
157
+
158
+ /** Release this card's subscription to the provider-owned settings form. */
159
+ dispose(): void {
160
+ this.form.dispose();
161
+ }
151
162
  }
152
163
 
153
164
  /** Props the renderer binds for the auto-continue plugin-configuration card. */
154
165
  export type AutoContinueSettingsCardProps =
155
- PropsRuntime<'settings.plugin.item'> & PropsLocale<'auto-continue'> & InjectFace<AutoContinueSettingsCardFace>;
166
+ PropsLocale<'auto-continue'> & InjectFace<AutoContinueSettingsCardFace>;
167
+
168
+ /** The bundle page supplies no list container, unlike the legacy settings slot. */
169
+ export function AutoContinueSettingsPage(props: AutoContinueSettingsCardProps) {
170
+ return (
171
+ <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
172
+ <AutoContinueSettingsCard {...props} />
173
+ </ul>
174
+ );
175
+ }
156
176
 
157
177
  const REPOSITORY_URL = 'https://github.com/HsiangNianian/dsh-auto-continue';
158
178
  const REPOSITORY_SLUG = 'HsiangNianian/dsh-auto-continue';
@@ -579,6 +599,27 @@ export function AutoContinueSettingsCard(props: AutoContinueSettingsCardProps) {
579
599
  placeholder={t('default.continueTextMaxTokens')}
580
600
  onReset={() => props.resetField('continueTextMaxTokens')}
581
601
  />
602
+ <BooleanField
603
+ wide
604
+ id="auto-continue-resume-silent-turns"
605
+ label={t('field.resumeSilentTurns')}
606
+ hint={t('field.resumeSilentTurnsHint')}
607
+ {...shared}
608
+ {...state.resumeSilentTurns}
609
+ onEdit={(text) => props.edit('resumeSilentTurns', text)}
610
+ onReset={() => props.resetField('resumeSilentTurns')}
611
+ />
612
+ <ValueField
613
+ wide
614
+ id="auto-continue-continue-text-silent"
615
+ label={t('field.continueTextSilent')}
616
+ hint={t('field.continueTextSilentHint')}
617
+ {...shared}
618
+ {...state.continueTextSilent}
619
+ onEdit={(text) => props.edit('continueTextSilent', text)}
620
+ placeholder={t('default.continueTextSilent')}
621
+ onReset={() => props.resetField('continueTextSilent')}
622
+ />
582
623
  </SettingsSection>
583
624
 
584
625
  <SettingsSection
@@ -128,6 +128,7 @@ export class CardForm<T> {
128
128
  private readonly specs: Map<string, CardFieldSpec>;
129
129
  private readonly staged = new Map<string, StagedEdit>();
130
130
  private readonly listeners = new Set<() => void>();
131
+ private readonly unsubscribe: () => void;
131
132
  private saving = false;
132
133
  private failed = false;
133
134
 
@@ -140,7 +141,13 @@ export class CardForm<T> {
140
141
  specs: CardFieldSpec[],
141
142
  ) {
142
143
  this.specs = new Map(specs.map((spec) => [spec.field, spec]));
143
- this.scope.subscribe(() => this.publish());
144
+ this.unsubscribe = this.scope.subscribe(() => this.publish());
145
+ }
146
+
147
+ /** Release this editor's listeners without disposing the provider's shared form. */
148
+ dispose(): void {
149
+ this.unsubscribe();
150
+ this.listeners.clear();
144
151
  }
145
152
 
146
153
  /** Publish a projection of this form, rebuilt whenever the scope or a draft changes. */
@@ -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';
@@ -201,10 +202,13 @@ export class AutoContinueRunner {
201
202
  private readonly disposeSessionEvents: () => void;
202
203
  private readonly disposeInboxEvents: () => void;
203
204
  private disposed = false;
205
+ private readonly bootScannedSessions = new WeakSet<Session>();
206
+ private bootScanTimer: ReturnType<typeof setTimeout> | undefined;
207
+ private wakeBootScan: (() => void) | undefined;
204
208
 
205
209
  /**
206
- * @param ctx - host plugin context (agents registry, session events, settings).
207
- * @param getConfig - read the current resolved configuration (settings service).
210
+ * @param ctx - host plugin context (agents registry, session events).
211
+ * @param getConfig - read the current resolved configuration (entry config).
208
212
  */
209
213
  constructor(
210
214
  private readonly ctx: Context,
@@ -326,6 +330,10 @@ export class AutoContinueRunner {
326
330
  dispose(): void {
327
331
  if (this.disposed) return;
328
332
  this.disposed = true;
333
+ if (this.bootScanTimer !== undefined) clearTimeout(this.bootScanTimer);
334
+ this.bootScanTimer = undefined;
335
+ this.wakeBootScan?.();
336
+ this.wakeBootScan = undefined;
329
337
  this.disposeSessionEvents();
330
338
  this.disposeInboxEvents();
331
339
  this.prioritizedFollowups.clear();
@@ -363,24 +371,58 @@ export class AutoContinueRunner {
363
371
  if (event.type === 'tool/call') {
364
372
  const state = this.state(sessionId);
365
373
  // 任何新鲜调用都代表进展(即使缺关联 id);旧帧重放不能清短句 streak。
366
- if (state.tools.recordCall(event)) state.shortRun = 0;
374
+ if (state.tools.recordCall(event)) {
375
+ state.shortRun = 0;
376
+ if (this.tracksOutput(state, event)) state.turnOutput = 'visible';
377
+ }
367
378
  } else if (event.type === 'tool/result') {
368
379
  const state = this.state(sessionId);
369
380
  state.tools.recordResult(event);
370
381
  } else if (event.type === 'step/start') {
371
382
  const state = this.state(sessionId);
383
+ if (this.tracksOutput(state, event) && state.turnOutput === 'empty') state.turnOutput = 'silent';
372
384
  const repeat = state.tools.confirmRepeatAtStep(event.seq);
373
385
  if (repeat !== undefined) this.checkLoop(sessionId, state, repeat);
374
386
  } else if (event.type === 'assistant/chunk') {
375
387
  const state = this.state(sessionId);
388
+ if (this.tracksOutput(state, event)) {
389
+ const chunk = event.data.chunk;
390
+ const visible = (chunk.type === 'text-delta' && chunk.text.trim() !== '') ||
391
+ chunk.type === 'tool-call-delta' ||
392
+ (chunk.type === 'block-end' && this.hasVisibleContent([chunk.block])) ||
393
+ (chunk.type === 'block-start' && chunk.blockType !== 'reasoning' && chunk.blockType !== 'text');
394
+ if (visible) state.turnOutput = 'visible';
395
+ else if (state.turnOutput === 'empty' && chunk.type !== 'usage' && chunk.type !== 'finish') state.turnOutput = 'silent';
396
+ }
376
397
  this.onAssistantChunk(sessionId, state, event);
377
398
  } else if (event.type === 'assistant/message') {
378
399
  const state = this.state(sessionId);
400
+ if (this.tracksOutput(state, event)) {
401
+ if (this.hasVisibleContent(event.data.message.content)) state.turnOutput = 'visible';
402
+ else if (state.turnOutput === 'empty') state.turnOutput = 'silent';
403
+ }
379
404
  this.onAssistantMessage(sessionId, state, event);
380
405
  }
381
406
  this.onSessionEvent(sessionId, event);
382
407
  }
383
408
 
409
+ private tracksOutput(state: SessionState, event: SessionEvent): boolean {
410
+ return state.running === true && state.outputTurn === (event.data as { turn?: number }).turn &&
411
+ event.seq > state.outputStartSeq;
412
+ }
413
+
414
+ /** Treat unknown block kinds conservatively: only reasoning and blank text are silent. */
415
+ private hasVisibleContent(content: unknown): boolean {
416
+ if (!Array.isArray(content)) return false;
417
+ return content.some((part: unknown) => {
418
+ if (part === null || typeof part !== 'object') return true;
419
+ const block = part as { type?: unknown; text?: unknown };
420
+ if (block.type === 'reasoning') return false;
421
+ if (block.type === 'text') return typeof block.text !== 'string' || block.text.trim() !== '';
422
+ return true;
423
+ });
424
+ }
425
+
384
426
  /** 从 assistant/message 事件提取纯文本。 */
385
427
  private assistantText(event: SessionEvent<'assistant/message'>): string {
386
428
  const content = event.data.message.content;
@@ -601,6 +643,9 @@ export class AutoContinueRunner {
601
643
  state.streamLastSegment = '';
602
644
  state.streamRepeatRun = 0;
603
645
  state.loopFired = false;
646
+ state.turnOutput = 'empty';
647
+ state.outputTurn = event.data.turn;
648
+ state.outputStartSeq = event.seq;
604
649
  if (state.loopRetryTimer !== undefined) {
605
650
  clearTimeout(state.loopRetryTimer);
606
651
  state.loopRetryTimer = undefined;
@@ -612,17 +657,34 @@ export class AutoContinueRunner {
612
657
  const loopCancelPending = state.loopFired;
613
658
  state.loopFired = false;
614
659
  this.cancelPending(sessionId, '收到新的 turn/end');
660
+ const turnOutput = state.outputTurn === event.data.turn ? state.turnOutput : 'unknown';
661
+ state.turnOutput = 'unknown';
662
+ state.outputTurn = undefined;
615
663
  const reason = event.data.reason;
616
664
  const reasonKind = readReasonKind(reason);
617
665
  if (reasonKind === undefined) {
618
666
  console.error(`[auto-continue] 忽略畸形 turn/end ${sessionId}: reason 无法解释`);
619
667
  break;
620
668
  }
621
- if (reasonKind === 'completed') {
622
- // 成功回合: 恢复健康状态, 并确认上一次自动发送的效果
623
- state.consecutive = 0;
669
+ if (reasonKind === 'no-visible-output' || (reasonKind === 'completed' && turnOutput === 'silent')) {
670
+ // 已观察到模型活动但没有可见输出; 没有模型活动的空回合不属于此类。
671
+ // 不清零 consecutive: 每轮都卡住的模型仍受冷却与连续上限约束。
672
+ // `no-visible-output` 是 DSH 为同一种回合提议的结束原因, 按同样方式处理。
624
673
  state.lastFailure = undefined;
625
- this.noteRecovery(sessionId, 'completed');
674
+ state.lastTurn = event.data.turn;
675
+ state.lastFailureAt = Date.now();
676
+ this.noteRecovery(sessionId, 'error');
677
+ if (this.getConfig().resumeSilentTurns) this.schedule(sessionId, `turn/end:${reasonKind}:silent`);
678
+ break;
679
+ }
680
+ if (reasonKind === 'completed') {
681
+ // Only observed visible output proves recovery; no-op and unknown
682
+ // turns must not erase the retry budget or count as successful.
683
+ if (turnOutput === 'visible') {
684
+ state.consecutive = 0;
685
+ state.lastFailure = undefined;
686
+ this.noteRecovery(sessionId, 'completed');
687
+ }
626
688
  } else if (reasonKind === 'aborted') {
627
689
  if (isLoopGuardCancelReason((reason as { reason?: unknown }).reason)) {
628
690
  // 我们自己的 loop guard 打断: 视为可恢复中断, 用循环提示文本重启回合。
@@ -650,7 +712,7 @@ export class AutoContinueRunner {
650
712
  } catch (error) {
651
713
  console.error(`[auto-continue] loop 重启异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
652
714
  }
653
- }, remaining);
715
+ }, 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
716
  this.log(`loop 重启延迟 ${remaining}ms(冷却期) ${sessionId}`);
655
717
  } else {
656
718
  this.schedule(sessionId, 'loop:aborted');
@@ -862,16 +924,20 @@ export class AutoContinueRunner {
862
924
  }
863
925
  }, config.graceMs);
864
926
  state.pendingTimer = timer;
865
- const template = reason.startsWith('loop:')
866
- ? config.loopText
867
- : reason.includes('max-tokens')
868
- ? config.continueTextMaxTokens
869
- : config.continueText;
927
+ const template = this.templateFor(config, reason);
870
928
  this.log(
871
929
  `检测到非人为中断 ${sessionId}(${reason}), ${config.graceMs}ms 后自动发送「${template}」`,
872
930
  );
873
931
  }
874
932
 
933
+ /** 按调度原因选择续跑模板: loop 重启、无输出回合、max-tokens, 其余用通用继续文本。 */
934
+ private templateFor(config: AutoContinueConfig, reason: string): string {
935
+ if (reason.startsWith('loop:')) return config.loopText;
936
+ if (reason.endsWith(':silent')) return config.continueTextSilent;
937
+ if (reason.includes('max-tokens')) return config.continueTextMaxTokens;
938
+ return config.continueText;
939
+ }
940
+
875
941
  private cancelPending(sessionId: SessionId, why: string): void {
876
942
  const state = this.state(sessionId);
877
943
  if (state.pendingTimer === undefined) return;
@@ -884,6 +950,7 @@ export class AutoContinueRunner {
884
950
  if (this.disposed) return;
885
951
  const state = this.state(sessionId);
886
952
  const config = this.getConfig();
953
+ if (reason.endsWith(':silent') && !config.resumeSilentTurns) return;
887
954
  if (state.subagent) return; // 子代理会话由父代理处理, 不抢跑
888
955
  if (config.paused) {
889
956
  this.log(`跳过 ${sessionId}(${reason}): 全局暂停中`);
@@ -903,11 +970,7 @@ export class AutoContinueRunner {
903
970
  return;
904
971
  }
905
972
  // 模板填充: 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;
973
+ const template = this.templateFor(config, reason);
911
974
  const text = this.buildContinueText(config, state, template);
912
975
  // 发送: followup 负责唤醒; 同步 inbox 插入事件会在唤醒前把本消息移到已有队列之前。
913
976
  const agent = this.ctx.agents.get(sessionId);
@@ -1003,12 +1066,11 @@ export class AutoContinueRunner {
1003
1066
  }
1004
1067
 
1005
1068
  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) {
1069
+ // Sessions restored after this window are too old for startup recovery.
1070
+ // Keep polling only within that window, including while globally paused.
1071
+ const deadline = Date.now() + this.getConfig().freshMs;
1072
+ for (let attempt = 0; !this.disposed; attempt += 1) {
1073
+ if (attempt > 0 && Date.now() >= deadline) return;
1012
1074
  try {
1013
1075
  if (await this.scanInterrupted()) return;
1014
1076
  } catch (error) {
@@ -1016,100 +1078,110 @@ export class AutoContinueRunner {
1016
1078
  // 宿主未就绪时每 3s 重试; 只节流记录日志, 避免刷屏。
1017
1079
  if (attempt % 10 === 0) {
1018
1080
  this.log(
1019
- `扫描失败(${attempt + 1}/${attempts === Infinity ? '∞' : attempts}): ${
1081
+ `扫描失败(${attempt + 1}): ${
1020
1082
  error instanceof Error ? error.message : String(error)
1021
1083
  }`,
1022
1084
  );
1023
1085
  }
1024
1086
  }
1025
- if (attempt + 1 < attempts) await sleep(delayMs);
1087
+ const remaining = deadline - Date.now();
1088
+ if (this.disposed || remaining <= 0) return;
1089
+ await new Promise<void>((resolve) => {
1090
+ this.wakeBootScan = resolve;
1091
+ this.bootScanTimer = setTimeout(() => {
1092
+ this.bootScanTimer = undefined;
1093
+ this.wakeBootScan = undefined;
1094
+ resolve();
1095
+ }, Math.min(3000, remaining));
1096
+ });
1026
1097
  }
1027
1098
  }
1028
1099
 
1029
- /**
1030
- * 扫描最近中断过的会话: 最后回合以非人为原因结束, 且其后没有新回合或用户消息。
1031
- * @returns 是否成功完成一次扫描(宿主就绪)。
1032
- */
1100
+ /** Inspect newly available sessions; process each settled startup history once. */
1033
1101
  private async scanInterrupted(): Promise<boolean> {
1034
1102
  const config = this.getConfig();
1035
- if (config.paused) return true; // 全局暂停: 不做任何扫描
1036
- // 只扫 live agents(host 重启后 agent-loop 会 resume 崩溃会话, 冷会话无需处理)
1103
+ if (config.paused || !config.scanOnBoot) return false;
1037
1104
  const now = Date.now();
1038
1105
  const candidates: {
1039
- sessionId: SessionId;
1106
+ session: Session;
1040
1107
  events: readonly SessionEvent[];
1108
+ lastEnd: SessionEvent<'turn/end'>;
1109
+ reasonKind: string;
1110
+ failure?: FailureFacts;
1041
1111
  lastActivityAt: number;
1042
1112
  listIndex: number;
1043
1113
  }[] = [];
1044
1114
  for (const agent of this.ctx.agents.list()) {
1045
1115
  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;
1116
+ if (session.header.origin === 'subagent' || this.bootScannedSessions.has(session)) continue;
1117
+ const state = this.state(session.id);
1118
+ if (state.pendingTimer !== undefined || state.consecutive >= config.maxConsecutive) continue;
1068
1119
  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
1120
+ if (now < (this.pauseUntil.get(session.id) ?? 0)) continue;
1121
+ const events = snapshotSessionEvents(session);
1122
+ // A published session may still be waiting for its first history snapshot.
1123
+ if (events.length === 0) continue;
1072
1124
  let lastEnd: SessionEvent<'turn/end'> | undefined;
1073
1125
  for (let i = events.length - 1; i >= 0; i -= 1) {
1074
1126
  const event = events[i];
1075
- if (event !== undefined && event.type === 'turn/end') {
1076
- lastEnd = event;
1077
- break;
1078
- }
1127
+ if (event?.type === 'turn/end') { lastEnd = event; break; }
1079
1128
  }
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;
1129
+ const reasonKind = readReasonKind(lastEnd?.data.reason);
1130
+ const silent = reasonKind === 'no-visible-output' && config.resumeSilentTurns;
1131
+ const superseded = lastEnd !== undefined && events.some((event) =>
1132
+ event.seq > lastEnd!.seq && (event.type === 'turn/start' ||
1133
+ (event.type === 'user/message' && event.data.source.kind === 'user')),
1134
+ );
1135
+ if (lastEnd === undefined || reasonKind === undefined || (!isNonHumanReason(reasonKind) && !silent) ||
1136
+ lastEnd.time < now - config.freshMs || superseded) {
1137
+ this.bootScannedSessions.add(session);
1138
+ continue;
1092
1139
  }
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}), 交给恢复策略处理`);
1140
+ let failure: FailureFacts | undefined;
1098
1141
  if (reasonKind === 'error') {
1099
- const failure = parseFailureFacts((reason as { error?: unknown }).error);
1142
+ failure = parseFailureFacts((lastEnd.data.reason as { error?: unknown }).error);
1100
1143
  if (failure === undefined) {
1101
- console.error(`[auto-continue] 忽略畸形扫描 turn/end ${candidate.sessionId}: error details 无法解释`);
1144
+ this.bootScannedSessions.add(session);
1145
+ console.error(`[auto-continue] 忽略畸形扫描 turn/end ${session.id}: error details 无法解释`);
1146
+ continue;
1147
+ }
1148
+ if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
1149
+ this.bootScannedSessions.add(session);
1150
+ this.onTurnFailure(session.id, 'scan:turn/end:error', failure);
1102
1151
  continue;
1103
1152
  }
1153
+ }
1154
+ candidates.push({
1155
+ session, events, lastEnd, reasonKind, failure,
1156
+ lastActivityAt: events.reduce((latest, event) => Math.max(latest, event.time), 0),
1157
+ listIndex: candidates.length,
1158
+ });
1159
+ }
1160
+ // Limit recoveries, not healthy/permanent histories that cannot be resumed.
1161
+ candidates.sort((left, right) => right.lastActivityAt - left.lastActivityAt || left.listIndex - right.listIndex);
1162
+ for (const candidate of candidates.slice(0, config.scanLimit)) {
1163
+ if (this.disposed) return true;
1164
+ const { session, events, lastEnd, reasonKind, failure } = candidate;
1165
+ this.bootScannedSessions.add(session);
1166
+ const state = this.state(session.id);
1167
+ this.applyGuardFromEvents(state, events, lastEnd.seq);
1168
+ const scanReason = `scan:turn/end:${reasonKind}${reasonKind === 'no-visible-output' ? ':silent' : ''}`;
1169
+ this.log(`扫描发现中断 ${session.id}(turn/end:${reasonKind}), 交给恢复策略处理`);
1170
+ if (failure !== undefined) {
1104
1171
  state.lastFailure = failure;
1105
1172
  state.lastTurn = lastEnd.data.turn;
1106
1173
  state.lastFailureAt = lastEnd.time;
1107
- this.onTurnFailure(candidate.sessionId, scanReason, state.lastFailure);
1174
+ this.onTurnFailure(session.id, scanReason, failure);
1108
1175
  } else {
1109
- this.schedule(candidate.sessionId, scanReason);
1176
+ if (reasonKind === 'no-visible-output') {
1177
+ state.lastFailure = undefined;
1178
+ state.lastTurn = lastEnd.data.turn;
1179
+ state.lastFailureAt = lastEnd.time;
1180
+ }
1181
+ this.schedule(session.id, scanReason);
1110
1182
  }
1111
1183
  }
1112
- return true;
1184
+ return false;
1113
1185
  }
1114
1186
 
1115
1187
  /** 从历史事件恢复上一步工具调用状态(扫描路径的幂等护栏)。 */