dsh-client-auto-continue 0.14.3 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -96,6 +96,29 @@ var alwaysPolicySchema = z.object({
96
96
  var RetryPolicySchema = z.union([normalPolicySchema, alwaysPolicySchema]);
97
97
  var { version } = createRequire(import.meta.url)("../package.json");
98
98
 
99
+ // node_modules/@deepseek-ai/dsh-session/lib/index.js
100
+ import { Service as Service2 } from "@deepseek-ai/cordis";
101
+
102
+ // node_modules/@deepseek-ai/dsh-scope/lib/index.js
103
+ import { Context } from "@deepseek-ai/cordis";
104
+ var kScope = Symbol("dsh.scope");
105
+
106
+ // node_modules/@deepseek-ai/dsh-session/lib/index.js
107
+ function canonicalHeader(header) {
108
+ const adapterDefaults = header.adapterDefaults;
109
+ return {
110
+ config: header.config,
111
+ ...adapterDefaults?.reasoningEffort === true || adapterDefaults?.maxTokens === true ? { adapterDefaults } : {},
112
+ ...header.system !== void 0 && header.system.length > 0 ? { system: header.system } : {},
113
+ ...header.tools !== void 0 && header.tools.length > 0 ? { tools: header.tools } : {}
114
+ };
115
+ }
116
+ function foldRequestHeader(events, from) {
117
+ let state = from;
118
+ for (const event of events) if (event.type === "request/header") state = canonicalHeader(event.data.header);
119
+ return state;
120
+ }
121
+
99
122
  // src/shared/core.ts
100
123
  var LOCALIZED_TEXT_DEFAULTS = {
101
124
  zh: {
@@ -103,6 +126,7 @@ var LOCALIZED_TEXT_DEFAULTS = {
103
126
  continueTextMaxTokens: "继续",
104
127
  continueTextSilent: "继续。你上一轮只输出了内部推理, 既没有回复也没有调用工具, 用户什么都没看到。每一轮都要以工具调用或可见回复结束。",
105
128
  continueTextLoop: "继续",
129
+ continueTextInterrupted: "继续。宿主在你上一轮运行期间重启了; 重启时未完成的工具调用已按「结果未知」收尾。从中断处继续, 重试可能有副作用的操作前先核实外部状态。",
106
130
  guardPendingText: "(上一步工具「{tool}」可能未完成, 先确认状态再继续, 不要重复执行)",
107
131
  guardDoneText: "(上一步工具「{tool}」已完成, 结果: {result}; 不要重复执行, 直接继续)",
108
132
  loopText: "(检测到你可能陷入循环, 请停止重复刚才的动作, 换一种方式继续)"
@@ -112,6 +136,7 @@ var LOCALIZED_TEXT_DEFAULTS = {
112
136
  continueTextMaxTokens: "Continue",
113
137
  continueTextSilent: "Continue. Your previous turn ended with internal reasoning only, with no message and no tool call, so nothing reached the user. Always finish a turn with a tool call or a visible answer.",
114
138
  continueTextLoop: "Continue",
139
+ continueTextInterrupted: "Continue. The harness was restarted while your previous turn was still running; tool calls pending at the restart are recorded with unknown outcomes. Resume where you left off, verifying external state before retrying anything that may have side effects.",
115
140
  guardPendingText: '(The previous tool "{tool}" may not have completed. Check its state before continuing and do not run it again.)',
116
141
  guardDoneText: '(The previous tool "{tool}" completed successfully. Result: {result}; do not run it again. Continue from there.)',
117
142
  loopText: "(You may be stuck in a loop. Stop repeating the last action and continue with a different approach.)"
@@ -159,6 +184,7 @@ function resolveConfig(section) {
159
184
  const maxTokensText = typeof value.continueTextMaxTokens === "string" && value.continueTextMaxTokens.trim() !== "" ? value.continueTextMaxTokens : localized.continueTextMaxTokens;
160
185
  const silentText = typeof value.continueTextSilent === "string" && value.continueTextSilent.trim() !== "" ? value.continueTextSilent : localized.continueTextSilent;
161
186
  const loopText = typeof value.continueTextLoop === "string" && value.continueTextLoop.trim() !== "" ? value.continueTextLoop : localized.continueTextLoop;
187
+ const interruptedText = typeof value.continueTextInterrupted === "string" && value.continueTextInterrupted.trim() !== "" ? value.continueTextInterrupted : localized.continueTextInterrupted;
162
188
  const guardPendingText = typeof value.guardPendingText === "string" && value.guardPendingText.trim() !== "" ? value.guardPendingText : localized.guardPendingText;
163
189
  const guardDoneText = typeof value.guardDoneText === "string" && value.guardDoneText.trim() !== "" ? value.guardDoneText : localized.guardDoneText;
164
190
  return {
@@ -169,6 +195,7 @@ function resolveConfig(section) {
169
195
  resumeCompletedTurns: booleanOr(value.resumeCompletedTurns, DEFAULT_CONFIG.resumeCompletedTurns),
170
196
  continueTextSilent: silentText,
171
197
  continueTextLoop: loopText,
198
+ continueTextInterrupted: interruptedText,
172
199
  guardTools: booleanOr(value.guardTools, DEFAULT_CONFIG.guardTools),
173
200
  guardPendingText,
174
201
  guardDoneText,
@@ -634,6 +661,9 @@ var LOOP_GUARD_CANCEL_CAUSE = {
634
661
  var LOOP_COMPLETED_REASON = "turn/end:completed";
635
662
  var LOOP_SILENT_REASON = "turn/end:loop-silent";
636
663
  var MANUAL_NOTIFICATION_REASON = "manual:notification";
664
+ var SWEEP_OBSERVE_BATCH = 16;
665
+ var STORED_READ_TIMEOUT_MS = 5e3;
666
+ var SWEEP_MAX_FAILURES = 3;
637
667
  var isLoopReason = (reason) => reason === LOOP_COMPLETED_REASON || reason === LOOP_SILENT_REASON;
638
668
  var STREAM_NEAR_DUPLICATE_MAX_CHARS = 2048;
639
669
  var STREAM_TAIL_MAX_CHARS = 4096;
@@ -642,6 +672,9 @@ function snapshotSessionEvents(session) {
642
672
  const compatible = session;
643
673
  const snapshot = compatible.snapshotEvents;
644
674
  const events = typeof snapshot === "function" ? snapshot.call(session) : compatible.events;
675
+ return validateSessionEvents(events);
676
+ }
677
+ function validateSessionEvents(events) {
645
678
  if (!Array.isArray(events)) throw new TypeError("session history is not an event array");
646
679
  for (let index = 0; index < events.length; index += 1) {
647
680
  const event = events[index];
@@ -685,6 +718,7 @@ var AutoContinueRunner = class {
685
718
  this.states = /* @__PURE__ */ new Map();
686
719
  this.pauseUntil = /* @__PURE__ */ new Map();
687
720
  this.dayStats = emptyDayStats();
721
+ this.recoveryAttempts = [];
688
722
  this.notices = [];
689
723
  this.noticeListeners = /* @__PURE__ */ new Set();
690
724
  this.stateListeners = /* @__PURE__ */ new Set();
@@ -693,6 +727,12 @@ var AutoContinueRunner = class {
693
727
  this.bootScannedSessions = /* @__PURE__ */ new WeakSet();
694
728
  /** Also bound diagnostics when even an agent's session getter is unavailable. */
695
729
  this.bootScanErrors = /* @__PURE__ */ new WeakSet();
730
+ /** 存储扫描已裁决的会话 id, 避免每轮重复冷读大日志。 */
731
+ this.storedSwept = /* @__PURE__ */ new Set();
732
+ /** 存储会话的连续观察/物化失败次数, 触达 SWEEP_MAX_FAILURES 后不再重试。 */
733
+ this.storedSweepFailures = /* @__PURE__ */ new Map();
734
+ this.storedSweepAnnounced = false;
735
+ this.stopStoredSweep = new AbortController();
696
736
  this.disposeSessionEvents = ctx.on("session/event", (session, event) => {
697
737
  try {
698
738
  this.onHostEvent(session, event);
@@ -743,6 +783,9 @@ var AutoContinueRunner = class {
743
783
  if (this.dayStats.date !== today) this.dayStats = emptyDayStats();
744
784
  return { ...this.dayStats, byCode: { ...this.dayStats.byCode } };
745
785
  }
786
+ recentRecoveryAttempts() {
787
+ return this.recoveryAttempts.map((attempt) => ({ ...attempt }));
788
+ }
746
789
  /** 对外(状态桥): 当前生效的会话级暂停列表。 */
747
790
  activePauses() {
748
791
  const now = Date.now();
@@ -789,6 +832,7 @@ var AutoContinueRunner = class {
789
832
  dispose() {
790
833
  if (this.disposed) return;
791
834
  this.disposed = true;
835
+ this.stopStoredSweep.abort();
792
836
  if (this.bootScanTimer !== void 0) clearTimeout(this.bootScanTimer);
793
837
  this.bootScanTimer = void 0;
794
838
  this.wakeBootScan?.();
@@ -1210,13 +1254,11 @@ var AutoContinueRunner = class {
1210
1254
  /** 通知操作按钮与回调(「立即续跑」/「暂停该会话 1 小时」)。 */
1211
1255
  notifyOptions(sessionId, locale) {
1212
1256
  const copy = NOTICE_COPY[locale];
1213
- return {
1214
- actions: [
1215
- { action: "resume", title: copy.resumeAction },
1216
- { action: "pause1h", title: copy.pauseAction }
1217
- ],
1218
- onAction: (action) => this.onNotifyAction(sessionId, action)
1219
- };
1257
+ const actions = this.ctx.agents.get(sessionId) === void 0 ? [{ action: "pause1h", title: copy.pauseAction }] : [
1258
+ { action: "resume", title: copy.resumeAction },
1259
+ { action: "pause1h", title: copy.pauseAction }
1260
+ ];
1261
+ return { actions, onAction: (action) => this.onNotifyAction(sessionId, action) };
1220
1262
  }
1221
1263
  onNotifyAction(sessionId, action) {
1222
1264
  if (action === "resume") {
@@ -1358,6 +1400,7 @@ var AutoContinueRunner = class {
1358
1400
  if (isLoopReason(reason)) return config.continueTextLoop;
1359
1401
  if (reason.endsWith(":silent")) return config.continueTextSilent;
1360
1402
  if (reason.includes("max-tokens")) return config.continueTextMaxTokens;
1403
+ if (reason.includes("interrupted")) return config.continueTextInterrupted;
1361
1404
  return config.continueText;
1362
1405
  }
1363
1406
  cancelPending(sessionId, why) {
@@ -1425,6 +1468,15 @@ var AutoContinueRunner = class {
1425
1468
  const now = Date.now();
1426
1469
  if (reason !== LOOP_COMPLETED_REASON) state.consecutive += 1;
1427
1470
  state.pendingRecoveryAt = now;
1471
+ if (reason !== LOOP_COMPLETED_REASON) {
1472
+ this.recoveryAttempts.unshift({
1473
+ sessionId,
1474
+ at: now,
1475
+ consecutive: state.consecutive,
1476
+ reason: manualResume ? "manual" : reason === "loop:aborted" ? "loop-guard" : reason.endsWith(":silent") || reason === LOOP_SILENT_REASON ? "silent" : reason.endsWith(":interrupted") ? "interrupted" : reason.endsWith(":max-tokens") ? "max-tokens" : "error"
1477
+ });
1478
+ this.recoveryAttempts.length = Math.min(this.recoveryAttempts.length, 20);
1479
+ }
1428
1480
  this.bumpStat({ sent: 1, ...state.lastFailure !== void 0 ? { code: state.lastFailure.code } : {} });
1429
1481
  this.log(`已自动发送「${text}」到 ${sessionId}(${reason}), 第 ${state.consecutive} 次连续`);
1430
1482
  if (config.notify) {
@@ -1487,6 +1539,14 @@ var AutoContinueRunner = class {
1487
1539
  if (attempt > 0 && Date.now() >= deadline) return;
1488
1540
  try {
1489
1541
  if (await this.scanInterrupted()) return;
1542
+ const config = this.getConfig();
1543
+ if (!config.paused && config.scanOnBoot && this.storedSweep === void 0) {
1544
+ this.storedSweep = this.sweepStoredSessions(config, deadline).catch((error) => {
1545
+ if (!this.disposed) this.ctx.logger.error(`Stored session scan failed: ${String(error)}`);
1546
+ }).finally(() => {
1547
+ this.storedSweep = void 0;
1548
+ });
1549
+ }
1490
1550
  } catch (error) {
1491
1551
  if (this.disposed) return;
1492
1552
  if (attempt % 10 === 0) {
@@ -1498,12 +1558,13 @@ var AutoContinueRunner = class {
1498
1558
  const remaining = deadline - Date.now();
1499
1559
  if (this.disposed || remaining <= 0) return;
1500
1560
  await new Promise((resolve) => {
1501
- this.wakeBootScan = resolve;
1502
- this.bootScanTimer = setTimeout(() => {
1561
+ this.wakeBootScan = () => {
1562
+ if (this.bootScanTimer !== void 0) clearTimeout(this.bootScanTimer);
1503
1563
  this.bootScanTimer = void 0;
1504
1564
  this.wakeBootScan = void 0;
1505
1565
  resolve();
1506
- }, Math.min(3e3, remaining));
1566
+ };
1567
+ this.bootScanTimer = setTimeout(this.wakeBootScan, Math.min(3e3, remaining));
1507
1568
  });
1508
1569
  }
1509
1570
  }
@@ -1596,11 +1657,9 @@ var AutoContinueRunner = class {
1596
1657
  state.lastFailureAt = lastEnd.time;
1597
1658
  this.onTurnFailure(sessionId, scanReason, failure);
1598
1659
  } else {
1599
- if (reasonKind === "no-visible-output") {
1600
- state.lastFailure = void 0;
1601
- state.lastTurn = lastEnd.data.turn;
1602
- state.lastFailureAt = lastEnd.time;
1603
- }
1660
+ if (reasonKind === "no-visible-output") state.lastFailure = void 0;
1661
+ state.lastTurn = lastEnd.data.turn;
1662
+ state.lastFailureAt = lastEnd.time;
1604
1663
  this.schedule(sessionId, scanReason);
1605
1664
  }
1606
1665
  recoveries += 1;
@@ -1612,6 +1671,173 @@ var AutoContinueRunner = class {
1612
1671
  }
1613
1672
  return false;
1614
1673
  }
1674
+ /** Bound cold reads even if a backend ignores cancellation; release late leases. */
1675
+ async readStored(read, deadline) {
1676
+ const timeout = new AbortController();
1677
+ const signal = AbortSignal.any([this.stopStoredSweep.signal, timeout.signal]);
1678
+ const timer = setTimeout(() => timeout.abort(new Error("Stored session read timed out")), Math.max(0, Math.min(STORED_READ_TIMEOUT_MS, deadline - Date.now())));
1679
+ let onAbort;
1680
+ const cancelled = new Promise((_resolve, reject) => {
1681
+ onAbort = () => reject(signal.reason);
1682
+ signal.addEventListener("abort", onAbort, { once: true });
1683
+ if (signal.aborted) onAbort();
1684
+ });
1685
+ const pending = Promise.resolve().then(() => {
1686
+ signal.throwIfAborted();
1687
+ return read(signal);
1688
+ });
1689
+ void pending.then((value) => {
1690
+ if (signal.aborted) value[Symbol.dispose]?.();
1691
+ }).catch(() => {
1692
+ });
1693
+ try {
1694
+ return await Promise.race([pending, cancelled]);
1695
+ } finally {
1696
+ clearTimeout(timer);
1697
+ signal.removeEventListener("abort", onAbort);
1698
+ }
1699
+ }
1700
+ /**
1701
+ * 存储扫描: 枚举持久化会话, 把尾部命中恢复谓词的未加载会话物化为
1702
+ * live agent。宿主重启后 agent 仅在客户端打开会话时才懒加载, 不物化
1703
+ * 则启动扫描永远看不到它们; 谓词与上方扫描一致, 仅失败类原因。
1704
+ */
1705
+ async sweepStoredSessions(config, deadline) {
1706
+ const query = this.ctx.get("sessionQuery");
1707
+ if (query === void 0) return;
1708
+ const records = await this.readStored((signal) => query.listSessions(signal), deadline);
1709
+ if (!Array.isArray(records)) throw new TypeError("stored session listing is not an array");
1710
+ if (!this.storedSweepAnnounced) {
1711
+ this.storedSweepAnnounced = true;
1712
+ this.ctx.logger.info(`存储扫描就绪: ${records.length} 个会话记录`);
1713
+ }
1714
+ let observed = 0;
1715
+ for (const record of records) {
1716
+ if (this.disposed || Date.now() >= deadline || this.getConfig().paused || !this.getConfig().scanOnBoot) return;
1717
+ if (typeof record?.header?.id !== "string" || record.header.id === "") {
1718
+ this.logBootScanFailure(void 0, new TypeError("stored session record has no id"));
1719
+ continue;
1720
+ }
1721
+ const sessionId = record.header.id;
1722
+ if (record.live || this.storedSwept.has(sessionId)) continue;
1723
+ this.storedSwept.add(sessionId);
1724
+ if (record.header.origin === "subagent") continue;
1725
+ observed += 1;
1726
+ let observation;
1727
+ try {
1728
+ const stored = await this.readStored((signal) => query.observeSession(sessionId, { projectionMode: "all", signal }), deadline);
1729
+ observation = stored;
1730
+ if (this.disposed) return;
1731
+ const events = validateSessionEvents(stored.events);
1732
+ if (events.length === 0) continue;
1733
+ if (this.ctx.agents.get(sessionId) !== void 0) continue;
1734
+ let lastEnd;
1735
+ for (let i = events.length - 1; i >= 0; i -= 1) {
1736
+ const event = events[i];
1737
+ if (event?.type === "turn/end") {
1738
+ lastEnd = event;
1739
+ break;
1740
+ }
1741
+ }
1742
+ let lastStart;
1743
+ for (let i = events.length - 1; i >= 0; i -= 1) {
1744
+ const event = events[i];
1745
+ if (event?.type === "turn/start") {
1746
+ lastStart = event;
1747
+ break;
1748
+ }
1749
+ }
1750
+ const openTurn = lastStart !== void 0 && (lastEnd === void 0 || lastStart.seq > lastEnd.seq);
1751
+ let reasonKind;
1752
+ let freshAt;
1753
+ if (openTurn) {
1754
+ reasonKind = "interrupted";
1755
+ freshAt = events[events.length - 1]?.time ?? 0;
1756
+ } else {
1757
+ reasonKind = readReasonKind(lastEnd?.data.reason);
1758
+ freshAt = lastEnd?.time ?? 0;
1759
+ }
1760
+ if (reasonKind === void 0 || freshAt < Date.now() - config.freshMs) continue;
1761
+ if (reasonKind !== void 0 && !openTurn) {
1762
+ const silent = reasonKind === "no-visible-output" && config.resumeSilentTurns;
1763
+ const superseded = events.some(
1764
+ (event) => lastEnd !== void 0 && event.seq > lastEnd.seq && event.type === "user/message" && event.data.source.kind === "user"
1765
+ );
1766
+ if (!isNonHumanReason(reasonKind) && !silent || superseded) continue;
1767
+ if (reasonKind === "error") {
1768
+ const failure = parseFailureFacts(lastEnd.data.reason.error);
1769
+ if (failure === void 0) {
1770
+ console.error(`[auto-continue] 忽略畸形存储 turn/end ${sessionId}: error details 无法解释`);
1771
+ continue;
1772
+ }
1773
+ if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
1774
+ this.onTurnFailure(sessionId, "sweep:turn/end:error", failure);
1775
+ continue;
1776
+ }
1777
+ }
1778
+ }
1779
+ const presetId = stored.projections?.values.agentPreset ?? stored.header.agentPreset;
1780
+ const loggedConfig = foldRequestHeader(events)?.config;
1781
+ if (!await this.materializeStored(
1782
+ sessionId,
1783
+ presetId,
1784
+ loggedConfig === void 0 ? void 0 : { provider: loggedConfig.provider, model: loggedConfig.model }
1785
+ )) {
1786
+ this.storedSwept.delete(sessionId);
1787
+ return;
1788
+ }
1789
+ this.storedSweepFailures.delete(sessionId);
1790
+ this.wakeBootScan?.();
1791
+ this.ctx.logger.info(openTurn ? `扫描物化存储会话 ${sessionId}(日志止于 turn/start, 视作 interrupted), 交给启动扫描接管` : `扫描物化存储会话 ${sessionId}(turn/end:${reasonKind}), 交给启动扫描接管`);
1792
+ } catch (error) {
1793
+ if (this.disposed) return;
1794
+ const failures = (this.storedSweepFailures.get(sessionId) ?? 0) + 1;
1795
+ if (failures < SWEEP_MAX_FAILURES) {
1796
+ this.storedSweepFailures.set(sessionId, failures);
1797
+ this.storedSwept.delete(sessionId);
1798
+ } else {
1799
+ this.storedSweepFailures.delete(sessionId);
1800
+ }
1801
+ this.ctx.logger.error(`存储会话 ${sessionId} 物化失败: ${error instanceof Error ? error.message : String(error)}`);
1802
+ } finally {
1803
+ observation?.[Symbol.dispose]?.();
1804
+ if (observed % SWEEP_OBSERVE_BATCH === 0 && !this.disposed) {
1805
+ await new Promise((resolve) => setTimeout(resolve, 0));
1806
+ }
1807
+ }
1808
+ }
1809
+ }
1810
+ /**
1811
+ * 按会话记录的 preset 组合把存储会话恢复为 live agent(镜像会话控制
1812
+ * 器的 adopt 路径: preset 挂载 + 会话已记录的模型选择回装)。模型选择
1813
+ * 以日志记录的 request-header 播种 agentOptions——{{model}}/{{provider}}
1814
+ * 提示变量与首次请求路由都读它, 驱动器还会因路由吻合而自行回装日志
1815
+ * 记录的 effort; 无落点(从未发过请求的会话)回落宿主默认。恢复时追
1816
+ * 加的合成 turn/end(`interrupted`)随后由常规扫描按既有关卡恢复。
1817
+ */
1818
+ async materializeStored(sessionId, presetId, logged) {
1819
+ if (this.disposed || this.getConfig().paused || !this.getConfig().scanOnBoot) return false;
1820
+ const presets = this.ctx.get("agentPresets");
1821
+ const defaultModel = this.ctx.get("agentDefaultModel");
1822
+ const selection = defaultModel?.currentSelection();
1823
+ const agentOptions = logged !== void 0 ? { provider: logged.provider, model: logged.model } : selection === void 0 ? void 0 : { provider: selection.provider, model: selection.model };
1824
+ if (presets === void 0) {
1825
+ await this.ctx.agents.resume({ resumeSessionId: sessionId, agentOptions, signal: this.stopStoredSweep.signal });
1826
+ return true;
1827
+ }
1828
+ const resolvedId = (await presets.resolve(presetId)).id;
1829
+ if (this.disposed || this.getConfig().paused || !this.getConfig().scanOnBoot) return false;
1830
+ if (this.ctx.agents.get(sessionId) !== void 0) return true;
1831
+ await this.ctx.agents.resume({
1832
+ resumeSessionId: sessionId,
1833
+ agentOptions,
1834
+ signal: this.stopStoredSweep.signal,
1835
+ setup: async (agentCtx) => {
1836
+ await presets.mount(agentCtx, resolvedId);
1837
+ }
1838
+ });
1839
+ return true;
1840
+ }
1615
1841
  /** Captured identity only: even session.id can throw when the header is damaged. */
1616
1842
  logBootScanFailure(sessionId, error) {
1617
1843
  console.error(`[auto-continue] 启动扫描跳过会话 ${sessionId ?? "(id unavailable)"}: ${error instanceof Error ? error.message : String(error)}`);
@@ -1639,6 +1865,8 @@ var AutoContinueSchema = z2.object({
1639
1865
  continueTextSilent: z2.string().default(""),
1640
1866
  /** Text sent for each autonomous-loop continuation (same placeholders as `continueText`). */
1641
1867
  continueTextLoop: z2.string().default(""),
1868
+ /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
1869
+ continueTextInterrupted: z2.string().default(""),
1642
1870
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
1643
1871
  guardTools: z2.boolean().default(true),
1644
1872
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -1723,7 +1951,8 @@ function apply(ctx, config) {
1723
1951
  const statePayload = () => JSON.stringify({
1724
1952
  type: "state",
1725
1953
  stats: runner.todayStats(),
1726
- paused: runner.activePauses()
1954
+ paused: runner.activePauses(),
1955
+ recoveryAttempts: runner.recentRecoveryAttempts()
1727
1956
  });
1728
1957
  runner.subscribeNotices(() => {
1729
1958
  for (const notice of runner.drainNotices()) {
@@ -6,6 +6,7 @@
6
6
  * to `/api/auto-continue-action`) and runtime state (today's stats and the
7
7
  * paused-sessions list) consumed by the settings card's live panels.
8
8
  */
9
+ import type { RecoveryAttempt } from '../shared/core.ts';
9
10
  /** 今日统计视图(与 host 引擎的 DayStats 对应)。 */
10
11
  export interface DayStatsView {
11
12
  date: string;
@@ -26,6 +27,7 @@ export interface PausedSessionView {
26
27
  export declare function pausedSessions(): PausedSessionView[];
27
28
  /** 当前桥状态里的今日统计(卡片面板用)。 */
28
29
  export declare function readTodayStats(): DayStatsView;
30
+ export declare function readRecoveryAttempts(): RecoveryAttempt[];
29
31
  /** 清零今日统计(经动作端点交给 host 引擎执行)。 */
30
32
  export declare function resetTodayStats(): void;
31
33
  /** 解除某个会话的暂停(经动作端点交给 host 引擎执行)。 */
@@ -35,7 +35,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
35
35
  }
36
36
  /** Settings services are injected separately: neither exists in every DSH cohort. */
37
37
  export declare const inject: string[];
38
- export { pausedSessions, readTodayStats, resetTodayStats, unpauseSession, } from './bridge.ts';
38
+ export { pausedSessions, readTodayStats, readRecoveryAttempts, resetTodayStats, unpauseSession, } from './bridge.ts';
39
39
  /**
40
40
  * Plugin body: settings card + host status bridge (notifications, stats,
41
41
  * paused sessions).
@@ -53,6 +53,9 @@ export declare const zh: {
53
53
  'field.continueTextSilent': string;
54
54
  'field.continueTextSilentHint': string;
55
55
  'default.continueTextSilent': "继续。你上一轮只输出了内部推理, 既没有回复也没有调用工具, 用户什么都没看到。每一轮都要以工具调用或可见回复结束。";
56
+ 'field.continueTextInterrupted': string;
57
+ 'field.continueTextInterruptedHint': string;
58
+ 'default.continueTextInterrupted': "继续。宿主在你上一轮运行期间重启了; 重启时未完成的工具调用已按「结果未知」收尾。从中断处继续, 重试可能有副作用的操作前先核实外部状态。";
56
59
  'field.guardTools': string;
57
60
  'field.guardToolsHint': string;
58
61
  'field.guardPendingText': string;
@@ -111,6 +114,18 @@ export declare const zh: {
111
114
  'stats.byCode': string;
112
115
  'stats.empty': string;
113
116
  'stats.reset': string;
117
+ 'recovery.title': string;
118
+ 'recovery.hint': string;
119
+ 'recovery.empty': string;
120
+ 'recovery.count': string;
121
+ 'recovery.consecutive': string;
122
+ 'recovery.latest': string;
123
+ 'recovery.reason.error': string;
124
+ 'recovery.reason.max-tokens': string;
125
+ 'recovery.reason.silent': string;
126
+ 'recovery.reason.interrupted': string;
127
+ 'recovery.reason.loop-guard': string;
128
+ 'recovery.reason.manual': string;
114
129
  'pause.title': string;
115
130
  'pause.none': string;
116
131
  'pause.clearAll': string;
@@ -18,6 +18,7 @@ export interface AutoContinueSettingsCardState extends CardShell {
18
18
  resumeCompletedTurns: CardFieldState;
19
19
  continueTextLoop: CardFieldState;
20
20
  continueTextSilent: CardFieldState;
21
+ continueTextInterrupted: CardFieldState;
21
22
  guardTools: CardFieldState;
22
23
  guardPendingText: CardFieldState;
23
24
  guardDoneText: CardFieldState;
@@ -14,7 +14,7 @@
14
14
  */
15
15
  import type { Context } from '@deepseek-ai/cordis';
16
16
  import type { SessionId } from '@deepseek-ai/dsh-session/types';
17
- import { type AutoContinueConfig, type DayStats, type NotifyAction } from '../shared/core.ts';
17
+ import { type AutoContinueConfig, type DayStats, type RecoveryAttempt, type NotifyAction } from '../shared/core.ts';
18
18
  /** 通知桥事件: host 引擎产生, browser 侧订阅展示(Notification / 动作按钮)。 */
19
19
  export interface HostNotice {
20
20
  /** 稳定标识(供 browser 去重)。 */
@@ -34,6 +34,7 @@ export declare class AutoContinueRunner {
34
34
  private readonly states;
35
35
  private readonly pauseUntil;
36
36
  private dayStats;
37
+ private readonly recoveryAttempts;
37
38
  private readonly notices;
38
39
  private readonly noticeListeners;
39
40
  private readonly stateListeners;
@@ -44,8 +45,15 @@ export declare class AutoContinueRunner {
44
45
  private readonly bootScannedSessions;
45
46
  /** Also bound diagnostics when even an agent's session getter is unavailable. */
46
47
  private readonly bootScanErrors;
48
+ /** 存储扫描已裁决的会话 id, 避免每轮重复冷读大日志。 */
49
+ private readonly storedSwept;
50
+ /** 存储会话的连续观察/物化失败次数, 触达 SWEEP_MAX_FAILURES 后不再重试。 */
51
+ private readonly storedSweepFailures;
52
+ private storedSweepAnnounced;
47
53
  private bootScanTimer;
48
54
  private wakeBootScan;
55
+ private storedSweep;
56
+ private readonly stopStoredSweep;
49
57
  /**
50
58
  * @param ctx - host plugin context (agents registry, session events).
51
59
  * @param getConfig - read the current resolved configuration (entry config).
@@ -54,6 +62,7 @@ export declare class AutoContinueRunner {
54
62
  private log;
55
63
  /** 对外(状态桥): 今日统计快照。 */
56
64
  todayStats(): DayStats;
65
+ recentRecoveryAttempts(): RecoveryAttempt[];
57
66
  /** 对外(状态桥): 当前生效的会话级暂停列表。 */
58
67
  activePauses(): {
59
68
  sessionId: SessionId;
@@ -137,6 +146,23 @@ export declare class AutoContinueRunner {
137
146
  private bootScanLoop;
138
147
  /** Inspect newly available sessions; process each settled startup history once. */
139
148
  private scanInterrupted;
149
+ /** Bound cold reads even if a backend ignores cancellation; release late leases. */
150
+ private readStored;
151
+ /**
152
+ * 存储扫描: 枚举持久化会话, 把尾部命中恢复谓词的未加载会话物化为
153
+ * live agent。宿主重启后 agent 仅在客户端打开会话时才懒加载, 不物化
154
+ * 则启动扫描永远看不到它们; 谓词与上方扫描一致, 仅失败类原因。
155
+ */
156
+ private sweepStoredSessions;
157
+ /**
158
+ * 按会话记录的 preset 组合把存储会话恢复为 live agent(镜像会话控制
159
+ * 器的 adopt 路径: preset 挂载 + 会话已记录的模型选择回装)。模型选择
160
+ * 以日志记录的 request-header 播种 agentOptions——{{model}}/{{provider}}
161
+ * 提示变量与首次请求路由都读它, 驱动器还会因路由吻合而自行回装日志
162
+ * 记录的 effort; 无落点(从未发过请求的会话)回落宿主默认。恢复时追
163
+ * 加的合成 turn/end(`interrupted`)随后由常规扫描按既有关卡恢复。
164
+ */
165
+ private materializeStored;
140
166
  /** Captured identity only: even session.id can throw when the header is damaged. */
141
167
  private logBootScanFailure;
142
168
  /** 从历史事件恢复上一步工具调用状态(扫描路径的幂等护栏)。 */
@@ -31,6 +31,8 @@ export declare const AutoContinueSchema: z<Schemastery.ObjectS<{
31
31
  continueTextSilent: z<string, string>;
32
32
  /** Text sent for each autonomous-loop continuation (same placeholders as `continueText`). */
33
33
  continueTextLoop: z<string, string>;
34
+ /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
35
+ continueTextInterrupted: z<string, string>;
34
36
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
35
37
  guardTools: z<boolean, boolean>;
36
38
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -94,6 +96,8 @@ export declare const AutoContinueSchema: z<Schemastery.ObjectS<{
94
96
  continueTextSilent: z<string, string>;
95
97
  /** Text sent for each autonomous-loop continuation (same placeholders as `continueText`). */
96
98
  continueTextLoop: z<string, string>;
99
+ /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
100
+ continueTextInterrupted: z<string, string>;
97
101
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
98
102
  guardTools: z<boolean, boolean>;
99
103
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -162,6 +166,8 @@ export declare const Config: z<Schemastery.ObjectS<{
162
166
  continueTextSilent: z<string, string>;
163
167
  /** Text sent for each autonomous-loop continuation (same placeholders as `continueText`). */
164
168
  continueTextLoop: z<string, string>;
169
+ /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
170
+ continueTextInterrupted: z<string, string>;
165
171
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
166
172
  guardTools: z<boolean, boolean>;
167
173
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -225,6 +231,8 @@ export declare const Config: z<Schemastery.ObjectS<{
225
231
  continueTextSilent: z<string, string>;
226
232
  /** Text sent for each autonomous-loop continuation (same placeholders as `continueText`). */
227
233
  continueTextLoop: z<string, string>;
234
+ /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
235
+ continueTextInterrupted: z<string, string>;
228
236
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
229
237
  guardTools: z<boolean, boolean>;
230
238
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -14,6 +14,7 @@ export declare const LOCALIZED_TEXT_DEFAULTS: {
14
14
  readonly continueTextMaxTokens: "继续";
15
15
  readonly continueTextSilent: "继续。你上一轮只输出了内部推理, 既没有回复也没有调用工具, 用户什么都没看到。每一轮都要以工具调用或可见回复结束。";
16
16
  readonly continueTextLoop: "继续";
17
+ readonly continueTextInterrupted: "继续。宿主在你上一轮运行期间重启了; 重启时未完成的工具调用已按「结果未知」收尾。从中断处继续, 重试可能有副作用的操作前先核实外部状态。";
17
18
  readonly guardPendingText: "(上一步工具「{tool}」可能未完成, 先确认状态再继续, 不要重复执行)";
18
19
  readonly guardDoneText: "(上一步工具「{tool}」已完成, 结果: {result}; 不要重复执行, 直接继续)";
19
20
  readonly loopText: "(检测到你可能陷入循环, 请停止重复刚才的动作, 换一种方式继续)";
@@ -23,6 +24,7 @@ export declare const LOCALIZED_TEXT_DEFAULTS: {
23
24
  readonly continueTextMaxTokens: "Continue";
24
25
  readonly continueTextSilent: "Continue. Your previous turn ended with internal reasoning only, with no message and no tool call, so nothing reached the user. Always finish a turn with a tool call or a visible answer.";
25
26
  readonly continueTextLoop: "Continue";
27
+ readonly continueTextInterrupted: "Continue. The harness was restarted while your previous turn was still running; tool calls pending at the restart are recorded with unknown outcomes. Resume where you left off, verifying external state before retrying anything that may have side effects.";
26
28
  readonly guardPendingText: "(The previous tool \"{tool}\" may not have completed. Check its state before continuing and do not run it again.)";
27
29
  readonly guardDoneText: "(The previous tool \"{tool}\" completed successfully. Result: {result}; do not run it again. Continue from there.)";
28
30
  readonly loopText: "(You may be stuck in a loop. Stop repeating the last action and continue with a different approach.)";
@@ -44,6 +46,8 @@ export interface AutoContinueSettings {
44
46
  continueTextSilent?: string;
45
47
  /** Text sent for each autonomous-loop continuation (same placeholders as `continueText`). */
46
48
  continueTextLoop?: string;
49
+ /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
50
+ continueTextInterrupted?: string;
47
51
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
48
52
  guardTools?: boolean;
49
53
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -255,6 +259,13 @@ export declare class ToolInvocationTracker {
255
259
  /** 自适应退避: 同一会话连续失败时的有效冷却间隔。 */
256
260
  export declare function effectiveCooldown(consecutive: number, base: number, factor: number, max: number): number;
257
261
  export declare function sleep(ms: number): Promise<void>;
262
+ /** A sent recovery prompt, not proof that the following turn succeeded. */
263
+ export interface RecoveryAttempt {
264
+ sessionId: string;
265
+ at: number;
266
+ reason: 'error' | 'max-tokens' | 'silent' | 'interrupted' | 'loop-guard' | 'manual';
267
+ consecutive: number;
268
+ }
258
269
  /** 一天的自动继续统计(host 单实例内存态)。 */
259
270
  export interface DayStats {
260
271
  /** 本地日期 YYYY-MM-DD。 */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-client-auto-continue",
3
3
  "description": "DSH Web UI plugin: automatically sends a localized continue prompt when a request is interrupted by network errors or other non-human causes",
4
- "version": "0.14.3",
4
+ "version": "0.15.0",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "types": "lib/types/index.d.ts",
@@ -46,8 +46,8 @@
46
46
  "build": "node build.mjs && tsc -p tsconfig.build.json",
47
47
  "watch": "node build.mjs --watch",
48
48
  "typecheck": "tsc --noEmit",
49
- "test:runtime": "node tests/settings-host-live.mjs 0.1.7 && node tests/settings-host-live.mjs 0.2.0 && node tests/settings-host-live.mjs 0.2.1 && node tests/profile-compatibility.mjs 0.2.0 && node tests/profile-compatibility.mjs 0.2.1 && node tests/client-settings-services.mjs 0.2.0 && node tests/client-settings-services.mjs 0.2.1 && node tests/boot-scan-host-live.mjs 0.2.0-rc.2 && node tests/boot-scan-host-live.mjs 0.2.1 && node tests/settings-host-live.mjs 0.2.1-rc.2 && node tests/profile-compatibility.mjs 0.2.1-rc.2",
50
- "test": "node tests/loop-guard-progress.mjs && node tests/scan-on-boot.mjs && node tests/boot-scan-isolation.mjs && node tests/silent-turn-boundaries.mjs && node tests/autonomous-loop.mjs && node tests/manual-resume-pauses.mjs && node tests/stats-freshness.mjs && node tests/simulate-host.mjs && node tests/settings-host-compat.mjs && node tests/simulate-client-loader.mjs && node tests/client-settings-services.mjs && node tests/client-settings-form.mjs && node tests/locale-mirror-bounded.mjs && node tests/settings-card-ui.mjs && node tests/composer-toggle.mjs && node tests/settings-notifications.mjs && node tests/prepare-github-package.mjs",
49
+ "test:runtime": "node tests/settings-host-live.mjs 0.1.7 && node tests/settings-host-live.mjs 0.2.0 && node tests/settings-host-live.mjs 0.2.1 && node tests/profile-compatibility.mjs 0.2.0 && node tests/profile-compatibility.mjs 0.2.1 && node tests/client-settings-services.mjs 0.2.0 && node tests/client-settings-services.mjs 0.2.1 && node tests/boot-scan-host-live.mjs 0.2.0-rc.2 && node tests/boot-scan-host-live.mjs 0.2.1 && node tests/settings-host-live.mjs 0.2.1-rc.2 && node tests/profile-compatibility.mjs 0.2.1-rc.2 && node tests/boot-scan-restart-live.mjs",
50
+ "test": "node tests/boot-scan-stored-sweep.mjs && node tests/loop-guard-progress.mjs && node tests/scan-on-boot.mjs && node tests/boot-scan-isolation.mjs && node tests/silent-turn-boundaries.mjs && node tests/autonomous-loop.mjs && node tests/manual-resume-pauses.mjs && node tests/stats-freshness.mjs && node tests/simulate-host.mjs && node tests/settings-host-compat.mjs && node tests/simulate-client-loader.mjs && node tests/client-settings-services.mjs && node tests/client-settings-form.mjs && node tests/locale-mirror-bounded.mjs && node tests/settings-card-ui.mjs && node tests/composer-toggle.mjs && node tests/settings-notifications.mjs && node tests/prepare-github-package.mjs",
51
51
  "prepack": "npm run build"
52
52
  },
53
53
  "keywords": [