dsh-client-auto-continue 0.18.0 → 0.19.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +230 -310
  3. package/README.ru.md +382 -0
  4. package/README.zh.md +229 -308
  5. package/docs/auto-continue-workflow.archify.json +3 -3
  6. package/docs/auto-continue-workflow.en.archify.json +3 -3
  7. package/docs/auto-continue-workflow.en.html +1 -1
  8. package/docs/auto-continue-workflow.html +1 -1
  9. package/docs/auto-continue-workflow.ru.svg +530 -0
  10. package/docs/banner-ru-dark.svg +38 -0
  11. package/docs/banner-ru.svg +38 -0
  12. package/docs/demo-ru-static.svg +115 -0
  13. package/docs/demo-ru.svg +147 -0
  14. package/docs/releases/v0.19.0.md +62 -0
  15. package/docs/social-preview.png +0 -0
  16. package/docs/social-preview.svg +30 -1
  17. package/lib/client.js +297 -99
  18. package/lib/client.js.map +3 -3
  19. package/lib/index.js +258 -43
  20. package/lib/types/client/auto-continue-icon.d.ts +7 -0
  21. package/lib/types/client/bridge.d.ts +2 -0
  22. package/lib/types/client/composer-toggle.d.ts +2 -0
  23. package/lib/types/client/locales.d.ts +5 -0
  24. package/lib/types/client/settings-card.d.ts +1 -0
  25. package/lib/types/host/engine.d.ts +47 -4
  26. package/lib/types/index.d.ts +8 -0
  27. package/lib/types/shared/core.d.ts +15 -1
  28. package/locale/ru.json +6 -0
  29. package/package.json +5 -3
  30. package/scripts/build-docs-assets.mjs +126 -0
  31. package/src/client/auto-continue-icon.tsx +6 -27
  32. package/src/client/bridge.ts +26 -6
  33. package/src/client/composer-toggle.tsx +22 -11
  34. package/src/client/index.ts +5 -1
  35. package/src/client/locales.ts +215 -40
  36. package/src/client/settings-card.tsx +8 -2
  37. package/src/client/settings-notifications.ts +3 -2
  38. package/src/client/styles.ts +17 -19
  39. package/src/host/engine.ts +283 -41
  40. package/src/host/settings-migration.ts +1 -1
  41. package/src/index.ts +12 -1
  42. package/src/shared/core.ts +26 -2
package/lib/index.js CHANGED
@@ -1121,7 +1121,10 @@ function foldRequestHeader(events, from) {
1121
1121
  // src/shared/core.ts
1122
1122
  var AUTO_CONTINUE_SOURCE_KIND = "plugin:dsh-client-auto-continue";
1123
1123
  function resolveLocale(locale) {
1124
- return typeof locale === "string" && /^zh(?:-|$)/i.test(locale) ? "zh" : "en";
1124
+ if (typeof locale !== "string") return "en";
1125
+ if (/^zh(?:-|$)/i.test(locale)) return "zh";
1126
+ if (/^ru(?:-|$)/i.test(locale)) return "ru";
1127
+ return "en";
1125
1128
  }
1126
1129
  var isSessionMode = (value) => value === "default" || value === "off" || value === "recover" || value === "loop";
1127
1130
  function sessionMode(modes, sessionId) {
@@ -1147,6 +1150,16 @@ var LOCALIZED_TEXT_DEFAULTS = {
1147
1150
  guardPendingText: '(The previous tool "{tool}" may not have completed. Check its state before continuing and do not run it again.)',
1148
1151
  guardDoneText: '(The previous tool "{tool}" completed successfully. Result: {result}; do not run it again. Continue from there.)',
1149
1152
  loopText: "(You may be stuck in a loop. Stop repeating the last action and continue with a different approach.)"
1153
+ },
1154
+ ru: {
1155
+ continueText: "Продолжай",
1156
+ continueTextMaxTokens: "Продолжай",
1157
+ continueTextSilent: "Продолжай. Предыдущий ход закончился только внутренним рассуждением: ни ответа, ни вызова инструмента, поэтому пользователь ничего не увидел. Каждый ход должен заканчиваться вызовом инструмента или видимым ответом.",
1158
+ continueTextLoop: "Продолжай",
1159
+ continueTextInterrupted: "Продолжай. Хост перезапустился, пока предыдущий ход ещё выполнялся; вызовы инструментов, незавершённые на момент перезапуска, записаны с неизвестным результатом. Продолжай с места остановки, проверяя внешнее состояние перед повтором действий с возможными побочными эффектами.",
1160
+ guardPendingText: "(Предыдущий инструмент «{tool}», возможно, не завершился. Проверь его состояние перед продолжением и не запускай его повторно.)",
1161
+ guardDoneText: "(Предыдущий инструмент «{tool}» завершился успешно. Результат: {result}; не запускай его повторно, продолжай с этого места.)",
1162
+ loopText: "(Похоже, ты застрял в цикле. Перестань повторять последнее действие и продолжай другим способом.)"
1150
1163
  }
1151
1164
  };
1152
1165
  var DEFAULT_CONFIG = {
@@ -1154,6 +1167,7 @@ var DEFAULT_CONFIG = {
1154
1167
  ...LOCALIZED_TEXT_DEFAULTS.en,
1155
1168
  usePluginSource: false,
1156
1169
  resumeSilentTurns: true,
1170
+ resumeSubagentSessions: false,
1157
1171
  resumeCompletedTurns: false,
1158
1172
  continueTextLoop: "",
1159
1173
  guardTools: true,
@@ -1208,6 +1222,7 @@ function resolveConfig(section) {
1208
1222
  continueText: text,
1209
1223
  continueTextMaxTokens: maxTokensText,
1210
1224
  resumeSilentTurns: booleanOr(value.resumeSilentTurns, DEFAULT_CONFIG.resumeSilentTurns),
1225
+ resumeSubagentSessions: booleanOr(value.resumeSubagentSessions, DEFAULT_CONFIG.resumeSubagentSessions),
1211
1226
  resumeCompletedTurns: booleanOr(value.resumeCompletedTurns, DEFAULT_CONFIG.resumeCompletedTurns),
1212
1227
  continueTextSilent: silentText,
1213
1228
  continueTextLoop: loopText,
@@ -1720,28 +1735,40 @@ var probeConnectivity = async () => {
1720
1735
  // src/host/engine.ts
1721
1736
  var NOTICE_COPY = {
1722
1737
  zh: {
1723
- notContinuedTitle: "dsh-auto-continue: 未自动继续",
1724
- permanentErrorBody: (sessionId, summary) => `${sessionId}: 永久性错误 ${summary},需要人工处理`,
1738
+ notContinuedTitle: "dsh-auto-continue: 请处理会话错误",
1739
+ permanentErrorBody: (sessionId, summary) => `${sessionId}: ${summary}。请处理此错误后再继续。`,
1725
1740
  resumeAction: "立即续跑",
1726
1741
  pauseAction: "暂停该会话 1 小时",
1727
- continuedTitle: "dsh-auto-continue: 已自动继续",
1728
- continuedBody: (sessionId, text, count) => `${sessionId}: 已发送「${text}」(第 ${count} 次连续)`,
1729
- stoppedTitle: "dsh-auto-continue: 已停止自动继续",
1730
- stoppedBody: (sessionId, count) => `${sessionId}: 连续失败 ${count} 次, 需要人工介入`,
1742
+ continuedTitle: "dsh-auto-continue: 已发送继续消息",
1743
+ continuedBody: (sessionId, text, count) => `${sessionId}: 已发送「${text}」(连续尝试 ${count} 次)`,
1744
+ stoppedTitle: "dsh-auto-continue: 已达到重试上限",
1745
+ stoppedBody: (sessionId, count) => `${sessionId}: 已连续尝试恢复 ${count} 次。请检查会话后再继续。`,
1731
1746
  loopCapTitle: "dsh-auto-continue: 自主循环已到上限",
1732
1747
  loopCapBody: (sessionId, count) => `${sessionId}: 已自主续跑 ${count} 轮, 循环暂停; 发一条消息或重新开启循环即可继续`
1733
1748
  },
1734
1749
  en: {
1735
- notContinuedTitle: "dsh-auto-continue: Not continued",
1736
- permanentErrorBody: (sessionId, summary) => `${sessionId}: Permanent error ${summary}; manual intervention required`,
1750
+ notContinuedTitle: "dsh-auto-continue: Review session error",
1751
+ permanentErrorBody: (sessionId, summary) => `${sessionId}: ${summary}. Resolve this error before continuing.`,
1737
1752
  resumeAction: "Resume now",
1738
1753
  pauseAction: "Pause this session for 1 hour",
1739
- continuedTitle: "dsh-auto-continue: Continued automatically",
1740
- continuedBody: (sessionId, text, count) => `${sessionId}: Sent "${text}" (consecutive attempt ${count})`,
1741
- stoppedTitle: "dsh-auto-continue: Auto-continue stopped",
1742
- stoppedBody: (sessionId, count) => `${sessionId}: ${count} consecutive failures; manual intervention required`,
1754
+ continuedTitle: "dsh-auto-continue: Continue message sent",
1755
+ continuedBody: (sessionId, text, count) => `${sessionId}: Sent "${text}" (consecutive attempts: ${count})`,
1756
+ stoppedTitle: "dsh-auto-continue: Retry limit reached",
1757
+ stoppedBody: (sessionId, count) => `${sessionId}: Consecutive recovery attempts: ${count}. Review the conversation before continuing.`,
1743
1758
  loopCapTitle: "dsh-auto-continue: Autonomous loop limit reached",
1744
1759
  loopCapBody: (sessionId, count) => `${sessionId}: Stopped after ${count} autonomous rounds; send a message or turn the loop back on to keep going`
1760
+ },
1761
+ ru: {
1762
+ notContinuedTitle: "dsh-auto-continue: продолжение не выполнено",
1763
+ permanentErrorBody: (sessionId, summary) => `${sessionId}: постоянная ошибка ${summary}; нужно вмешательство вручную`,
1764
+ resumeAction: "Продолжить сейчас",
1765
+ pauseAction: "Приостановить сессию на 1 час",
1766
+ continuedTitle: "dsh-auto-continue: продолжено автоматически",
1767
+ continuedBody: (sessionId, text, count) => `${sessionId}: отправлено «${text}» (попытка подряд: ${count})`,
1768
+ stoppedTitle: "dsh-auto-continue: авто-продолжение остановлено",
1769
+ stoppedBody: (sessionId, count) => `${sessionId}: сбоев подряд: ${count}; нужно вмешательство вручную`,
1770
+ loopCapTitle: "dsh-auto-continue: достигнут лимит автономного цикла",
1771
+ loopCapBody: (sessionId, count) => `${sessionId}: остановлено после ${count} автономных раундов; отправьте сообщение или включите цикл снова, чтобы продолжить`
1745
1772
  }
1746
1773
  };
1747
1774
  var LOOP_GUARD_CANCEL_CAUSE = {
@@ -1773,6 +1800,13 @@ var CHILD_CAUSE_COPY = {
1773
1800
  interrupted: "closed by crash recovery",
1774
1801
  "max-tokens": "output ceiling reached",
1775
1802
  error: "retryable error"
1803
+ },
1804
+ ru: {
1805
+ "open-turn": "ход прерван после начала",
1806
+ disposed: "хост уничтожил агента",
1807
+ interrupted: "закрыт восстановлением после сбоя",
1808
+ "max-tokens": "достигнут лимит вывода",
1809
+ error: "повторяемая ошибка"
1776
1810
  }
1777
1811
  };
1778
1812
  var isLoopReason = (reason) => reason === LOOP_COMPLETED_REASON || reason === LOOP_SILENT_REASON;
@@ -1829,6 +1863,10 @@ function readCancelCause(value) {
1829
1863
  if (reason.kind !== "aborted") return void 0;
1830
1864
  return readReasonKind(reason.reason);
1831
1865
  }
1866
+ function isHostCancel(value) {
1867
+ const cause = readCancelCause(value);
1868
+ return cause !== void 0 && RESTART_CANCEL_CAUSES.has(cause);
1869
+ }
1832
1870
  function classifyChildInterruption(events, config) {
1833
1871
  let lastEnd;
1834
1872
  for (let i = events.length - 1; i >= 0; i -= 1) {
@@ -1886,6 +1924,7 @@ function isLoopGuardCancelReason(value) {
1886
1924
  const cause = value;
1887
1925
  return cause.kind === LOOP_GUARD_CANCEL_CAUSE.kind && cause.reason === LOOP_GUARD_CANCEL_CAUSE.reason;
1888
1926
  }
1927
+ var LINEAGE_CACHE_LIMIT = 2e3;
1889
1928
  var AutoContinueRunner = class {
1890
1929
  /**
1891
1930
  * @param ctx - host plugin context (agents registry, session events).
@@ -1896,6 +1935,10 @@ var AutoContinueRunner = class {
1896
1935
  this.getConfig = getConfig;
1897
1936
  this.probe = probe;
1898
1937
  this.states = /* @__PURE__ */ new Map();
1938
+ /** Cached subagent lineage: session id -> direct parent id (undefined when the header has none). */
1939
+ this.parents = /* @__PURE__ */ new Map();
1940
+ /** Sessions already identified as subagents, including event views without header metadata. */
1941
+ this.subagentSessions = /* @__PURE__ */ new Set();
1899
1942
  this.pauseUntil = /* @__PURE__ */ new Map();
1900
1943
  this.dayStats = emptyDayStats();
1901
1944
  this.recoveryAttempts = [];
@@ -1961,7 +2004,7 @@ var AutoContinueRunner = class {
1961
2004
  void this.bootScanLoop();
1962
2005
  }
1963
2006
  this.log(
1964
- `已启动(host 单实例, 文本="${config.continueText}", 宽限 ${config.graceMs}ms, 冷却 ${config.cooldownMs}ms, 最多连续 ${config.maxConsecutive} 次)`
2007
+ `已启动(文本="${config.continueText}", 宽限 ${config.graceMs}ms, 冷却 ${config.cooldownMs}ms, 最多连续 ${config.maxConsecutive} 次)`
1965
2008
  );
1966
2009
  }
1967
2010
  log(message) {
@@ -2003,6 +2046,24 @@ var AutoContinueRunner = class {
2003
2046
  for (const listener of this.stateListeners) listener();
2004
2047
  }
2005
2048
  sessionConfig(sessionId) {
2049
+ const config = this.getConfig();
2050
+ if (this.isSubagentSession(sessionId)) {
2051
+ const enabled = this.subagentRecoveryEnabled(sessionId);
2052
+ return {
2053
+ ...config,
2054
+ paused: config.paused || !enabled,
2055
+ resumeCompletedTurns: false,
2056
+ loopGuard: false
2057
+ };
2058
+ }
2059
+ return this.ownSessionConfig(sessionId);
2060
+ }
2061
+ /**
2062
+ * The session's own mode, ignoring subagent inheritance. The stored-session
2063
+ * sweep and the restart hand-off (`resumeInterruptedChildren`) use this, so
2064
+ * turning live subagent recovery off never silently disables them.
2065
+ */
2066
+ ownSessionConfig(sessionId) {
2006
2067
  const config = this.getConfig();
2007
2068
  const mode = sessionMode(config.sessionModes, sessionId);
2008
2069
  return {
@@ -2060,6 +2121,8 @@ var AutoContinueRunner = class {
2060
2121
  state.offlineWait = void 0;
2061
2122
  }
2062
2123
  this.states.clear();
2124
+ this.parents.clear();
2125
+ this.subagentSessions.clear();
2063
2126
  }
2064
2127
  state(sessionId) {
2065
2128
  let state = this.states.get(sessionId);
@@ -2069,19 +2132,157 @@ var AutoContinueRunner = class {
2069
2132
  }
2070
2133
  return state;
2071
2134
  }
2072
- /** Mark a child session and clear queued grace/cooldown sends. */
2073
- markSubagent(sessionId, state) {
2074
- state.subagent = true;
2075
- this.cancelPending(sessionId, "子代理会话");
2135
+ /** Record a subagent session's lineage and its parent id when the header carries one. */
2136
+ noteSubagent(sessionId, parentSession) {
2137
+ this.subagentSessions.add(sessionId);
2138
+ if (parentSession !== void 0 && parentSession !== "") {
2139
+ this.parents.set(sessionId, parentSession);
2140
+ } else if (!this.parents.has(sessionId)) {
2141
+ this.parents.set(sessionId, void 0);
2142
+ }
2076
2143
  }
2077
2144
  /** Read durable origin from the live agent for direct action paths as well. */
2078
2145
  isSubagent(sessionId, state) {
2079
2146
  if (state.subagent) return true;
2080
- const agent = this.ctx.agents.get(sessionId);
2081
- if (agent?.session?.header?.origin !== "subagent") return false;
2082
- this.markSubagent(sessionId, state);
2147
+ const header = this.ctx.agents.get(sessionId)?.session?.header;
2148
+ if (header?.origin !== "subagent") return false;
2149
+ state.subagent = true;
2150
+ this.noteSubagent(sessionId, header.parentSession);
2151
+ return true;
2152
+ }
2153
+ /** Header origin, cached set or state flag; for paths that only have the session id. */
2154
+ isSubagentSession(sessionId) {
2155
+ if (this.subagentSessions.has(sessionId)) return true;
2156
+ const state = this.states.get(sessionId);
2157
+ if (state?.subagent === true) return true;
2158
+ const header = this.ctx.agents.get(sessionId)?.session?.header;
2159
+ if (header?.origin !== "subagent") return false;
2160
+ this.noteSubagent(sessionId, header.parentSession);
2083
2161
  return true;
2084
2162
  }
2163
+ /**
2164
+ * Direct subagent parent id. DSH stores fork lineage in the same
2165
+ * `header.parentSession` field, so only a session whose header origin is
2166
+ * `subagent` may be followed upward: an ordinary ancestor (the visible main
2167
+ * conversation, even a forked one) is the top of the recovery lineage.
2168
+ */
2169
+ parentOf(sessionId) {
2170
+ if (this.parents.has(sessionId)) return this.parents.get(sessionId);
2171
+ const header = this.ctx.agents.get(sessionId)?.session?.header;
2172
+ if (header === void 0) return void 0;
2173
+ if (header.origin !== "subagent") {
2174
+ this.parents.set(sessionId, void 0);
2175
+ return void 0;
2176
+ }
2177
+ const parent = header.parentSession;
2178
+ this.noteSubagent(sessionId, parent);
2179
+ return parent;
2180
+ }
2181
+ /** Explicit session mode stored for this exact id, if the user gave one. */
2182
+ explicitMode(sessionId) {
2183
+ const modes = this.getConfig().sessionModes;
2184
+ const mode = modes[sessionId];
2185
+ return Object.prototype.hasOwnProperty.call(modes, sessionId) && isSessionMode(mode) ? mode : void 0;
2186
+ }
2187
+ /**
2188
+ * A subagent's effective mode, or `undefined` when the lineage cannot be
2189
+ * verified. An intermediate parent that is no longer live (and was never seen
2190
+ * here) used to stop the walk early, fall back to the profile default and
2191
+ * resume a child whose main conversation is Off; refusing the send is safe.
2192
+ */
2193
+ resolveSubagentMode(sessionId) {
2194
+ const own = this.explicitMode(sessionId);
2195
+ if (own !== void 0) return own;
2196
+ const seen = /* @__PURE__ */ new Set([sessionId]);
2197
+ let current = sessionId;
2198
+ for (let depth = 0; depth < 32; depth += 1) {
2199
+ const known = this.parents.has(current);
2200
+ const header = this.ctx.agents.get(current)?.session?.header;
2201
+ if (!known && header === void 0) return void 0;
2202
+ const parent = known ? this.parents.get(current) : header?.origin === "subagent" ? header.parentSession : void 0;
2203
+ if (parent === void 0 || parent === "") {
2204
+ if (header?.origin === "subagent" || this.subagentSessions.has(current)) return void 0;
2205
+ return this.explicitMode(current) ?? "default";
2206
+ }
2207
+ if (seen.has(parent)) return void 0;
2208
+ seen.add(parent);
2209
+ current = parent;
2210
+ }
2211
+ return void 0;
2212
+ }
2213
+ /** Whether the setting and the inherited main-chat mode allow live recovery for this child. */
2214
+ subagentRecoveryEnabled(sessionId) {
2215
+ if (!this.getConfig().resumeSubagentSessions) return false;
2216
+ const mode = this.resolveSubagentMode(sessionId);
2217
+ return mode !== void 0 && mode !== "off";
2218
+ }
2219
+ /** Modes children inherit from their main conversation, for the composer's display. */
2220
+ inheritedSubagentModes() {
2221
+ this.pruneLineage();
2222
+ const inherited = {};
2223
+ for (const sessionId of this.parents.keys()) {
2224
+ if (this.ctx.agents.get(sessionId) === void 0) continue;
2225
+ if (!this.isSubagentSession(sessionId)) continue;
2226
+ if (this.explicitMode(sessionId) !== void 0) continue;
2227
+ const mode = this.resolveSubagentMode(sessionId);
2228
+ if (mode !== void 0) inherited[sessionId] = mode === "loop" ? "recover" : mode;
2229
+ }
2230
+ return inherited;
2231
+ }
2232
+ /**
2233
+ * Keep the lineage caches bounded on long-lived hosts. Once the cache grows,
2234
+ * entries for sessions that are no longer loaded are dropped; they are re-read
2235
+ * from the live header if the session comes back.
2236
+ */
2237
+ pruneLineage() {
2238
+ if (this.parents.size + this.subagentSessions.size <= LINEAGE_CACHE_LIMIT) return;
2239
+ const keep = (sessionId) => this.ctx.agents.get(sessionId) !== void 0;
2240
+ const needed = /* @__PURE__ */ new Set();
2241
+ for (const sessionId of this.parents.keys()) {
2242
+ if (!keep(sessionId)) continue;
2243
+ let current = sessionId;
2244
+ for (let depth = 0; depth < 32 && current !== void 0 && !needed.has(current); depth += 1) {
2245
+ needed.add(current);
2246
+ current = this.parents.get(current);
2247
+ }
2248
+ }
2249
+ for (const sessionId of [...this.parents.keys()]) if (!needed.has(sessionId)) this.parents.delete(sessionId);
2250
+ for (const sessionId of [...this.subagentSessions]) if (!needed.has(sessionId) && !keep(sessionId)) this.subagentSessions.delete(sessionId);
2251
+ }
2252
+ /** Mark a child session; drop only queued sends that its effective policy no longer allows. */
2253
+ markSubagent(sessionId, state, parentSession) {
2254
+ const first = !state.subagent;
2255
+ state.subagent = true;
2256
+ this.noteSubagent(sessionId, parentSession);
2257
+ if (first && !this.subagentRecoveryEnabled(sessionId)) this.cancelPending(sessionId, "子代理会话");
2258
+ }
2259
+ /** Pause deadline, including the parents' "pause this session 1h" for subagents. */
2260
+ effectivePauseUntil(sessionId) {
2261
+ let until = this.pauseUntil.get(sessionId) ?? 0;
2262
+ if (!this.isSubagentSession(sessionId)) return until;
2263
+ const seen = /* @__PURE__ */ new Set([sessionId]);
2264
+ let current = sessionId;
2265
+ for (let depth = 0; depth < 32; depth += 1) {
2266
+ current = this.parentOf(current);
2267
+ if (current === void 0 || current === "" || seen.has(current)) break;
2268
+ seen.add(current);
2269
+ until = Math.max(until, this.pauseUntil.get(current) ?? 0);
2270
+ }
2271
+ return until;
2272
+ }
2273
+ /** Whether this session sits below `ancestorId` in the subagent lineage (never fork lineage). */
2274
+ isDescendantOf(sessionId, ancestorId) {
2275
+ const seen = /* @__PURE__ */ new Set([sessionId]);
2276
+ let current = sessionId;
2277
+ for (let depth = 0; depth < 32; depth += 1) {
2278
+ current = this.parentOf(current);
2279
+ if (current === void 0 || current === "") return false;
2280
+ if (current === ancestorId) return true;
2281
+ if (seen.has(current)) return false;
2282
+ seen.add(current);
2283
+ }
2284
+ return false;
2285
+ }
2085
2286
  /**
2086
2287
  * 事件入口(host 单实例): 预处理工具调用/结果/模型消息(护栏与循环信号),
2087
2288
  * 然后交给回合状态机。
@@ -2090,10 +2291,10 @@ var AutoContinueRunner = class {
2090
2291
  const sessionId = session.id;
2091
2292
  const sessionState = this.states.get(sessionId);
2092
2293
  if (session.header?.origin === "subagent") {
2093
- this.markSubagent(sessionId, sessionState ?? this.state(sessionId));
2094
- return;
2294
+ this.markSubagent(sessionId, sessionState ?? this.state(sessionId), session.header.parentSession);
2295
+ } else if (sessionState?.subagent) {
2296
+ this.noteSubagent(sessionId, session.header?.parentSession ?? this.parentOf(sessionId));
2095
2297
  }
2096
- if (sessionState?.subagent) return;
2097
2298
  if (sessionState?.maintenanceTurn !== void 0 && sessionState.maintenanceTurn === event.data.turn && event.type !== "turn/start" && event.type !== "turn/end") return;
2098
2299
  if ((event.type === "user/message" || event.type === "assistant/message") && typeof event.surfaceOp === "object" && event.surfaceOp !== null) {
2099
2300
  this.state(sessionId).tools.recordSurfaceReplacement(event.seq);
@@ -2459,7 +2660,9 @@ var AutoContinueRunner = class {
2459
2660
  // ---------- host 帧 ----------
2460
2661
  onTurnFailure(sessionId, reason, failure) {
2461
2662
  const config = this.getConfig();
2462
- if (sessionMode(config.sessionModes, sessionId) === "off") return;
2663
+ if (this.isSubagentSession(sessionId)) {
2664
+ if (!this.subagentRecoveryEnabled(sessionId)) return;
2665
+ } else if (sessionMode(config.sessionModes, sessionId) === "off") return;
2463
2666
  if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
2464
2667
  const copy = NOTICE_COPY[config.locale];
2465
2668
  const summary = `${failure.code}${failure.status !== void 0 ? ` (HTTP ${failure.status})` : ""}`;
@@ -2494,6 +2697,11 @@ var AutoContinueRunner = class {
2494
2697
  this.log(`通知按钮: 暂停 ${sessionId} 1 小时`);
2495
2698
  this.pauseUntil.set(sessionId, Date.now() + 60 * 60 * 1e3);
2496
2699
  this.cancelPending(sessionId, "通知按钮暂停该会话");
2700
+ for (const candidate of this.states.keys()) {
2701
+ if (candidate !== sessionId && this.isDescendantOf(candidate, sessionId)) {
2702
+ this.cancelPending(candidate, "父会话已暂停");
2703
+ }
2704
+ }
2497
2705
  }
2498
2706
  }
2499
2707
  /** 内存统计(host 单实例): 按今日桶累计。 */
@@ -2540,12 +2748,8 @@ var AutoContinueRunner = class {
2540
2748
  /** 立即为该会话发送一次自动继续(无视冷却与连续上限; 由通知按钮触发)。 */
2541
2749
  async resumeNow(sessionId) {
2542
2750
  if (this.disposed) return;
2543
- const state = this.state(sessionId);
2544
- if (this.isSubagent(sessionId, state)) return;
2545
- if (state.pendingTimer !== void 0) {
2546
- clearTimeout(state.pendingTimer);
2547
- state.pendingTimer = void 0;
2548
- }
2751
+ if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) return;
2752
+ this.cancelPending(sessionId, "手动续跑");
2549
2753
  try {
2550
2754
  await this.fire(sessionId, MANUAL_NOTIFICATION_REASON, true);
2551
2755
  } catch (error) {
@@ -2566,12 +2770,11 @@ var AutoContinueRunner = class {
2566
2770
  const state = this.state(sessionId);
2567
2771
  const config = this.sessionConfig(sessionId);
2568
2772
  if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
2569
- if (this.isSubagent(sessionId, state)) return;
2570
2773
  if (config.paused) {
2571
2774
  this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
2572
2775
  return;
2573
2776
  }
2574
- if (Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) {
2777
+ if (Date.now() < this.effectivePauseUntil(sessionId)) {
2575
2778
  this.log(`跳过 ${sessionId}(${reason}): 会话暂停中`);
2576
2779
  return;
2577
2780
  }
@@ -2671,12 +2874,12 @@ var AutoContinueRunner = class {
2671
2874
  const manualResume = force && reason === MANUAL_NOTIFICATION_REASON;
2672
2875
  if (reason.endsWith(":silent") && !config.resumeSilentTurns) return;
2673
2876
  if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
2674
- if (this.isSubagent(sessionId, state)) return;
2877
+ if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) return;
2675
2878
  if (config.paused && !manualResume) {
2676
2879
  this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
2677
2880
  return;
2678
2881
  }
2679
- if (!manualResume && Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) {
2882
+ if (!manualResume && Date.now() < this.effectivePauseUntil(sessionId)) {
2680
2883
  this.log(`跳过 ${sessionId}(${reason}): 会话暂停中`);
2681
2884
  return;
2682
2885
  }
@@ -2923,7 +3126,8 @@ var AutoContinueRunner = class {
2923
3126
  break;
2924
3127
  }
2925
3128
  }
2926
- const reasonKind = readReasonKind(lastEnd?.data.reason);
3129
+ let reasonKind = readReasonKind(lastEnd?.data.reason);
3130
+ if (reasonKind === "aborted" && isHostCancel(lastEnd?.data.reason)) reasonKind = "interrupted";
2927
3131
  const lastStart = latestTurnStart(events);
2928
3132
  const maintenance = lastStart?.data.turn === lastEnd?.data.turn && isMaintenanceTurnStart(lastStart);
2929
3133
  const silent = reasonKind === "no-visible-output" && config.resumeSilentTurns;
@@ -3066,7 +3270,7 @@ var AutoContinueRunner = class {
3066
3270
  continue;
3067
3271
  }
3068
3272
  const sessionId = record2.header.id;
3069
- if (this.sessionConfig(sessionId).paused || Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) continue;
3273
+ if (this.ownSessionConfig(sessionId).paused || Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) continue;
3070
3274
  if (record2.header.origin === "subagent") {
3071
3275
  if (config.resumeInterruptedChildren) {
3072
3276
  await this.sweepChild(record2, headersById, config, deadline);
@@ -3106,6 +3310,7 @@ var AutoContinueRunner = class {
3106
3310
  freshAt = events[events.length - 1]?.time ?? 0;
3107
3311
  } else {
3108
3312
  reasonKind = readReasonKind(lastEnd?.data.reason);
3313
+ if (reasonKind === "aborted" && isHostCancel(lastEnd?.data.reason)) reasonKind = "interrupted";
3109
3314
  freshAt = lastEnd?.time ?? 0;
3110
3315
  }
3111
3316
  if (reasonKind === void 0 || freshAt < Date.now() - config.freshMs) continue;
@@ -3173,7 +3378,7 @@ var AutoContinueRunner = class {
3173
3378
  if (this.childSwept.has(sessionId)) return;
3174
3379
  if (this.ctx.agents.get(sessionId) !== void 0) return;
3175
3380
  if (this.childScanned >= CHILD_SWEEP_LIMIT) return;
3176
- if (this.sessionConfig(sessionId).paused) return;
3381
+ if (this.ownSessionConfig(sessionId).paused) return;
3177
3382
  const rootId = resolveRootHeader(header, headersById);
3178
3383
  if (rootId === void 0 || rootId === sessionId) {
3179
3384
  if (!this.childDirtyLogged.has(sessionId)) {
@@ -3303,10 +3508,7 @@ var AutoContinueRunner = class {
3303
3508
  if (end === void 0) return false;
3304
3509
  const kind = readReasonKind(end.data.reason);
3305
3510
  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
- }
3511
+ if (kind === "aborted") return isHostCancel(end.data.reason);
3310
3512
  return false;
3311
3513
  }
3312
3514
  /** 发送需要 live agent; 存储会话沿既有物化路径拉起, 复用 preset 与模型回装。 */
@@ -9714,7 +9916,7 @@ function migrateLegacySettings(ctx, config, fields, validate) {
9714
9916
  });
9715
9917
  const failed = () => {
9716
9918
  if (disposed) return;
9717
- migration.logger.error("[auto-continue] Could not import settings-legacy.yaml; automatic recovery and loop guard are held until the file/profile can be read and saved, then restart the host");
9919
+ migration.logger.error("[auto-continue] Could not import settings-legacy.yaml. Automatic recovery and loop guard are paused. Check the legacy settings file and profile permissions, then restart DSH.");
9718
9920
  };
9719
9921
  void (async () => {
9720
9922
  try {
@@ -9781,6 +9983,7 @@ function migrateLegacySettings(ctx, config, fields, validate) {
9781
9983
 
9782
9984
  // src/index.ts
9783
9985
  var AUTO_CONTINUE_NS = "auto-continue";
9986
+ var BRIDGE_HEARTBEAT_MS = 2e4;
9784
9987
  var settingsFields = {
9785
9988
  /** Active browser/UI locale mirrored by the client. */
9786
9989
  locale: z2.string().default("en"),
@@ -9792,6 +9995,8 @@ var settingsFields = {
9792
9995
  continueTextMaxTokens: z2.string().default(""),
9793
9996
  /** Resume observed model activity that completes without visible output. */
9794
9997
  resumeSilentTurns: z2.boolean().default(true),
9998
+ /** Resume interrupted subagent sessions when their main conversation has auto-continue enabled. Subagents never enter the autonomous loop. */
9999
+ resumeSubagentSessions: z2.boolean().default(false),
9795
10000
  /** Autonomous mode: hand the thread back to the agent after every completed turn, looping until the user stops it. The consecutive-failure cap only throttles failures, never successful completions. */
9796
10001
  resumeCompletedTurns: z2.boolean().default(false),
9797
10002
  /** Text sent to resume a silent turn (same placeholders as `continueText`). */
@@ -9915,6 +10120,7 @@ function apply(ctx, config) {
9915
10120
  recoveryAttempts: runner.recentRecoveryAttempts(),
9916
10121
  sessionPolicy: {
9917
10122
  modes: config2.sessionModes,
10123
+ inheritedModes: runner.inheritedSubagentModes(),
9918
10124
  defaultMode: config2.resumeCompletedTurns ? "loop" : "recover",
9919
10125
  paused: config2.paused,
9920
10126
  writable: writableSettings() !== void 0
@@ -9952,11 +10158,20 @@ function apply(ctx, config) {
9952
10158
  res.write(data);
9953
10159
  };
9954
10160
  sseClients.add(send);
10161
+ const heartbeat = setInterval(() => {
10162
+ try {
10163
+ res.write(": ping\n\n");
10164
+ } catch {
10165
+ }
10166
+ }, BRIDGE_HEARTBEAT_MS);
10167
+ heartbeat.unref?.();
9955
10168
  const close = () => {
10169
+ clearInterval(heartbeat);
9956
10170
  res.end();
9957
10171
  };
9958
10172
  closeClients.add(close);
9959
10173
  req.on("close", () => {
10174
+ clearInterval(heartbeat);
9960
10175
  sseClients.delete(send);
9961
10176
  closeClients.delete(close);
9962
10177
  });
@@ -1 +1,8 @@
1
+ /**
2
+ * Auto-continue glyph: a single-stroke infinity loop.
3
+ *
4
+ * Deliberately not the host's refresh icon. Refresh reads as "start over",
5
+ * auto-continue means "keep going without stopping" (#86). Drawn on a 16px grid
6
+ * with a 2px margin so both loops stay distinct at 14px.
7
+ */
1
8
  export declare function AutoContinueIcon(): import("react").JSX.Element;
@@ -28,7 +28,9 @@ export declare function pausedSessions(): PausedSessionView[];
28
28
  /** 当前桥状态里的今日统计(卡片面板用)。 */
29
29
  export declare function readTodayStats(): DayStatsView;
30
30
  export declare function readRecoveryAttempts(): RecoveryAttempt[];
31
+ /** Last policy the host sent. It survives a bridge reconnect, so check {@link isBridgeConnected} before writing. */
31
32
  export declare function readSessionPolicy(): SessionPolicy | undefined;
33
+ export declare function isBridgeConnected(): boolean;
32
34
  export declare function setSessionMode(sessionId: string, mode: SessionMode): Promise<void>;
33
35
  /** 清零今日统计(经动作端点交给 host 引擎执行)。 */
34
36
  export declare function resetTodayStats(): void;
@@ -4,6 +4,8 @@ import { type SessionMode, type SessionPolicy } from '../shared/core.ts';
4
4
  export interface ComposerToggleState {
5
5
  visible: boolean;
6
6
  policy: SessionPolicy | undefined;
7
+ /** The bridge dropped; `policy` is the last known one and stays on screen, read-only. */
8
+ reconnecting: boolean;
7
9
  writable: boolean;
8
10
  saving: ReadonlySet<string>;
9
11
  failed: ReadonlySet<string>;
@@ -38,6 +38,7 @@ export declare const zh: {
38
38
  'composer.loop': string;
39
39
  'composer.paused': string;
40
40
  'composer.unavailable': string;
41
+ 'composer.reconnecting': string;
41
42
  'composer.saving': string;
42
43
  'composer.saveFailed': string;
43
44
  'field.pausedHint': string;
@@ -49,6 +50,8 @@ export declare const zh: {
49
50
  'default.continueTextMaxTokens': "继续";
50
51
  'field.resumeSilentTurns': string;
51
52
  'field.resumeSilentTurnsHint': string;
53
+ 'field.resumeSubagentSessions': string;
54
+ 'field.resumeSubagentSessionsHint': string;
52
55
  'field.resumeCompletedTurns': string;
53
56
  'field.resumeCompletedTurnsHint': string;
54
57
  'field.resumeInterruptedChildren': string;
@@ -167,3 +170,5 @@ export declare const zh: {
167
170
  export type SettingsCardKey = keyof typeof zh;
168
171
  /** English dictionary, checked complete against the zh key set. */
169
172
  export declare const en: Record<SettingsCardKey, string>;
173
+ /** Russian dictionary, checked complete against the zh key set. */
174
+ export declare const ru: Record<SettingsCardKey, string>;
@@ -16,6 +16,7 @@ export interface AutoContinueSettingsCardState extends CardShell {
16
16
  continueText: CardFieldState;
17
17
  continueTextMaxTokens: CardFieldState;
18
18
  resumeSilentTurns: CardFieldState;
19
+ resumeSubagentSessions: CardFieldState;
19
20
  resumeCompletedTurns: CardFieldState;
20
21
  resumeInterruptedChildren: CardFieldState;
21
22
  resumeGoals: CardFieldState;