dsh-client-auto-continue 0.19.0 → 0.20.1

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.
@@ -14,6 +14,7 @@
14
14
  */
15
15
 
16
16
  import type { Context } from '@deepseek-ai/cordis';
17
+ import { randomUUID } from 'node:crypto';
17
18
  import { createUserMessage } from '@deepseek-ai/dsh-llm';
18
19
  import type { Agent } from '@deepseek-ai/dsh-agent';
19
20
  import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types';
@@ -128,6 +129,13 @@ const SWEEP_OBSERVE_BATCH = 16;
128
129
  const STORED_READ_TIMEOUT_MS = 5000;
129
130
  /** 单个存储会话连续观察/物化失败达此数后放弃, 避免坏日志反复占满每轮观察配额。 */
130
131
  const SWEEP_MAX_FAILURES = 3;
132
+ /**
133
+ * 一次启动最多冷读多少个存储会话。冷读要整份解码日志(zstd → 逐行 JSON.parse),
134
+ * 几百个会话连着读完足以把宿主堆(默认约 3.4GB)打满; 配额把启动期的内存和耗时
135
+ * 都封住。每个会话只计一次(失败重试、暂停后重读不再扣配额)。排序每次启动都一样,
136
+ * 配额之外的会话等于被跳过——它们最近活动最早, 在 freshMs 窗口内几乎不可能还新鲜。
137
+ */
138
+ const STORED_SWEEP_READ_LIMIT = 32;
131
139
 
132
140
  /** Why a child session needs its root session woken after a restart. */
133
141
  type ChildInterruptCause = 'open-turn' | 'disposed' | 'interrupted' | 'max-tokens' | 'error';
@@ -147,6 +155,14 @@ interface SessionHeaderLike {
147
155
  readonly parentSession?: SessionId;
148
156
  }
149
157
 
158
+ /** The projection cache's zero-I/O listing read, as far as this module uses it. */
159
+ interface ProjectionCacheLike {
160
+ cachedSnapshot(
161
+ meta: SessionHeaderLike,
162
+ keys?: readonly string[],
163
+ ): { readonly values: Record<string, unknown> } | undefined;
164
+ }
165
+
150
166
  /** Cancel causes a host shutdown or a restart produces; only these justify a wake-up. */
151
167
  const RESTART_CANCEL_CAUSES: ReadonlySet<string> = new Set(['disposed', 'legacy']);
152
168
  /** Cancel causes that record an explicit human or parent decision; never recover these. */
@@ -155,9 +171,25 @@ const DECISION_CANCEL_CAUSES: ReadonlySet<string> = new Set(['user', 'parent', '
155
171
  const CHILD_SWEEP_LIMIT = 8;
156
172
  /** Bound how many ancestor hops a dirty parent chain may cost before giving up. */
157
173
  const CHILD_ROOT_MAX_DEPTH = 8;
174
+ /** Do not hand the same child failure to its main conversation more often than this. */
175
+ const HANDOFF_COOLDOWN_MS = 5 * 60 * 1000;
176
+ /** Bound the host cold-resume call: a stalled service must not block recovery forever. */
177
+ const REVIVE_TIMEOUT_MS = 15_000;
178
+
179
+ /** Copy for the live hand-off that replaces an impossible child resume, keyed by UI locale. */
180
+ const HANDOFF_COPY = {
181
+ zh: (child: string, code: string) =>
182
+ `子代理会话 ${child} 因 ${code} 中断, 已无法直接续跑。请检查它的状态, 然后继续或收尾。`,
183
+ en: (child: string, code: string) =>
184
+ `Child session ${child} was interrupted by ${code} and can no longer be resumed directly. Check its state, then continue it or wrap it up.`,
185
+ ru: (child: string, code: string) =>
186
+ `Дочерняя сессия ${child} прервалась из-за ${code} и больше не может быть продолжена напрямую. Проверь её состояние и продолжи или заверши.`,
187
+ } as const satisfies Record<AutoContinueLocale, (child: string, code: string) => string>;
158
188
 
159
189
  /** Host service key for goals (0.2.x); older hosts simply do not register it. */
160
190
  const GOALS_SERVICE_KEY = 'goals';
191
+ /** Host service key for the projection checkpoint cache; older hosts do not register it. */
192
+ const PROJECTION_CACHE_SERVICE_KEY = 'sessionProjectionCache';
161
193
 
162
194
  /** Copy for each child interruption cause, keyed by UI locale. */
163
195
  const CHILD_CAUSE_COPY = {
@@ -459,6 +491,10 @@ export class AutoContinueRunner {
459
491
  private readonly noticeListeners = new Set<() => void>();
460
492
  private readonly stateListeners = new Set<() => void>();
461
493
  private readonly prioritizedFollowups = new Set<string>();
494
+ /** In-flight cold-resume calls, aborted when the plugin unloads. */
495
+ private readonly reviveControllers = new Set<AbortController>();
496
+ /** Hand-offs waiting for a live main conversation: parent -> child -> text. */
497
+ private readonly deferredHandoffs = new Map<SessionId, Map<SessionId, string>>();
462
498
  private readonly disposeSessionEvents: () => void;
463
499
  private readonly disposeInboxEvents: () => void;
464
500
  private disposed = false;
@@ -480,6 +516,9 @@ export class AutoContinueRunner {
480
516
  /** 存储会话的连续观察/物化失败次数, 触达 SWEEP_MAX_FAILURES 后不再重试。 */
481
517
  private readonly storedSweepFailures = new Map<SessionId, number>();
482
518
  private storedSweepAnnounced = false;
519
+ /** 本次启动已花掉的存储会话冷读配额(跨轮累计, 启动扫描窗口内不再重置)。 */
520
+ private readonly storedReadIds = new Set<SessionId>();
521
+ private storedBudgetLogged = false;
483
522
  private bootScanTimer: ReturnType<typeof setTimeout> | undefined;
484
523
  private wakeBootScan: (() => void) | undefined;
485
524
  private storedSweep: Promise<void> | undefined;
@@ -671,6 +710,10 @@ export class AutoContinueRunner {
671
710
  this.wakeBootScan = undefined;
672
711
  this.disposeSessionEvents();
673
712
  this.disposeInboxEvents();
713
+ // Unload is an opt-out: never deliver a continuation after disposal.
714
+ for (const controller of this.reviveControllers) controller.abort();
715
+ this.reviveControllers.clear();
716
+ this.deferredHandoffs.clear();
674
717
  this.prioritizedFollowups.clear();
675
718
  for (const state of this.states.values()) {
676
719
  if (state.pendingTimer !== undefined) clearTimeout(state.pendingTimer);
@@ -877,6 +920,9 @@ export class AutoContinueRunner {
877
920
  */
878
921
  private onHostEvent(session: Session, event: SessionEvent): void {
879
922
  const sessionId = session.id;
923
+ // A main conversation that just came live again receives the hand-offs that
924
+ // were deferred while it had no agent.
925
+ this.flushDeferredHandoffs(sessionId);
880
926
  const sessionState = this.states.get(sessionId);
881
927
  if (session.header?.origin === 'subagent') {
882
928
  this.markSubagent(sessionId, sessionState ?? this.state(sessionId), session.header.parentSession);
@@ -1232,12 +1278,14 @@ export class AutoContinueRunner {
1232
1278
  if (this.sessionConfig(sessionId).resumeCompletedTurns) {
1233
1279
  if (turnOutput === 'visible') {
1234
1280
  state.consecutive = 0;
1281
+ state.recovering = false;
1235
1282
  state.lastFailure = undefined;
1236
1283
  this.noteRecovery(sessionId, 'completed');
1237
1284
  }
1238
1285
  this.schedule(sessionId, LOOP_COMPLETED_REASON, true);
1239
1286
  } else if (turnOutput === 'visible') {
1240
1287
  state.consecutive = 0;
1288
+ state.recovering = false;
1241
1289
  state.lastFailure = undefined;
1242
1290
  this.noteRecovery(sessionId, 'completed');
1243
1291
  }
@@ -1277,6 +1325,7 @@ export class AutoContinueRunner {
1277
1325
  } else {
1278
1326
  // 用户主动停止: 不自动继续, 视为用户介入
1279
1327
  state.consecutive = 0;
1328
+ state.recovering = false;
1280
1329
  state.pendingRecoveryAt = 0;
1281
1330
  }
1282
1331
  } else if (reasonKind === 'blocked') {
@@ -1311,6 +1360,7 @@ export class AutoContinueRunner {
1311
1360
  if (event.data.source.kind === 'user') {
1312
1361
  // 用户手动介入: 清零上限与跨标签页发送计数
1313
1362
  state.consecutive = 0;
1363
+ state.recovering = false;
1314
1364
  this.resetLoopIterations(state);
1315
1365
  this.cancelPending(sessionId, '用户手动发送消息');
1316
1366
  }
@@ -1329,7 +1379,15 @@ export class AutoContinueRunner {
1329
1379
  // Off parent or the disabled setting means no live recovery at all. The
1330
1380
  // global pause is not checked here, so diagnostics for permanent errors
1331
1381
  // match ordinary sessions while paused.
1332
- if (!this.subagentRecoveryEnabled(sessionId)) return;
1382
+ if (!this.subagentRecoveryEnabled(sessionId)) {
1383
+ const parent = this.parentOf(sessionId);
1384
+ if (parent !== undefined && parent !== '' && this.ctx.agents.get(parent) === undefined) {
1385
+ // Lineage is known but the parent is offline: keep the failure so the
1386
+ // hand-off is delivered once the main conversation is live again.
1387
+ this.deferHandoff(parent, sessionId, this.handoffText(sessionId, reason));
1388
+ }
1389
+ return;
1390
+ }
1333
1391
  } else if (sessionMode(config.sessionModes, sessionId) === 'off') return;
1334
1392
  if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
1335
1393
  const copy = NOTICE_COPY[config.locale];
@@ -1515,6 +1573,7 @@ export class AutoContinueRunner {
1515
1573
  }, config.graceMs);
1516
1574
  state.pendingTimer = timer;
1517
1575
  state.pendingReason = reason;
1576
+ state.recovering = true;
1518
1577
  const template = this.templateFor(config, reason);
1519
1578
  this.log(
1520
1579
  `检测到非人为中断 ${sessionId}(${reason}), ${config.graceMs}ms 后自动发送「${template}」`,
@@ -1529,6 +1588,7 @@ export class AutoContinueRunner {
1529
1588
  const state = this.state(sessionId);
1530
1589
  if (state.cooldownRetryTimer !== undefined) clearTimeout(state.cooldownRetryTimer);
1531
1590
  state.pendingReason = reason;
1591
+ state.recovering = true;
1532
1592
  state.cooldownRetryTimer = setTimeout(() => {
1533
1593
  state.cooldownRetryTimer = undefined;
1534
1594
  state.pendingReason = undefined;
@@ -1582,6 +1642,234 @@ export class AutoContinueRunner {
1582
1642
  if (cancelled) this.log(`取消 ${sessionId} 的自动继续(${why})`);
1583
1643
  }
1584
1644
 
1645
+ /** Host-service facade used to cold-resume a disposed direct child. */
1646
+ private subagentPromptProvider: (() => unknown) | undefined;
1647
+
1648
+ /** Attach the loader-provided subagent service; it may load after this plugin. */
1649
+ setSubagentPromptProvider(provider: (() => unknown) | undefined): void {
1650
+ this.subagentPromptProvider = provider;
1651
+ }
1652
+
1653
+ private subagentPrompts(): {
1654
+ prompt?: (
1655
+ request: {
1656
+ parentSessionId: string;
1657
+ childSessionId: string;
1658
+ mode: 'continuable';
1659
+ requestId: string;
1660
+ content: readonly { type: 'text'; text: string }[];
1661
+ delivery: 'queue' | 'steer';
1662
+ },
1663
+ signal: AbortSignal,
1664
+ ) => Promise<{ messageId?: string }>
1665
+ } | undefined {
1666
+ const provided = this.subagentPromptProvider?.();
1667
+ if (provided !== undefined && provided !== null) return provided as ReturnType<typeof this.subagentPrompts>;
1668
+ try {
1669
+ return this.ctx.get('subagents') as ReturnType<typeof this.subagentPrompts>;
1670
+ } catch {
1671
+ return undefined;
1672
+ }
1673
+ }
1674
+
1675
+ /** Copy for one child hand-off, built once so a deferred delivery matches. */
1676
+ private handoffText(sessionId: SessionId, reason: string): string {
1677
+ const code = this.state(sessionId).lastFailure?.code ?? reason;
1678
+ return HANDOFF_COPY[this.sessionConfig(sessionId).locale](sessionId, code);
1679
+ }
1680
+
1681
+ /**
1682
+ * Revive a disposed child through the host's cold resume and deliver the
1683
+ * continuation to it. Falls back to the main-conversation hand-off when the
1684
+ * host cannot resume (no persistence, no live parent, not a direct child).
1685
+ * The child's own recovery mode decides; the parent only has to be alive to
1686
+ * authorize the call.
1687
+ */
1688
+ private async reviveChild(sessionId: SessionId, reason: string, text: string, force: boolean): Promise<void> {
1689
+ if (this.disposed || this.getConfig().paused) return;
1690
+ if (!this.subagentRecoveryEnabled(sessionId)) return;
1691
+ const state = this.state(sessionId);
1692
+ if (state.reviveInFlight === true) {
1693
+ this.log(`冷恢复跳过 ${sessionId}: 已有请求在途中`);
1694
+ return;
1695
+ }
1696
+ const config = this.sessionConfig(sessionId);
1697
+ if (!force) {
1698
+ // Cold resume spends the same retry budget as a live send: record the
1699
+ // attempt before awaiting, otherwise repeated failures bypass cooldown and
1700
+ // the consecutive cap.
1701
+ if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) {
1702
+ this.log(`冷恢复跳过 ${sessionId}: 处于冷却期`);
1703
+ return;
1704
+ }
1705
+ if (state.consecutive >= config.maxConsecutive) {
1706
+ this.log(`冷恢复跳过 ${sessionId}: 已连续自动继续 ${state.consecutive} 次`);
1707
+ return;
1708
+ }
1709
+ }
1710
+ const parent = this.parentOf(sessionId);
1711
+ if (parent === undefined || parent === '') return;
1712
+ const handoff = this.handoffText(sessionId, reason);
1713
+ const parentAgent = this.ctx.agents.get(parent);
1714
+ if (parentAgent === undefined) {
1715
+ this.deferHandoff(parent, sessionId, handoff);
1716
+ return;
1717
+ }
1718
+ const prompts = this.subagentPrompts();
1719
+ if (typeof prompts?.prompt !== 'function') {
1720
+ this.handOffToParent(sessionId, reason, handoff);
1721
+ return;
1722
+ }
1723
+ state.lastAttemptAt = Date.now();
1724
+ state.consecutive += 1;
1725
+ state.reviveInFlight = true;
1726
+ const controller = new AbortController();
1727
+ this.reviveControllers.add(controller);
1728
+ let timedOut = false;
1729
+ const timeout = setTimeout(() => {
1730
+ timedOut = true;
1731
+ controller.abort();
1732
+ }, REVIVE_TIMEOUT_MS);
1733
+ try {
1734
+ await prompts.prompt(
1735
+ {
1736
+ parentSessionId: parent,
1737
+ childSessionId: sessionId,
1738
+ mode: 'continuable',
1739
+ requestId: randomUUID(),
1740
+ content: [{ type: 'text', text }],
1741
+ delivery: 'queue',
1742
+ },
1743
+ controller.signal,
1744
+ );
1745
+ this.log(`已冷恢复子代理 ${sessionId}`);
1746
+ } catch (error) {
1747
+ // An unload aborts the call on purpose; deliver nothing after opting out.
1748
+ if (this.disposed) return;
1749
+ this.log(`冷恢复 ${sessionId} 失败${timedOut ? '(超时)' : ''}: ${error instanceof Error ? error.message : String(error)}`);
1750
+ this.handOffToParent(sessionId, reason, handoff);
1751
+ } finally {
1752
+ clearTimeout(timeout);
1753
+ this.reviveControllers.delete(controller);
1754
+ state.reviveInFlight = false;
1755
+ }
1756
+ }
1757
+
1758
+ /** Existing state of a session, without materializing one just to read it. */
1759
+ private parentState(sessionId: SessionId): SessionState | undefined {
1760
+ return this.states.get(sessionId);
1761
+ }
1762
+
1763
+ /** Whether this session already has a continuation on the way. */
1764
+ private hasPendingSend(state: SessionState): boolean {
1765
+ return state.pendingTimer !== undefined
1766
+ || state.cooldownRetryTimer !== undefined
1767
+ || state.loopRetryTimer !== undefined
1768
+ || state.offlineWait !== undefined
1769
+ || state.offlineTimer !== undefined;
1770
+ }
1771
+
1772
+ /**
1773
+ * Ask the child's main conversation to take over a failure the plugin cannot
1774
+ * repair itself: the child handle is gone, so only the root can continue it.
1775
+ * The main conversation's Off is respected because this writes a user message
1776
+ * into it; a child's own mode is never overridden by that Off for cold resume.
1777
+ */
1778
+ private handOffToParent(sessionId: SessionId, reason: string, text?: string): void {
1779
+ if (this.disposed || this.getConfig().paused) return;
1780
+ if (!this.subagentRecoveryEnabled(sessionId)) return;
1781
+ const parent = this.parentOf(sessionId);
1782
+ if (parent === undefined || parent === '') return;
1783
+ if (this.explicitMode(parent) === 'off') return;
1784
+ const state = this.state(sessionId);
1785
+ const now = Date.now();
1786
+ if (state.handedOffAt !== undefined && now - state.handedOffAt < HANDOFF_COOLDOWN_MS) return;
1787
+ const handoff = text ?? this.handoffText(sessionId, reason);
1788
+ const parentAgent = this.ctx.agents.get(parent);
1789
+ if (parentAgent === undefined) {
1790
+ this.deferHandoff(parent, sessionId, handoff);
1791
+ return;
1792
+ }
1793
+ // Any user message into the main conversation cancels its queued continuation,
1794
+ // and DSH already tells it which child failed. Stay silent while it recovers.
1795
+ const parentState = this.parentState(parent);
1796
+ if (parentState !== undefined && (parentState.recovering === true || this.hasPendingSend(parentState))) {
1797
+ this.log(`移交跳过 ${sessionId}: 主会话 ${parent} 正在自行恢复`);
1798
+ return;
1799
+ }
1800
+ try {
1801
+ this.sendHandoff(parent, parentAgent, handoff);
1802
+ state.handedOffAt = now;
1803
+ this.log(`已将子代理 ${sessionId} 的失败移交主会话 ${parent}`);
1804
+ } catch (error) {
1805
+ this.log(`移交 ${sessionId} 失败: ${error instanceof Error ? error.message : String(error)}`);
1806
+ }
1807
+ }
1808
+
1809
+ /**
1810
+ * Post a hand-off into the main conversation the same way a continuation is
1811
+ * sent: with the configured message source, and registered as our own echo so
1812
+ * the parent does not read it as the user stepping in (which would reset its
1813
+ * retry and loop counters and cancel whatever it had queued).
1814
+ */
1815
+ private sendHandoff(parent: SessionId, parentAgent: Agent, text: string): void {
1816
+ const parentState = this.state(parent);
1817
+ const message = createUserMessage({
1818
+ content: [{ type: 'text', text }],
1819
+ source: { kind: this.getConfig().usePluginSource ? AUTO_CONTINUE_SOURCE_KIND : 'user' },
1820
+ });
1821
+ trackPendingEcho(parentState, message.id);
1822
+ try {
1823
+ parentAgent.followup(message);
1824
+ } catch (error) {
1825
+ forgetPendingEcho(parentState, message.id);
1826
+ throw error;
1827
+ }
1828
+ }
1829
+
1830
+ /** Keep one hand-off until its main conversation has a live agent again. */
1831
+ private deferHandoff(parent: SessionId, sessionId: SessionId, text: string): void {
1832
+ // Only live subagent recovery hands failures off; with it off nothing is kept.
1833
+ if (!this.getConfig().resumeSubagentSessions) return;
1834
+ const state = this.state(sessionId);
1835
+ const now = Date.now();
1836
+ if (state.handedOffAt !== undefined && now - state.handedOffAt < HANDOFF_COOLDOWN_MS) return;
1837
+ let pending = this.deferredHandoffs.get(parent);
1838
+ if (pending === undefined) {
1839
+ pending = new Map();
1840
+ this.deferredHandoffs.set(parent, pending);
1841
+ }
1842
+ pending.set(sessionId, text);
1843
+ this.log(`移交暂存 ${sessionId}: 主会话 ${parent} 无 live agent`);
1844
+ }
1845
+
1846
+ /** Deliver queued hand-offs once their main conversation is live again. */
1847
+ private flushDeferredHandoffs(parent: SessionId): void {
1848
+ const pending = this.deferredHandoffs.get(parent);
1849
+ if (pending === undefined || pending.size === 0) return;
1850
+ if (this.explicitMode(parent) === 'off') {
1851
+ this.deferredHandoffs.delete(parent);
1852
+ return;
1853
+ }
1854
+ const parentAgent = this.ctx.agents.get(parent);
1855
+ if (parentAgent === undefined) return;
1856
+ this.deferredHandoffs.delete(parent);
1857
+ const now = Date.now();
1858
+ for (const [child, text] of pending) {
1859
+ // The parent may have turned the child's recovery off meanwhile.
1860
+ if (!this.subagentRecoveryEnabled(child)) continue;
1861
+ const state = this.state(child);
1862
+ if (state.handedOffAt !== undefined && now - state.handedOffAt < HANDOFF_COOLDOWN_MS) continue;
1863
+ try {
1864
+ this.sendHandoff(parent, parentAgent, text);
1865
+ state.handedOffAt = now;
1866
+ this.log(`已移交暂存子代理 ${child} 给主会话 ${parent}`);
1867
+ } catch (error) {
1868
+ this.log(`暂存移交 ${child} 失败: ${error instanceof Error ? error.message : String(error)}`);
1869
+ }
1870
+ }
1871
+ }
1872
+
1585
1873
  private fire(sessionId: SessionId, reason: string, force = false): void {
1586
1874
  if (this.disposed) return;
1587
1875
  const state = this.state(sessionId);
@@ -1593,7 +1881,15 @@ export class AutoContinueRunner {
1593
1881
  if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
1594
1882
  // Direct sends (notifications) must respect the setting and the inherited
1595
1883
  // mode even though they bypass the paused flag below.
1596
- if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) return;
1884
+ if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) {
1885
+ const parent = this.parentOf(sessionId);
1886
+ if (parent !== undefined && parent !== '' && this.ctx.agents.get(parent) === undefined) {
1887
+ // Lineage is known but the parent is offline: keep the failure so the
1888
+ // hand-off can be delivered once the main conversation is live again.
1889
+ this.deferHandoff(parent, sessionId, this.handoffText(sessionId, reason));
1890
+ }
1891
+ return;
1892
+ }
1597
1893
  if (config.paused && !manualResume) {
1598
1894
  this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
1599
1895
  return;
@@ -1617,6 +1913,14 @@ export class AutoContinueRunner {
1617
1913
  // 发送: followup 负责唤醒; 同步 inbox 插入事件会在唤醒前把本消息移到已有队列之前。
1618
1914
  const agent = this.ctx.agents.get(sessionId);
1619
1915
  if (agent === undefined) {
1916
+ // A failed child is settled and disposed by the subagent runtime before the
1917
+ // send window opens, so a direct resume cannot reach it. Ask the host to
1918
+ // cold-resume it from persistence; when that is unavailable, hand the
1919
+ // failure to its main conversation instead. A manual "Resume now" must
1920
+ // revive a disposed child too: its force flag only relaxes the cooldown.
1921
+ if (this.isSubagentSession(sessionId) && this.subagentRecoveryEnabled(sessionId)) {
1922
+ void this.reviveChild(sessionId, reason, text, manualResume);
1923
+ }
1620
1924
  this.log(`跳过 ${sessionId}(${reason}): 无 live agent`);
1621
1925
  return;
1622
1926
  }
@@ -1638,6 +1942,9 @@ export class AutoContinueRunner {
1638
1942
  this.prioritizedFollowups.delete(message.id);
1639
1943
  }
1640
1944
  const now = Date.now();
1945
+ // The continuation is on the wire: the session is recovering itself until a
1946
+ // successful turn ends or the user intervenes. Child hand-offs read this.
1947
+ state.recovering = true;
1641
1948
  // 续跑已发出: 被重启失活的 goal 需要在这里重新武装, 否则续跑消息会跑但
1642
1949
  // goal 的自动继续轮不会转起来(disarm 是宿主卸载驱动的正常动作)。
1643
1950
  this.rearmGoal(sessionId, config);
@@ -1742,6 +2049,7 @@ export class AutoContinueRunner {
1742
2049
  const token = {};
1743
2050
  state.offlineWait = token;
1744
2051
  state.pendingReason = reason;
2052
+ state.recovering = true;
1745
2053
  void this.checkConnectivity().then((online) => {
1746
2054
  if (this.disposed || state.offlineWait !== token) return; // 已被取消或被新的检测取代
1747
2055
  if (online) {
@@ -2027,6 +2335,13 @@ export class AutoContinueRunner {
2027
2335
  }
2028
2336
  }
2029
2337
  let observed = 0;
2338
+ // 先只做零成本的筛除, 把要花冷读的根会话收进候选集, 再统一排序、按配额读。
2339
+ const roots: {
2340
+ sessionId: SessionId;
2341
+ header: SessionHeaderLike & { createdAt?: number };
2342
+ recency: number;
2343
+ index: number;
2344
+ }[] = [];
2030
2345
  for (const record of records) {
2031
2346
  if (this.disposed || Date.now() >= deadline || this.getConfig().paused || !this.getConfig().scanOnBoot) return;
2032
2347
  if (typeof record?.header?.id !== 'string' || record.header.id === '') {
@@ -2045,6 +2360,24 @@ export class AutoContinueRunner {
2045
2360
  continue;
2046
2361
  }
2047
2362
  if (record.live || this.storedSwept.has(sessionId)) continue;
2363
+ roots.push({ sessionId, header: record.header, recency: 0, index: roots.length });
2364
+ }
2365
+ if (roots.length > 0) {
2366
+ const cache = this.projectionCache();
2367
+ for (const root of roots) root.recency = this.storedRecency(cache, root.header);
2368
+ roots.sort((left, right) => right.recency - left.recency || left.index - right.index);
2369
+ }
2370
+ for (const root of roots) {
2371
+ if (this.disposed || Date.now() >= deadline || this.getConfig().paused || !this.getConfig().scanOnBoot) return;
2372
+ if (!this.storedReadIds.has(root.sessionId) && this.storedReadIds.size >= STORED_SWEEP_READ_LIMIT) {
2373
+ if (!this.storedBudgetLogged) {
2374
+ this.storedBudgetLogged = true;
2375
+ this.log(`存储扫描冷读已达上限 ${STORED_SWEEP_READ_LIMIT} 个会话, 其余会话本次启动跳过`);
2376
+ }
2377
+ return;
2378
+ }
2379
+ const sessionId = root.sessionId;
2380
+ this.storedReadIds.add(sessionId);
2048
2381
  this.storedSwept.add(sessionId);
2049
2382
  observed += 1;
2050
2383
  let observation: StoredObservation | undefined;
@@ -2142,6 +2475,40 @@ export class AutoContinueRunner {
2142
2475
  }
2143
2476
  }
2144
2477
 
2478
+ /** The optional projection checkpoint cache; absent on hosts that do not ship it. */
2479
+ private projectionCache(): ProjectionCacheLike | undefined {
2480
+ try {
2481
+ return this.ctx.get(PROJECTION_CACHE_SERVICE_KEY) as ProjectionCacheLike | undefined;
2482
+ } catch {
2483
+ // 排序提示拿不到时回退到创建时间, 不能影响裁决。
2484
+ return undefined;
2485
+ }
2486
+ }
2487
+
2488
+ /**
2489
+ * 冷读排序提示: 投影检查点里的最近活动时间, 没有检查点时回退到会话创建时间。
2490
+ * 检查点只会落后于日志、不会超前, 所以这个数只用来排序, 不用来跳过会话。
2491
+ */
2492
+ private storedRecency(
2493
+ cache: ProjectionCacheLike | undefined,
2494
+ header: SessionHeaderLike & { createdAt?: number },
2495
+ ): number {
2496
+ const created = typeof header.createdAt === 'number' ? header.createdAt : 0;
2497
+ if (cache === undefined) return created;
2498
+ try {
2499
+ const block = cache.cachedSnapshot(header, ['timeContext', 'sessionListMetadata']);
2500
+ const values = block?.values as {
2501
+ timeContext?: { lastMessageTime?: number };
2502
+ sessionListMetadata?: { lastPromptAt?: number };
2503
+ } | undefined;
2504
+ const at = values?.timeContext?.lastMessageTime ?? values?.sessionListMetadata?.lastPromptAt;
2505
+ return typeof at === 'number' && Number.isFinite(at) ? at : created;
2506
+ } catch {
2507
+ // 缓存读失败只影响排序, 不影响裁决。
2508
+ return created;
2509
+ }
2510
+ }
2511
+
2145
2512
  /**
2146
2513
  * 子会话裁决。子会话本身永不直接续跑(父代理权威, 见 README), 但启动扫描要
2147
2514
  * 知道它是否在重启时被打断, 才能在自己的 root 会话上补一次带清单的唤醒。
package/src/index.ts CHANGED
@@ -180,6 +180,17 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
180
180
  disposeEngine?.();
181
181
  const readConfig = () => resolveConfig(legacyConfig?.() ?? readEntry());
182
182
  const runner = new AutoContinueRunner(engineCtx, readConfig);
183
+ // The subagent service may load after this plugin, and the engine context does
184
+ // not see it through `get`; inject the facade lazily so a later load is picked
185
+ // up and a disposed child can be cold-resumed instead of only handed off.
186
+ // Scoped to this engine, so a rebuilt engine does not stack another inject,
187
+ // and the provider is cleared again when the service unloads.
188
+ engineCtx.inject(['subagents'], (subagentCtx) => {
189
+ runner.setSubagentPromptProvider(
190
+ () => (subagentCtx as unknown as { subagents?: unknown }).subagents,
191
+ );
192
+ subagentCtx.effect(() => () => runner.setSubagentPromptProvider(undefined));
193
+ });
183
194
  const writableSettings = () => {
184
195
  const settings = engineCtx.get('settings');
185
196
  return settings?.writable && typeof settings.mutate === 'function' ? settings : undefined;
@@ -961,6 +961,12 @@ export interface SessionState {
961
961
  lastFailure: FailureFacts | undefined;
962
962
  /** 最近一次失败的发生时间(模板 {elapsed} 与恢复统计用)。 */
963
963
  lastFailureAt: number;
964
+ /** 最近一次把子代理失败移交主会话的时间戳(去重)。 */
965
+ handedOffAt?: number;
966
+ /** 冷恢复请求正在途中(去重, 防止重复 prompt)。 */
967
+ reviveInFlight?: boolean;
968
+ /** 主会话正在自行恢复: 由插件自己的调度/发送显式维护, 不用时间戳猜测。 */
969
+ recovering?: boolean;
964
970
  /** callId 精确配对的工具调用、幂等护栏与 loop 重复态。 */
965
971
  tools: ToolInvocationTracker;
966
972
  /** 失败回合的编号(模板 {turn})。 */