dsh-client-auto-continue 0.17.4 → 0.18.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.
@@ -19,6 +19,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent';
19
19
  import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types';
20
20
  import { foldRequestHeader, type Session } from '@deepseek-ai/dsh-session';
21
21
  import {
22
+ AUTO_CONTINUE_SOURCE_KIND,
22
23
  DEFAULT_CONFIG,
23
24
  RECOVERY_WINDOW_MS,
24
25
  effectiveCooldown,
@@ -28,6 +29,7 @@ import {
28
29
  freshState,
29
30
  isNonHumanReason,
30
31
  isOurEcho,
32
+ isNetworkFailure,
31
33
  isTransientAgentError,
32
34
  isTransientFailure,
33
35
  resolveConfig,
@@ -46,6 +48,7 @@ import {
46
48
  type TemplateContext,
47
49
  type ToolRepeatSignal,
48
50
  } from '../shared/core.ts';
51
+ import { probeConnectivity, type ConnectivityProbe } from './connectivity.ts';
49
52
 
50
53
  const NOTICE_COPY = {
51
54
  zh: {
@@ -60,6 +63,9 @@ const NOTICE_COPY = {
60
63
  stoppedTitle: 'dsh-auto-continue: 已停止自动继续',
61
64
  stoppedBody: (sessionId: SessionId, count: number) =>
62
65
  `${sessionId}: 连续失败 ${count} 次, 需要人工介入`,
66
+ loopCapTitle: 'dsh-auto-continue: 自主循环已到上限',
67
+ loopCapBody: (sessionId: SessionId, count: number) =>
68
+ `${sessionId}: 已自主续跑 ${count} 轮, 循环暂停; 发一条消息或重新开启循环即可继续`,
63
69
  },
64
70
  en: {
65
71
  notContinuedTitle: 'dsh-auto-continue: Not continued',
@@ -73,6 +79,9 @@ const NOTICE_COPY = {
73
79
  stoppedTitle: 'dsh-auto-continue: Auto-continue stopped',
74
80
  stoppedBody: (sessionId: SessionId, count: number) =>
75
81
  `${sessionId}: ${count} consecutive failures; manual intervention required`,
82
+ loopCapTitle: 'dsh-auto-continue: Autonomous loop limit reached',
83
+ loopCapBody: (sessionId: SessionId, count: number) =>
84
+ `${sessionId}: Stopped after ${count} autonomous rounds; send a message or turn the loop back on to keep going`,
76
85
  },
77
86
  } as const satisfies Record<AutoContinueLocale, Record<string, unknown>>;
78
87
 
@@ -102,6 +111,75 @@ const STORED_READ_TIMEOUT_MS = 5000;
102
111
  /** 单个存储会话连续观察/物化失败达此数后放弃, 避免坏日志反复占满每轮观察配额。 */
103
112
  const SWEEP_MAX_FAILURES = 3;
104
113
 
114
+ /** Why a child session needs its root session woken after a restart. */
115
+ type ChildInterruptCause = 'open-turn' | 'disposed' | 'interrupted' | 'max-tokens' | 'error';
116
+
117
+ /** One interrupted child session, grouped under the root session that owns it. */
118
+ interface ChildInterrupt {
119
+ readonly id: SessionId;
120
+ readonly title: string | undefined;
121
+ readonly preset: string | undefined;
122
+ readonly cause: ChildInterruptCause;
123
+ readonly at: number;
124
+ }
125
+
126
+ /** A header-shaped record good enough to resolve a parent chain. */
127
+ interface SessionHeaderLike {
128
+ readonly id: SessionId;
129
+ readonly parentSession?: SessionId;
130
+ }
131
+
132
+ /** Cancel causes a host shutdown or a restart produces; only these justify a wake-up. */
133
+ const RESTART_CANCEL_CAUSES: ReadonlySet<string> = new Set(['disposed', 'legacy']);
134
+ /** Cancel causes that record an explicit human or parent decision; never recover these. */
135
+ const DECISION_CANCEL_CAUSES: ReadonlySet<string> = new Set(['user', 'parent', 'hook']);
136
+ /** Bound child observations per sweep round: child logs are as large as root logs. */
137
+ const CHILD_SWEEP_LIMIT = 8;
138
+ /** Bound how many ancestor hops a dirty parent chain may cost before giving up. */
139
+ const CHILD_ROOT_MAX_DEPTH = 8;
140
+
141
+ /** Host service key for goals (0.2.x); older hosts simply do not register it. */
142
+ const GOALS_SERVICE_KEY = 'goals';
143
+
144
+ /** Copy for each child interruption cause, keyed by UI locale. */
145
+ const CHILD_CAUSE_COPY = {
146
+ zh: {
147
+ 'open-turn': '回合开始后中断',
148
+ disposed: '宿主销毁',
149
+ interrupted: '崩溃恢复标记',
150
+ 'max-tokens': '输出长度耗尽',
151
+ error: '可重试错误',
152
+ },
153
+ en: {
154
+ 'open-turn': 'turn cut off after start',
155
+ disposed: 'host disposed the agent',
156
+ interrupted: 'closed by crash recovery',
157
+ 'max-tokens': 'output ceiling reached',
158
+ error: 'retryable error',
159
+ },
160
+ } as const satisfies Record<AutoContinueLocale, Record<ChildInterruptCause, string>>;
161
+
162
+ /** Structural view of `ctx.goals`; declared locally because devDeps target an older host. */
163
+ interface GoalRefLike {
164
+ readonly id: string;
165
+ /** Mutations are CAS-checked against this revision; omitting it raises GOAL_STALE_REVISION. */
166
+ readonly revision: number;
167
+ }
168
+
169
+ interface GoalViewLike {
170
+ readonly id: string;
171
+ /** The host's `view()` exposes no `ref`; callers build `{ id, revision }` from the view. */
172
+ readonly ref?: GoalRefLike;
173
+ readonly phase?: string;
174
+ readonly activation?: string;
175
+ readonly revision?: number;
176
+ }
177
+
178
+ interface GoalServiceLike {
179
+ get(agent: Agent): GoalViewLike | undefined;
180
+ resume(agent: Agent, ref: GoalRefLike): unknown;
181
+ }
182
+
105
183
  /**
106
184
  * 存储扫描消费的宿主服务结构类型。这些服务(sessionQuery 等)随 dsh
107
185
  * 版本整组演进, 直接引类型包会拖动 devDependency 时代; 按消费面声明,
@@ -214,6 +292,80 @@ function readReasonKind(value: unknown): string | undefined {
214
292
  return typeof kind === 'string' && kind.trim() !== '' ? kind : undefined;
215
293
  }
216
294
 
295
+ /** Read the nested cancel cause of an `aborted` turn/end (`reason.reason.kind`). */
296
+ function readCancelCause(value: unknown): string | undefined {
297
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;
298
+ const reason = value as { kind?: unknown; reason?: unknown };
299
+ if (reason.kind !== 'aborted') return undefined;
300
+ return readReasonKind(reason.reason);
301
+ }
302
+
303
+ /**
304
+ * Decide whether a child session's tail is a restart interruption worth waking
305
+ * its root session for. Returns `undefined` when the child finished normally,
306
+ * was stopped by a human or by its parent, or was superseded by a later user
307
+ * message — i.e. whenever a wake-up would be a ghost turn.
308
+ */
309
+ function classifyChildInterruption(
310
+ events: readonly SessionEvent[],
311
+ config: AutoContinueConfig,
312
+ ): ChildInterruptCause | undefined {
313
+ let lastEnd: SessionEvent<'turn/end'> | undefined;
314
+ for (let i = events.length - 1; i >= 0; i -= 1) {
315
+ const event = events[i];
316
+ if (event?.type === 'turn/end') { lastEnd = event; break; }
317
+ }
318
+ const lastStart = latestTurnStart(events);
319
+ if (lastStart !== undefined && (lastEnd === undefined || lastStart.seq > lastEnd.seq)) {
320
+ if (isMaintenanceTurnStart(lastStart)) return undefined;
321
+ // 与主扫描同口径: 过了 freshMs 的中断不是这次重启造成的, 唤醒只会复活陈年父会话。
322
+ if ((events[events.length - 1]?.time ?? 0) < Date.now() - config.freshMs) return undefined;
323
+ return 'open-turn';
324
+ }
325
+ const end = lastEnd;
326
+ if (end === undefined) return undefined;
327
+ if (end.time < Date.now() - config.freshMs) return undefined;
328
+ // A message written after the closing turn means someone already took over.
329
+ for (let i = events.length - 1; i >= 0; i -= 1) {
330
+ const event = events[i];
331
+ if (event === undefined || event.seq <= end.seq) break;
332
+ if (event.type === 'user/message') return undefined;
333
+ }
334
+ const reason = end.data.reason;
335
+ const kind = readReasonKind(reason);
336
+ if (kind === undefined) return undefined;
337
+ if (kind === 'aborted') {
338
+ const cause = readCancelCause(reason);
339
+ if (cause === undefined || DECISION_CANCEL_CAUSES.has(cause)) return undefined;
340
+ return RESTART_CANCEL_CAUSES.has(cause) ? 'disposed' : undefined;
341
+ }
342
+ if (kind === 'interrupted') return 'interrupted';
343
+ if (kind === 'max-tokens') return 'max-tokens';
344
+ if (kind === 'error') {
345
+ const failure = parseFailureFacts((reason as { error?: unknown }).error);
346
+ if (failure === undefined) return undefined;
347
+ if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) return undefined;
348
+ return 'error';
349
+ }
350
+ return undefined;
351
+ }
352
+
353
+ /** Walk `parentSession` up to a root session; `undefined` when the chain is dirty. */
354
+ function resolveRootHeader(
355
+ header: SessionHeaderLike,
356
+ byId: ReadonlyMap<string, SessionHeaderLike>,
357
+ ): SessionId | undefined {
358
+ let current: SessionHeaderLike = header;
359
+ for (let depth = 0; depth <= CHILD_ROOT_MAX_DEPTH; depth += 1) {
360
+ const parentId = current.parentSession;
361
+ if (parentId === undefined || parentId === '') return current.id;
362
+ const parent = byId.get(parentId);
363
+ if (parent === undefined) return undefined;
364
+ current = parent;
365
+ }
366
+ return undefined;
367
+ }
368
+
217
369
  function isLoopGuardCancelReason(value: unknown): boolean {
218
370
  if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
219
371
  const cause = value as { kind?: unknown; reason?: unknown };
@@ -277,6 +429,16 @@ export class AutoContinueRunner {
277
429
  private readonly bootScanErrors = new WeakSet<object>();
278
430
  /** 存储扫描已裁决的会话 id, 避免每轮重复冷读大日志。 */
279
431
  private readonly storedSwept = new Set<SessionId>();
432
+ /** 子会话裁决独立记账: storedSwept 在 origin 判断之前就已标记, 不能复用。 */
433
+ private readonly childSwept = new Set<SessionId>();
434
+ /** 本轮已花掉的子会话观察配额(每轮重置, 子会话日志与主会话同等昂贵)。 */
435
+ private childScanned = 0;
436
+ /** 本轮收集到的子会话中断, 按 root 主会话 id 归组。 */
437
+ private readonly childInterrupts = new Map<SessionId, ChildInterrupt[]>();
438
+ /** 已唤醒过的 root 会话 → 上次唤醒覆盖的子会话签名, 防止每轮重复催同一批。 */
439
+ private readonly childWoken = new Map<SessionId, string>();
440
+ /** 已打印过「父链不可解析」的子会话, 避免 15 分钟扫描窗口内每轮重扫把日志刷爆。 */
441
+ private readonly childDirtyLogged = new Set<SessionId>();
280
442
  /** 存储会话的连续观察/物化失败次数, 触达 SWEEP_MAX_FAILURES 后不再重试。 */
281
443
  private readonly storedSweepFailures = new Map<SessionId, number>();
282
444
  private storedSweepAnnounced = false;
@@ -284,6 +446,8 @@ export class AutoContinueRunner {
284
446
  private wakeBootScan: (() => void) | undefined;
285
447
  private storedSweep: Promise<void> | undefined;
286
448
  private readonly stopStoredSweep = new AbortController();
449
+ /** 并发的断网挂起共用同一次连通性检测。 */
450
+ private connectivityCheck: Promise<boolean> | undefined;
287
451
 
288
452
  /**
289
453
  * @param ctx - host plugin context (agents registry, session events).
@@ -292,6 +456,7 @@ export class AutoContinueRunner {
292
456
  constructor(
293
457
  private readonly ctx: Context,
294
458
  private readonly getConfig: () => AutoContinueConfig,
459
+ private readonly probe: ConnectivityProbe = probeConnectivity,
295
460
  ) {
296
461
  // 单实例事件源: 宿主进程内的会话事件 firehose, 天然覆盖所有会话。
297
462
  this.disposeSessionEvents = ctx.on('session/event', (session, event) => {
@@ -406,6 +571,9 @@ export class AutoContinueRunner {
406
571
  if (this.disposed) return;
407
572
  for (const [sessionId, state] of this.states) {
408
573
  const config = this.sessionConfig(sessionId);
574
+ // 循环由关到开视为一次新的授权: 轮数上限重新计数。
575
+ if (config.resumeCompletedTurns && state.loopEnabled === false) this.resetLoopIterations(state);
576
+ state.loopEnabled = config.resumeCompletedTurns;
409
577
  if (config.paused || (isLoopReason(state.pendingReason ?? '') && !config.resumeCompletedTurns)) {
410
578
  this.cancelPending(sessionId, '会话模式或全局设置已更改');
411
579
  }
@@ -447,6 +615,8 @@ export class AutoContinueRunner {
447
615
  if (state.pendingTimer !== undefined) clearTimeout(state.pendingTimer);
448
616
  if (state.loopRetryTimer !== undefined) clearTimeout(state.loopRetryTimer);
449
617
  if (state.cooldownRetryTimer !== undefined) clearTimeout(state.cooldownRetryTimer);
618
+ if (state.offlineTimer !== undefined) clearTimeout(state.offlineTimer);
619
+ state.offlineWait = undefined;
450
620
  }
451
621
  this.states.clear();
452
622
  }
@@ -913,6 +1083,7 @@ export class AutoContinueRunner {
913
1083
  if (event.data.source.kind === 'user') {
914
1084
  // 用户手动介入: 清零上限与跨标签页发送计数
915
1085
  state.consecutive = 0;
1086
+ this.resetLoopIterations(state);
916
1087
  this.cancelPending(sessionId, '用户手动发送消息');
917
1088
  }
918
1089
  break;
@@ -1072,6 +1243,8 @@ export class AutoContinueRunner {
1072
1243
  return;
1073
1244
  }
1074
1245
  if (state.pendingTimer !== undefined) return; // 已有待发送
1246
+ if (state.offlineWait !== undefined || state.offlineTimer !== undefined) return; // 断网挂起中, 恢复后自会续跑
1247
+ if (isLoopReason(reason) && this.loopCapReached(sessionId, state, config)) return;
1075
1248
  // 连续上限优先于冷却: 已经放弃的会话不该再安排冷却后的重试。
1076
1249
  // 自主循环的完成续跑(force)不受二者约束。
1077
1250
  if (!force && state.consecutive >= config.maxConsecutive) {
@@ -1095,7 +1268,7 @@ export class AutoContinueRunner {
1095
1268
  state.pendingReason = undefined;
1096
1269
  // 保险丝: 定时器回调内任何异常(含 inactive context)都不得成为未捕获异常炸掉进程。
1097
1270
  try {
1098
- void this.fire(sessionId, reason, force);
1271
+ this.fireWhenOnline(sessionId, reason, force);
1099
1272
  } catch (error) {
1100
1273
  console.error(`[auto-continue] 定时发送异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
1101
1274
  }
@@ -1159,6 +1332,13 @@ export class AutoContinueRunner {
1159
1332
  state.loopRetryTimer = undefined;
1160
1333
  cancelled = true;
1161
1334
  }
1335
+ if (state.offlineWait !== undefined || state.offlineTimer !== undefined) {
1336
+ if (state.offlineTimer !== undefined) clearTimeout(state.offlineTimer);
1337
+ state.offlineTimer = undefined;
1338
+ state.offlineWait = undefined;
1339
+ state.offlineSince = 0;
1340
+ cancelled = true;
1341
+ }
1162
1342
  if (cancelled) this.log(`取消 ${sessionId} 的自动继续(${why})`);
1163
1343
  }
1164
1344
 
@@ -1202,7 +1382,7 @@ export class AutoContinueRunner {
1202
1382
  try {
1203
1383
  const message = createUserMessage({
1204
1384
  content: [{ type: 'text', text }],
1205
- source: { kind: 'user' },
1385
+ source: { kind: config.usePluginSource ? AUTO_CONTINUE_SOURCE_KIND : 'user' },
1206
1386
  });
1207
1387
  // `followup` may publish the matching session event synchronously.
1208
1388
  trackPendingEcho(state, message.id);
@@ -1216,8 +1396,12 @@ export class AutoContinueRunner {
1216
1396
  this.prioritizedFollowups.delete(message.id);
1217
1397
  }
1218
1398
  const now = Date.now();
1399
+ // 续跑已发出: 被重启失活的 goal 需要在这里重新武装, 否则续跑消息会跑但
1400
+ // goal 的自动继续轮不会转起来(disarm 是宿主卸载驱动的正常动作)。
1401
+ this.rearmGoal(sessionId, config);
1219
1402
  // 自主循环的成功续跑不计入连续上限: 上限只约束失败(网络中断等)。
1220
1403
  if (reason !== LOOP_COMPLETED_REASON) state.consecutive += 1;
1404
+ if (isLoopReason(reason)) state.loopIterations += 1;
1221
1405
  state.pendingRecoveryAt = now; // 等待窗口内的下一个回合结束来判定恢复结果
1222
1406
  if (reason !== LOOP_COMPLETED_REASON) {
1223
1407
  this.recoveryAttempts.unshift({
@@ -1259,6 +1443,93 @@ export class AutoContinueRunner {
1259
1443
  }
1260
1444
  }
1261
1445
 
1446
+ private resetLoopIterations(state: SessionState): void {
1447
+ state.loopIterations = 0;
1448
+ state.loopCapNotified = false;
1449
+ }
1450
+
1451
+ /** 自主循环轮数上限: 触顶后静默停下, 每次触顶只提示一次。 */
1452
+ private loopCapReached(sessionId: SessionId, state: SessionState, config: AutoContinueConfig): boolean {
1453
+ const cap = config.loopMaxIterations;
1454
+ if (cap <= 0 || state.loopIterations < cap) return false;
1455
+ if (!state.loopCapNotified) {
1456
+ state.loopCapNotified = true;
1457
+ this.log(`自主循环已续跑 ${state.loopIterations} 轮, 达到上限 ${cap}, 停止 ${sessionId}; 用户发消息或重新开启循环后重新计数`);
1458
+ if (config.notify) {
1459
+ const copy = NOTICE_COPY[config.locale];
1460
+ this.notify(
1461
+ sessionId,
1462
+ copy.loopCapTitle,
1463
+ copy.loopCapBody(sessionId, state.loopIterations),
1464
+ this.notifyOptions(sessionId, config.locale),
1465
+ );
1466
+ }
1467
+ }
1468
+ return true;
1469
+ }
1470
+
1471
+ private checkConnectivity(): Promise<boolean> {
1472
+ if (this.connectivityCheck === undefined) {
1473
+ const check = this.probe()
1474
+ .catch(() => true) // 检测本身出错时放行, 不因探测失败卡住恢复
1475
+ .finally(() => {
1476
+ if (this.connectivityCheck === check) this.connectivityCheck = undefined;
1477
+ });
1478
+ this.connectivityCheck = check;
1479
+ }
1480
+ return this.connectivityCheck;
1481
+ }
1482
+
1483
+ /**
1484
+ * 网络类失败的续跑先过连通性检测: 断网时发出去必然再失败一次, 白白吃掉连续上限,
1485
+ * 等网络恢复时预算已耗尽。挂起期间不计次数, 每 offlineCheckMs 复检一次, 恢复后
1486
+ * 重新走 schedule(宽限、冷却照常)。手动续跑和非网络原因不受影响。
1487
+ */
1488
+ private fireWhenOnline(sessionId: SessionId, reason: string, force: boolean): void {
1489
+ const state = this.state(sessionId);
1490
+ const config = this.sessionConfig(sessionId);
1491
+ const gated = config.pauseWhenOffline &&
1492
+ reason !== MANUAL_NOTIFICATION_REASON &&
1493
+ !isLoopReason(reason) &&
1494
+ state.lastFailure !== undefined &&
1495
+ isNetworkFailure(state.lastFailure);
1496
+ if (!gated) {
1497
+ this.fire(sessionId, reason, force);
1498
+ return;
1499
+ }
1500
+ const token = {};
1501
+ state.offlineWait = token;
1502
+ state.pendingReason = reason;
1503
+ void this.checkConnectivity().then((online) => {
1504
+ if (this.disposed || state.offlineWait !== token) return; // 已被取消或被新的检测取代
1505
+ if (online) {
1506
+ state.offlineWait = undefined;
1507
+ state.pendingReason = undefined;
1508
+ if (state.offlineSince !== 0) {
1509
+ this.log(`网络已恢复 ${sessionId}, 断网挂起 ${Math.round((Date.now() - state.offlineSince) / 1000)}s 后继续(${reason})`);
1510
+ state.offlineSince = 0;
1511
+ this.schedule(sessionId, reason, force);
1512
+ return;
1513
+ }
1514
+ this.fire(sessionId, reason, force);
1515
+ return;
1516
+ }
1517
+ if (state.offlineSince === 0) {
1518
+ state.offlineSince = Date.now();
1519
+ this.log(`网络不可用, 挂起 ${sessionId} 的自动继续(${reason}), 每 ${config.offlineCheckMs}ms 复检, 不消耗重试次数`);
1520
+ }
1521
+ state.offlineTimer = setTimeout(() => {
1522
+ state.offlineTimer = undefined;
1523
+ if (state.offlineWait !== token) return;
1524
+ try {
1525
+ this.fireWhenOnline(sessionId, reason, force);
1526
+ } catch (error) {
1527
+ console.error(`[auto-continue] 断网复检异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
1528
+ }
1529
+ }, config.offlineCheckMs);
1530
+ });
1531
+ }
1532
+
1262
1533
  /**
1263
1534
  * 组装本次续跑消息: 模板填充 + 幂等护栏。
1264
1535
  * 护栏依据上一步工具调用的执行状态附加指引, 防止重跑副作用操作:
@@ -1307,7 +1578,9 @@ export class AutoContinueRunner {
1307
1578
  if (await this.scanInterrupted()) return;
1308
1579
  const config = this.getConfig();
1309
1580
  if (!config.paused && config.scanOnBoot && this.storedSweep === undefined) {
1581
+ this.childScanned = 0; // 每轮重置子会话观察配额
1310
1582
  this.storedSweep = this.sweepStoredSessions(config, deadline)
1583
+ .then(() => this.wakeInterruptedChildren(config, deadline))
1311
1584
  .catch(error => {
1312
1585
  if (!this.disposed) this.ctx.logger.error(`Stored session scan failed: ${String(error)}`);
1313
1586
  })
@@ -1487,7 +1760,27 @@ export class AutoContinueRunner {
1487
1760
  if (!Array.isArray(records)) throw new TypeError('stored session listing is not an array');
1488
1761
  if (!this.storedSweepAnnounced) {
1489
1762
  this.storedSweepAnnounced = true;
1490
- this.ctx.logger.info(`存储扫描就绪: ${records.length} 个会话记录`);
1763
+ // 诊断口径: 宿主返回的 header 是否携带 origin, 决定子会话分支能否进入。
1764
+ let children = 0;
1765
+ let otherOrigins = 0;
1766
+ let originMissing = 0;
1767
+ for (const record of records) {
1768
+ const origin = (record?.header as { origin?: string } | undefined)?.origin;
1769
+ if (origin === 'subagent') children += 1;
1770
+ else if (origin === undefined) originMissing += 1;
1771
+ else otherOrigins += 1;
1772
+ }
1773
+ this.ctx.logger.info(
1774
+ `存储扫描就绪: ${records.length} 个会话记录 (subagent ${children} / 无 origin ${originMissing} / 其它 origin ${otherOrigins})`,
1775
+ );
1776
+ }
1777
+ // 父子链解析只依赖 header: 一次建成索引, 子会话不必各自再读父日志。
1778
+ const headersById = new Map<string, SessionHeaderLike>();
1779
+ for (const record of records) {
1780
+ const header = record?.header as SessionHeaderLike | undefined;
1781
+ if (header !== undefined && typeof header.id === 'string' && header.id !== '') {
1782
+ headersById.set(header.id, header);
1783
+ }
1491
1784
  }
1492
1785
  let observed = 0;
1493
1786
  for (const record of records) {
@@ -1498,9 +1791,17 @@ export class AutoContinueRunner {
1498
1791
  }
1499
1792
  const sessionId = record.header.id;
1500
1793
  if (this.sessionConfig(sessionId).paused || Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) continue;
1794
+ if (record.header.origin === 'subagent') {
1795
+ // 子会话的记账完全交给 childSwept。若沿用 storedSwept(它在下面为 root 记账),
1796
+ // 配额用尽的那一批会被永久标成"已裁决": 之后每轮都在这里被挡掉, 775 个子会话
1797
+ // 只判 8 个, 而配额本意只是限制单轮的冷读成本。
1798
+ if (config.resumeInterruptedChildren) {
1799
+ await this.sweepChild(record, headersById, config, deadline);
1800
+ }
1801
+ continue;
1802
+ }
1501
1803
  if (record.live || this.storedSwept.has(sessionId)) continue;
1502
1804
  this.storedSwept.add(sessionId);
1503
- if (record.header.origin === 'subagent') continue;
1504
1805
  observed += 1;
1505
1806
  let observation: StoredObservation | undefined;
1506
1807
  try {
@@ -1596,6 +1897,275 @@ export class AutoContinueRunner {
1596
1897
  }
1597
1898
  }
1598
1899
 
1900
+ /**
1901
+ * 子会话裁决。子会话本身永不直接续跑(父代理权威, 见 README), 但启动扫描要
1902
+ * 知道它是否在重启时被打断, 才能在自己的 root 会话上补一次带清单的唤醒。
1903
+ * 独立 `childSwept` 记账与独立配额: 主扫描的 `storedSwept` 在 origin 判断
1904
+ * 之前就已标记, 复用它会让子会话永远扫不到, 也会吃掉主扫描的观察预算。
1905
+ */
1906
+ private async sweepChild(
1907
+ record: {
1908
+ readonly header: SessionHeaderLike & {
1909
+ readonly origin?: string;
1910
+ readonly agentPreset?: string;
1911
+ readonly title?: unknown;
1912
+ };
1913
+ readonly persisted?: boolean;
1914
+ },
1915
+ headersById: ReadonlyMap<string, SessionHeaderLike>,
1916
+ config: AutoContinueConfig,
1917
+ deadline: number,
1918
+ ): Promise<void> {
1919
+ const header = record.header;
1920
+ const sessionId = header.id;
1921
+ const parentId = header.parentSession;
1922
+ if (parentId === undefined || parentId === '') return;
1923
+ // one-shot 子会话在结果落库后已被丢弃, 没有可续的日志。
1924
+ if (record.persisted !== true) return;
1925
+ if (this.childSwept.has(sessionId)) return;
1926
+ // live 会话由实时事件路径负责; 冷读它既费钱又会与写归属相撞。
1927
+ if (this.ctx.agents.get(sessionId) !== undefined) return;
1928
+ if (this.childScanned >= CHILD_SWEEP_LIMIT) return;
1929
+ if (this.sessionConfig(sessionId).paused) return;
1930
+ const rootId = resolveRootHeader(header, headersById);
1931
+ if (rootId === undefined || rootId === sessionId) {
1932
+ // 每轮扫描都会重走这里; 只记一次, 否则 15 分钟 freshMs 窗口内会刷出数万行噪声。
1933
+ if (!this.childDirtyLogged.has(sessionId)) {
1934
+ this.childDirtyLogged.add(sessionId);
1935
+ this.log(`子会话 ${sessionId} 父链不可解析(脏引用或自环), 跳过(每会话只记一次)`);
1936
+ }
1937
+ return; // 脏引用或自环: 不猜
1938
+ }
1939
+ const query = this.ctx.get('sessionQuery');
1940
+ if (query === undefined) return;
1941
+ this.childSwept.add(sessionId);
1942
+ this.childScanned += 1;
1943
+ let observation: StoredObservation | undefined;
1944
+ try {
1945
+ const stored: StoredObservation = await this.readStored(
1946
+ signal => query.observeSession(sessionId, { projectionMode: 'all', signal }),
1947
+ deadline,
1948
+ );
1949
+ observation = stored;
1950
+ if (this.disposed) return;
1951
+ const events = validateSessionEvents(stored.events);
1952
+ if (events.length === 0) return;
1953
+ const cause = classifyChildInterruption(events, config);
1954
+ if (cause === undefined) return;
1955
+ const tail = events[events.length - 1];
1956
+ const list = this.childInterrupts.get(rootId) ?? [];
1957
+ list.push({
1958
+ id: sessionId,
1959
+ title: typeof header.title === 'string' && header.title !== '' ? header.title : undefined,
1960
+ preset: header.agentPreset,
1961
+ cause,
1962
+ at: tail?.time ?? Date.now(),
1963
+ });
1964
+ this.childInterrupts.set(rootId, list);
1965
+ this.log(`子会话 ${sessionId} 重启时被打断(${cause}), 记入 root ${rootId}`);
1966
+ } catch (error) {
1967
+ this.childSwept.delete(sessionId); // 冷读失败允许下一轮重试
1968
+ if (!this.disposed) {
1969
+ this.ctx.logger.info(
1970
+ `子会话 ${sessionId} 冷读失败: ${error instanceof Error ? error.message : String(error)}`,
1971
+ );
1972
+ }
1973
+ } finally {
1974
+ observation?.[Symbol.dispose]?.();
1975
+ }
1976
+ }
1977
+
1978
+ /** 把本轮收集到的子会话中断转成 root 会话上的一次唤醒(同一批只催一次)。 */
1979
+ private async wakeInterruptedChildren(
1980
+ config: AutoContinueConfig,
1981
+ deadline: number,
1982
+ ): Promise<void> {
1983
+ if (this.disposed || this.childInterrupts.size === 0) return;
1984
+ if (config.paused || !config.scanOnBoot || !config.resumeInterruptedChildren) return;
1985
+ // 不整体 clear: 只有"已裁决"的 root 才销账。若在循环前 clear, 任一 root 因冷却或
1986
+ // 主路径已排期而提前返回, 这批孩子就永久丢了 —— 它们已在 childSwept 里, 不会再被收集。
1987
+ for (const [rootId, children] of [...this.childInterrupts]) {
1988
+ if (this.disposed || Date.now() >= deadline) return; // 未处理的留到下一轮
1989
+ try {
1990
+ if (await this.wakeRoot(config, rootId, children, deadline)) {
1991
+ this.childInterrupts.delete(rootId);
1992
+ }
1993
+ } catch (error) {
1994
+ // 抛错也要销账, 否则每轮重试同一条坏数据。
1995
+ this.childInterrupts.delete(rootId);
1996
+ if (!this.disposed) {
1997
+ this.ctx.logger.info(
1998
+ `子会话唤醒 ${rootId} 失败: ${error instanceof Error ? error.message : String(error)}`,
1999
+ );
2000
+ }
2001
+ }
2002
+ }
2003
+ }
2004
+
2005
+ /**
2006
+ * 在 root 会话上唤醒一次。只有在 root 自己是"干净终态"时才动手: 它若被打断,
2007
+ * 主扫描本来就会续跑它; 它若被用户手动停止, 唤醒就是幽灵回合。
2008
+ */
2009
+ private async wakeRoot(
2010
+ config: AutoContinueConfig,
2011
+ rootId: SessionId,
2012
+ children: readonly ChildInterrupt[],
2013
+ deadline: number,
2014
+ ): Promise<boolean> {
2015
+ // 返回值语义: true = 已裁决(可销账), false = 稍后重试(必须留住这一批)。
2016
+ if (this.sessionConfig(rootId).paused) return false;
2017
+ if (Date.now() < (this.pauseUntil.get(rootId) ?? 0)) return false;
2018
+ const state = this.state(rootId);
2019
+ if (state.pendingTimer !== undefined) return false; // 主路径已排好, 下一轮再看
2020
+ if (state.consecutive >= config.maxConsecutive) return true; // 预算耗尽: 不必每轮重试
2021
+ if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) return false;
2022
+ const batch = children.map(child => `${child.id}:${child.cause}`).sort().join(',');
2023
+ if (this.childWoken.get(rootId) === batch) return true;
2024
+ if (!(await this.rootAcceptsWake(rootId, deadline))) return true; // 明确裁决: 不该唤醒
2025
+ const agent = await this.ensureLiveAgent(rootId, deadline);
2026
+ if (agent === undefined || this.disposed) return false;
2027
+ const text = this.buildChildResumeText(config, children);
2028
+ const message = createUserMessage({
2029
+ content: [{ type: 'text', text }],
2030
+ source: { kind: 'user' },
2031
+ });
2032
+ state.lastAttemptAt = Date.now();
2033
+ agent.followup(message);
2034
+ this.childWoken.set(rootId, batch);
2035
+ this.log(
2036
+ `已唤醒 ${rootId}: ${children.length} 个子会话在重启时被打断, 清单已交给父会话处置`,
2037
+ );
2038
+ this.rearmGoal(rootId, config);
2039
+ return true;
2040
+ }
2041
+
2042
+ /** 父会话只在"干净结束"或"被宿主关闭"时接受唤醒; 用户手动停止的绝不复活。 */
2043
+ private async rootAcceptsWake(sessionId: SessionId, deadline: number): Promise<boolean> {
2044
+ const query = this.ctx.get('sessionQuery');
2045
+ if (query === undefined) return false;
2046
+ let events: readonly SessionEvent[];
2047
+ let stored: StoredObservation | undefined;
2048
+ try {
2049
+ const observation: StoredObservation = await this.readStored(
2050
+ signal => query.observeSession(sessionId, { projectionMode: 'all', signal }),
2051
+ deadline,
2052
+ );
2053
+ stored = observation;
2054
+ events = validateSessionEvents(observation.events);
2055
+ } catch {
2056
+ return false;
2057
+ } finally {
2058
+ // validateSessionEvents 可能抛在畸形日志上, 租约必须无条件释放。
2059
+ stored?.[Symbol.dispose]?.();
2060
+ }
2061
+ if (events.length === 0) return false;
2062
+ let lastEnd: SessionEvent<'turn/end'> | undefined;
2063
+ for (let i = events.length - 1; i >= 0; i -= 1) {
2064
+ const event = events[i];
2065
+ if (event?.type === 'turn/end') { lastEnd = event; break; }
2066
+ }
2067
+ const lastStart = latestTurnStart(events);
2068
+ const end = lastEnd;
2069
+ if (lastStart !== undefined && (end === undefined || lastStart.seq > end.seq)) return false;
2070
+ if (end === undefined) return false;
2071
+ const kind = readReasonKind(end.data.reason);
2072
+ if (kind === 'completed') return true;
2073
+ if (kind === 'aborted') {
2074
+ const cause = readCancelCause(end.data.reason);
2075
+ return cause !== undefined && RESTART_CANCEL_CAUSES.has(cause);
2076
+ }
2077
+ return false;
2078
+ }
2079
+
2080
+ /** 发送需要 live agent; 存储会话沿既有物化路径拉起, 复用 preset 与模型回装。 */
2081
+ private async ensureLiveAgent(sessionId: SessionId, deadline: number): Promise<Agent | undefined> {
2082
+ const live = this.ctx.agents.get(sessionId);
2083
+ if (live !== undefined) return live;
2084
+ const query = this.ctx.get('sessionQuery');
2085
+ if (query === undefined) return undefined;
2086
+ let presetId: string | undefined;
2087
+ let model: { provider: string; model: string } | undefined;
2088
+ let stored: StoredObservation | undefined;
2089
+ try {
2090
+ const observation: StoredObservation = await this.readStored(
2091
+ signal => query.observeSession(sessionId, { projectionMode: 'all', signal }),
2092
+ deadline,
2093
+ );
2094
+ stored = observation;
2095
+ presetId = observation.projections?.values.agentPreset ?? observation.header.agentPreset;
2096
+ // 与主扫描一致回装日志记录的模型选择, 否则父会话会以默认模型被拉起。
2097
+ const loggedConfig = foldRequestHeader(validateSessionEvents(observation.events))?.config;
2098
+ if (loggedConfig !== undefined) model = { provider: loggedConfig.provider, model: loggedConfig.model };
2099
+ } catch {
2100
+ return undefined;
2101
+ } finally {
2102
+ stored?.[Symbol.dispose]?.();
2103
+ }
2104
+ const ok = await this.materializeStored(sessionId, presetId, model);
2105
+ if (!ok || this.disposed) return undefined;
2106
+ return this.ctx.agents.get(sessionId);
2107
+ }
2108
+
2109
+ /** 唤醒文本必须带会话级证据: 否则父会话看不到任何状态, 只会白跑一轮再回一句"都结束了"。 */
2110
+ private buildChildResumeText(
2111
+ config: AutoContinueConfig,
2112
+ children: readonly ChildInterrupt[],
2113
+ ): string {
2114
+ const lines = children.map((child) => {
2115
+ const label = child.title !== undefined ? `「${child.title}」` : '';
2116
+ const preset = child.preset !== undefined ? ` (${child.preset})` : '';
2117
+ const cause = CHILD_CAUSE_COPY[config.locale][child.cause];
2118
+ return `- ${child.id} ${label}${preset} — ${cause}`;
2119
+ });
2120
+ const header = config.locale === 'zh'
2121
+ ? '重启时你开的以下子代理 / 团队成员会话被打断, 没有跑完。请逐个检查, 按需要继续或收尾:'
2122
+ : 'These child sessions you started (subagent / team member) were interrupted by a restart and did not finish. Check each one and either continue it or wrap it up:';
2123
+ const tail = config.locale === 'zh'
2124
+ ? '要继续的用 send_message / subagent 重新拉起对应会话(重启后它们并未加载); 已完成或不再需要的, 说明结论即可。'
2125
+ : 'Use send_message (or subagent) to bring back the ones that should continue — they are not loaded after the restart; for finished or abandoned ones, just state the conclusion.';
2126
+ return [header, ...lines, tail].join('\n');
2127
+ }
2128
+
2129
+ /**
2130
+ * 重启会把 active goal 置为 disarmed(宿主卸载驱动的正常动作), 只有人类授权的
2131
+ * resume 能重新 arm; paused 则是人类的显式决定。两者都默认关闭。
2132
+ */
2133
+ private rearmGoal(sessionId: SessionId, config: AutoContinueConfig): void {
2134
+ if (!config.resumeGoals) return;
2135
+ const goals = (this.ctx as unknown as { get(key: string): unknown }).get(GOALS_SERVICE_KEY) as
2136
+ | GoalServiceLike
2137
+ | undefined;
2138
+ if (goals === undefined) return;
2139
+ const agent = this.ctx.agents.get(sessionId);
2140
+ if (agent === undefined) return;
2141
+ try {
2142
+ const view = goals.get(agent);
2143
+ if (view === undefined) return;
2144
+ // 宿主的 view() 不带 ref 字段, 而 resume() 用 revision 做 CAS 校验(expectCurrent):
2145
+ // 只带 id 必定抛 GOAL_STALE_REVISION 被这里 catch 成一行日志 —— 等于开关失效。
2146
+ // 缺 revision 时 fail closed, 不猜。
2147
+ const revision = view.revision;
2148
+ if (revision === undefined) {
2149
+ this.log(`会话 ${sessionId}: goal 视图缺 revision, 跳过重新武装(宿主会拒绝无 revision 的 resume)`);
2150
+ return;
2151
+ }
2152
+ const ref: GoalRefLike = view.ref ?? { id: view.id, revision };
2153
+ if (view.phase === 'active' && view.activation === 'disarmed') {
2154
+ goals.resume(agent, ref);
2155
+ this.log(`会话 ${sessionId}: goal 被重启失活, 已重新武装`);
2156
+ return;
2157
+ }
2158
+ if (view.phase === 'paused' && config.resumePausedGoals) {
2159
+ goals.resume(agent, ref);
2160
+ this.log(`会话 ${sessionId}: 已恢复被暂停的 goal`);
2161
+ }
2162
+ } catch (error) {
2163
+ this.ctx.logger.info(
2164
+ `goal 恢复失败 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`,
2165
+ );
2166
+ }
2167
+ }
2168
+
1599
2169
  /**
1600
2170
  * 按会话记录的 preset 组合把存储会话恢复为 live agent(镜像会话控制
1601
2171
  * 器的 adopt 路径: preset 挂载 + 会话已记录的模型选择回装)。模型选择