dsh-client-auto-continue 0.19.0 → 0.20.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.
@@ -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';
@@ -155,6 +156,20 @@ const DECISION_CANCEL_CAUSES: ReadonlySet<string> = new Set(['user', 'parent', '
155
156
  const CHILD_SWEEP_LIMIT = 8;
156
157
  /** Bound how many ancestor hops a dirty parent chain may cost before giving up. */
157
158
  const CHILD_ROOT_MAX_DEPTH = 8;
159
+ /** Do not hand the same child failure to its main conversation more often than this. */
160
+ const HANDOFF_COOLDOWN_MS = 5 * 60 * 1000;
161
+ /** Bound the host cold-resume call: a stalled service must not block recovery forever. */
162
+ const REVIVE_TIMEOUT_MS = 15_000;
163
+
164
+ /** Copy for the live hand-off that replaces an impossible child resume, keyed by UI locale. */
165
+ const HANDOFF_COPY = {
166
+ zh: (child: string, code: string) =>
167
+ `子代理会话 ${child} 因 ${code} 中断, 已无法直接续跑。请检查它的状态, 然后继续或收尾。`,
168
+ en: (child: string, code: string) =>
169
+ `Child session ${child} was interrupted by ${code} and can no longer be resumed directly. Check its state, then continue it or wrap it up.`,
170
+ ru: (child: string, code: string) =>
171
+ `Дочерняя сессия ${child} прервалась из-за ${code} и больше не может быть продолжена напрямую. Проверь её состояние и продолжи или заверши.`,
172
+ } as const satisfies Record<AutoContinueLocale, (child: string, code: string) => string>;
158
173
 
159
174
  /** Host service key for goals (0.2.x); older hosts simply do not register it. */
160
175
  const GOALS_SERVICE_KEY = 'goals';
@@ -459,6 +474,10 @@ export class AutoContinueRunner {
459
474
  private readonly noticeListeners = new Set<() => void>();
460
475
  private readonly stateListeners = new Set<() => void>();
461
476
  private readonly prioritizedFollowups = new Set<string>();
477
+ /** In-flight cold-resume calls, aborted when the plugin unloads. */
478
+ private readonly reviveControllers = new Set<AbortController>();
479
+ /** Hand-offs waiting for a live main conversation: parent -> child -> text. */
480
+ private readonly deferredHandoffs = new Map<SessionId, Map<SessionId, string>>();
462
481
  private readonly disposeSessionEvents: () => void;
463
482
  private readonly disposeInboxEvents: () => void;
464
483
  private disposed = false;
@@ -671,6 +690,10 @@ export class AutoContinueRunner {
671
690
  this.wakeBootScan = undefined;
672
691
  this.disposeSessionEvents();
673
692
  this.disposeInboxEvents();
693
+ // Unload is an opt-out: never deliver a continuation after disposal.
694
+ for (const controller of this.reviveControllers) controller.abort();
695
+ this.reviveControllers.clear();
696
+ this.deferredHandoffs.clear();
674
697
  this.prioritizedFollowups.clear();
675
698
  for (const state of this.states.values()) {
676
699
  if (state.pendingTimer !== undefined) clearTimeout(state.pendingTimer);
@@ -877,6 +900,9 @@ export class AutoContinueRunner {
877
900
  */
878
901
  private onHostEvent(session: Session, event: SessionEvent): void {
879
902
  const sessionId = session.id;
903
+ // A main conversation that just came live again receives the hand-offs that
904
+ // were deferred while it had no agent.
905
+ this.flushDeferredHandoffs(sessionId);
880
906
  const sessionState = this.states.get(sessionId);
881
907
  if (session.header?.origin === 'subagent') {
882
908
  this.markSubagent(sessionId, sessionState ?? this.state(sessionId), session.header.parentSession);
@@ -1232,12 +1258,14 @@ export class AutoContinueRunner {
1232
1258
  if (this.sessionConfig(sessionId).resumeCompletedTurns) {
1233
1259
  if (turnOutput === 'visible') {
1234
1260
  state.consecutive = 0;
1261
+ state.recovering = false;
1235
1262
  state.lastFailure = undefined;
1236
1263
  this.noteRecovery(sessionId, 'completed');
1237
1264
  }
1238
1265
  this.schedule(sessionId, LOOP_COMPLETED_REASON, true);
1239
1266
  } else if (turnOutput === 'visible') {
1240
1267
  state.consecutive = 0;
1268
+ state.recovering = false;
1241
1269
  state.lastFailure = undefined;
1242
1270
  this.noteRecovery(sessionId, 'completed');
1243
1271
  }
@@ -1277,6 +1305,7 @@ export class AutoContinueRunner {
1277
1305
  } else {
1278
1306
  // 用户主动停止: 不自动继续, 视为用户介入
1279
1307
  state.consecutive = 0;
1308
+ state.recovering = false;
1280
1309
  state.pendingRecoveryAt = 0;
1281
1310
  }
1282
1311
  } else if (reasonKind === 'blocked') {
@@ -1311,6 +1340,7 @@ export class AutoContinueRunner {
1311
1340
  if (event.data.source.kind === 'user') {
1312
1341
  // 用户手动介入: 清零上限与跨标签页发送计数
1313
1342
  state.consecutive = 0;
1343
+ state.recovering = false;
1314
1344
  this.resetLoopIterations(state);
1315
1345
  this.cancelPending(sessionId, '用户手动发送消息');
1316
1346
  }
@@ -1329,7 +1359,15 @@ export class AutoContinueRunner {
1329
1359
  // Off parent or the disabled setting means no live recovery at all. The
1330
1360
  // global pause is not checked here, so diagnostics for permanent errors
1331
1361
  // match ordinary sessions while paused.
1332
- if (!this.subagentRecoveryEnabled(sessionId)) return;
1362
+ if (!this.subagentRecoveryEnabled(sessionId)) {
1363
+ const parent = this.parentOf(sessionId);
1364
+ if (parent !== undefined && parent !== '' && this.ctx.agents.get(parent) === undefined) {
1365
+ // Lineage is known but the parent is offline: keep the failure so the
1366
+ // hand-off is delivered once the main conversation is live again.
1367
+ this.deferHandoff(parent, sessionId, this.handoffText(sessionId, reason));
1368
+ }
1369
+ return;
1370
+ }
1333
1371
  } else if (sessionMode(config.sessionModes, sessionId) === 'off') return;
1334
1372
  if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
1335
1373
  const copy = NOTICE_COPY[config.locale];
@@ -1515,6 +1553,7 @@ export class AutoContinueRunner {
1515
1553
  }, config.graceMs);
1516
1554
  state.pendingTimer = timer;
1517
1555
  state.pendingReason = reason;
1556
+ state.recovering = true;
1518
1557
  const template = this.templateFor(config, reason);
1519
1558
  this.log(
1520
1559
  `检测到非人为中断 ${sessionId}(${reason}), ${config.graceMs}ms 后自动发送「${template}」`,
@@ -1529,6 +1568,7 @@ export class AutoContinueRunner {
1529
1568
  const state = this.state(sessionId);
1530
1569
  if (state.cooldownRetryTimer !== undefined) clearTimeout(state.cooldownRetryTimer);
1531
1570
  state.pendingReason = reason;
1571
+ state.recovering = true;
1532
1572
  state.cooldownRetryTimer = setTimeout(() => {
1533
1573
  state.cooldownRetryTimer = undefined;
1534
1574
  state.pendingReason = undefined;
@@ -1582,6 +1622,234 @@ export class AutoContinueRunner {
1582
1622
  if (cancelled) this.log(`取消 ${sessionId} 的自动继续(${why})`);
1583
1623
  }
1584
1624
 
1625
+ /** Host-service facade used to cold-resume a disposed direct child. */
1626
+ private subagentPromptProvider: (() => unknown) | undefined;
1627
+
1628
+ /** Attach the loader-provided subagent service; it may load after this plugin. */
1629
+ setSubagentPromptProvider(provider: (() => unknown) | undefined): void {
1630
+ this.subagentPromptProvider = provider;
1631
+ }
1632
+
1633
+ private subagentPrompts(): {
1634
+ prompt?: (
1635
+ request: {
1636
+ parentSessionId: string;
1637
+ childSessionId: string;
1638
+ mode: 'continuable';
1639
+ requestId: string;
1640
+ content: readonly { type: 'text'; text: string }[];
1641
+ delivery: 'queue' | 'steer';
1642
+ },
1643
+ signal: AbortSignal,
1644
+ ) => Promise<{ messageId?: string }>
1645
+ } | undefined {
1646
+ const provided = this.subagentPromptProvider?.();
1647
+ if (provided !== undefined && provided !== null) return provided as ReturnType<typeof this.subagentPrompts>;
1648
+ try {
1649
+ return this.ctx.get('subagents') as ReturnType<typeof this.subagentPrompts>;
1650
+ } catch {
1651
+ return undefined;
1652
+ }
1653
+ }
1654
+
1655
+ /** Copy for one child hand-off, built once so a deferred delivery matches. */
1656
+ private handoffText(sessionId: SessionId, reason: string): string {
1657
+ const code = this.state(sessionId).lastFailure?.code ?? reason;
1658
+ return HANDOFF_COPY[this.sessionConfig(sessionId).locale](sessionId, code);
1659
+ }
1660
+
1661
+ /**
1662
+ * Revive a disposed child through the host's cold resume and deliver the
1663
+ * continuation to it. Falls back to the main-conversation hand-off when the
1664
+ * host cannot resume (no persistence, no live parent, not a direct child).
1665
+ * The child's own recovery mode decides; the parent only has to be alive to
1666
+ * authorize the call.
1667
+ */
1668
+ private async reviveChild(sessionId: SessionId, reason: string, text: string, force: boolean): Promise<void> {
1669
+ if (this.disposed || this.getConfig().paused) return;
1670
+ if (!this.subagentRecoveryEnabled(sessionId)) return;
1671
+ const state = this.state(sessionId);
1672
+ if (state.reviveInFlight === true) {
1673
+ this.log(`冷恢复跳过 ${sessionId}: 已有请求在途中`);
1674
+ return;
1675
+ }
1676
+ const config = this.sessionConfig(sessionId);
1677
+ if (!force) {
1678
+ // Cold resume spends the same retry budget as a live send: record the
1679
+ // attempt before awaiting, otherwise repeated failures bypass cooldown and
1680
+ // the consecutive cap.
1681
+ if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) {
1682
+ this.log(`冷恢复跳过 ${sessionId}: 处于冷却期`);
1683
+ return;
1684
+ }
1685
+ if (state.consecutive >= config.maxConsecutive) {
1686
+ this.log(`冷恢复跳过 ${sessionId}: 已连续自动继续 ${state.consecutive} 次`);
1687
+ return;
1688
+ }
1689
+ }
1690
+ const parent = this.parentOf(sessionId);
1691
+ if (parent === undefined || parent === '') return;
1692
+ const handoff = this.handoffText(sessionId, reason);
1693
+ const parentAgent = this.ctx.agents.get(parent);
1694
+ if (parentAgent === undefined) {
1695
+ this.deferHandoff(parent, sessionId, handoff);
1696
+ return;
1697
+ }
1698
+ const prompts = this.subagentPrompts();
1699
+ if (typeof prompts?.prompt !== 'function') {
1700
+ this.handOffToParent(sessionId, reason, handoff);
1701
+ return;
1702
+ }
1703
+ state.lastAttemptAt = Date.now();
1704
+ state.consecutive += 1;
1705
+ state.reviveInFlight = true;
1706
+ const controller = new AbortController();
1707
+ this.reviveControllers.add(controller);
1708
+ let timedOut = false;
1709
+ const timeout = setTimeout(() => {
1710
+ timedOut = true;
1711
+ controller.abort();
1712
+ }, REVIVE_TIMEOUT_MS);
1713
+ try {
1714
+ await prompts.prompt(
1715
+ {
1716
+ parentSessionId: parent,
1717
+ childSessionId: sessionId,
1718
+ mode: 'continuable',
1719
+ requestId: randomUUID(),
1720
+ content: [{ type: 'text', text }],
1721
+ delivery: 'queue',
1722
+ },
1723
+ controller.signal,
1724
+ );
1725
+ this.log(`已冷恢复子代理 ${sessionId}`);
1726
+ } catch (error) {
1727
+ // An unload aborts the call on purpose; deliver nothing after opting out.
1728
+ if (this.disposed) return;
1729
+ this.log(`冷恢复 ${sessionId} 失败${timedOut ? '(超时)' : ''}: ${error instanceof Error ? error.message : String(error)}`);
1730
+ this.handOffToParent(sessionId, reason, handoff);
1731
+ } finally {
1732
+ clearTimeout(timeout);
1733
+ this.reviveControllers.delete(controller);
1734
+ state.reviveInFlight = false;
1735
+ }
1736
+ }
1737
+
1738
+ /** Existing state of a session, without materializing one just to read it. */
1739
+ private parentState(sessionId: SessionId): SessionState | undefined {
1740
+ return this.states.get(sessionId);
1741
+ }
1742
+
1743
+ /** Whether this session already has a continuation on the way. */
1744
+ private hasPendingSend(state: SessionState): boolean {
1745
+ return state.pendingTimer !== undefined
1746
+ || state.cooldownRetryTimer !== undefined
1747
+ || state.loopRetryTimer !== undefined
1748
+ || state.offlineWait !== undefined
1749
+ || state.offlineTimer !== undefined;
1750
+ }
1751
+
1752
+ /**
1753
+ * Ask the child's main conversation to take over a failure the plugin cannot
1754
+ * repair itself: the child handle is gone, so only the root can continue it.
1755
+ * The main conversation's Off is respected because this writes a user message
1756
+ * into it; a child's own mode is never overridden by that Off for cold resume.
1757
+ */
1758
+ private handOffToParent(sessionId: SessionId, reason: string, text?: string): void {
1759
+ if (this.disposed || this.getConfig().paused) return;
1760
+ if (!this.subagentRecoveryEnabled(sessionId)) return;
1761
+ const parent = this.parentOf(sessionId);
1762
+ if (parent === undefined || parent === '') return;
1763
+ if (this.explicitMode(parent) === 'off') return;
1764
+ const state = this.state(sessionId);
1765
+ const now = Date.now();
1766
+ if (state.handedOffAt !== undefined && now - state.handedOffAt < HANDOFF_COOLDOWN_MS) return;
1767
+ const handoff = text ?? this.handoffText(sessionId, reason);
1768
+ const parentAgent = this.ctx.agents.get(parent);
1769
+ if (parentAgent === undefined) {
1770
+ this.deferHandoff(parent, sessionId, handoff);
1771
+ return;
1772
+ }
1773
+ // Any user message into the main conversation cancels its queued continuation,
1774
+ // and DSH already tells it which child failed. Stay silent while it recovers.
1775
+ const parentState = this.parentState(parent);
1776
+ if (parentState !== undefined && (parentState.recovering === true || this.hasPendingSend(parentState))) {
1777
+ this.log(`移交跳过 ${sessionId}: 主会话 ${parent} 正在自行恢复`);
1778
+ return;
1779
+ }
1780
+ try {
1781
+ this.sendHandoff(parent, parentAgent, handoff);
1782
+ state.handedOffAt = now;
1783
+ this.log(`已将子代理 ${sessionId} 的失败移交主会话 ${parent}`);
1784
+ } catch (error) {
1785
+ this.log(`移交 ${sessionId} 失败: ${error instanceof Error ? error.message : String(error)}`);
1786
+ }
1787
+ }
1788
+
1789
+ /**
1790
+ * Post a hand-off into the main conversation the same way a continuation is
1791
+ * sent: with the configured message source, and registered as our own echo so
1792
+ * the parent does not read it as the user stepping in (which would reset its
1793
+ * retry and loop counters and cancel whatever it had queued).
1794
+ */
1795
+ private sendHandoff(parent: SessionId, parentAgent: Agent, text: string): void {
1796
+ const parentState = this.state(parent);
1797
+ const message = createUserMessage({
1798
+ content: [{ type: 'text', text }],
1799
+ source: { kind: this.getConfig().usePluginSource ? AUTO_CONTINUE_SOURCE_KIND : 'user' },
1800
+ });
1801
+ trackPendingEcho(parentState, message.id);
1802
+ try {
1803
+ parentAgent.followup(message);
1804
+ } catch (error) {
1805
+ forgetPendingEcho(parentState, message.id);
1806
+ throw error;
1807
+ }
1808
+ }
1809
+
1810
+ /** Keep one hand-off until its main conversation has a live agent again. */
1811
+ private deferHandoff(parent: SessionId, sessionId: SessionId, text: string): void {
1812
+ // Only live subagent recovery hands failures off; with it off nothing is kept.
1813
+ if (!this.getConfig().resumeSubagentSessions) return;
1814
+ const state = this.state(sessionId);
1815
+ const now = Date.now();
1816
+ if (state.handedOffAt !== undefined && now - state.handedOffAt < HANDOFF_COOLDOWN_MS) return;
1817
+ let pending = this.deferredHandoffs.get(parent);
1818
+ if (pending === undefined) {
1819
+ pending = new Map();
1820
+ this.deferredHandoffs.set(parent, pending);
1821
+ }
1822
+ pending.set(sessionId, text);
1823
+ this.log(`移交暂存 ${sessionId}: 主会话 ${parent} 无 live agent`);
1824
+ }
1825
+
1826
+ /** Deliver queued hand-offs once their main conversation is live again. */
1827
+ private flushDeferredHandoffs(parent: SessionId): void {
1828
+ const pending = this.deferredHandoffs.get(parent);
1829
+ if (pending === undefined || pending.size === 0) return;
1830
+ if (this.explicitMode(parent) === 'off') {
1831
+ this.deferredHandoffs.delete(parent);
1832
+ return;
1833
+ }
1834
+ const parentAgent = this.ctx.agents.get(parent);
1835
+ if (parentAgent === undefined) return;
1836
+ this.deferredHandoffs.delete(parent);
1837
+ const now = Date.now();
1838
+ for (const [child, text] of pending) {
1839
+ // The parent may have turned the child's recovery off meanwhile.
1840
+ if (!this.subagentRecoveryEnabled(child)) continue;
1841
+ const state = this.state(child);
1842
+ if (state.handedOffAt !== undefined && now - state.handedOffAt < HANDOFF_COOLDOWN_MS) continue;
1843
+ try {
1844
+ this.sendHandoff(parent, parentAgent, text);
1845
+ state.handedOffAt = now;
1846
+ this.log(`已移交暂存子代理 ${child} 给主会话 ${parent}`);
1847
+ } catch (error) {
1848
+ this.log(`暂存移交 ${child} 失败: ${error instanceof Error ? error.message : String(error)}`);
1849
+ }
1850
+ }
1851
+ }
1852
+
1585
1853
  private fire(sessionId: SessionId, reason: string, force = false): void {
1586
1854
  if (this.disposed) return;
1587
1855
  const state = this.state(sessionId);
@@ -1593,7 +1861,15 @@ export class AutoContinueRunner {
1593
1861
  if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
1594
1862
  // Direct sends (notifications) must respect the setting and the inherited
1595
1863
  // mode even though they bypass the paused flag below.
1596
- if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) return;
1864
+ if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) {
1865
+ const parent = this.parentOf(sessionId);
1866
+ if (parent !== undefined && parent !== '' && this.ctx.agents.get(parent) === undefined) {
1867
+ // Lineage is known but the parent is offline: keep the failure so the
1868
+ // hand-off can be delivered once the main conversation is live again.
1869
+ this.deferHandoff(parent, sessionId, this.handoffText(sessionId, reason));
1870
+ }
1871
+ return;
1872
+ }
1597
1873
  if (config.paused && !manualResume) {
1598
1874
  this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
1599
1875
  return;
@@ -1617,6 +1893,14 @@ export class AutoContinueRunner {
1617
1893
  // 发送: followup 负责唤醒; 同步 inbox 插入事件会在唤醒前把本消息移到已有队列之前。
1618
1894
  const agent = this.ctx.agents.get(sessionId);
1619
1895
  if (agent === undefined) {
1896
+ // A failed child is settled and disposed by the subagent runtime before the
1897
+ // send window opens, so a direct resume cannot reach it. Ask the host to
1898
+ // cold-resume it from persistence; when that is unavailable, hand the
1899
+ // failure to its main conversation instead. A manual "Resume now" must
1900
+ // revive a disposed child too: its force flag only relaxes the cooldown.
1901
+ if (this.isSubagentSession(sessionId) && this.subagentRecoveryEnabled(sessionId)) {
1902
+ void this.reviveChild(sessionId, reason, text, manualResume);
1903
+ }
1620
1904
  this.log(`跳过 ${sessionId}(${reason}): 无 live agent`);
1621
1905
  return;
1622
1906
  }
@@ -1638,6 +1922,9 @@ export class AutoContinueRunner {
1638
1922
  this.prioritizedFollowups.delete(message.id);
1639
1923
  }
1640
1924
  const now = Date.now();
1925
+ // The continuation is on the wire: the session is recovering itself until a
1926
+ // successful turn ends or the user intervenes. Child hand-offs read this.
1927
+ state.recovering = true;
1641
1928
  // 续跑已发出: 被重启失活的 goal 需要在这里重新武装, 否则续跑消息会跑但
1642
1929
  // goal 的自动继续轮不会转起来(disarm 是宿主卸载驱动的正常动作)。
1643
1930
  this.rearmGoal(sessionId, config);
@@ -1742,6 +2029,7 @@ export class AutoContinueRunner {
1742
2029
  const token = {};
1743
2030
  state.offlineWait = token;
1744
2031
  state.pendingReason = reason;
2032
+ state.recovering = true;
1745
2033
  void this.checkConnectivity().then((online) => {
1746
2034
  if (this.disposed || state.offlineWait !== token) return; // 已被取消或被新的检测取代
1747
2035
  if (online) {
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})。 */