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.
package/lib/index.js CHANGED
@@ -20,6 +20,9 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
20
20
  // src/index.ts
21
21
  import z2 from "@deepseek-ai/schemastery";
22
22
 
23
+ // src/host/engine.ts
24
+ import { randomUUID as randomUUID2 } from "node:crypto";
25
+
23
26
  // node_modules/@deepseek-ai/dsh-llm/lib/index.js
24
27
  import { createRequire } from "node:module";
25
28
 
@@ -1781,11 +1784,20 @@ var MANUAL_NOTIFICATION_REASON = "manual:notification";
1781
1784
  var SWEEP_OBSERVE_BATCH = 16;
1782
1785
  var STORED_READ_TIMEOUT_MS = 5e3;
1783
1786
  var SWEEP_MAX_FAILURES = 3;
1787
+ var STORED_SWEEP_READ_LIMIT = 32;
1784
1788
  var RESTART_CANCEL_CAUSES = /* @__PURE__ */ new Set(["disposed", "legacy"]);
1785
1789
  var DECISION_CANCEL_CAUSES = /* @__PURE__ */ new Set(["user", "parent", "hook"]);
1786
1790
  var CHILD_SWEEP_LIMIT = 8;
1787
1791
  var CHILD_ROOT_MAX_DEPTH = 8;
1792
+ var HANDOFF_COOLDOWN_MS = 5 * 60 * 1e3;
1793
+ var REVIVE_TIMEOUT_MS = 15e3;
1794
+ var HANDOFF_COPY = {
1795
+ zh: (child, code) => `子代理会话 ${child} 因 ${code} 中断, 已无法直接续跑。请检查它的状态, 然后继续或收尾。`,
1796
+ en: (child, code) => `Child session ${child} was interrupted by ${code} and can no longer be resumed directly. Check its state, then continue it or wrap it up.`,
1797
+ ru: (child, code) => `Дочерняя сессия ${child} прервалась из-за ${code} и больше не может быть продолжена напрямую. Проверь её состояние и продолжи или заверши.`
1798
+ };
1788
1799
  var GOALS_SERVICE_KEY = "goals";
1800
+ var PROJECTION_CACHE_SERVICE_KEY = "sessionProjectionCache";
1789
1801
  var CHILD_CAUSE_COPY = {
1790
1802
  zh: {
1791
1803
  "open-turn": "回合开始后中断",
@@ -1946,6 +1958,10 @@ var AutoContinueRunner = class {
1946
1958
  this.noticeListeners = /* @__PURE__ */ new Set();
1947
1959
  this.stateListeners = /* @__PURE__ */ new Set();
1948
1960
  this.prioritizedFollowups = /* @__PURE__ */ new Set();
1961
+ /** In-flight cold-resume calls, aborted when the plugin unloads. */
1962
+ this.reviveControllers = /* @__PURE__ */ new Set();
1963
+ /** Hand-offs waiting for a live main conversation: parent -> child -> text. */
1964
+ this.deferredHandoffs = /* @__PURE__ */ new Map();
1949
1965
  this.disposed = false;
1950
1966
  this.bootScannedSessions = /* @__PURE__ */ new WeakSet();
1951
1967
  /** Also bound diagnostics when even an agent's session getter is unavailable. */
@@ -1965,6 +1981,9 @@ var AutoContinueRunner = class {
1965
1981
  /** 存储会话的连续观察/物化失败次数, 触达 SWEEP_MAX_FAILURES 后不再重试。 */
1966
1982
  this.storedSweepFailures = /* @__PURE__ */ new Map();
1967
1983
  this.storedSweepAnnounced = false;
1984
+ /** 本次启动已花掉的存储会话冷读配额(跨轮累计, 启动扫描窗口内不再重置)。 */
1985
+ this.storedReadIds = /* @__PURE__ */ new Set();
1986
+ this.storedBudgetLogged = false;
1968
1987
  this.stopStoredSweep = new AbortController();
1969
1988
  this.disposeSessionEvents = ctx.on("session/event", (session, event) => {
1970
1989
  try {
@@ -2112,6 +2131,9 @@ var AutoContinueRunner = class {
2112
2131
  this.wakeBootScan = void 0;
2113
2132
  this.disposeSessionEvents();
2114
2133
  this.disposeInboxEvents();
2134
+ for (const controller of this.reviveControllers) controller.abort();
2135
+ this.reviveControllers.clear();
2136
+ this.deferredHandoffs.clear();
2115
2137
  this.prioritizedFollowups.clear();
2116
2138
  for (const state of this.states.values()) {
2117
2139
  if (state.pendingTimer !== void 0) clearTimeout(state.pendingTimer);
@@ -2289,6 +2311,7 @@ var AutoContinueRunner = class {
2289
2311
  */
2290
2312
  onHostEvent(session, event) {
2291
2313
  const sessionId = session.id;
2314
+ this.flushDeferredHandoffs(sessionId);
2292
2315
  const sessionState = this.states.get(sessionId);
2293
2316
  if (session.header?.origin === "subagent") {
2294
2317
  this.markSubagent(sessionId, sessionState ?? this.state(sessionId), session.header.parentSession);
@@ -2581,12 +2604,14 @@ var AutoContinueRunner = class {
2581
2604
  if (this.sessionConfig(sessionId).resumeCompletedTurns) {
2582
2605
  if (turnOutput === "visible") {
2583
2606
  state.consecutive = 0;
2607
+ state.recovering = false;
2584
2608
  state.lastFailure = void 0;
2585
2609
  this.noteRecovery(sessionId, "completed");
2586
2610
  }
2587
2611
  this.schedule(sessionId, LOOP_COMPLETED_REASON, true);
2588
2612
  } else if (turnOutput === "visible") {
2589
2613
  state.consecutive = 0;
2614
+ state.recovering = false;
2590
2615
  state.lastFailure = void 0;
2591
2616
  this.noteRecovery(sessionId, "completed");
2592
2617
  }
@@ -2621,6 +2646,7 @@ var AutoContinueRunner = class {
2621
2646
  }
2622
2647
  } else {
2623
2648
  state.consecutive = 0;
2649
+ state.recovering = false;
2624
2650
  state.pendingRecoveryAt = 0;
2625
2651
  }
2626
2652
  } else if (reasonKind === "blocked") {
@@ -2649,6 +2675,7 @@ var AutoContinueRunner = class {
2649
2675
  if (isOurEcho(state, event)) break;
2650
2676
  if (event.data.source.kind === "user") {
2651
2677
  state.consecutive = 0;
2678
+ state.recovering = false;
2652
2679
  this.resetLoopIterations(state);
2653
2680
  this.cancelPending(sessionId, "用户手动发送消息");
2654
2681
  }
@@ -2661,7 +2688,13 @@ var AutoContinueRunner = class {
2661
2688
  onTurnFailure(sessionId, reason, failure) {
2662
2689
  const config = this.getConfig();
2663
2690
  if (this.isSubagentSession(sessionId)) {
2664
- if (!this.subagentRecoveryEnabled(sessionId)) return;
2691
+ if (!this.subagentRecoveryEnabled(sessionId)) {
2692
+ const parent = this.parentOf(sessionId);
2693
+ if (parent !== void 0 && parent !== "" && this.ctx.agents.get(parent) === void 0) {
2694
+ this.deferHandoff(parent, sessionId, this.handoffText(sessionId, reason));
2695
+ }
2696
+ return;
2697
+ }
2665
2698
  } else if (sessionMode(config.sessionModes, sessionId) === "off") return;
2666
2699
  if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
2667
2700
  const copy = NOTICE_COPY[config.locale];
@@ -2806,6 +2839,7 @@ var AutoContinueRunner = class {
2806
2839
  }, config.graceMs);
2807
2840
  state.pendingTimer = timer;
2808
2841
  state.pendingReason = reason;
2842
+ state.recovering = true;
2809
2843
  const template = this.templateFor(config, reason);
2810
2844
  this.log(
2811
2845
  `检测到非人为中断 ${sessionId}(${reason}), ${config.graceMs}ms 后自动发送「${template}」`
@@ -2819,6 +2853,7 @@ var AutoContinueRunner = class {
2819
2853
  const state = this.state(sessionId);
2820
2854
  if (state.cooldownRetryTimer !== void 0) clearTimeout(state.cooldownRetryTimer);
2821
2855
  state.pendingReason = reason;
2856
+ state.recovering = true;
2822
2857
  state.cooldownRetryTimer = setTimeout(() => {
2823
2858
  state.cooldownRetryTimer = void 0;
2824
2859
  state.pendingReason = void 0;
@@ -2867,6 +2902,197 @@ var AutoContinueRunner = class {
2867
2902
  }
2868
2903
  if (cancelled) this.log(`取消 ${sessionId} 的自动继续(${why})`);
2869
2904
  }
2905
+ /** Attach the loader-provided subagent service; it may load after this plugin. */
2906
+ setSubagentPromptProvider(provider) {
2907
+ this.subagentPromptProvider = provider;
2908
+ }
2909
+ subagentPrompts() {
2910
+ const provided = this.subagentPromptProvider?.();
2911
+ if (provided !== void 0 && provided !== null) return provided;
2912
+ try {
2913
+ return this.ctx.get("subagents");
2914
+ } catch {
2915
+ return void 0;
2916
+ }
2917
+ }
2918
+ /** Copy for one child hand-off, built once so a deferred delivery matches. */
2919
+ handoffText(sessionId, reason) {
2920
+ const code = this.state(sessionId).lastFailure?.code ?? reason;
2921
+ return HANDOFF_COPY[this.sessionConfig(sessionId).locale](sessionId, code);
2922
+ }
2923
+ /**
2924
+ * Revive a disposed child through the host's cold resume and deliver the
2925
+ * continuation to it. Falls back to the main-conversation hand-off when the
2926
+ * host cannot resume (no persistence, no live parent, not a direct child).
2927
+ * The child's own recovery mode decides; the parent only has to be alive to
2928
+ * authorize the call.
2929
+ */
2930
+ async reviveChild(sessionId, reason, text, force) {
2931
+ if (this.disposed || this.getConfig().paused) return;
2932
+ if (!this.subagentRecoveryEnabled(sessionId)) return;
2933
+ const state = this.state(sessionId);
2934
+ if (state.reviveInFlight === true) {
2935
+ this.log(`冷恢复跳过 ${sessionId}: 已有请求在途中`);
2936
+ return;
2937
+ }
2938
+ const config = this.sessionConfig(sessionId);
2939
+ if (!force) {
2940
+ if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) {
2941
+ this.log(`冷恢复跳过 ${sessionId}: 处于冷却期`);
2942
+ return;
2943
+ }
2944
+ if (state.consecutive >= config.maxConsecutive) {
2945
+ this.log(`冷恢复跳过 ${sessionId}: 已连续自动继续 ${state.consecutive} 次`);
2946
+ return;
2947
+ }
2948
+ }
2949
+ const parent = this.parentOf(sessionId);
2950
+ if (parent === void 0 || parent === "") return;
2951
+ const handoff = this.handoffText(sessionId, reason);
2952
+ const parentAgent = this.ctx.agents.get(parent);
2953
+ if (parentAgent === void 0) {
2954
+ this.deferHandoff(parent, sessionId, handoff);
2955
+ return;
2956
+ }
2957
+ const prompts = this.subagentPrompts();
2958
+ if (typeof prompts?.prompt !== "function") {
2959
+ this.handOffToParent(sessionId, reason, handoff);
2960
+ return;
2961
+ }
2962
+ state.lastAttemptAt = Date.now();
2963
+ state.consecutive += 1;
2964
+ state.reviveInFlight = true;
2965
+ const controller = new AbortController();
2966
+ this.reviveControllers.add(controller);
2967
+ let timedOut = false;
2968
+ const timeout = setTimeout(() => {
2969
+ timedOut = true;
2970
+ controller.abort();
2971
+ }, REVIVE_TIMEOUT_MS);
2972
+ try {
2973
+ await prompts.prompt(
2974
+ {
2975
+ parentSessionId: parent,
2976
+ childSessionId: sessionId,
2977
+ mode: "continuable",
2978
+ requestId: randomUUID2(),
2979
+ content: [{ type: "text", text }],
2980
+ delivery: "queue"
2981
+ },
2982
+ controller.signal
2983
+ );
2984
+ this.log(`已冷恢复子代理 ${sessionId}`);
2985
+ } catch (error) {
2986
+ if (this.disposed) return;
2987
+ this.log(`冷恢复 ${sessionId} 失败${timedOut ? "(超时)" : ""}: ${error instanceof Error ? error.message : String(error)}`);
2988
+ this.handOffToParent(sessionId, reason, handoff);
2989
+ } finally {
2990
+ clearTimeout(timeout);
2991
+ this.reviveControllers.delete(controller);
2992
+ state.reviveInFlight = false;
2993
+ }
2994
+ }
2995
+ /** Existing state of a session, without materializing one just to read it. */
2996
+ parentState(sessionId) {
2997
+ return this.states.get(sessionId);
2998
+ }
2999
+ /** Whether this session already has a continuation on the way. */
3000
+ hasPendingSend(state) {
3001
+ return state.pendingTimer !== void 0 || state.cooldownRetryTimer !== void 0 || state.loopRetryTimer !== void 0 || state.offlineWait !== void 0 || state.offlineTimer !== void 0;
3002
+ }
3003
+ /**
3004
+ * Ask the child's main conversation to take over a failure the plugin cannot
3005
+ * repair itself: the child handle is gone, so only the root can continue it.
3006
+ * The main conversation's Off is respected because this writes a user message
3007
+ * into it; a child's own mode is never overridden by that Off for cold resume.
3008
+ */
3009
+ handOffToParent(sessionId, reason, text) {
3010
+ if (this.disposed || this.getConfig().paused) return;
3011
+ if (!this.subagentRecoveryEnabled(sessionId)) return;
3012
+ const parent = this.parentOf(sessionId);
3013
+ if (parent === void 0 || parent === "") return;
3014
+ if (this.explicitMode(parent) === "off") return;
3015
+ const state = this.state(sessionId);
3016
+ const now = Date.now();
3017
+ if (state.handedOffAt !== void 0 && now - state.handedOffAt < HANDOFF_COOLDOWN_MS) return;
3018
+ const handoff = text ?? this.handoffText(sessionId, reason);
3019
+ const parentAgent = this.ctx.agents.get(parent);
3020
+ if (parentAgent === void 0) {
3021
+ this.deferHandoff(parent, sessionId, handoff);
3022
+ return;
3023
+ }
3024
+ const parentState = this.parentState(parent);
3025
+ if (parentState !== void 0 && (parentState.recovering === true || this.hasPendingSend(parentState))) {
3026
+ this.log(`移交跳过 ${sessionId}: 主会话 ${parent} 正在自行恢复`);
3027
+ return;
3028
+ }
3029
+ try {
3030
+ this.sendHandoff(parent, parentAgent, handoff);
3031
+ state.handedOffAt = now;
3032
+ this.log(`已将子代理 ${sessionId} 的失败移交主会话 ${parent}`);
3033
+ } catch (error) {
3034
+ this.log(`移交 ${sessionId} 失败: ${error instanceof Error ? error.message : String(error)}`);
3035
+ }
3036
+ }
3037
+ /**
3038
+ * Post a hand-off into the main conversation the same way a continuation is
3039
+ * sent: with the configured message source, and registered as our own echo so
3040
+ * the parent does not read it as the user stepping in (which would reset its
3041
+ * retry and loop counters and cancel whatever it had queued).
3042
+ */
3043
+ sendHandoff(parent, parentAgent, text) {
3044
+ const parentState = this.state(parent);
3045
+ const message = createUserMessage({
3046
+ content: [{ type: "text", text }],
3047
+ source: { kind: this.getConfig().usePluginSource ? AUTO_CONTINUE_SOURCE_KIND : "user" }
3048
+ });
3049
+ trackPendingEcho(parentState, message.id);
3050
+ try {
3051
+ parentAgent.followup(message);
3052
+ } catch (error) {
3053
+ forgetPendingEcho(parentState, message.id);
3054
+ throw error;
3055
+ }
3056
+ }
3057
+ /** Keep one hand-off until its main conversation has a live agent again. */
3058
+ deferHandoff(parent, sessionId, text) {
3059
+ if (!this.getConfig().resumeSubagentSessions) return;
3060
+ const state = this.state(sessionId);
3061
+ const now = Date.now();
3062
+ if (state.handedOffAt !== void 0 && now - state.handedOffAt < HANDOFF_COOLDOWN_MS) return;
3063
+ let pending = this.deferredHandoffs.get(parent);
3064
+ if (pending === void 0) {
3065
+ pending = /* @__PURE__ */ new Map();
3066
+ this.deferredHandoffs.set(parent, pending);
3067
+ }
3068
+ pending.set(sessionId, text);
3069
+ this.log(`移交暂存 ${sessionId}: 主会话 ${parent} 无 live agent`);
3070
+ }
3071
+ /** Deliver queued hand-offs once their main conversation is live again. */
3072
+ flushDeferredHandoffs(parent) {
3073
+ const pending = this.deferredHandoffs.get(parent);
3074
+ if (pending === void 0 || pending.size === 0) return;
3075
+ if (this.explicitMode(parent) === "off") {
3076
+ this.deferredHandoffs.delete(parent);
3077
+ return;
3078
+ }
3079
+ const parentAgent = this.ctx.agents.get(parent);
3080
+ if (parentAgent === void 0) return;
3081
+ this.deferredHandoffs.delete(parent);
3082
+ const now = Date.now();
3083
+ for (const [child, text] of pending) {
3084
+ if (!this.subagentRecoveryEnabled(child)) continue;
3085
+ const state = this.state(child);
3086
+ if (state.handedOffAt !== void 0 && now - state.handedOffAt < HANDOFF_COOLDOWN_MS) continue;
3087
+ try {
3088
+ this.sendHandoff(parent, parentAgent, text);
3089
+ state.handedOffAt = now;
3090
+ this.log(`已移交暂存子代理 ${child} 给主会话 ${parent}`);
3091
+ } catch (error) {
3092
+ this.log(`暂存移交 ${child} 失败: ${error instanceof Error ? error.message : String(error)}`);
3093
+ }
3094
+ }
3095
+ }
2870
3096
  fire(sessionId, reason, force = false) {
2871
3097
  if (this.disposed) return;
2872
3098
  const state = this.state(sessionId);
@@ -2874,7 +3100,13 @@ var AutoContinueRunner = class {
2874
3100
  const manualResume = force && reason === MANUAL_NOTIFICATION_REASON;
2875
3101
  if (reason.endsWith(":silent") && !config.resumeSilentTurns) return;
2876
3102
  if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
2877
- if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) return;
3103
+ if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) {
3104
+ const parent = this.parentOf(sessionId);
3105
+ if (parent !== void 0 && parent !== "" && this.ctx.agents.get(parent) === void 0) {
3106
+ this.deferHandoff(parent, sessionId, this.handoffText(sessionId, reason));
3107
+ }
3108
+ return;
3109
+ }
2878
3110
  if (config.paused && !manualResume) {
2879
3111
  this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
2880
3112
  return;
@@ -2895,6 +3127,9 @@ var AutoContinueRunner = class {
2895
3127
  const text = this.buildContinueText(config, state, template);
2896
3128
  const agent = this.ctx.agents.get(sessionId);
2897
3129
  if (agent === void 0) {
3130
+ if (this.isSubagentSession(sessionId) && this.subagentRecoveryEnabled(sessionId)) {
3131
+ void this.reviveChild(sessionId, reason, text, manualResume);
3132
+ }
2898
3133
  this.log(`跳过 ${sessionId}(${reason}): 无 live agent`);
2899
3134
  return;
2900
3135
  }
@@ -2915,6 +3150,7 @@ var AutoContinueRunner = class {
2915
3150
  this.prioritizedFollowups.delete(message.id);
2916
3151
  }
2917
3152
  const now = Date.now();
3153
+ state.recovering = true;
2918
3154
  this.rearmGoal(sessionId, config);
2919
3155
  if (reason !== LOOP_COMPLETED_REASON) state.consecutive += 1;
2920
3156
  if (isLoopReason(reason)) state.loopIterations += 1;
@@ -3004,6 +3240,7 @@ var AutoContinueRunner = class {
3004
3240
  const token = {};
3005
3241
  state.offlineWait = token;
3006
3242
  state.pendingReason = reason;
3243
+ state.recovering = true;
3007
3244
  void this.checkConnectivity().then((online) => {
3008
3245
  if (this.disposed || state.offlineWait !== token) return;
3009
3246
  if (online) {
@@ -3263,6 +3500,7 @@ var AutoContinueRunner = class {
3263
3500
  }
3264
3501
  }
3265
3502
  let observed = 0;
3503
+ const roots = [];
3266
3504
  for (const record2 of records) {
3267
3505
  if (this.disposed || Date.now() >= deadline || this.getConfig().paused || !this.getConfig().scanOnBoot) return;
3268
3506
  if (typeof record2?.header?.id !== "string" || record2.header.id === "") {
@@ -3278,6 +3516,24 @@ var AutoContinueRunner = class {
3278
3516
  continue;
3279
3517
  }
3280
3518
  if (record2.live || this.storedSwept.has(sessionId)) continue;
3519
+ roots.push({ sessionId, header: record2.header, recency: 0, index: roots.length });
3520
+ }
3521
+ if (roots.length > 0) {
3522
+ const cache = this.projectionCache();
3523
+ for (const root of roots) root.recency = this.storedRecency(cache, root.header);
3524
+ roots.sort((left, right) => right.recency - left.recency || left.index - right.index);
3525
+ }
3526
+ for (const root of roots) {
3527
+ if (this.disposed || Date.now() >= deadline || this.getConfig().paused || !this.getConfig().scanOnBoot) return;
3528
+ if (!this.storedReadIds.has(root.sessionId) && this.storedReadIds.size >= STORED_SWEEP_READ_LIMIT) {
3529
+ if (!this.storedBudgetLogged) {
3530
+ this.storedBudgetLogged = true;
3531
+ this.log(`存储扫描冷读已达上限 ${STORED_SWEEP_READ_LIMIT} 个会话, 其余会话本次启动跳过`);
3532
+ }
3533
+ return;
3534
+ }
3535
+ const sessionId = root.sessionId;
3536
+ this.storedReadIds.add(sessionId);
3281
3537
  this.storedSwept.add(sessionId);
3282
3538
  observed += 1;
3283
3539
  let observation;
@@ -3363,6 +3619,30 @@ var AutoContinueRunner = class {
3363
3619
  }
3364
3620
  }
3365
3621
  }
3622
+ /** The optional projection checkpoint cache; absent on hosts that do not ship it. */
3623
+ projectionCache() {
3624
+ try {
3625
+ return this.ctx.get(PROJECTION_CACHE_SERVICE_KEY);
3626
+ } catch {
3627
+ return void 0;
3628
+ }
3629
+ }
3630
+ /**
3631
+ * 冷读排序提示: 投影检查点里的最近活动时间, 没有检查点时回退到会话创建时间。
3632
+ * 检查点只会落后于日志、不会超前, 所以这个数只用来排序, 不用来跳过会话。
3633
+ */
3634
+ storedRecency(cache, header) {
3635
+ const created = typeof header.createdAt === "number" ? header.createdAt : 0;
3636
+ if (cache === void 0) return created;
3637
+ try {
3638
+ const block = cache.cachedSnapshot(header, ["timeContext", "sessionListMetadata"]);
3639
+ const values = block?.values;
3640
+ const at = values?.timeContext?.lastMessageTime ?? values?.sessionListMetadata?.lastPromptAt;
3641
+ return typeof at === "number" && Number.isFinite(at) ? at : created;
3642
+ } catch {
3643
+ return created;
3644
+ }
3645
+ }
3366
3646
  /**
3367
3647
  * 子会话裁决。子会话本身永不直接续跑(父代理权威, 见 README), 但启动扫描要
3368
3648
  * 知道它是否在重启时被打断, 才能在自己的 root 会话上补一次带清单的唤醒。
@@ -10096,6 +10376,12 @@ function apply(ctx, config) {
10096
10376
  disposeEngine?.();
10097
10377
  const readConfig = () => resolveConfig(legacyConfig?.() ?? readEntry());
10098
10378
  const runner = new AutoContinueRunner(engineCtx, readConfig);
10379
+ engineCtx.inject(["subagents"], (subagentCtx) => {
10380
+ runner.setSubagentPromptProvider(
10381
+ () => subagentCtx.subagents
10382
+ );
10383
+ subagentCtx.effect(() => () => runner.setSubagentPromptProvider(void 0));
10384
+ });
10099
10385
  const writableSettings = () => {
10100
10386
  const settings = engineCtx.get("settings");
10101
10387
  return settings?.writable && typeof settings.mutate === "function" ? settings : void 0;
@@ -44,6 +44,10 @@ export declare class AutoContinueRunner {
44
44
  private readonly noticeListeners;
45
45
  private readonly stateListeners;
46
46
  private readonly prioritizedFollowups;
47
+ /** In-flight cold-resume calls, aborted when the plugin unloads. */
48
+ private readonly reviveControllers;
49
+ /** Hand-offs waiting for a live main conversation: parent -> child -> text. */
50
+ private readonly deferredHandoffs;
47
51
  private readonly disposeSessionEvents;
48
52
  private readonly disposeInboxEvents;
49
53
  private disposed;
@@ -65,6 +69,9 @@ export declare class AutoContinueRunner {
65
69
  /** 存储会话的连续观察/物化失败次数, 触达 SWEEP_MAX_FAILURES 后不再重试。 */
66
70
  private readonly storedSweepFailures;
67
71
  private storedSweepAnnounced;
72
+ /** 本次启动已花掉的存储会话冷读配额(跨轮累计, 启动扫描窗口内不再重置)。 */
73
+ private readonly storedReadIds;
74
+ private storedBudgetLogged;
68
75
  private bootScanTimer;
69
76
  private wakeBootScan;
70
77
  private storedSweep;
@@ -191,6 +198,43 @@ export declare class AutoContinueRunner {
191
198
  /** 按调度原因选择续跑模板: loop 重启、无输出回合、max-tokens、自主循环, 其余用通用继续文本。 */
192
199
  private templateFor;
193
200
  private cancelPending;
201
+ /** Host-service facade used to cold-resume a disposed direct child. */
202
+ private subagentPromptProvider;
203
+ /** Attach the loader-provided subagent service; it may load after this plugin. */
204
+ setSubagentPromptProvider(provider: (() => unknown) | undefined): void;
205
+ private subagentPrompts;
206
+ /** Copy for one child hand-off, built once so a deferred delivery matches. */
207
+ private handoffText;
208
+ /**
209
+ * Revive a disposed child through the host's cold resume and deliver the
210
+ * continuation to it. Falls back to the main-conversation hand-off when the
211
+ * host cannot resume (no persistence, no live parent, not a direct child).
212
+ * The child's own recovery mode decides; the parent only has to be alive to
213
+ * authorize the call.
214
+ */
215
+ private reviveChild;
216
+ /** Existing state of a session, without materializing one just to read it. */
217
+ private parentState;
218
+ /** Whether this session already has a continuation on the way. */
219
+ private hasPendingSend;
220
+ /**
221
+ * Ask the child's main conversation to take over a failure the plugin cannot
222
+ * repair itself: the child handle is gone, so only the root can continue it.
223
+ * The main conversation's Off is respected because this writes a user message
224
+ * into it; a child's own mode is never overridden by that Off for cold resume.
225
+ */
226
+ private handOffToParent;
227
+ /**
228
+ * Post a hand-off into the main conversation the same way a continuation is
229
+ * sent: with the configured message source, and registered as our own echo so
230
+ * the parent does not read it as the user stepping in (which would reset its
231
+ * retry and loop counters and cancel whatever it had queued).
232
+ */
233
+ private sendHandoff;
234
+ /** Keep one hand-off until its main conversation has a live agent again. */
235
+ private deferHandoff;
236
+ /** Deliver queued hand-offs once their main conversation is live again. */
237
+ private flushDeferredHandoffs;
194
238
  private fire;
195
239
  private resetLoopIterations;
196
240
  /** 自主循环轮数上限: 触顶后静默停下, 每次触顶只提示一次。 */
@@ -223,6 +267,13 @@ export declare class AutoContinueRunner {
223
267
  * 则启动扫描永远看不到它们; 谓词与上方扫描一致, 仅失败类原因。
224
268
  */
225
269
  private sweepStoredSessions;
270
+ /** The optional projection checkpoint cache; absent on hosts that do not ship it. */
271
+ private projectionCache;
272
+ /**
273
+ * 冷读排序提示: 投影检查点里的最近活动时间, 没有检查点时回退到会话创建时间。
274
+ * 检查点只会落后于日志、不会超前, 所以这个数只用来排序, 不用来跳过会话。
275
+ */
276
+ private storedRecency;
226
277
  /**
227
278
  * 子会话裁决。子会话本身永不直接续跑(父代理权威, 见 README), 但启动扫描要
228
279
  * 知道它是否在重启时被打断, 才能在自己的 root 会话上补一次带清单的唤醒。
@@ -362,6 +362,12 @@ export interface SessionState {
362
362
  lastFailure: FailureFacts | undefined;
363
363
  /** 最近一次失败的发生时间(模板 {elapsed} 与恢复统计用)。 */
364
364
  lastFailureAt: number;
365
+ /** 最近一次把子代理失败移交主会话的时间戳(去重)。 */
366
+ handedOffAt?: number;
367
+ /** 冷恢复请求正在途中(去重, 防止重复 prompt)。 */
368
+ reviveInFlight?: boolean;
369
+ /** 主会话正在自行恢复: 由插件自己的调度/发送显式维护, 不用时间戳猜测。 */
370
+ recovering?: boolean;
365
371
  /** callId 精确配对的工具调用、幂等护栏与 loop 重复态。 */
366
372
  tools: ToolInvocationTracker;
367
373
  /** 失败回合的编号(模板 {turn})。 */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-client-auto-continue",
3
3
  "description": "Automatically resume interrupted DSH conversations, with an optional autonomous loop.",
4
- "version": "0.19.0",
4
+ "version": "0.20.1",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "types": "lib/types/index.d.ts",
@@ -58,7 +58,7 @@ export const zh = {
58
58
  'field.resumeSilentTurns': '续跑无输出回合',
59
59
  'field.resumeSilentTurnsHint': '已观察到模型活动但没有可见输出时续跑;不把空回合、图片或扩展内容误判为静默,冷却与连续上限照常生效。',
60
60
  'field.resumeSubagentSessions': '续跑子代理会话',
61
- 'field.resumeSubagentSessionsHint': '当子代理所属主会话启用自动继续时,自动续跑其中断的子代理会话。子代理不会进入自主循环、不会被循环守卫重启,也不会由启动扫描恢复。默认关闭。只对仍处于加载状态的子代理生效:DSH 通常会在后台子代理失败后立即关闭它,并把失败结果交给父会话。',
61
+ 'field.resumeSubagentSessionsHint': '当子代理所属主会话启用自动继续时,自动续跑其中断的子代理会话。子代理不会进入自主循环、不会被循环守卫重启,也不会由启动扫描恢复。默认关闭。DSH 已释放子代理时,引擎会通过宿主的子代理服务从持久化会话冷恢复它;宿主无法恢复时,把失败交给主会话处理,并在主会话自行恢复期间保持安静。',
62
62
  'field.resumeCompletedTurns': '默认会话模式',
63
63
  'field.resumeCompletedTurnsHint': '用于未单独设置模式的会话。仅故障恢复继续中断和无输出回合;自主循环还会在正常完成后继续。无输出和失败回合仍计入连续重试次数。',
64
64
  'field.resumeInterruptedChildren': '重启后唤醒子代理会话',
@@ -230,7 +230,7 @@ export const en: Record<SettingsCardKey, string> = {
230
230
  'field.resumeSilentTurns': 'Resume silent turns',
231
231
  'field.resumeSilentTurnsHint': 'Resume observed model activity without visible output. No-op turns, images and extension blocks are not treated as silent; cooldown and retry limits still apply.',
232
232
  'field.resumeSubagentSessions': 'Resume subagent sessions',
233
- 'field.resumeSubagentSessionsHint': 'Auto-continue interrupted subagent sessions when their main conversation has auto-continue enabled. Subagents never start the autonomous loop, are never loop-guard restarted, and are not recovered by the startup scan. Off by default. Only applies while the subagent is still loaded: DSH usually closes a background subagent as soon as it fails and reports the failure to its parent.',
233
+ 'field.resumeSubagentSessionsHint': 'Auto-continue interrupted subagent sessions when their main conversation has auto-continue enabled. Subagents never start the autonomous loop, are never loop-guard restarted, and are not recovered by the startup scan. Off by default. When DSH already disposed the subagent, the engine cold-resumes it from its persisted session through the host subagent service; if the host cannot resume it, the failure is handed to the main conversation, staying silent while that conversation recovers itself.',
234
234
  'field.resumeCompletedTurns': 'Default session mode',
235
235
  'field.resumeCompletedTurnsHint': 'Applies to sessions without their own mode. Recovery only resumes interruptions and silent turns; autonomous loop also continues after normal completions. Silent and failed turns still count toward the consecutive retry limit.',
236
236
  'field.resumeInterruptedChildren': 'Wake child sessions after restart',
@@ -397,7 +397,7 @@ export const ru: Record<SettingsCardKey, string> = {
397
397
  'field.resumeSilentTurns': 'Продолжать ходы без вывода',
398
398
  'field.resumeSilentTurnsHint': 'Продолжать при наблюдаемой активности модели без видимого вывода. Пустые ходы, изображения и блоки расширений тихими не считаются; задержка и лимиты повторов действуют.',
399
399
  'field.resumeSubagentSessions': 'Продолжать сессии субагентов',
400
- 'field.resumeSubagentSessionsHint': 'Автоматически продолжать прерванные сессии субагентов, если в их основном диалоге включено авто-продолжение. Субагенты не запускают автономный цикл, не перезапускаются защитой от циклов и не восстанавливаются сканированием при запуске. По умолчанию выключено. Работает, только пока субагент ещё загружен: DSH обычно закрывает фоновый субагент сразу после сбоя и сообщает об ошибке родительскому диалогу.',
400
+ 'field.resumeSubagentSessionsHint': 'Автоматически продолжать прерванные сессии субагентов, если в их основном диалоге включено авто-продолжение. Субагенты не запускают автономный цикл, не перезапускаются защитой от циклов и не восстанавливаются сканированием при запуске. По умолчанию выключено. Если DSH уже освободил субагент, движок холодно поднимает его из сохранённой сессии через сервис субагентов хоста; когда хост не может его поднять, сбой передаётся основному диалогу, и пока тот восстанавливается сам, передача молчит.',
401
401
  'field.resumeCompletedTurns': 'Режим сессии по умолчанию',
402
402
  'field.resumeCompletedTurnsHint': 'Для сессий без собственного режима. «Только восстановление» не трогает обычные завершения; «Автономный цикл» продолжает после них. Тихие и неудачные ходы по-прежнему расходуют бюджет повторов.',
403
403
  'field.continueTextLoop': 'Текст продолжения (автономный цикл)',