dsh-client-auto-continue 0.14.3 → 0.15.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.
@@ -7,6 +7,8 @@
7
7
  * paused-sessions list) consumed by the settings card's live panels.
8
8
  */
9
9
 
10
+ import type { RecoveryAttempt } from '../shared/core.ts';
11
+
10
12
  /** 今日统计视图(与 host 引擎的 DayStats 对应)。 */
11
13
  export interface DayStatsView {
12
14
  date: string;
@@ -28,6 +30,7 @@ export interface PausedSessionView {
28
30
  interface BridgeState {
29
31
  stats: DayStatsView;
30
32
  paused: PausedSessionView[];
33
+ recoveryAttempts: RecoveryAttempt[];
31
34
  }
32
35
 
33
36
  interface BridgeNotice {
@@ -50,7 +53,7 @@ const EMPTY_STATS: DayStatsView = {
50
53
  byCode: {},
51
54
  };
52
55
 
53
- let state: BridgeState = { stats: EMPTY_STATS, paused: [] };
56
+ let state: BridgeState = { stats: EMPTY_STATS, paused: [], recoveryAttempts: [] };
54
57
  const listeners = new Set<() => void>();
55
58
 
56
59
  /** 当前桥状态里的已暂停会话(卡片面板用)。 */
@@ -63,6 +66,10 @@ export function readTodayStats(): DayStatsView {
63
66
  return state.stats;
64
67
  }
65
68
 
69
+ export function readRecoveryAttempts(): RecoveryAttempt[] {
70
+ return state.recoveryAttempts;
71
+ }
72
+
66
73
  /** 清零今日统计(经动作端点交给 host 引擎执行)。 */
67
74
  export function resetTodayStats(): void {
68
75
  void postAction({ action: 'reset-stats' });
@@ -94,11 +101,12 @@ async function postAction(payload: { action: string; sessionId?: string }): Prom
94
101
  }
95
102
  }
96
103
 
97
- function handleEvent(event: { type: string; notice?: BridgeNotice; stats?: DayStatsView; paused?: PausedSessionView[] }): void {
104
+ function handleEvent(event: { type: string; notice?: BridgeNotice; stats?: DayStatsView; paused?: PausedSessionView[]; recoveryAttempts?: RecoveryAttempt[] }): void {
98
105
  if (event.type === 'state') {
99
106
  state = {
100
107
  stats: event.stats ?? EMPTY_STATS,
101
108
  paused: event.paused ?? [],
109
+ recoveryAttempts: event.recoveryAttempts ?? [],
102
110
  };
103
111
  for (const listener of listeners) listener();
104
112
  } else if (event.type === 'notice' && event.notice !== undefined) {
@@ -67,6 +67,7 @@ export const inject = ['slots', 'locale'];
67
67
  export {
68
68
  pausedSessions,
69
69
  readTodayStats,
70
+ readRecoveryAttempts,
70
71
  resetTodayStats,
71
72
  unpauseSession,
72
73
  } from './bridge.ts';
@@ -60,6 +60,9 @@ export const zh = {
60
60
  'field.continueTextSilent': '无输出回合的继续文本',
61
61
  'field.continueTextSilentHint': '回合只输出推理就结束时自动发送的文本, 支持与继续文本相同的占位符。',
62
62
  'default.continueTextSilent': LOCALIZED_TEXT_DEFAULTS.zh.continueTextSilent,
63
+ 'field.continueTextInterrupted': '宿主重启后恢复的继续文本',
64
+ 'field.continueTextInterruptedHint': '启动扫描恢复重启中断的会话时发送的文本, 默认说明重启并提醒先核实再重试。',
65
+ 'default.continueTextInterrupted': LOCALIZED_TEXT_DEFAULTS.zh.continueTextInterrupted,
63
66
  'field.guardTools': '幂等护栏',
64
67
  'field.guardToolsHint': '续跑前检查上一步工具调用: 结果未确认时提示先确认状态, 已成功时提示不要重复执行, 避免重复 commit/调 API。',
65
68
  'field.guardPendingText': '结果未确认时的护栏文本',
@@ -75,7 +78,7 @@ export const zh = {
75
78
  'field.maxConsecutive': '最大连续次数',
76
79
  'field.maxConsecutiveHint': '连续恢复尝试上限;用户介入或观察到有可见输出的成功回合后清零。正常完成后的自主循环接力不计入。',
77
80
  'field.scanOnBoot': '启动恢复扫描',
78
- 'field.scanOnBootHint': '宿主启动后在扫描时间窗内等待延迟加载的中断会话,每个已就绪会话只检查一次。',
81
+ 'field.scanOnBootHint': '宿主启动后在扫描时间窗内等待延迟加载的中断会话,未重新加载的持久化会话也会被物化一并检查,每个已就绪会话只检查一次。',
79
82
  'field.scanLimit': '扫描会话数',
80
83
  'field.scanLimitHint': '每次扫描最多恢复多少个符合条件的会话,优先最近活动的会话。',
81
84
  'field.freshMs': '扫描时间窗 (ms)',
@@ -118,6 +121,18 @@ export const zh = {
118
121
  'stats.byCode': '按错误码统计',
119
122
  'stats.empty': '今天还没有自动继续记录。',
120
123
  'stats.reset': '清零',
124
+ 'recovery.title': '近期恢复尝试',
125
+ 'recovery.hint': '按会话汇总宿主最近 20 次恢复提示,重启插件后清空。正常自主续跑不计入。提示已发送不代表任务已完成;若反复恢复,请检查会话并考虑交接到新会话。',
126
+ 'recovery.empty': '尚无恢复尝试。',
127
+ 'recovery.count': '窗口内尝试',
128
+ 'recovery.consecutive': '最近发送时连续次数',
129
+ 'recovery.latest': '最近原因',
130
+ 'recovery.reason.error': '请求错误',
131
+ 'recovery.reason.max-tokens': '输出上限',
132
+ 'recovery.reason.silent': '无可见输出',
133
+ 'recovery.reason.interrupted': '宿主重启中断',
134
+ 'recovery.reason.loop-guard': '循环守卫',
135
+ 'recovery.reason.manual': '手动立即续跑',
121
136
  'pause.title': '已暂停会话',
122
137
  'pause.none': '没有暂停中的会话。',
123
138
  'pause.clearAll': '全部解除',
@@ -197,6 +212,9 @@ export const en: Record<SettingsCardKey, string> = {
197
212
  'field.continueTextSilent': 'Continue text (silent turn)',
198
213
  'field.continueTextSilentHint': 'Text sent when a turn ends with reasoning only; same placeholders as the continue text.',
199
214
  'default.continueTextSilent': LOCALIZED_TEXT_DEFAULTS.en.continueTextSilent,
215
+ 'field.continueTextInterrupted': 'Continue text (after harness restart)',
216
+ 'field.continueTextInterruptedHint': 'Text sent when the boot scan resumes a session interrupted by a restart; the default explains the restart and asks to verify before retrying.',
217
+ 'default.continueTextInterrupted': LOCALIZED_TEXT_DEFAULTS.en.continueTextInterrupted,
200
218
  'field.guardTools': 'Idempotency guard',
201
219
  'field.guardToolsHint': 'Before resuming, inspect the last tool call: if its result is unconfirmed, tell the model to check state first; if it succeeded, tell it not to rerun — avoids duplicate commits / API calls.',
202
220
  'field.guardPendingText': 'Guard text (unconfirmed result)',
@@ -212,7 +230,7 @@ export const en: Record<SettingsCardKey, string> = {
212
230
  'field.maxConsecutive': 'Max consecutive',
213
231
  'field.maxConsecutiveHint': 'Consecutive recovery-attempt cap; resets on user intervention or an observed completion with visible output. Normal autonomous-loop handoffs are exempt.',
214
232
  'field.scanOnBoot': 'Scan on host startup',
215
- 'field.scanOnBootHint': 'Wait for delayed interrupted sessions during the startup scan window; inspect each settled session once.',
233
+ 'field.scanOnBootHint': 'Wait for delayed interrupted sessions during the startup scan window; persisted sessions the host never reloaded are materialized and inspected too; each settled session is inspected once.',
216
234
  'field.scanLimit': 'Scan limit',
217
235
  'field.scanLimitHint': 'Maximum eligible sessions to recover per pass, most recently active first.',
218
236
  'field.freshMs': 'Scan window (ms)',
@@ -255,6 +273,18 @@ export const en: Record<SettingsCardKey, string> = {
255
273
  'stats.byCode': 'By error code',
256
274
  'stats.empty': 'No auto-continue activity today.',
257
275
  'stats.reset': 'Reset',
276
+ 'recovery.title': 'Recent recovery attempts',
277
+ 'recovery.hint': 'Per-session counts from the last 20 recovery prompts across this host, cleared when the plugin restarts. Normal autonomous continuations are excluded. A sent prompt does not mean the task finished. If recovery keeps repeating, review the conversation and consider handing off to a fresh session.',
278
+ 'recovery.empty': 'No recovery attempts yet.',
279
+ 'recovery.count': 'Attempts in window',
280
+ 'recovery.consecutive': 'Consecutive at last send',
281
+ 'recovery.latest': 'Latest reason',
282
+ 'recovery.reason.error': 'Request error',
283
+ 'recovery.reason.max-tokens': 'Output limit',
284
+ 'recovery.reason.silent': 'No visible output',
285
+ 'recovery.reason.interrupted': 'Host restart interruption',
286
+ 'recovery.reason.loop-guard': 'Loop guard',
287
+ 'recovery.reason.manual': 'Manual resume',
258
288
  'pause.title': 'Paused sessions',
259
289
  'pause.none': 'No sessions paused.',
260
290
  'pause.clearAll': 'Clear all',
@@ -16,6 +16,7 @@ import { createSnapshotStore, type SettingsScope, type SnapshotStore } from './d
16
16
  import {
17
17
  pausedSessions,
18
18
  readTodayStats,
19
+ readRecoveryAttempts,
19
20
  resetTodayStats,
20
21
  subscribeBridge,
21
22
  unpauseSession,
@@ -52,6 +53,7 @@ export interface AutoContinueSettingsCardState extends CardShell {
52
53
  resumeCompletedTurns: CardFieldState;
53
54
  continueTextLoop: CardFieldState;
54
55
  continueTextSilent: CardFieldState;
56
+ continueTextInterrupted: CardFieldState;
55
57
  guardTools: CardFieldState;
56
58
  guardPendingText: CardFieldState;
57
59
  guardDoneText: CardFieldState;
@@ -111,6 +113,7 @@ export class AutoContinueSettingsCardController {
111
113
  booleanField('resumeCompletedTurns'),
112
114
  textField('continueTextLoop'),
113
115
  textField('continueTextSilent'),
116
+ textField('continueTextInterrupted'),
114
117
  booleanField('guardTools'),
115
118
  textField('guardPendingText'),
116
119
  textField('guardDoneText'),
@@ -151,6 +154,7 @@ export class AutoContinueSettingsCardController {
151
154
  resumeCompletedTurns: this.form.field('resumeCompletedTurns'),
152
155
  continueTextLoop: this.form.field('continueTextLoop'),
153
156
  continueTextSilent: this.form.field('continueTextSilent'),
157
+ continueTextInterrupted: this.form.field('continueTextInterrupted'),
154
158
  guardTools: this.form.field('guardTools'),
155
159
  guardPendingText: this.form.field('guardPendingText'),
156
160
  guardDoneText: this.form.field('guardDoneText'),
@@ -262,7 +266,7 @@ const groups = [
262
266
  { id: 'general', fields: ['paused', 'showComposerToggle', 'resumeSilentTurns', 'resumeCompletedTurns', 'notify'] },
263
267
  { id: 'recovery', fields: ['graceMs', 'cooldownMs', 'maxConsecutive', 'classify', 'retryableErrorPatterns', 'backoffFactor', 'backoffMaxMs'] },
264
268
  { id: 'startup', fields: ['scanOnBoot', 'scanLimit', 'freshMs'] },
265
- { id: 'prompts', fields: ['continueText', 'continueTextMaxTokens', 'continueTextSilent', 'continueTextLoop', 'guardPendingText', 'guardDoneText', 'loopText'] },
269
+ { id: 'prompts', fields: ['continueText', 'continueTextMaxTokens', 'continueTextSilent', 'continueTextInterrupted', 'continueTextLoop', 'guardPendingText', 'guardDoneText', 'loopText'] },
266
270
  { id: 'safety', fields: ['guardTools', 'loopGuard', 'loopShortChars', 'loopWindowMs', 'loopShortCount', 'loopRepeatText', 'loopToolRepeat'] },
267
271
  { id: 'status', fields: ['verbose'] },
268
272
  ] as const satisfies ReadonlyArray<{ id: string; fields: readonly FieldName[] }>;
@@ -270,6 +274,7 @@ type Category = typeof groups[number]['id'];
270
274
  const textDefaults: Partial<Record<FieldName, SettingsCardKey>> = {
271
275
  continueText: 'default.continueText', continueTextMaxTokens: 'default.continueTextMaxTokens',
272
276
  continueTextSilent: 'default.continueTextSilent', continueTextLoop: 'default.continueTextLoop',
277
+ continueTextInterrupted: 'default.continueTextInterrupted',
273
278
  guardPendingText: 'default.guardPendingText', guardDoneText: 'default.guardDoneText', loopText: 'default.loopText',
274
279
  };
275
280
 
@@ -334,6 +339,8 @@ function LivePanels(props: { t: (key: SettingsCardKey) => string }) {
334
339
  .sort((a, b) => b[1] - a[1])
335
340
  .slice(0, 5);
336
341
  const paused = pausedSessions();
342
+ const attempts = readRecoveryAttempts();
343
+ const sessions = [...new Set(attempts.map(attempt => attempt.sessionId))];
337
344
  return (
338
345
  <>
339
346
  <section className="dshAcPanel">
@@ -377,6 +384,30 @@ function LivePanels(props: { t: (key: SettingsCardKey) => string }) {
377
384
  </>
378
385
  )}
379
386
  </section>
387
+ <section className="dshAcPanel">
388
+ <div className="dshAcPanelHead">
389
+ <span className="dshAcPanelTitle">{t('recovery.title')}</span>
390
+ </div>
391
+ <p className="dshAcHint">{t('recovery.hint')}</p>
392
+ {sessions.length === 0 ? <p className="dshAcHint">{t('recovery.empty')}</p> : (
393
+ <ul className="dshAcPauseList">
394
+ {sessions.map(sessionId => {
395
+ const recent = attempts.filter(attempt => attempt.sessionId === sessionId);
396
+ const latest = recent[0]!;
397
+ return (
398
+ <li key={sessionId}>
399
+ <div className="dshAcRecovery">
400
+ <span className="dshAcPauseId">{sessionId}</span>
401
+ <span>{t('recovery.count')}: {recent.length} · {t('recovery.consecutive')}: {latest.consecutive}</span>
402
+ <span>{t('recovery.latest')}: {t(`recovery.reason.${latest.reason}`)}</span>
403
+ <time className="dshAcHint" dateTime={new Date(latest.at).toISOString()}>{new Date(latest.at).toLocaleString()}</time>
404
+ </div>
405
+ </li>
406
+ );
407
+ })}
408
+ </ul>
409
+ )}
410
+ </section>
380
411
  <section className="dshAcPanel">
381
412
  <div className="dshAcPanelHead">
382
413
  <span className="dshAcPanelTitle">{t('pause.title')}</span>
@@ -104,6 +104,7 @@ const css = `
104
104
  .dshAcPauseList { list-style: none; margin: 0; padding: 0; }
105
105
  .dshAcPauseList li { display: flex; align-items: center; gap: 12px; padding: 10px 0; }
106
106
  .dshAcPauseId { flex: 1; font: 12px ui-monospace, SFMono-Regular, monospace; }
107
+ .dshAcRecovery { display: grid; gap: 4px; min-width: 0; overflow-wrap: anywhere; }
107
108
  @container auto-continue-settings (max-width: 760px) {
108
109
  .dshAcHeaderFrame { grid-template-columns: minmax(0, 1fr) auto; gap: 16px; }
109
110
  .dshAcRepositoryCopy { display: none; }
@@ -17,7 +17,7 @@ import type { Context } from '@deepseek-ai/cordis';
17
17
  import { createUserMessage } from '@deepseek-ai/dsh-llm';
18
18
  import type { Agent } from '@deepseek-ai/dsh-agent';
19
19
  import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types';
20
- import type { Session } from '@deepseek-ai/dsh-session';
20
+ import { foldRequestHeader, type Session } from '@deepseek-ai/dsh-session';
21
21
  import {
22
22
  DEFAULT_CONFIG,
23
23
  RECOVERY_WINDOW_MS,
@@ -37,6 +37,7 @@ import {
37
37
  type AutoContinueConfig,
38
38
  type AutoContinueLocale,
39
39
  type DayStats,
40
+ type RecoveryAttempt,
40
41
  type FailureFacts,
41
42
  type SessionState,
42
43
  type NotifyAction,
@@ -93,6 +94,25 @@ const LOOP_GUARD_CANCEL_CAUSE = {
93
94
  const LOOP_COMPLETED_REASON = 'turn/end:completed';
94
95
  const LOOP_SILENT_REASON = 'turn/end:loop-silent';
95
96
  const MANUAL_NOTIFICATION_REASON = 'manual:notification';
97
+
98
+ /** Yield between storage batches without spending a live-scan polling interval. */
99
+ const SWEEP_OBSERVE_BATCH = 16;
100
+ const STORED_READ_TIMEOUT_MS = 5000;
101
+ /** 单个存储会话连续观察/物化失败达此数后放弃, 避免坏日志反复占满每轮观察配额。 */
102
+ const SWEEP_MAX_FAILURES = 3;
103
+
104
+ /**
105
+ * 存储扫描消费的宿主服务结构类型。这些服务(sessionQuery 等)随 dsh
106
+ * 版本整组演进, 直接引类型包会拖动 devDependency 时代; 按消费面声明,
107
+ * 缺服务的宿主在运行时禁用存储扫描即可。
108
+ */
109
+ interface StoredObservation {
110
+ readonly events: readonly SessionEvent[];
111
+ readonly header: { readonly id?: SessionId; readonly origin?: string; readonly agentPreset?: string };
112
+ readonly projections?: { readonly values: { readonly agentPreset?: string } };
113
+ [Symbol.dispose]?: () => void;
114
+ }
115
+
96
116
  const isLoopReason = (reason: string): boolean =>
97
117
  reason === LOOP_COMPLETED_REASON || reason === LOOP_SILENT_REASON;
98
118
 
@@ -133,6 +153,10 @@ function snapshotSessionEvents(session: Session): readonly SessionEvent[] {
133
153
  const compatible = session as CompatibleSession;
134
154
  const snapshot = compatible.snapshotEvents;
135
155
  const events = typeof snapshot === 'function' ? snapshot.call(session) : compatible.events;
156
+ return validateSessionEvents(events);
157
+ }
158
+
159
+ function validateSessionEvents(events: unknown): readonly SessionEvent[] {
136
160
  if (!Array.isArray(events)) throw new TypeError('session history is not an event array');
137
161
  // Do not filter damaged entries: one could have been a manual stop, newer turn,
138
162
  // or tool result. An incomplete history is not safe evidence for a continuation.
@@ -226,6 +250,7 @@ export class AutoContinueRunner {
226
250
  private readonly states = new Map<SessionId, SessionState>();
227
251
  private readonly pauseUntil = new Map<SessionId, number>();
228
252
  private dayStats: DayStats = emptyDayStats();
253
+ private readonly recoveryAttempts: RecoveryAttempt[] = [];
229
254
  private readonly notices: HostNotice[] = [];
230
255
  private readonly noticeListeners = new Set<() => void>();
231
256
  private readonly stateListeners = new Set<() => void>();
@@ -236,8 +261,15 @@ export class AutoContinueRunner {
236
261
  private readonly bootScannedSessions = new WeakSet<Session>();
237
262
  /** Also bound diagnostics when even an agent's session getter is unavailable. */
238
263
  private readonly bootScanErrors = new WeakSet<object>();
264
+ /** 存储扫描已裁决的会话 id, 避免每轮重复冷读大日志。 */
265
+ private readonly storedSwept = new Set<SessionId>();
266
+ /** 存储会话的连续观察/物化失败次数, 触达 SWEEP_MAX_FAILURES 后不再重试。 */
267
+ private readonly storedSweepFailures = new Map<SessionId, number>();
268
+ private storedSweepAnnounced = false;
239
269
  private bootScanTimer: ReturnType<typeof setTimeout> | undefined;
240
270
  private wakeBootScan: (() => void) | undefined;
271
+ private storedSweep: Promise<void> | undefined;
272
+ private readonly stopStoredSweep = new AbortController();
241
273
 
242
274
  /**
243
275
  * @param ctx - host plugin context (agents registry, session events).
@@ -311,6 +343,10 @@ export class AutoContinueRunner {
311
343
  return { ...this.dayStats, byCode: { ...this.dayStats.byCode } };
312
344
  }
313
345
 
346
+ recentRecoveryAttempts(): RecoveryAttempt[] {
347
+ return this.recoveryAttempts.map(attempt => ({ ...attempt }));
348
+ }
349
+
314
350
  /** 对外(状态桥): 当前生效的会话级暂停列表。 */
315
351
  activePauses(): { sessionId: SessionId; until: number }[] {
316
352
  const now = Date.now();
@@ -363,6 +399,7 @@ export class AutoContinueRunner {
363
399
  dispose(): void {
364
400
  if (this.disposed) return;
365
401
  this.disposed = true;
402
+ this.stopStoredSweep.abort();
366
403
  if (this.bootScanTimer !== undefined) clearTimeout(this.bootScanTimer);
367
404
  this.bootScanTimer = undefined;
368
405
  this.wakeBootScan?.();
@@ -861,13 +898,14 @@ export class AutoContinueRunner {
861
898
  /** 通知操作按钮与回调(「立即续跑」/「暂停该会话 1 小时」)。 */
862
899
  private notifyOptions(sessionId: SessionId, locale: AutoContinueLocale): NotifyOptions {
863
900
  const copy = NOTICE_COPY[locale];
864
- return {
865
- actions: [
901
+ // 未物化的存储会话没有 live agent, 「立即续跑」只会空转; 只保留暂停。
902
+ const actions: NotifyAction[] = this.ctx.agents.get(sessionId) === undefined
903
+ ? [{ action: 'pause1h', title: copy.pauseAction }]
904
+ : [
866
905
  { action: 'resume', title: copy.resumeAction },
867
906
  { action: 'pause1h', title: copy.pauseAction },
868
- ],
869
- onAction: (action) => this.onNotifyAction(sessionId, action),
870
- };
907
+ ];
908
+ return { actions, onAction: (action) => this.onNotifyAction(sessionId, action) };
871
909
  }
872
910
 
873
911
  private onNotifyAction(sessionId: SessionId, action: string): void {
@@ -1043,6 +1081,7 @@ export class AutoContinueRunner {
1043
1081
  if (isLoopReason(reason)) return config.continueTextLoop;
1044
1082
  if (reason.endsWith(':silent')) return config.continueTextSilent;
1045
1083
  if (reason.includes('max-tokens')) return config.continueTextMaxTokens;
1084
+ if (reason.includes('interrupted')) return config.continueTextInterrupted;
1046
1085
  return config.continueText;
1047
1086
  }
1048
1087
 
@@ -1120,6 +1159,17 @@ export class AutoContinueRunner {
1120
1159
  // 自主循环的成功续跑不计入连续上限: 上限只约束失败(网络中断等)。
1121
1160
  if (reason !== LOOP_COMPLETED_REASON) state.consecutive += 1;
1122
1161
  state.pendingRecoveryAt = now; // 等待窗口内的下一个回合结束来判定恢复结果
1162
+ if (reason !== LOOP_COMPLETED_REASON) {
1163
+ this.recoveryAttempts.unshift({
1164
+ sessionId, at: now, consecutive: state.consecutive,
1165
+ reason: manualResume ? 'manual'
1166
+ : reason === 'loop:aborted' ? 'loop-guard'
1167
+ : reason.endsWith(':silent') || reason === LOOP_SILENT_REASON ? 'silent'
1168
+ : reason.endsWith(':interrupted') ? 'interrupted'
1169
+ : reason.endsWith(':max-tokens') ? 'max-tokens' : 'error',
1170
+ });
1171
+ this.recoveryAttempts.length = Math.min(this.recoveryAttempts.length, 20);
1172
+ }
1123
1173
  this.bumpStat({ sent: 1, ...(state.lastFailure !== undefined ? { code: state.lastFailure.code } : {}) });
1124
1174
  this.log(`已自动发送「${text}」到 ${sessionId}(${reason}), 第 ${state.consecutive} 次连续`);
1125
1175
  if (config.notify) {
@@ -1195,6 +1245,14 @@ export class AutoContinueRunner {
1195
1245
  if (attempt > 0 && Date.now() >= deadline) return;
1196
1246
  try {
1197
1247
  if (await this.scanInterrupted()) return;
1248
+ const config = this.getConfig();
1249
+ if (!config.paused && config.scanOnBoot && this.storedSweep === undefined) {
1250
+ this.storedSweep = this.sweepStoredSessions(config, deadline)
1251
+ .catch(error => {
1252
+ if (!this.disposed) this.ctx.logger.error(`Stored session scan failed: ${String(error)}`);
1253
+ })
1254
+ .finally(() => { this.storedSweep = undefined; });
1255
+ }
1198
1256
  } catch (error) {
1199
1257
  if (this.disposed) return;
1200
1258
  // 宿主未就绪时每 3s 重试; 只节流记录日志, 避免刷屏。
@@ -1209,12 +1267,13 @@ export class AutoContinueRunner {
1209
1267
  const remaining = deadline - Date.now();
1210
1268
  if (this.disposed || remaining <= 0) return;
1211
1269
  await new Promise<void>((resolve) => {
1212
- this.wakeBootScan = resolve;
1213
- this.bootScanTimer = setTimeout(() => {
1270
+ this.wakeBootScan = () => {
1271
+ if (this.bootScanTimer !== undefined) clearTimeout(this.bootScanTimer);
1214
1272
  this.bootScanTimer = undefined;
1215
1273
  this.wakeBootScan = undefined;
1216
1274
  resolve();
1217
- }, Math.min(3000, remaining));
1275
+ };
1276
+ this.bootScanTimer = setTimeout(this.wakeBootScan, Math.min(3000, remaining));
1218
1277
  });
1219
1278
  }
1220
1279
  }
@@ -1314,11 +1373,10 @@ export class AutoContinueRunner {
1314
1373
  state.lastFailureAt = lastEnd.time;
1315
1374
  this.onTurnFailure(sessionId, scanReason, failure);
1316
1375
  } else {
1317
- if (reasonKind === 'no-visible-output') {
1318
- state.lastFailure = undefined;
1319
- state.lastTurn = lastEnd.data.turn;
1320
- state.lastFailureAt = lastEnd.time;
1321
- }
1376
+ if (reasonKind === 'no-visible-output') state.lastFailure = undefined;
1377
+ // 没有失败事实的恢复(如 interrupted)也要填 {turn}/{elapsed}, README 对所有继续文本承诺这些占位符。
1378
+ state.lastTurn = lastEnd.data.turn;
1379
+ state.lastFailureAt = lastEnd.time;
1322
1380
  this.schedule(sessionId, scanReason);
1323
1381
  }
1324
1382
  recoveries += 1;
@@ -1331,6 +1389,189 @@ export class AutoContinueRunner {
1331
1389
  return false;
1332
1390
  }
1333
1391
 
1392
+ /** Bound cold reads even if a backend ignores cancellation; release late leases. */
1393
+ private async readStored<T extends object>(read: (signal: AbortSignal) => Promise<T>, deadline: number): Promise<T> {
1394
+ const timeout = new AbortController();
1395
+ const signal = AbortSignal.any([this.stopStoredSweep.signal, timeout.signal]);
1396
+ const timer = setTimeout(() => timeout.abort(new Error('Stored session read timed out')), Math.max(0, Math.min(STORED_READ_TIMEOUT_MS, deadline - Date.now())));
1397
+ let onAbort: () => void;
1398
+ const cancelled = new Promise<never>((_resolve, reject) => {
1399
+ onAbort = () => reject(signal.reason);
1400
+ signal.addEventListener('abort', onAbort, { once: true });
1401
+ if (signal.aborted) onAbort();
1402
+ });
1403
+ const pending = Promise.resolve().then(() => { signal.throwIfAborted(); return read(signal); });
1404
+ void pending.then(value => {
1405
+ if (signal.aborted) (value as { [Symbol.dispose]?: () => void })[Symbol.dispose]?.();
1406
+ }).catch(() => {});
1407
+ try {
1408
+ return await Promise.race([pending, cancelled]);
1409
+ } finally {
1410
+ clearTimeout(timer);
1411
+ signal.removeEventListener('abort', onAbort!);
1412
+ }
1413
+ }
1414
+
1415
+ /**
1416
+ * 存储扫描: 枚举持久化会话, 把尾部命中恢复谓词的未加载会话物化为
1417
+ * live agent。宿主重启后 agent 仅在客户端打开会话时才懒加载, 不物化
1418
+ * 则启动扫描永远看不到它们; 谓词与上方扫描一致, 仅失败类原因。
1419
+ */
1420
+ private async sweepStoredSessions(config: AutoContinueConfig, deadline: number): Promise<void> {
1421
+ const query = this.ctx.get('sessionQuery');
1422
+ if (query === undefined) return;
1423
+ const records = await this.readStored(signal => query.listSessions(signal), deadline);
1424
+ if (!Array.isArray(records)) throw new TypeError('stored session listing is not an array');
1425
+ if (!this.storedSweepAnnounced) {
1426
+ this.storedSweepAnnounced = true;
1427
+ this.ctx.logger.info(`存储扫描就绪: ${records.length} 个会话记录`);
1428
+ }
1429
+ let observed = 0;
1430
+ for (const record of records) {
1431
+ if (this.disposed || Date.now() >= deadline || this.getConfig().paused || !this.getConfig().scanOnBoot) return;
1432
+ if (typeof record?.header?.id !== 'string' || record.header.id === '') {
1433
+ this.logBootScanFailure(undefined, new TypeError('stored session record has no id'));
1434
+ continue;
1435
+ }
1436
+ const sessionId = record.header.id;
1437
+ if (record.live || this.storedSwept.has(sessionId)) continue;
1438
+ this.storedSwept.add(sessionId);
1439
+ if (record.header.origin === 'subagent') continue;
1440
+ observed += 1;
1441
+ let observation: StoredObservation | undefined;
1442
+ try {
1443
+ const stored: StoredObservation = await this.readStored(signal => query.observeSession(sessionId, { projectionMode: 'all', signal }), deadline);
1444
+ observation = stored;
1445
+ if (this.disposed) return;
1446
+ const events = validateSessionEvents(stored.events);
1447
+ if (events.length === 0) continue;
1448
+ // 快照之后客户端可能已打开该会话: 归还 live 扫描, 避免与 live 路径
1449
+ // 重复上报, 也避免物化撞上写归属。
1450
+ if (this.ctx.agents.get(sessionId) !== undefined) continue;
1451
+ let lastEnd: SessionEvent<'turn/end'> | undefined;
1452
+ for (let i = events.length - 1; i >= 0; i -= 1) {
1453
+ const event = events[i];
1454
+ if (event?.type === 'turn/end') { lastEnd = event; break; }
1455
+ }
1456
+ let lastStart: SessionEvent<'turn/start'> | undefined;
1457
+ for (let i = events.length - 1; i >= 0; i -= 1) {
1458
+ const event = events[i];
1459
+ if (event?.type === 'turn/start') { lastStart = event; break; }
1460
+ }
1461
+ // 兜底分支: 真实 sessionQuery 冷读会把内存中的 interruptedTurnClosers
1462
+ // 折叠进返回日志(尾部即合成 turn/end), 上方 closed-tail 才是生产主路
1463
+ // 径。这里覆盖两种例外——不折叠的宿主实现, 以及 listSessions 快照与
1464
+ // observeSession 之间客户端刚打开、切在轮次中间的 live 视图。
1465
+ const openTurn = lastStart !== undefined && (lastEnd === undefined || lastStart.seq > lastEnd.seq);
1466
+ let reasonKind: string | undefined;
1467
+ let freshAt: number;
1468
+ if (openTurn) {
1469
+ reasonKind = 'interrupted';
1470
+ freshAt = events[events.length - 1]?.time ?? 0;
1471
+ } else {
1472
+ reasonKind = readReasonKind(lastEnd?.data.reason);
1473
+ freshAt = lastEnd?.time ?? 0;
1474
+ }
1475
+ // 过期或被取代的永久错误与 live 扫描一致地静默跳过, 不再单独上报。
1476
+ if (reasonKind === undefined || freshAt < Date.now() - config.freshMs) continue;
1477
+ if (reasonKind !== undefined && !openTurn) {
1478
+ const silent = reasonKind === 'no-visible-output' && config.resumeSilentTurns;
1479
+ // 尾随 turn/start 已按 openTurn 处理, 这里只剩用户接管一种取代形态。
1480
+ const superseded = events.some((event) =>
1481
+ lastEnd !== undefined && event.seq > lastEnd.seq && event.type === 'user/message' && event.data.source.kind === 'user',
1482
+ );
1483
+ if ((!isNonHumanReason(reasonKind) && !silent) || superseded) continue;
1484
+ // 镜像 live 扫描的裁决: 畸形/永久错误不值得物化——物化后同样会被拦下。
1485
+ if (reasonKind === 'error') {
1486
+ const failure = parseFailureFacts((lastEnd!.data.reason as { error?: unknown }).error);
1487
+ if (failure === undefined) {
1488
+ console.error(`[auto-continue] 忽略畸形存储 turn/end ${sessionId}: error details 无法解释`);
1489
+ continue;
1490
+ }
1491
+ // 永久错误同样走 onTurnFailure, 镜像 live 路径的统计与通知旁效。
1492
+ if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
1493
+ this.onTurnFailure(sessionId, 'sweep:turn/end:error', failure);
1494
+ continue;
1495
+ }
1496
+ }
1497
+ }
1498
+ const presetId = stored.projections?.values.agentPreset ?? stored.header.agentPreset;
1499
+ const loggedConfig = foldRequestHeader(events)?.config;
1500
+ if (!await this.materializeStored(
1501
+ sessionId,
1502
+ presetId,
1503
+ loggedConfig === undefined ? undefined : { provider: loggedConfig.provider, model: loggedConfig.model },
1504
+ )) {
1505
+ this.storedSwept.delete(sessionId);
1506
+ return;
1507
+ }
1508
+ this.storedSweepFailures.delete(sessionId);
1509
+ this.wakeBootScan?.();
1510
+ this.ctx.logger.info(openTurn
1511
+ ? `扫描物化存储会话 ${sessionId}(日志止于 turn/start, 视作 interrupted), 交给启动扫描接管`
1512
+ : `扫描物化存储会话 ${sessionId}(turn/end:${reasonKind}), 交给启动扫描接管`);
1513
+ } catch (error) {
1514
+ if (this.disposed) return;
1515
+ // 观察或物化失败允许下一轮重试; 连续触达上限后放弃, 并清掉计数——
1516
+ // 已永久跳过的会话不再进入该映射, 不给长存活宿主留死重。
1517
+ const failures = (this.storedSweepFailures.get(sessionId) ?? 0) + 1;
1518
+ if (failures < SWEEP_MAX_FAILURES) {
1519
+ this.storedSweepFailures.set(sessionId, failures);
1520
+ this.storedSwept.delete(sessionId);
1521
+ } else {
1522
+ this.storedSweepFailures.delete(sessionId);
1523
+ }
1524
+ this.ctx.logger.error(`存储会话 ${sessionId} 物化失败: ${error instanceof Error ? error.message : String(error)}`);
1525
+ } finally {
1526
+ observation?.[Symbol.dispose]?.();
1527
+ if (observed % SWEEP_OBSERVE_BATCH === 0 && !this.disposed) {
1528
+ await new Promise<void>(resolve => setTimeout(resolve, 0));
1529
+ }
1530
+ }
1531
+ }
1532
+ }
1533
+
1534
+ /**
1535
+ * 按会话记录的 preset 组合把存储会话恢复为 live agent(镜像会话控制
1536
+ * 器的 adopt 路径: preset 挂载 + 会话已记录的模型选择回装)。模型选择
1537
+ * 以日志记录的 request-header 播种 agentOptions——{{model}}/{{provider}}
1538
+ * 提示变量与首次请求路由都读它, 驱动器还会因路由吻合而自行回装日志
1539
+ * 记录的 effort; 无落点(从未发过请求的会话)回落宿主默认。恢复时追
1540
+ * 加的合成 turn/end(`interrupted`)随后由常规扫描按既有关卡恢复。
1541
+ */
1542
+ private async materializeStored(
1543
+ sessionId: SessionId,
1544
+ presetId: string | undefined,
1545
+ logged: { provider: string; model: string } | undefined,
1546
+ ): Promise<boolean> {
1547
+ if (this.disposed || this.getConfig().paused || !this.getConfig().scanOnBoot) return false;
1548
+ const presets = this.ctx.get('agentPresets');
1549
+ // Mirrors session-controller's adopt: without agent options the agent has no
1550
+ // provider/model, so prompt variables like {{model}} have no value and the
1551
+ // request carries no route.
1552
+ const defaultModel = this.ctx.get('agentDefaultModel');
1553
+ const selection = defaultModel?.currentSelection();
1554
+ const agentOptions = logged !== undefined
1555
+ ? { provider: logged.provider, model: logged.model }
1556
+ : selection === undefined ? undefined : { provider: selection.provider, model: selection.model };
1557
+ if (presets === undefined) {
1558
+ await this.ctx.agents.resume({ resumeSessionId: sessionId, agentOptions, signal: this.stopStoredSweep.signal });
1559
+ return true;
1560
+ }
1561
+ const resolvedId = (await presets.resolve(presetId)).id;
1562
+ if (this.disposed || this.getConfig().paused || !this.getConfig().scanOnBoot) return false;
1563
+ if (this.ctx.agents.get(sessionId) !== undefined) return true;
1564
+ await this.ctx.agents.resume({
1565
+ resumeSessionId: sessionId,
1566
+ agentOptions,
1567
+ signal: this.stopStoredSweep.signal,
1568
+ setup: async (agentCtx) => {
1569
+ await presets.mount(agentCtx, resolvedId);
1570
+ },
1571
+ });
1572
+ return true;
1573
+ }
1574
+
1334
1575
  /** Captured identity only: even session.id can throw when the header is damaged. */
1335
1576
  private logBootScanFailure(sessionId: SessionId | undefined, error: unknown): void {
1336
1577
  console.error(`[auto-continue] 启动扫描跳过会话 ${sessionId ?? '(id unavailable)'}: ${
package/src/index.ts CHANGED
@@ -38,6 +38,8 @@ export const AutoContinueSchema = z.object({
38
38
  continueTextSilent: z.string().default(''),
39
39
  /** Text sent for each autonomous-loop continuation (same placeholders as `continueText`). */
40
40
  continueTextLoop: z.string().default(''),
41
+ /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
42
+ continueTextInterrupted: z.string().default(''),
41
43
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
42
44
  guardTools: z.boolean().default(true),
43
45
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -163,6 +165,7 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
163
165
  type: 'state',
164
166
  stats: runner.todayStats(),
165
167
  paused: runner.activePauses(),
168
+ recoveryAttempts: runner.recentRecoveryAttempts(),
166
169
  });
167
170
 
168
171
  runner.subscribeNotices(() => {