dsh-client-auto-continue 0.17.4 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1119,6 +1119,7 @@ function foldRequestHeader(events, from) {
1119
1119
  }
1120
1120
 
1121
1121
  // src/shared/core.ts
1122
+ var AUTO_CONTINUE_SOURCE_KIND = "plugin:dsh-client-auto-continue";
1122
1123
  function resolveLocale(locale) {
1123
1124
  return typeof locale === "string" && /^zh(?:-|$)/i.test(locale) ? "zh" : "en";
1124
1125
  }
@@ -1151,6 +1152,7 @@ var LOCALIZED_TEXT_DEFAULTS = {
1151
1152
  var DEFAULT_CONFIG = {
1152
1153
  locale: "en",
1153
1154
  ...LOCALIZED_TEXT_DEFAULTS.en,
1155
+ usePluginSource: false,
1154
1156
  resumeSilentTurns: true,
1155
1157
  resumeCompletedTurns: false,
1156
1158
  continueTextLoop: "",
@@ -1175,7 +1177,13 @@ var DEFAULT_CONFIG = {
1175
1177
  loopWindowMs: 3e4,
1176
1178
  loopShortCount: 12,
1177
1179
  loopRepeatText: 4,
1178
- loopToolRepeat: 5
1180
+ loopToolRepeat: 5,
1181
+ resumeInterruptedChildren: false,
1182
+ resumeGoals: false,
1183
+ resumePausedGoals: false,
1184
+ pauseWhenOffline: true,
1185
+ offlineCheckMs: 15e3,
1186
+ loopMaxIterations: 0
1179
1187
  };
1180
1188
  function numberOr(value, fallback) {
1181
1189
  return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fallback;
@@ -1196,6 +1204,7 @@ function resolveConfig(section) {
1196
1204
  const guardDoneText = typeof value.guardDoneText === "string" && value.guardDoneText.trim() !== "" ? value.guardDoneText : localized.guardDoneText;
1197
1205
  return {
1198
1206
  locale,
1207
+ usePluginSource: booleanOr(value.usePluginSource, DEFAULT_CONFIG.usePluginSource),
1199
1208
  continueText: text,
1200
1209
  continueTextMaxTokens: maxTokensText,
1201
1210
  resumeSilentTurns: booleanOr(value.resumeSilentTurns, DEFAULT_CONFIG.resumeSilentTurns),
@@ -1227,7 +1236,16 @@ function resolveConfig(section) {
1227
1236
  loopShortCount: Math.max(2, numberOr(value.loopShortCount, DEFAULT_CONFIG.loopShortCount)),
1228
1237
  loopRepeatText: Math.max(2, numberOr(value.loopRepeatText, DEFAULT_CONFIG.loopRepeatText)),
1229
1238
  loopToolRepeat: Math.max(2, numberOr(value.loopToolRepeat, DEFAULT_CONFIG.loopToolRepeat)),
1230
- loopText: typeof value.loopText === "string" && value.loopText.trim() !== "" ? value.loopText : localized.loopText
1239
+ loopText: typeof value.loopText === "string" && value.loopText.trim() !== "" ? value.loopText : localized.loopText,
1240
+ resumeInterruptedChildren: booleanOr(
1241
+ value.resumeInterruptedChildren,
1242
+ DEFAULT_CONFIG.resumeInterruptedChildren
1243
+ ),
1244
+ resumeGoals: booleanOr(value.resumeGoals, DEFAULT_CONFIG.resumeGoals),
1245
+ resumePausedGoals: booleanOr(value.resumePausedGoals, DEFAULT_CONFIG.resumePausedGoals),
1246
+ pauseWhenOffline: booleanOr(value.pauseWhenOffline, DEFAULT_CONFIG.pauseWhenOffline),
1247
+ offlineCheckMs: Math.max(1e3, numberOr(value.offlineCheckMs, DEFAULT_CONFIG.offlineCheckMs)),
1248
+ loopMaxIterations: Math.floor(numberOr(value.loopMaxIterations, DEFAULT_CONFIG.loopMaxIterations))
1231
1249
  };
1232
1250
  }
1233
1251
  function isNonHumanReason(kind) {
@@ -1243,6 +1261,10 @@ function isTransientFailure(failure, retryableErrorPatterns = "") {
1243
1261
  const permanent = /auth|unauthor|forbidden|credential|api[_-]?key|permission/i.test(haystack) || /insufficient.*(balance|quota)|billing|payment|quota.*exceeded.*(?!retry)/i.test(haystack) || /model.*not[_-]?found|unknown[_-]?model|model[_-]?not[_-]?found|not.*support.*model/i.test(haystack) || /context.*(length|limit|overflow|exceed)|token.*limit|max.*context/i.test(haystack) || /invalid[_-]?request|bad[_-]?request/i.test(haystack) || /prompt variable "\{\{[^"\r\n]+\}\}" has no value for this assembly/i.test(haystack);
1244
1262
  return !permanent;
1245
1263
  }
1264
+ function isNetworkFailure(failure) {
1265
+ if (/^(TRANSPORT|TIMEOUT|NETWORK|E(CONN|NET|HOST|AI_|NOTFOUND|TIMEDOUT|PIPE))/i.test(failure.code)) return true;
1266
+ return /network|fetch failed|econn|enotfound|eai_again|etimedout|enetunreach|ehostunreach|enetdown|getaddrinfo|socket hang up|offline|could not reach|connection (reset|refused|closed)|timed? ?out/i.test(failure.message);
1267
+ }
1246
1268
  function formatElapsed(ms) {
1247
1269
  if (ms === void 0 || !Number.isFinite(ms) || ms < 0) return "";
1248
1270
  if (ms < 1e3) return `${Math.round(ms)}ms`;
@@ -1607,7 +1629,13 @@ var freshState = () => ({
1607
1629
  streamRepeatRun: 0,
1608
1630
  loopFired: false,
1609
1631
  loopRetryTimer: void 0,
1610
- cooldownRetryTimer: void 0
1632
+ cooldownRetryTimer: void 0,
1633
+ offlineWait: void 0,
1634
+ offlineTimer: void 0,
1635
+ offlineSince: 0,
1636
+ loopIterations: 0,
1637
+ loopCapNotified: false,
1638
+ loopEnabled: void 0
1611
1639
  });
1612
1640
  var RECOVERY_WINDOW_MS = 10 * 60 * 1e3;
1613
1641
  var ECHO_WINDOW_MS = 10 * 60 * 1e3;
@@ -1633,13 +1661,62 @@ function forgetPendingEcho(state, messageId) {
1633
1661
  function isOurEcho(state, event) {
1634
1662
  if (event.type !== "user/message") return false;
1635
1663
  const message = event.data;
1636
- if (message.source.kind !== "user") return false;
1664
+ if (message.source.kind !== "user" && message.source.kind !== AUTO_CONTINUE_SOURCE_KIND) return false;
1637
1665
  if (state.pendingEchoMessageIds.size === 0) return false;
1638
1666
  const now = Date.now();
1639
1667
  prunePendingEchoMessageIds(state, now);
1640
1668
  return state.pendingEchoMessageIds.delete(message.id);
1641
1669
  }
1642
1670
 
1671
+ // src/host/connectivity.ts
1672
+ import dns from "node:dns";
1673
+ import os from "node:os";
1674
+ var PROBE_HOSTS = ["api.deepseek.com", "www.baidu.com", "one.one.one.one"];
1675
+ var PROBE_TIMEOUT_MS = 3e3;
1676
+ function hasExternalInterface() {
1677
+ try {
1678
+ return Object.values(os.networkInterfaces()).some((list) => list?.some((entry) => !entry.internal) ?? false);
1679
+ } catch {
1680
+ return true;
1681
+ }
1682
+ }
1683
+ function usesExplicitProxy() {
1684
+ const env = process.env;
1685
+ return [env.HTTPS_PROXY, env.https_proxy, env.HTTP_PROXY, env.http_proxy, env.ALL_PROXY, env.all_proxy].some((value) => typeof value === "string" && value.trim() !== "");
1686
+ }
1687
+ function lookupWithin(host, ms) {
1688
+ return new Promise((resolve, reject) => {
1689
+ const timer = setTimeout(() => reject(new Error(`dns lookup timed out: ${host}`)), ms);
1690
+ timer.unref?.();
1691
+ dns.promises.lookup(host).then(
1692
+ (value) => {
1693
+ clearTimeout(timer);
1694
+ resolve(value);
1695
+ },
1696
+ (error) => {
1697
+ clearTimeout(timer);
1698
+ reject(error);
1699
+ }
1700
+ );
1701
+ });
1702
+ }
1703
+ var probeConnectivity = async () => {
1704
+ if (!hasExternalInterface()) return false;
1705
+ if (usesExplicitProxy()) return true;
1706
+ return new Promise((resolve) => {
1707
+ let pending = PROBE_HOSTS.length;
1708
+ for (const host of PROBE_HOSTS) {
1709
+ lookupWithin(host, PROBE_TIMEOUT_MS).then(
1710
+ () => resolve(true),
1711
+ () => {
1712
+ pending -= 1;
1713
+ if (pending === 0) resolve(false);
1714
+ }
1715
+ );
1716
+ }
1717
+ });
1718
+ };
1719
+
1643
1720
  // src/host/engine.ts
1644
1721
  var NOTICE_COPY = {
1645
1722
  zh: {
@@ -1650,7 +1727,9 @@ var NOTICE_COPY = {
1650
1727
  continuedTitle: "dsh-auto-continue: 已自动继续",
1651
1728
  continuedBody: (sessionId, text, count) => `${sessionId}: 已发送「${text}」(第 ${count} 次连续)`,
1652
1729
  stoppedTitle: "dsh-auto-continue: 已停止自动继续",
1653
- stoppedBody: (sessionId, count) => `${sessionId}: 连续失败 ${count} 次, 需要人工介入`
1730
+ stoppedBody: (sessionId, count) => `${sessionId}: 连续失败 ${count} 次, 需要人工介入`,
1731
+ loopCapTitle: "dsh-auto-continue: 自主循环已到上限",
1732
+ loopCapBody: (sessionId, count) => `${sessionId}: 已自主续跑 ${count} 轮, 循环暂停; 发一条消息或重新开启循环即可继续`
1654
1733
  },
1655
1734
  en: {
1656
1735
  notContinuedTitle: "dsh-auto-continue: Not continued",
@@ -1660,7 +1739,9 @@ var NOTICE_COPY = {
1660
1739
  continuedTitle: "dsh-auto-continue: Continued automatically",
1661
1740
  continuedBody: (sessionId, text, count) => `${sessionId}: Sent "${text}" (consecutive attempt ${count})`,
1662
1741
  stoppedTitle: "dsh-auto-continue: Auto-continue stopped",
1663
- stoppedBody: (sessionId, count) => `${sessionId}: ${count} consecutive failures; manual intervention required`
1742
+ stoppedBody: (sessionId, count) => `${sessionId}: ${count} consecutive failures; manual intervention required`,
1743
+ loopCapTitle: "dsh-auto-continue: Autonomous loop limit reached",
1744
+ loopCapBody: (sessionId, count) => `${sessionId}: Stopped after ${count} autonomous rounds; send a message or turn the loop back on to keep going`
1664
1745
  }
1665
1746
  };
1666
1747
  var LOOP_GUARD_CANCEL_CAUSE = {
@@ -1673,6 +1754,27 @@ var MANUAL_NOTIFICATION_REASON = "manual:notification";
1673
1754
  var SWEEP_OBSERVE_BATCH = 16;
1674
1755
  var STORED_READ_TIMEOUT_MS = 5e3;
1675
1756
  var SWEEP_MAX_FAILURES = 3;
1757
+ var RESTART_CANCEL_CAUSES = /* @__PURE__ */ new Set(["disposed", "legacy"]);
1758
+ var DECISION_CANCEL_CAUSES = /* @__PURE__ */ new Set(["user", "parent", "hook"]);
1759
+ var CHILD_SWEEP_LIMIT = 8;
1760
+ var CHILD_ROOT_MAX_DEPTH = 8;
1761
+ var GOALS_SERVICE_KEY = "goals";
1762
+ var CHILD_CAUSE_COPY = {
1763
+ zh: {
1764
+ "open-turn": "回合开始后中断",
1765
+ disposed: "宿主销毁",
1766
+ interrupted: "崩溃恢复标记",
1767
+ "max-tokens": "输出长度耗尽",
1768
+ error: "可重试错误"
1769
+ },
1770
+ en: {
1771
+ "open-turn": "turn cut off after start",
1772
+ disposed: "host disposed the agent",
1773
+ interrupted: "closed by crash recovery",
1774
+ "max-tokens": "output ceiling reached",
1775
+ error: "retryable error"
1776
+ }
1777
+ };
1676
1778
  var isLoopReason = (reason) => reason === LOOP_COMPLETED_REASON || reason === LOOP_SILENT_REASON;
1677
1779
  var STREAM_NEAR_DUPLICATE_MAX_CHARS = 2048;
1678
1780
  var STREAM_TAIL_MAX_CHARS = 4096;
@@ -1721,6 +1823,64 @@ function readReasonKind(value) {
1721
1823
  const kind = value.kind;
1722
1824
  return typeof kind === "string" && kind.trim() !== "" ? kind : void 0;
1723
1825
  }
1826
+ function readCancelCause(value) {
1827
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
1828
+ const reason = value;
1829
+ if (reason.kind !== "aborted") return void 0;
1830
+ return readReasonKind(reason.reason);
1831
+ }
1832
+ function classifyChildInterruption(events, config) {
1833
+ let lastEnd;
1834
+ for (let i = events.length - 1; i >= 0; i -= 1) {
1835
+ const event = events[i];
1836
+ if (event?.type === "turn/end") {
1837
+ lastEnd = event;
1838
+ break;
1839
+ }
1840
+ }
1841
+ const lastStart = latestTurnStart(events);
1842
+ if (lastStart !== void 0 && (lastEnd === void 0 || lastStart.seq > lastEnd.seq)) {
1843
+ if (isMaintenanceTurnStart(lastStart)) return void 0;
1844
+ if ((events[events.length - 1]?.time ?? 0) < Date.now() - config.freshMs) return void 0;
1845
+ return "open-turn";
1846
+ }
1847
+ const end = lastEnd;
1848
+ if (end === void 0) return void 0;
1849
+ if (end.time < Date.now() - config.freshMs) return void 0;
1850
+ for (let i = events.length - 1; i >= 0; i -= 1) {
1851
+ const event = events[i];
1852
+ if (event === void 0 || event.seq <= end.seq) break;
1853
+ if (event.type === "user/message") return void 0;
1854
+ }
1855
+ const reason = end.data.reason;
1856
+ const kind = readReasonKind(reason);
1857
+ if (kind === void 0) return void 0;
1858
+ if (kind === "aborted") {
1859
+ const cause = readCancelCause(reason);
1860
+ if (cause === void 0 || DECISION_CANCEL_CAUSES.has(cause)) return void 0;
1861
+ return RESTART_CANCEL_CAUSES.has(cause) ? "disposed" : void 0;
1862
+ }
1863
+ if (kind === "interrupted") return "interrupted";
1864
+ if (kind === "max-tokens") return "max-tokens";
1865
+ if (kind === "error") {
1866
+ const failure = parseFailureFacts(reason.error);
1867
+ if (failure === void 0) return void 0;
1868
+ if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) return void 0;
1869
+ return "error";
1870
+ }
1871
+ return void 0;
1872
+ }
1873
+ function resolveRootHeader(header, byId) {
1874
+ let current = header;
1875
+ for (let depth = 0; depth <= CHILD_ROOT_MAX_DEPTH; depth += 1) {
1876
+ const parentId = current.parentSession;
1877
+ if (parentId === void 0 || parentId === "") return current.id;
1878
+ const parent = byId.get(parentId);
1879
+ if (parent === void 0) return void 0;
1880
+ current = parent;
1881
+ }
1882
+ return void 0;
1883
+ }
1724
1884
  function isLoopGuardCancelReason(value) {
1725
1885
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
1726
1886
  const cause = value;
@@ -1731,9 +1891,10 @@ var AutoContinueRunner = class {
1731
1891
  * @param ctx - host plugin context (agents registry, session events).
1732
1892
  * @param getConfig - read the current resolved configuration (entry config).
1733
1893
  */
1734
- constructor(ctx, getConfig) {
1894
+ constructor(ctx, getConfig, probe = probeConnectivity) {
1735
1895
  this.ctx = ctx;
1736
1896
  this.getConfig = getConfig;
1897
+ this.probe = probe;
1737
1898
  this.states = /* @__PURE__ */ new Map();
1738
1899
  this.pauseUntil = /* @__PURE__ */ new Map();
1739
1900
  this.dayStats = emptyDayStats();
@@ -1748,6 +1909,16 @@ var AutoContinueRunner = class {
1748
1909
  this.bootScanErrors = /* @__PURE__ */ new WeakSet();
1749
1910
  /** 存储扫描已裁决的会话 id, 避免每轮重复冷读大日志。 */
1750
1911
  this.storedSwept = /* @__PURE__ */ new Set();
1912
+ /** 子会话裁决独立记账: storedSwept 在 origin 判断之前就已标记, 不能复用。 */
1913
+ this.childSwept = /* @__PURE__ */ new Set();
1914
+ /** 本轮已花掉的子会话观察配额(每轮重置, 子会话日志与主会话同等昂贵)。 */
1915
+ this.childScanned = 0;
1916
+ /** 本轮收集到的子会话中断, 按 root 主会话 id 归组。 */
1917
+ this.childInterrupts = /* @__PURE__ */ new Map();
1918
+ /** 已唤醒过的 root 会话 → 上次唤醒覆盖的子会话签名, 防止每轮重复催同一批。 */
1919
+ this.childWoken = /* @__PURE__ */ new Map();
1920
+ /** 已打印过「父链不可解析」的子会话, 避免 15 分钟扫描窗口内每轮重扫把日志刷爆。 */
1921
+ this.childDirtyLogged = /* @__PURE__ */ new Set();
1751
1922
  /** 存储会话的连续观察/物化失败次数, 触达 SWEEP_MAX_FAILURES 后不再重试。 */
1752
1923
  this.storedSweepFailures = /* @__PURE__ */ new Map();
1753
1924
  this.storedSweepAnnounced = false;
@@ -1845,6 +2016,8 @@ var AutoContinueRunner = class {
1845
2016
  if (this.disposed) return;
1846
2017
  for (const [sessionId, state] of this.states) {
1847
2018
  const config = this.sessionConfig(sessionId);
2019
+ if (config.resumeCompletedTurns && state.loopEnabled === false) this.resetLoopIterations(state);
2020
+ state.loopEnabled = config.resumeCompletedTurns;
1848
2021
  if (config.paused || isLoopReason(state.pendingReason ?? "") && !config.resumeCompletedTurns) {
1849
2022
  this.cancelPending(sessionId, "会话模式或全局设置已更改");
1850
2023
  }
@@ -1883,6 +2056,8 @@ var AutoContinueRunner = class {
1883
2056
  if (state.pendingTimer !== void 0) clearTimeout(state.pendingTimer);
1884
2057
  if (state.loopRetryTimer !== void 0) clearTimeout(state.loopRetryTimer);
1885
2058
  if (state.cooldownRetryTimer !== void 0) clearTimeout(state.cooldownRetryTimer);
2059
+ if (state.offlineTimer !== void 0) clearTimeout(state.offlineTimer);
2060
+ state.offlineWait = void 0;
1886
2061
  }
1887
2062
  this.states.clear();
1888
2063
  }
@@ -2273,6 +2448,7 @@ var AutoContinueRunner = class {
2273
2448
  if (isOurEcho(state, event)) break;
2274
2449
  if (event.data.source.kind === "user") {
2275
2450
  state.consecutive = 0;
2451
+ this.resetLoopIterations(state);
2276
2452
  this.cancelPending(sessionId, "用户手动发送消息");
2277
2453
  }
2278
2454
  break;
@@ -2400,6 +2576,8 @@ var AutoContinueRunner = class {
2400
2576
  return;
2401
2577
  }
2402
2578
  if (state.pendingTimer !== void 0) return;
2579
+ if (state.offlineWait !== void 0 || state.offlineTimer !== void 0) return;
2580
+ if (isLoopReason(reason) && this.loopCapReached(sessionId, state, config)) return;
2403
2581
  if (!force && state.consecutive >= config.maxConsecutive) {
2404
2582
  this.log(
2405
2583
  `跳过 ${sessionId}(${reason}): 已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`
@@ -2418,7 +2596,7 @@ var AutoContinueRunner = class {
2418
2596
  state.pendingTimer = void 0;
2419
2597
  state.pendingReason = void 0;
2420
2598
  try {
2421
- void this.fire(sessionId, reason, force);
2599
+ this.fireWhenOnline(sessionId, reason, force);
2422
2600
  } catch (error) {
2423
2601
  console.error(`[auto-continue] 定时发送异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
2424
2602
  }
@@ -2477,6 +2655,13 @@ var AutoContinueRunner = class {
2477
2655
  state.loopRetryTimer = void 0;
2478
2656
  cancelled = true;
2479
2657
  }
2658
+ if (state.offlineWait !== void 0 || state.offlineTimer !== void 0) {
2659
+ if (state.offlineTimer !== void 0) clearTimeout(state.offlineTimer);
2660
+ state.offlineTimer = void 0;
2661
+ state.offlineWait = void 0;
2662
+ state.offlineSince = 0;
2663
+ cancelled = true;
2664
+ }
2480
2665
  if (cancelled) this.log(`取消 ${sessionId} 的自动继续(${why})`);
2481
2666
  }
2482
2667
  fire(sessionId, reason, force = false) {
@@ -2514,7 +2699,7 @@ var AutoContinueRunner = class {
2514
2699
  try {
2515
2700
  const message = createUserMessage({
2516
2701
  content: [{ type: "text", text }],
2517
- source: { kind: "user" }
2702
+ source: { kind: config.usePluginSource ? AUTO_CONTINUE_SOURCE_KIND : "user" }
2518
2703
  });
2519
2704
  trackPendingEcho(state, message.id);
2520
2705
  if (agent.inbox.nextTurn.length > 0) this.prioritizedFollowups.add(message.id);
@@ -2527,7 +2712,9 @@ var AutoContinueRunner = class {
2527
2712
  this.prioritizedFollowups.delete(message.id);
2528
2713
  }
2529
2714
  const now = Date.now();
2715
+ this.rearmGoal(sessionId, config);
2530
2716
  if (reason !== LOOP_COMPLETED_REASON) state.consecutive += 1;
2717
+ if (isLoopReason(reason)) state.loopIterations += 1;
2531
2718
  state.pendingRecoveryAt = now;
2532
2719
  if (reason !== LOOP_COMPLETED_REASON) {
2533
2720
  this.recoveryAttempts.unshift({
@@ -2566,6 +2753,83 @@ var AutoContinueRunner = class {
2566
2753
  this.log(`发送异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
2567
2754
  }
2568
2755
  }
2756
+ resetLoopIterations(state) {
2757
+ state.loopIterations = 0;
2758
+ state.loopCapNotified = false;
2759
+ }
2760
+ /** 自主循环轮数上限: 触顶后静默停下, 每次触顶只提示一次。 */
2761
+ loopCapReached(sessionId, state, config) {
2762
+ const cap = config.loopMaxIterations;
2763
+ if (cap <= 0 || state.loopIterations < cap) return false;
2764
+ if (!state.loopCapNotified) {
2765
+ state.loopCapNotified = true;
2766
+ this.log(`自主循环已续跑 ${state.loopIterations} 轮, 达到上限 ${cap}, 停止 ${sessionId}; 用户发消息或重新开启循环后重新计数`);
2767
+ if (config.notify) {
2768
+ const copy = NOTICE_COPY[config.locale];
2769
+ this.notify(
2770
+ sessionId,
2771
+ copy.loopCapTitle,
2772
+ copy.loopCapBody(sessionId, state.loopIterations),
2773
+ this.notifyOptions(sessionId, config.locale)
2774
+ );
2775
+ }
2776
+ }
2777
+ return true;
2778
+ }
2779
+ checkConnectivity() {
2780
+ if (this.connectivityCheck === void 0) {
2781
+ const check = this.probe().catch(() => true).finally(() => {
2782
+ if (this.connectivityCheck === check) this.connectivityCheck = void 0;
2783
+ });
2784
+ this.connectivityCheck = check;
2785
+ }
2786
+ return this.connectivityCheck;
2787
+ }
2788
+ /**
2789
+ * 网络类失败的续跑先过连通性检测: 断网时发出去必然再失败一次, 白白吃掉连续上限,
2790
+ * 等网络恢复时预算已耗尽。挂起期间不计次数, 每 offlineCheckMs 复检一次, 恢复后
2791
+ * 重新走 schedule(宽限、冷却照常)。手动续跑和非网络原因不受影响。
2792
+ */
2793
+ fireWhenOnline(sessionId, reason, force) {
2794
+ const state = this.state(sessionId);
2795
+ const config = this.sessionConfig(sessionId);
2796
+ const gated = config.pauseWhenOffline && reason !== MANUAL_NOTIFICATION_REASON && !isLoopReason(reason) && state.lastFailure !== void 0 && isNetworkFailure(state.lastFailure);
2797
+ if (!gated) {
2798
+ this.fire(sessionId, reason, force);
2799
+ return;
2800
+ }
2801
+ const token = {};
2802
+ state.offlineWait = token;
2803
+ state.pendingReason = reason;
2804
+ void this.checkConnectivity().then((online) => {
2805
+ if (this.disposed || state.offlineWait !== token) return;
2806
+ if (online) {
2807
+ state.offlineWait = void 0;
2808
+ state.pendingReason = void 0;
2809
+ if (state.offlineSince !== 0) {
2810
+ this.log(`网络已恢复 ${sessionId}, 断网挂起 ${Math.round((Date.now() - state.offlineSince) / 1e3)}s 后继续(${reason})`);
2811
+ state.offlineSince = 0;
2812
+ this.schedule(sessionId, reason, force);
2813
+ return;
2814
+ }
2815
+ this.fire(sessionId, reason, force);
2816
+ return;
2817
+ }
2818
+ if (state.offlineSince === 0) {
2819
+ state.offlineSince = Date.now();
2820
+ this.log(`网络不可用, 挂起 ${sessionId} 的自动继续(${reason}), 每 ${config.offlineCheckMs}ms 复检, 不消耗重试次数`);
2821
+ }
2822
+ state.offlineTimer = setTimeout(() => {
2823
+ state.offlineTimer = void 0;
2824
+ if (state.offlineWait !== token) return;
2825
+ try {
2826
+ this.fireWhenOnline(sessionId, reason, force);
2827
+ } catch (error) {
2828
+ console.error(`[auto-continue] 断网复检异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
2829
+ }
2830
+ }, config.offlineCheckMs);
2831
+ });
2832
+ }
2569
2833
  /**
2570
2834
  * 组装本次续跑消息: 模板填充 + 幂等护栏。
2571
2835
  * 护栏依据上一步工具调用的执行状态附加指引, 防止重跑副作用操作:
@@ -2602,7 +2866,8 @@ var AutoContinueRunner = class {
2602
2866
  if (await this.scanInterrupted()) return;
2603
2867
  const config = this.getConfig();
2604
2868
  if (!config.paused && config.scanOnBoot && this.storedSweep === void 0) {
2605
- this.storedSweep = this.sweepStoredSessions(config, deadline).catch((error) => {
2869
+ this.childScanned = 0;
2870
+ this.storedSweep = this.sweepStoredSessions(config, deadline).then(() => this.wakeInterruptedChildren(config, deadline)).catch((error) => {
2606
2871
  if (!this.disposed) this.ctx.logger.error(`Stored session scan failed: ${String(error)}`);
2607
2872
  }).finally(() => {
2608
2873
  this.storedSweep = void 0;
@@ -2773,7 +3038,25 @@ var AutoContinueRunner = class {
2773
3038
  if (!Array.isArray(records)) throw new TypeError("stored session listing is not an array");
2774
3039
  if (!this.storedSweepAnnounced) {
2775
3040
  this.storedSweepAnnounced = true;
2776
- this.ctx.logger.info(`存储扫描就绪: ${records.length} 个会话记录`);
3041
+ let children = 0;
3042
+ let otherOrigins = 0;
3043
+ let originMissing = 0;
3044
+ for (const record2 of records) {
3045
+ const origin = record2?.header?.origin;
3046
+ if (origin === "subagent") children += 1;
3047
+ else if (origin === void 0) originMissing += 1;
3048
+ else otherOrigins += 1;
3049
+ }
3050
+ this.ctx.logger.info(
3051
+ `存储扫描就绪: ${records.length} 个会话记录 (subagent ${children} / 无 origin ${originMissing} / 其它 origin ${otherOrigins})`
3052
+ );
3053
+ }
3054
+ const headersById = /* @__PURE__ */ new Map();
3055
+ for (const record2 of records) {
3056
+ const header = record2?.header;
3057
+ if (header !== void 0 && typeof header.id === "string" && header.id !== "") {
3058
+ headersById.set(header.id, header);
3059
+ }
2777
3060
  }
2778
3061
  let observed = 0;
2779
3062
  for (const record2 of records) {
@@ -2784,9 +3067,14 @@ var AutoContinueRunner = class {
2784
3067
  }
2785
3068
  const sessionId = record2.header.id;
2786
3069
  if (this.sessionConfig(sessionId).paused || Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) continue;
3070
+ if (record2.header.origin === "subagent") {
3071
+ if (config.resumeInterruptedChildren) {
3072
+ await this.sweepChild(record2, headersById, config, deadline);
3073
+ }
3074
+ continue;
3075
+ }
2787
3076
  if (record2.live || this.storedSwept.has(sessionId)) continue;
2788
3077
  this.storedSwept.add(sessionId);
2789
- if (record2.header.origin === "subagent") continue;
2790
3078
  observed += 1;
2791
3079
  let observation;
2792
3080
  try {
@@ -2870,6 +3158,230 @@ var AutoContinueRunner = class {
2870
3158
  }
2871
3159
  }
2872
3160
  }
3161
+ /**
3162
+ * 子会话裁决。子会话本身永不直接续跑(父代理权威, 见 README), 但启动扫描要
3163
+ * 知道它是否在重启时被打断, 才能在自己的 root 会话上补一次带清单的唤醒。
3164
+ * 独立 `childSwept` 记账与独立配额: 主扫描的 `storedSwept` 在 origin 判断
3165
+ * 之前就已标记, 复用它会让子会话永远扫不到, 也会吃掉主扫描的观察预算。
3166
+ */
3167
+ async sweepChild(record2, headersById, config, deadline) {
3168
+ const header = record2.header;
3169
+ const sessionId = header.id;
3170
+ const parentId = header.parentSession;
3171
+ if (parentId === void 0 || parentId === "") return;
3172
+ if (record2.persisted !== true) return;
3173
+ if (this.childSwept.has(sessionId)) return;
3174
+ if (this.ctx.agents.get(sessionId) !== void 0) return;
3175
+ if (this.childScanned >= CHILD_SWEEP_LIMIT) return;
3176
+ if (this.sessionConfig(sessionId).paused) return;
3177
+ const rootId = resolveRootHeader(header, headersById);
3178
+ if (rootId === void 0 || rootId === sessionId) {
3179
+ if (!this.childDirtyLogged.has(sessionId)) {
3180
+ this.childDirtyLogged.add(sessionId);
3181
+ this.log(`子会话 ${sessionId} 父链不可解析(脏引用或自环), 跳过(每会话只记一次)`);
3182
+ }
3183
+ return;
3184
+ }
3185
+ const query = this.ctx.get("sessionQuery");
3186
+ if (query === void 0) return;
3187
+ this.childSwept.add(sessionId);
3188
+ this.childScanned += 1;
3189
+ let observation;
3190
+ try {
3191
+ const stored = await this.readStored(
3192
+ (signal) => query.observeSession(sessionId, { projectionMode: "all", signal }),
3193
+ deadline
3194
+ );
3195
+ observation = stored;
3196
+ if (this.disposed) return;
3197
+ const events = validateSessionEvents(stored.events);
3198
+ if (events.length === 0) return;
3199
+ const cause = classifyChildInterruption(events, config);
3200
+ if (cause === void 0) return;
3201
+ const tail = events[events.length - 1];
3202
+ const list = this.childInterrupts.get(rootId) ?? [];
3203
+ list.push({
3204
+ id: sessionId,
3205
+ title: typeof header.title === "string" && header.title !== "" ? header.title : void 0,
3206
+ preset: header.agentPreset,
3207
+ cause,
3208
+ at: tail?.time ?? Date.now()
3209
+ });
3210
+ this.childInterrupts.set(rootId, list);
3211
+ this.log(`子会话 ${sessionId} 重启时被打断(${cause}), 记入 root ${rootId}`);
3212
+ } catch (error) {
3213
+ this.childSwept.delete(sessionId);
3214
+ if (!this.disposed) {
3215
+ this.ctx.logger.info(
3216
+ `子会话 ${sessionId} 冷读失败: ${error instanceof Error ? error.message : String(error)}`
3217
+ );
3218
+ }
3219
+ } finally {
3220
+ observation?.[Symbol.dispose]?.();
3221
+ }
3222
+ }
3223
+ /** 把本轮收集到的子会话中断转成 root 会话上的一次唤醒(同一批只催一次)。 */
3224
+ async wakeInterruptedChildren(config, deadline) {
3225
+ if (this.disposed || this.childInterrupts.size === 0) return;
3226
+ if (config.paused || !config.scanOnBoot || !config.resumeInterruptedChildren) return;
3227
+ for (const [rootId, children] of [...this.childInterrupts]) {
3228
+ if (this.disposed || Date.now() >= deadline) return;
3229
+ try {
3230
+ if (await this.wakeRoot(config, rootId, children, deadline)) {
3231
+ this.childInterrupts.delete(rootId);
3232
+ }
3233
+ } catch (error) {
3234
+ this.childInterrupts.delete(rootId);
3235
+ if (!this.disposed) {
3236
+ this.ctx.logger.info(
3237
+ `子会话唤醒 ${rootId} 失败: ${error instanceof Error ? error.message : String(error)}`
3238
+ );
3239
+ }
3240
+ }
3241
+ }
3242
+ }
3243
+ /**
3244
+ * 在 root 会话上唤醒一次。只有在 root 自己是"干净终态"时才动手: 它若被打断,
3245
+ * 主扫描本来就会续跑它; 它若被用户手动停止, 唤醒就是幽灵回合。
3246
+ */
3247
+ async wakeRoot(config, rootId, children, deadline) {
3248
+ if (this.sessionConfig(rootId).paused) return false;
3249
+ if (Date.now() < (this.pauseUntil.get(rootId) ?? 0)) return false;
3250
+ const state = this.state(rootId);
3251
+ if (state.pendingTimer !== void 0) return false;
3252
+ if (state.consecutive >= config.maxConsecutive) return true;
3253
+ if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) return false;
3254
+ const batch = children.map((child) => `${child.id}:${child.cause}`).sort().join(",");
3255
+ if (this.childWoken.get(rootId) === batch) return true;
3256
+ if (!await this.rootAcceptsWake(rootId, deadline)) return true;
3257
+ const agent = await this.ensureLiveAgent(rootId, deadline);
3258
+ if (agent === void 0 || this.disposed) return false;
3259
+ const text = this.buildChildResumeText(config, children);
3260
+ const message = createUserMessage({
3261
+ content: [{ type: "text", text }],
3262
+ source: { kind: "user" }
3263
+ });
3264
+ state.lastAttemptAt = Date.now();
3265
+ agent.followup(message);
3266
+ this.childWoken.set(rootId, batch);
3267
+ this.log(
3268
+ `已唤醒 ${rootId}: ${children.length} 个子会话在重启时被打断, 清单已交给父会话处置`
3269
+ );
3270
+ this.rearmGoal(rootId, config);
3271
+ return true;
3272
+ }
3273
+ /** 父会话只在"干净结束"或"被宿主关闭"时接受唤醒; 用户手动停止的绝不复活。 */
3274
+ async rootAcceptsWake(sessionId, deadline) {
3275
+ const query = this.ctx.get("sessionQuery");
3276
+ if (query === void 0) return false;
3277
+ let events;
3278
+ let stored;
3279
+ try {
3280
+ const observation = await this.readStored(
3281
+ (signal) => query.observeSession(sessionId, { projectionMode: "all", signal }),
3282
+ deadline
3283
+ );
3284
+ stored = observation;
3285
+ events = validateSessionEvents(observation.events);
3286
+ } catch {
3287
+ return false;
3288
+ } finally {
3289
+ stored?.[Symbol.dispose]?.();
3290
+ }
3291
+ if (events.length === 0) return false;
3292
+ let lastEnd;
3293
+ for (let i = events.length - 1; i >= 0; i -= 1) {
3294
+ const event = events[i];
3295
+ if (event?.type === "turn/end") {
3296
+ lastEnd = event;
3297
+ break;
3298
+ }
3299
+ }
3300
+ const lastStart = latestTurnStart(events);
3301
+ const end = lastEnd;
3302
+ if (lastStart !== void 0 && (end === void 0 || lastStart.seq > end.seq)) return false;
3303
+ if (end === void 0) return false;
3304
+ const kind = readReasonKind(end.data.reason);
3305
+ if (kind === "completed") return true;
3306
+ if (kind === "aborted") {
3307
+ const cause = readCancelCause(end.data.reason);
3308
+ return cause !== void 0 && RESTART_CANCEL_CAUSES.has(cause);
3309
+ }
3310
+ return false;
3311
+ }
3312
+ /** 发送需要 live agent; 存储会话沿既有物化路径拉起, 复用 preset 与模型回装。 */
3313
+ async ensureLiveAgent(sessionId, deadline) {
3314
+ const live = this.ctx.agents.get(sessionId);
3315
+ if (live !== void 0) return live;
3316
+ const query = this.ctx.get("sessionQuery");
3317
+ if (query === void 0) return void 0;
3318
+ let presetId;
3319
+ let model;
3320
+ let stored;
3321
+ try {
3322
+ const observation = await this.readStored(
3323
+ (signal) => query.observeSession(sessionId, { projectionMode: "all", signal }),
3324
+ deadline
3325
+ );
3326
+ stored = observation;
3327
+ presetId = observation.projections?.values.agentPreset ?? observation.header.agentPreset;
3328
+ const loggedConfig = foldRequestHeader(validateSessionEvents(observation.events))?.config;
3329
+ if (loggedConfig !== void 0) model = { provider: loggedConfig.provider, model: loggedConfig.model };
3330
+ } catch {
3331
+ return void 0;
3332
+ } finally {
3333
+ stored?.[Symbol.dispose]?.();
3334
+ }
3335
+ const ok = await this.materializeStored(sessionId, presetId, model);
3336
+ if (!ok || this.disposed) return void 0;
3337
+ return this.ctx.agents.get(sessionId);
3338
+ }
3339
+ /** 唤醒文本必须带会话级证据: 否则父会话看不到任何状态, 只会白跑一轮再回一句"都结束了"。 */
3340
+ buildChildResumeText(config, children) {
3341
+ const lines = children.map((child) => {
3342
+ const label = child.title !== void 0 ? `「${child.title}」` : "";
3343
+ const preset = child.preset !== void 0 ? ` (${child.preset})` : "";
3344
+ const cause = CHILD_CAUSE_COPY[config.locale][child.cause];
3345
+ return `- ${child.id} ${label}${preset} — ${cause}`;
3346
+ });
3347
+ const header = config.locale === "zh" ? "重启时你开的以下子代理 / 团队成员会话被打断, 没有跑完。请逐个检查, 按需要继续或收尾:" : "These child sessions you started (subagent / team member) were interrupted by a restart and did not finish. Check each one and either continue it or wrap it up:";
3348
+ const tail = config.locale === "zh" ? "要继续的用 send_message / subagent 重新拉起对应会话(重启后它们并未加载); 已完成或不再需要的, 说明结论即可。" : "Use send_message (or subagent) to bring back the ones that should continue — they are not loaded after the restart; for finished or abandoned ones, just state the conclusion.";
3349
+ return [header, ...lines, tail].join("\n");
3350
+ }
3351
+ /**
3352
+ * 重启会把 active goal 置为 disarmed(宿主卸载驱动的正常动作), 只有人类授权的
3353
+ * resume 能重新 arm; paused 则是人类的显式决定。两者都默认关闭。
3354
+ */
3355
+ rearmGoal(sessionId, config) {
3356
+ if (!config.resumeGoals) return;
3357
+ const goals = this.ctx.get(GOALS_SERVICE_KEY);
3358
+ if (goals === void 0) return;
3359
+ const agent = this.ctx.agents.get(sessionId);
3360
+ if (agent === void 0) return;
3361
+ try {
3362
+ const view = goals.get(agent);
3363
+ if (view === void 0) return;
3364
+ const revision = view.revision;
3365
+ if (revision === void 0) {
3366
+ this.log(`会话 ${sessionId}: goal 视图缺 revision, 跳过重新武装(宿主会拒绝无 revision 的 resume)`);
3367
+ return;
3368
+ }
3369
+ const ref = view.ref ?? { id: view.id, revision };
3370
+ if (view.phase === "active" && view.activation === "disarmed") {
3371
+ goals.resume(agent, ref);
3372
+ this.log(`会话 ${sessionId}: goal 被重启失活, 已重新武装`);
3373
+ return;
3374
+ }
3375
+ if (view.phase === "paused" && config.resumePausedGoals) {
3376
+ goals.resume(agent, ref);
3377
+ this.log(`会话 ${sessionId}: 已恢复被暂停的 goal`);
3378
+ }
3379
+ } catch (error) {
3380
+ this.ctx.logger.info(
3381
+ `goal 恢复失败 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`
3382
+ );
3383
+ }
3384
+ }
2873
3385
  /**
2874
3386
  * 按会话记录的 preset 组合把存储会话恢复为 live agent(镜像会话控制
2875
3387
  * 器的 adopt 路径: preset 挂载 + 会话已记录的模型选择回装)。模型选择
@@ -9272,6 +9784,8 @@ var AUTO_CONTINUE_NS = "auto-continue";
9272
9784
  var settingsFields = {
9273
9785
  /** Active browser/UI locale mirrored by the client. */
9274
9786
  locale: z2.string().default("en"),
9787
+ /** Send continue messages with the plugin source instead of the legacy user source. */
9788
+ usePluginSource: z2.boolean().default(false),
9275
9789
  /** Text automatically sent after an interruption. */
9276
9790
  continueText: z2.string().default(""),
9277
9791
  /** Text sent when the output token ceiling is reached (same placeholders as `continueText`). */
@@ -9335,7 +9849,19 @@ var settingsFields = {
9335
9849
  /** Consecutive identical tool calls with identical arguments AND results trip the loop guard. */
9336
9850
  loopToolRepeat: z2.natural().min(2).default(5),
9337
9851
  /** Text sent after the loop guard cancels and restarts a turn (supports {tool}). */
9338
- loopText: z2.string().default("")
9852
+ loopText: z2.string().default(""),
9853
+ /** Recover child (subagent / Agent Teams) sessions a restart interrupted by waking their root session once. */
9854
+ resumeInterruptedChildren: z2.boolean().default(false),
9855
+ /** Re-arm a goal a restart left `active` but `disarmed`, when its own session is resumed. */
9856
+ resumeGoals: z2.boolean().default(false),
9857
+ /** Also resume goals the user explicitly paused. Off by default: pausing is a human decision. */
9858
+ resumePausedGoals: z2.boolean().default(false),
9859
+ /** Hold network-error recoveries while the host is offline; waiting does not consume the retry budget. */
9860
+ pauseWhenOffline: z2.boolean().default(true),
9861
+ /** How often (ms) a held recovery re-checks connectivity. */
9862
+ offlineCheckMs: z2.natural().min(1e3).default(15e3),
9863
+ /** Autonomous-loop round cap per session; 0 means unlimited. */
9864
+ loopMaxIterations: z2.natural().default(0)
9339
9865
  };
9340
9866
  var AutoContinueSchema = z2.object(settingsFields);
9341
9867
  var entrySchema = z2.object({