dsh-client-auto-continue 0.18.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -0
- package/README.md +230 -310
- package/README.ru.md +382 -0
- package/README.zh.md +229 -308
- package/docs/auto-continue-workflow.archify.json +3 -3
- package/docs/auto-continue-workflow.en.archify.json +3 -3
- package/docs/auto-continue-workflow.en.html +1 -1
- package/docs/auto-continue-workflow.html +1 -1
- package/docs/auto-continue-workflow.ru.svg +530 -0
- package/docs/banner-ru-dark.svg +38 -0
- package/docs/banner-ru.svg +38 -0
- package/docs/demo-ru-static.svg +115 -0
- package/docs/demo-ru.svg +147 -0
- package/docs/releases/v0.19.0.md +62 -0
- package/docs/releases/v0.20.0.md +46 -0
- package/docs/social-preview.png +0 -0
- package/docs/social-preview.svg +30 -1
- package/lib/client.js +297 -99
- package/lib/client.js.map +3 -3
- package/lib/index.js +496 -43
- package/lib/types/client/auto-continue-icon.d.ts +7 -0
- package/lib/types/client/bridge.d.ts +2 -0
- package/lib/types/client/composer-toggle.d.ts +2 -0
- package/lib/types/client/locales.d.ts +5 -0
- package/lib/types/client/settings-card.d.ts +1 -0
- package/lib/types/host/engine.d.ts +88 -4
- package/lib/types/index.d.ts +8 -0
- package/lib/types/shared/core.d.ts +21 -1
- package/locale/ru.json +6 -0
- package/package.json +5 -3
- package/scripts/build-docs-assets.mjs +126 -0
- package/src/client/auto-continue-icon.tsx +6 -27
- package/src/client/bridge.ts +26 -6
- package/src/client/composer-toggle.tsx +22 -11
- package/src/client/index.ts +5 -1
- package/src/client/locales.ts +215 -40
- package/src/client/settings-card.tsx +8 -2
- package/src/client/settings-notifications.ts +3 -2
- package/src/client/styles.ts +17 -19
- package/src/host/engine.ts +571 -41
- package/src/host/settings-migration.ts +1 -1
- package/src/index.ts +23 -1
- package/src/shared/core.ts +32 -2
package/lib/index.js
CHANGED
|
@@ -20,6 +20,9 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
|
|
|
20
20
|
// src/index.ts
|
|
21
21
|
import z2 from "@deepseek-ai/schemastery";
|
|
22
22
|
|
|
23
|
+
// src/host/engine.ts
|
|
24
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
25
|
+
|
|
23
26
|
// node_modules/@deepseek-ai/dsh-llm/lib/index.js
|
|
24
27
|
import { createRequire } from "node:module";
|
|
25
28
|
|
|
@@ -1121,7 +1124,10 @@ function foldRequestHeader(events, from) {
|
|
|
1121
1124
|
// src/shared/core.ts
|
|
1122
1125
|
var AUTO_CONTINUE_SOURCE_KIND = "plugin:dsh-client-auto-continue";
|
|
1123
1126
|
function resolveLocale(locale) {
|
|
1124
|
-
|
|
1127
|
+
if (typeof locale !== "string") return "en";
|
|
1128
|
+
if (/^zh(?:-|$)/i.test(locale)) return "zh";
|
|
1129
|
+
if (/^ru(?:-|$)/i.test(locale)) return "ru";
|
|
1130
|
+
return "en";
|
|
1125
1131
|
}
|
|
1126
1132
|
var isSessionMode = (value) => value === "default" || value === "off" || value === "recover" || value === "loop";
|
|
1127
1133
|
function sessionMode(modes, sessionId) {
|
|
@@ -1147,6 +1153,16 @@ var LOCALIZED_TEXT_DEFAULTS = {
|
|
|
1147
1153
|
guardPendingText: '(The previous tool "{tool}" may not have completed. Check its state before continuing and do not run it again.)',
|
|
1148
1154
|
guardDoneText: '(The previous tool "{tool}" completed successfully. Result: {result}; do not run it again. Continue from there.)',
|
|
1149
1155
|
loopText: "(You may be stuck in a loop. Stop repeating the last action and continue with a different approach.)"
|
|
1156
|
+
},
|
|
1157
|
+
ru: {
|
|
1158
|
+
continueText: "Продолжай",
|
|
1159
|
+
continueTextMaxTokens: "Продолжай",
|
|
1160
|
+
continueTextSilent: "Продолжай. Предыдущий ход закончился только внутренним рассуждением: ни ответа, ни вызова инструмента, поэтому пользователь ничего не увидел. Каждый ход должен заканчиваться вызовом инструмента или видимым ответом.",
|
|
1161
|
+
continueTextLoop: "Продолжай",
|
|
1162
|
+
continueTextInterrupted: "Продолжай. Хост перезапустился, пока предыдущий ход ещё выполнялся; вызовы инструментов, незавершённые на момент перезапуска, записаны с неизвестным результатом. Продолжай с места остановки, проверяя внешнее состояние перед повтором действий с возможными побочными эффектами.",
|
|
1163
|
+
guardPendingText: "(Предыдущий инструмент «{tool}», возможно, не завершился. Проверь его состояние перед продолжением и не запускай его повторно.)",
|
|
1164
|
+
guardDoneText: "(Предыдущий инструмент «{tool}» завершился успешно. Результат: {result}; не запускай его повторно, продолжай с этого места.)",
|
|
1165
|
+
loopText: "(Похоже, ты застрял в цикле. Перестань повторять последнее действие и продолжай другим способом.)"
|
|
1150
1166
|
}
|
|
1151
1167
|
};
|
|
1152
1168
|
var DEFAULT_CONFIG = {
|
|
@@ -1154,6 +1170,7 @@ var DEFAULT_CONFIG = {
|
|
|
1154
1170
|
...LOCALIZED_TEXT_DEFAULTS.en,
|
|
1155
1171
|
usePluginSource: false,
|
|
1156
1172
|
resumeSilentTurns: true,
|
|
1173
|
+
resumeSubagentSessions: false,
|
|
1157
1174
|
resumeCompletedTurns: false,
|
|
1158
1175
|
continueTextLoop: "",
|
|
1159
1176
|
guardTools: true,
|
|
@@ -1208,6 +1225,7 @@ function resolveConfig(section) {
|
|
|
1208
1225
|
continueText: text,
|
|
1209
1226
|
continueTextMaxTokens: maxTokensText,
|
|
1210
1227
|
resumeSilentTurns: booleanOr(value.resumeSilentTurns, DEFAULT_CONFIG.resumeSilentTurns),
|
|
1228
|
+
resumeSubagentSessions: booleanOr(value.resumeSubagentSessions, DEFAULT_CONFIG.resumeSubagentSessions),
|
|
1211
1229
|
resumeCompletedTurns: booleanOr(value.resumeCompletedTurns, DEFAULT_CONFIG.resumeCompletedTurns),
|
|
1212
1230
|
continueTextSilent: silentText,
|
|
1213
1231
|
continueTextLoop: loopText,
|
|
@@ -1720,28 +1738,40 @@ var probeConnectivity = async () => {
|
|
|
1720
1738
|
// src/host/engine.ts
|
|
1721
1739
|
var NOTICE_COPY = {
|
|
1722
1740
|
zh: {
|
|
1723
|
-
notContinuedTitle: "dsh-auto-continue:
|
|
1724
|
-
permanentErrorBody: (sessionId, summary) => `${sessionId}:
|
|
1741
|
+
notContinuedTitle: "dsh-auto-continue: 请处理会话错误",
|
|
1742
|
+
permanentErrorBody: (sessionId, summary) => `${sessionId}: ${summary}。请处理此错误后再继续。`,
|
|
1725
1743
|
resumeAction: "立即续跑",
|
|
1726
1744
|
pauseAction: "暂停该会话 1 小时",
|
|
1727
|
-
continuedTitle: "dsh-auto-continue:
|
|
1728
|
-
continuedBody: (sessionId, text, count) => `${sessionId}: 已发送「${text}
|
|
1729
|
-
stoppedTitle: "dsh-auto-continue:
|
|
1730
|
-
stoppedBody: (sessionId, count) => `${sessionId}:
|
|
1745
|
+
continuedTitle: "dsh-auto-continue: 已发送继续消息",
|
|
1746
|
+
continuedBody: (sessionId, text, count) => `${sessionId}: 已发送「${text}」(连续尝试 ${count} 次)`,
|
|
1747
|
+
stoppedTitle: "dsh-auto-continue: 已达到重试上限",
|
|
1748
|
+
stoppedBody: (sessionId, count) => `${sessionId}: 已连续尝试恢复 ${count} 次。请检查会话后再继续。`,
|
|
1731
1749
|
loopCapTitle: "dsh-auto-continue: 自主循环已到上限",
|
|
1732
1750
|
loopCapBody: (sessionId, count) => `${sessionId}: 已自主续跑 ${count} 轮, 循环暂停; 发一条消息或重新开启循环即可继续`
|
|
1733
1751
|
},
|
|
1734
1752
|
en: {
|
|
1735
|
-
notContinuedTitle: "dsh-auto-continue:
|
|
1736
|
-
permanentErrorBody: (sessionId, summary) => `${sessionId}:
|
|
1753
|
+
notContinuedTitle: "dsh-auto-continue: Review session error",
|
|
1754
|
+
permanentErrorBody: (sessionId, summary) => `${sessionId}: ${summary}. Resolve this error before continuing.`,
|
|
1737
1755
|
resumeAction: "Resume now",
|
|
1738
1756
|
pauseAction: "Pause this session for 1 hour",
|
|
1739
|
-
continuedTitle: "dsh-auto-continue:
|
|
1740
|
-
continuedBody: (sessionId, text, count) => `${sessionId}: Sent "${text}" (consecutive
|
|
1741
|
-
stoppedTitle: "dsh-auto-continue:
|
|
1742
|
-
stoppedBody: (sessionId, count) => `${sessionId}: ${count}
|
|
1757
|
+
continuedTitle: "dsh-auto-continue: Continue message sent",
|
|
1758
|
+
continuedBody: (sessionId, text, count) => `${sessionId}: Sent "${text}" (consecutive attempts: ${count})`,
|
|
1759
|
+
stoppedTitle: "dsh-auto-continue: Retry limit reached",
|
|
1760
|
+
stoppedBody: (sessionId, count) => `${sessionId}: Consecutive recovery attempts: ${count}. Review the conversation before continuing.`,
|
|
1743
1761
|
loopCapTitle: "dsh-auto-continue: Autonomous loop limit reached",
|
|
1744
1762
|
loopCapBody: (sessionId, count) => `${sessionId}: Stopped after ${count} autonomous rounds; send a message or turn the loop back on to keep going`
|
|
1763
|
+
},
|
|
1764
|
+
ru: {
|
|
1765
|
+
notContinuedTitle: "dsh-auto-continue: продолжение не выполнено",
|
|
1766
|
+
permanentErrorBody: (sessionId, summary) => `${sessionId}: постоянная ошибка ${summary}; нужно вмешательство вручную`,
|
|
1767
|
+
resumeAction: "Продолжить сейчас",
|
|
1768
|
+
pauseAction: "Приостановить сессию на 1 час",
|
|
1769
|
+
continuedTitle: "dsh-auto-continue: продолжено автоматически",
|
|
1770
|
+
continuedBody: (sessionId, text, count) => `${sessionId}: отправлено «${text}» (попытка подряд: ${count})`,
|
|
1771
|
+
stoppedTitle: "dsh-auto-continue: авто-продолжение остановлено",
|
|
1772
|
+
stoppedBody: (sessionId, count) => `${sessionId}: сбоев подряд: ${count}; нужно вмешательство вручную`,
|
|
1773
|
+
loopCapTitle: "dsh-auto-continue: достигнут лимит автономного цикла",
|
|
1774
|
+
loopCapBody: (sessionId, count) => `${sessionId}: остановлено после ${count} автономных раундов; отправьте сообщение или включите цикл снова, чтобы продолжить`
|
|
1745
1775
|
}
|
|
1746
1776
|
};
|
|
1747
1777
|
var LOOP_GUARD_CANCEL_CAUSE = {
|
|
@@ -1758,6 +1788,13 @@ var RESTART_CANCEL_CAUSES = /* @__PURE__ */ new Set(["disposed", "legacy"]);
|
|
|
1758
1788
|
var DECISION_CANCEL_CAUSES = /* @__PURE__ */ new Set(["user", "parent", "hook"]);
|
|
1759
1789
|
var CHILD_SWEEP_LIMIT = 8;
|
|
1760
1790
|
var CHILD_ROOT_MAX_DEPTH = 8;
|
|
1791
|
+
var HANDOFF_COOLDOWN_MS = 5 * 60 * 1e3;
|
|
1792
|
+
var REVIVE_TIMEOUT_MS = 15e3;
|
|
1793
|
+
var HANDOFF_COPY = {
|
|
1794
|
+
zh: (child, code) => `子代理会话 ${child} 因 ${code} 中断, 已无法直接续跑。请检查它的状态, 然后继续或收尾。`,
|
|
1795
|
+
en: (child, code) => `Child session ${child} was interrupted by ${code} and can no longer be resumed directly. Check its state, then continue it or wrap it up.`,
|
|
1796
|
+
ru: (child, code) => `Дочерняя сессия ${child} прервалась из-за ${code} и больше не может быть продолжена напрямую. Проверь её состояние и продолжи или заверши.`
|
|
1797
|
+
};
|
|
1761
1798
|
var GOALS_SERVICE_KEY = "goals";
|
|
1762
1799
|
var CHILD_CAUSE_COPY = {
|
|
1763
1800
|
zh: {
|
|
@@ -1773,6 +1810,13 @@ var CHILD_CAUSE_COPY = {
|
|
|
1773
1810
|
interrupted: "closed by crash recovery",
|
|
1774
1811
|
"max-tokens": "output ceiling reached",
|
|
1775
1812
|
error: "retryable error"
|
|
1813
|
+
},
|
|
1814
|
+
ru: {
|
|
1815
|
+
"open-turn": "ход прерван после начала",
|
|
1816
|
+
disposed: "хост уничтожил агента",
|
|
1817
|
+
interrupted: "закрыт восстановлением после сбоя",
|
|
1818
|
+
"max-tokens": "достигнут лимит вывода",
|
|
1819
|
+
error: "повторяемая ошибка"
|
|
1776
1820
|
}
|
|
1777
1821
|
};
|
|
1778
1822
|
var isLoopReason = (reason) => reason === LOOP_COMPLETED_REASON || reason === LOOP_SILENT_REASON;
|
|
@@ -1829,6 +1873,10 @@ function readCancelCause(value) {
|
|
|
1829
1873
|
if (reason.kind !== "aborted") return void 0;
|
|
1830
1874
|
return readReasonKind(reason.reason);
|
|
1831
1875
|
}
|
|
1876
|
+
function isHostCancel(value) {
|
|
1877
|
+
const cause = readCancelCause(value);
|
|
1878
|
+
return cause !== void 0 && RESTART_CANCEL_CAUSES.has(cause);
|
|
1879
|
+
}
|
|
1832
1880
|
function classifyChildInterruption(events, config) {
|
|
1833
1881
|
let lastEnd;
|
|
1834
1882
|
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
@@ -1886,6 +1934,7 @@ function isLoopGuardCancelReason(value) {
|
|
|
1886
1934
|
const cause = value;
|
|
1887
1935
|
return cause.kind === LOOP_GUARD_CANCEL_CAUSE.kind && cause.reason === LOOP_GUARD_CANCEL_CAUSE.reason;
|
|
1888
1936
|
}
|
|
1937
|
+
var LINEAGE_CACHE_LIMIT = 2e3;
|
|
1889
1938
|
var AutoContinueRunner = class {
|
|
1890
1939
|
/**
|
|
1891
1940
|
* @param ctx - host plugin context (agents registry, session events).
|
|
@@ -1896,6 +1945,10 @@ var AutoContinueRunner = class {
|
|
|
1896
1945
|
this.getConfig = getConfig;
|
|
1897
1946
|
this.probe = probe;
|
|
1898
1947
|
this.states = /* @__PURE__ */ new Map();
|
|
1948
|
+
/** Cached subagent lineage: session id -> direct parent id (undefined when the header has none). */
|
|
1949
|
+
this.parents = /* @__PURE__ */ new Map();
|
|
1950
|
+
/** Sessions already identified as subagents, including event views without header metadata. */
|
|
1951
|
+
this.subagentSessions = /* @__PURE__ */ new Set();
|
|
1899
1952
|
this.pauseUntil = /* @__PURE__ */ new Map();
|
|
1900
1953
|
this.dayStats = emptyDayStats();
|
|
1901
1954
|
this.recoveryAttempts = [];
|
|
@@ -1903,6 +1956,10 @@ var AutoContinueRunner = class {
|
|
|
1903
1956
|
this.noticeListeners = /* @__PURE__ */ new Set();
|
|
1904
1957
|
this.stateListeners = /* @__PURE__ */ new Set();
|
|
1905
1958
|
this.prioritizedFollowups = /* @__PURE__ */ new Set();
|
|
1959
|
+
/** In-flight cold-resume calls, aborted when the plugin unloads. */
|
|
1960
|
+
this.reviveControllers = /* @__PURE__ */ new Set();
|
|
1961
|
+
/** Hand-offs waiting for a live main conversation: parent -> child -> text. */
|
|
1962
|
+
this.deferredHandoffs = /* @__PURE__ */ new Map();
|
|
1906
1963
|
this.disposed = false;
|
|
1907
1964
|
this.bootScannedSessions = /* @__PURE__ */ new WeakSet();
|
|
1908
1965
|
/** Also bound diagnostics when even an agent's session getter is unavailable. */
|
|
@@ -1961,7 +2018,7 @@ var AutoContinueRunner = class {
|
|
|
1961
2018
|
void this.bootScanLoop();
|
|
1962
2019
|
}
|
|
1963
2020
|
this.log(
|
|
1964
|
-
`已启动(
|
|
2021
|
+
`已启动(文本="${config.continueText}", 宽限 ${config.graceMs}ms, 冷却 ${config.cooldownMs}ms, 最多连续 ${config.maxConsecutive} 次)`
|
|
1965
2022
|
);
|
|
1966
2023
|
}
|
|
1967
2024
|
log(message) {
|
|
@@ -2003,6 +2060,24 @@ var AutoContinueRunner = class {
|
|
|
2003
2060
|
for (const listener of this.stateListeners) listener();
|
|
2004
2061
|
}
|
|
2005
2062
|
sessionConfig(sessionId) {
|
|
2063
|
+
const config = this.getConfig();
|
|
2064
|
+
if (this.isSubagentSession(sessionId)) {
|
|
2065
|
+
const enabled = this.subagentRecoveryEnabled(sessionId);
|
|
2066
|
+
return {
|
|
2067
|
+
...config,
|
|
2068
|
+
paused: config.paused || !enabled,
|
|
2069
|
+
resumeCompletedTurns: false,
|
|
2070
|
+
loopGuard: false
|
|
2071
|
+
};
|
|
2072
|
+
}
|
|
2073
|
+
return this.ownSessionConfig(sessionId);
|
|
2074
|
+
}
|
|
2075
|
+
/**
|
|
2076
|
+
* The session's own mode, ignoring subagent inheritance. The stored-session
|
|
2077
|
+
* sweep and the restart hand-off (`resumeInterruptedChildren`) use this, so
|
|
2078
|
+
* turning live subagent recovery off never silently disables them.
|
|
2079
|
+
*/
|
|
2080
|
+
ownSessionConfig(sessionId) {
|
|
2006
2081
|
const config = this.getConfig();
|
|
2007
2082
|
const mode = sessionMode(config.sessionModes, sessionId);
|
|
2008
2083
|
return {
|
|
@@ -2051,6 +2126,9 @@ var AutoContinueRunner = class {
|
|
|
2051
2126
|
this.wakeBootScan = void 0;
|
|
2052
2127
|
this.disposeSessionEvents();
|
|
2053
2128
|
this.disposeInboxEvents();
|
|
2129
|
+
for (const controller of this.reviveControllers) controller.abort();
|
|
2130
|
+
this.reviveControllers.clear();
|
|
2131
|
+
this.deferredHandoffs.clear();
|
|
2054
2132
|
this.prioritizedFollowups.clear();
|
|
2055
2133
|
for (const state of this.states.values()) {
|
|
2056
2134
|
if (state.pendingTimer !== void 0) clearTimeout(state.pendingTimer);
|
|
@@ -2060,6 +2138,8 @@ var AutoContinueRunner = class {
|
|
|
2060
2138
|
state.offlineWait = void 0;
|
|
2061
2139
|
}
|
|
2062
2140
|
this.states.clear();
|
|
2141
|
+
this.parents.clear();
|
|
2142
|
+
this.subagentSessions.clear();
|
|
2063
2143
|
}
|
|
2064
2144
|
state(sessionId) {
|
|
2065
2145
|
let state = this.states.get(sessionId);
|
|
@@ -2069,31 +2149,170 @@ var AutoContinueRunner = class {
|
|
|
2069
2149
|
}
|
|
2070
2150
|
return state;
|
|
2071
2151
|
}
|
|
2072
|
-
/**
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2152
|
+
/** Record a subagent session's lineage and its parent id when the header carries one. */
|
|
2153
|
+
noteSubagent(sessionId, parentSession) {
|
|
2154
|
+
this.subagentSessions.add(sessionId);
|
|
2155
|
+
if (parentSession !== void 0 && parentSession !== "") {
|
|
2156
|
+
this.parents.set(sessionId, parentSession);
|
|
2157
|
+
} else if (!this.parents.has(sessionId)) {
|
|
2158
|
+
this.parents.set(sessionId, void 0);
|
|
2159
|
+
}
|
|
2076
2160
|
}
|
|
2077
2161
|
/** Read durable origin from the live agent for direct action paths as well. */
|
|
2078
2162
|
isSubagent(sessionId, state) {
|
|
2079
2163
|
if (state.subagent) return true;
|
|
2080
|
-
const
|
|
2081
|
-
if (
|
|
2082
|
-
|
|
2164
|
+
const header = this.ctx.agents.get(sessionId)?.session?.header;
|
|
2165
|
+
if (header?.origin !== "subagent") return false;
|
|
2166
|
+
state.subagent = true;
|
|
2167
|
+
this.noteSubagent(sessionId, header.parentSession);
|
|
2168
|
+
return true;
|
|
2169
|
+
}
|
|
2170
|
+
/** Header origin, cached set or state flag; for paths that only have the session id. */
|
|
2171
|
+
isSubagentSession(sessionId) {
|
|
2172
|
+
if (this.subagentSessions.has(sessionId)) return true;
|
|
2173
|
+
const state = this.states.get(sessionId);
|
|
2174
|
+
if (state?.subagent === true) return true;
|
|
2175
|
+
const header = this.ctx.agents.get(sessionId)?.session?.header;
|
|
2176
|
+
if (header?.origin !== "subagent") return false;
|
|
2177
|
+
this.noteSubagent(sessionId, header.parentSession);
|
|
2083
2178
|
return true;
|
|
2084
2179
|
}
|
|
2180
|
+
/**
|
|
2181
|
+
* Direct subagent parent id. DSH stores fork lineage in the same
|
|
2182
|
+
* `header.parentSession` field, so only a session whose header origin is
|
|
2183
|
+
* `subagent` may be followed upward: an ordinary ancestor (the visible main
|
|
2184
|
+
* conversation, even a forked one) is the top of the recovery lineage.
|
|
2185
|
+
*/
|
|
2186
|
+
parentOf(sessionId) {
|
|
2187
|
+
if (this.parents.has(sessionId)) return this.parents.get(sessionId);
|
|
2188
|
+
const header = this.ctx.agents.get(sessionId)?.session?.header;
|
|
2189
|
+
if (header === void 0) return void 0;
|
|
2190
|
+
if (header.origin !== "subagent") {
|
|
2191
|
+
this.parents.set(sessionId, void 0);
|
|
2192
|
+
return void 0;
|
|
2193
|
+
}
|
|
2194
|
+
const parent = header.parentSession;
|
|
2195
|
+
this.noteSubagent(sessionId, parent);
|
|
2196
|
+
return parent;
|
|
2197
|
+
}
|
|
2198
|
+
/** Explicit session mode stored for this exact id, if the user gave one. */
|
|
2199
|
+
explicitMode(sessionId) {
|
|
2200
|
+
const modes = this.getConfig().sessionModes;
|
|
2201
|
+
const mode = modes[sessionId];
|
|
2202
|
+
return Object.prototype.hasOwnProperty.call(modes, sessionId) && isSessionMode(mode) ? mode : void 0;
|
|
2203
|
+
}
|
|
2204
|
+
/**
|
|
2205
|
+
* A subagent's effective mode, or `undefined` when the lineage cannot be
|
|
2206
|
+
* verified. An intermediate parent that is no longer live (and was never seen
|
|
2207
|
+
* here) used to stop the walk early, fall back to the profile default and
|
|
2208
|
+
* resume a child whose main conversation is Off; refusing the send is safe.
|
|
2209
|
+
*/
|
|
2210
|
+
resolveSubagentMode(sessionId) {
|
|
2211
|
+
const own = this.explicitMode(sessionId);
|
|
2212
|
+
if (own !== void 0) return own;
|
|
2213
|
+
const seen = /* @__PURE__ */ new Set([sessionId]);
|
|
2214
|
+
let current = sessionId;
|
|
2215
|
+
for (let depth = 0; depth < 32; depth += 1) {
|
|
2216
|
+
const known = this.parents.has(current);
|
|
2217
|
+
const header = this.ctx.agents.get(current)?.session?.header;
|
|
2218
|
+
if (!known && header === void 0) return void 0;
|
|
2219
|
+
const parent = known ? this.parents.get(current) : header?.origin === "subagent" ? header.parentSession : void 0;
|
|
2220
|
+
if (parent === void 0 || parent === "") {
|
|
2221
|
+
if (header?.origin === "subagent" || this.subagentSessions.has(current)) return void 0;
|
|
2222
|
+
return this.explicitMode(current) ?? "default";
|
|
2223
|
+
}
|
|
2224
|
+
if (seen.has(parent)) return void 0;
|
|
2225
|
+
seen.add(parent);
|
|
2226
|
+
current = parent;
|
|
2227
|
+
}
|
|
2228
|
+
return void 0;
|
|
2229
|
+
}
|
|
2230
|
+
/** Whether the setting and the inherited main-chat mode allow live recovery for this child. */
|
|
2231
|
+
subagentRecoveryEnabled(sessionId) {
|
|
2232
|
+
if (!this.getConfig().resumeSubagentSessions) return false;
|
|
2233
|
+
const mode = this.resolveSubagentMode(sessionId);
|
|
2234
|
+
return mode !== void 0 && mode !== "off";
|
|
2235
|
+
}
|
|
2236
|
+
/** Modes children inherit from their main conversation, for the composer's display. */
|
|
2237
|
+
inheritedSubagentModes() {
|
|
2238
|
+
this.pruneLineage();
|
|
2239
|
+
const inherited = {};
|
|
2240
|
+
for (const sessionId of this.parents.keys()) {
|
|
2241
|
+
if (this.ctx.agents.get(sessionId) === void 0) continue;
|
|
2242
|
+
if (!this.isSubagentSession(sessionId)) continue;
|
|
2243
|
+
if (this.explicitMode(sessionId) !== void 0) continue;
|
|
2244
|
+
const mode = this.resolveSubagentMode(sessionId);
|
|
2245
|
+
if (mode !== void 0) inherited[sessionId] = mode === "loop" ? "recover" : mode;
|
|
2246
|
+
}
|
|
2247
|
+
return inherited;
|
|
2248
|
+
}
|
|
2249
|
+
/**
|
|
2250
|
+
* Keep the lineage caches bounded on long-lived hosts. Once the cache grows,
|
|
2251
|
+
* entries for sessions that are no longer loaded are dropped; they are re-read
|
|
2252
|
+
* from the live header if the session comes back.
|
|
2253
|
+
*/
|
|
2254
|
+
pruneLineage() {
|
|
2255
|
+
if (this.parents.size + this.subagentSessions.size <= LINEAGE_CACHE_LIMIT) return;
|
|
2256
|
+
const keep = (sessionId) => this.ctx.agents.get(sessionId) !== void 0;
|
|
2257
|
+
const needed = /* @__PURE__ */ new Set();
|
|
2258
|
+
for (const sessionId of this.parents.keys()) {
|
|
2259
|
+
if (!keep(sessionId)) continue;
|
|
2260
|
+
let current = sessionId;
|
|
2261
|
+
for (let depth = 0; depth < 32 && current !== void 0 && !needed.has(current); depth += 1) {
|
|
2262
|
+
needed.add(current);
|
|
2263
|
+
current = this.parents.get(current);
|
|
2264
|
+
}
|
|
2265
|
+
}
|
|
2266
|
+
for (const sessionId of [...this.parents.keys()]) if (!needed.has(sessionId)) this.parents.delete(sessionId);
|
|
2267
|
+
for (const sessionId of [...this.subagentSessions]) if (!needed.has(sessionId) && !keep(sessionId)) this.subagentSessions.delete(sessionId);
|
|
2268
|
+
}
|
|
2269
|
+
/** Mark a child session; drop only queued sends that its effective policy no longer allows. */
|
|
2270
|
+
markSubagent(sessionId, state, parentSession) {
|
|
2271
|
+
const first = !state.subagent;
|
|
2272
|
+
state.subagent = true;
|
|
2273
|
+
this.noteSubagent(sessionId, parentSession);
|
|
2274
|
+
if (first && !this.subagentRecoveryEnabled(sessionId)) this.cancelPending(sessionId, "子代理会话");
|
|
2275
|
+
}
|
|
2276
|
+
/** Pause deadline, including the parents' "pause this session 1h" for subagents. */
|
|
2277
|
+
effectivePauseUntil(sessionId) {
|
|
2278
|
+
let until = this.pauseUntil.get(sessionId) ?? 0;
|
|
2279
|
+
if (!this.isSubagentSession(sessionId)) return until;
|
|
2280
|
+
const seen = /* @__PURE__ */ new Set([sessionId]);
|
|
2281
|
+
let current = sessionId;
|
|
2282
|
+
for (let depth = 0; depth < 32; depth += 1) {
|
|
2283
|
+
current = this.parentOf(current);
|
|
2284
|
+
if (current === void 0 || current === "" || seen.has(current)) break;
|
|
2285
|
+
seen.add(current);
|
|
2286
|
+
until = Math.max(until, this.pauseUntil.get(current) ?? 0);
|
|
2287
|
+
}
|
|
2288
|
+
return until;
|
|
2289
|
+
}
|
|
2290
|
+
/** Whether this session sits below `ancestorId` in the subagent lineage (never fork lineage). */
|
|
2291
|
+
isDescendantOf(sessionId, ancestorId) {
|
|
2292
|
+
const seen = /* @__PURE__ */ new Set([sessionId]);
|
|
2293
|
+
let current = sessionId;
|
|
2294
|
+
for (let depth = 0; depth < 32; depth += 1) {
|
|
2295
|
+
current = this.parentOf(current);
|
|
2296
|
+
if (current === void 0 || current === "") return false;
|
|
2297
|
+
if (current === ancestorId) return true;
|
|
2298
|
+
if (seen.has(current)) return false;
|
|
2299
|
+
seen.add(current);
|
|
2300
|
+
}
|
|
2301
|
+
return false;
|
|
2302
|
+
}
|
|
2085
2303
|
/**
|
|
2086
2304
|
* 事件入口(host 单实例): 预处理工具调用/结果/模型消息(护栏与循环信号),
|
|
2087
2305
|
* 然后交给回合状态机。
|
|
2088
2306
|
*/
|
|
2089
2307
|
onHostEvent(session, event) {
|
|
2090
2308
|
const sessionId = session.id;
|
|
2309
|
+
this.flushDeferredHandoffs(sessionId);
|
|
2091
2310
|
const sessionState = this.states.get(sessionId);
|
|
2092
2311
|
if (session.header?.origin === "subagent") {
|
|
2093
|
-
this.markSubagent(sessionId, sessionState ?? this.state(sessionId));
|
|
2094
|
-
|
|
2312
|
+
this.markSubagent(sessionId, sessionState ?? this.state(sessionId), session.header.parentSession);
|
|
2313
|
+
} else if (sessionState?.subagent) {
|
|
2314
|
+
this.noteSubagent(sessionId, session.header?.parentSession ?? this.parentOf(sessionId));
|
|
2095
2315
|
}
|
|
2096
|
-
if (sessionState?.subagent) return;
|
|
2097
2316
|
if (sessionState?.maintenanceTurn !== void 0 && sessionState.maintenanceTurn === event.data.turn && event.type !== "turn/start" && event.type !== "turn/end") return;
|
|
2098
2317
|
if ((event.type === "user/message" || event.type === "assistant/message") && typeof event.surfaceOp === "object" && event.surfaceOp !== null) {
|
|
2099
2318
|
this.state(sessionId).tools.recordSurfaceReplacement(event.seq);
|
|
@@ -2380,12 +2599,14 @@ var AutoContinueRunner = class {
|
|
|
2380
2599
|
if (this.sessionConfig(sessionId).resumeCompletedTurns) {
|
|
2381
2600
|
if (turnOutput === "visible") {
|
|
2382
2601
|
state.consecutive = 0;
|
|
2602
|
+
state.recovering = false;
|
|
2383
2603
|
state.lastFailure = void 0;
|
|
2384
2604
|
this.noteRecovery(sessionId, "completed");
|
|
2385
2605
|
}
|
|
2386
2606
|
this.schedule(sessionId, LOOP_COMPLETED_REASON, true);
|
|
2387
2607
|
} else if (turnOutput === "visible") {
|
|
2388
2608
|
state.consecutive = 0;
|
|
2609
|
+
state.recovering = false;
|
|
2389
2610
|
state.lastFailure = void 0;
|
|
2390
2611
|
this.noteRecovery(sessionId, "completed");
|
|
2391
2612
|
}
|
|
@@ -2420,6 +2641,7 @@ var AutoContinueRunner = class {
|
|
|
2420
2641
|
}
|
|
2421
2642
|
} else {
|
|
2422
2643
|
state.consecutive = 0;
|
|
2644
|
+
state.recovering = false;
|
|
2423
2645
|
state.pendingRecoveryAt = 0;
|
|
2424
2646
|
}
|
|
2425
2647
|
} else if (reasonKind === "blocked") {
|
|
@@ -2448,6 +2670,7 @@ var AutoContinueRunner = class {
|
|
|
2448
2670
|
if (isOurEcho(state, event)) break;
|
|
2449
2671
|
if (event.data.source.kind === "user") {
|
|
2450
2672
|
state.consecutive = 0;
|
|
2673
|
+
state.recovering = false;
|
|
2451
2674
|
this.resetLoopIterations(state);
|
|
2452
2675
|
this.cancelPending(sessionId, "用户手动发送消息");
|
|
2453
2676
|
}
|
|
@@ -2459,7 +2682,15 @@ var AutoContinueRunner = class {
|
|
|
2459
2682
|
// ---------- host 帧 ----------
|
|
2460
2683
|
onTurnFailure(sessionId, reason, failure) {
|
|
2461
2684
|
const config = this.getConfig();
|
|
2462
|
-
if (
|
|
2685
|
+
if (this.isSubagentSession(sessionId)) {
|
|
2686
|
+
if (!this.subagentRecoveryEnabled(sessionId)) {
|
|
2687
|
+
const parent = this.parentOf(sessionId);
|
|
2688
|
+
if (parent !== void 0 && parent !== "" && this.ctx.agents.get(parent) === void 0) {
|
|
2689
|
+
this.deferHandoff(parent, sessionId, this.handoffText(sessionId, reason));
|
|
2690
|
+
}
|
|
2691
|
+
return;
|
|
2692
|
+
}
|
|
2693
|
+
} else if (sessionMode(config.sessionModes, sessionId) === "off") return;
|
|
2463
2694
|
if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
|
|
2464
2695
|
const copy = NOTICE_COPY[config.locale];
|
|
2465
2696
|
const summary = `${failure.code}${failure.status !== void 0 ? ` (HTTP ${failure.status})` : ""}`;
|
|
@@ -2494,6 +2725,11 @@ var AutoContinueRunner = class {
|
|
|
2494
2725
|
this.log(`通知按钮: 暂停 ${sessionId} 1 小时`);
|
|
2495
2726
|
this.pauseUntil.set(sessionId, Date.now() + 60 * 60 * 1e3);
|
|
2496
2727
|
this.cancelPending(sessionId, "通知按钮暂停该会话");
|
|
2728
|
+
for (const candidate of this.states.keys()) {
|
|
2729
|
+
if (candidate !== sessionId && this.isDescendantOf(candidate, sessionId)) {
|
|
2730
|
+
this.cancelPending(candidate, "父会话已暂停");
|
|
2731
|
+
}
|
|
2732
|
+
}
|
|
2497
2733
|
}
|
|
2498
2734
|
}
|
|
2499
2735
|
/** 内存统计(host 单实例): 按今日桶累计。 */
|
|
@@ -2540,12 +2776,8 @@ var AutoContinueRunner = class {
|
|
|
2540
2776
|
/** 立即为该会话发送一次自动继续(无视冷却与连续上限; 由通知按钮触发)。 */
|
|
2541
2777
|
async resumeNow(sessionId) {
|
|
2542
2778
|
if (this.disposed) return;
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
if (state.pendingTimer !== void 0) {
|
|
2546
|
-
clearTimeout(state.pendingTimer);
|
|
2547
|
-
state.pendingTimer = void 0;
|
|
2548
|
-
}
|
|
2779
|
+
if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) return;
|
|
2780
|
+
this.cancelPending(sessionId, "手动续跑");
|
|
2549
2781
|
try {
|
|
2550
2782
|
await this.fire(sessionId, MANUAL_NOTIFICATION_REASON, true);
|
|
2551
2783
|
} catch (error) {
|
|
@@ -2566,12 +2798,11 @@ var AutoContinueRunner = class {
|
|
|
2566
2798
|
const state = this.state(sessionId);
|
|
2567
2799
|
const config = this.sessionConfig(sessionId);
|
|
2568
2800
|
if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
|
|
2569
|
-
if (this.isSubagent(sessionId, state)) return;
|
|
2570
2801
|
if (config.paused) {
|
|
2571
2802
|
this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
|
|
2572
2803
|
return;
|
|
2573
2804
|
}
|
|
2574
|
-
if (Date.now() <
|
|
2805
|
+
if (Date.now() < this.effectivePauseUntil(sessionId)) {
|
|
2575
2806
|
this.log(`跳过 ${sessionId}(${reason}): 会话暂停中`);
|
|
2576
2807
|
return;
|
|
2577
2808
|
}
|
|
@@ -2603,6 +2834,7 @@ var AutoContinueRunner = class {
|
|
|
2603
2834
|
}, config.graceMs);
|
|
2604
2835
|
state.pendingTimer = timer;
|
|
2605
2836
|
state.pendingReason = reason;
|
|
2837
|
+
state.recovering = true;
|
|
2606
2838
|
const template = this.templateFor(config, reason);
|
|
2607
2839
|
this.log(
|
|
2608
2840
|
`检测到非人为中断 ${sessionId}(${reason}), ${config.graceMs}ms 后自动发送「${template}」`
|
|
@@ -2616,6 +2848,7 @@ var AutoContinueRunner = class {
|
|
|
2616
2848
|
const state = this.state(sessionId);
|
|
2617
2849
|
if (state.cooldownRetryTimer !== void 0) clearTimeout(state.cooldownRetryTimer);
|
|
2618
2850
|
state.pendingReason = reason;
|
|
2851
|
+
state.recovering = true;
|
|
2619
2852
|
state.cooldownRetryTimer = setTimeout(() => {
|
|
2620
2853
|
state.cooldownRetryTimer = void 0;
|
|
2621
2854
|
state.pendingReason = void 0;
|
|
@@ -2664,6 +2897,197 @@ var AutoContinueRunner = class {
|
|
|
2664
2897
|
}
|
|
2665
2898
|
if (cancelled) this.log(`取消 ${sessionId} 的自动继续(${why})`);
|
|
2666
2899
|
}
|
|
2900
|
+
/** Attach the loader-provided subagent service; it may load after this plugin. */
|
|
2901
|
+
setSubagentPromptProvider(provider) {
|
|
2902
|
+
this.subagentPromptProvider = provider;
|
|
2903
|
+
}
|
|
2904
|
+
subagentPrompts() {
|
|
2905
|
+
const provided = this.subagentPromptProvider?.();
|
|
2906
|
+
if (provided !== void 0 && provided !== null) return provided;
|
|
2907
|
+
try {
|
|
2908
|
+
return this.ctx.get("subagents");
|
|
2909
|
+
} catch {
|
|
2910
|
+
return void 0;
|
|
2911
|
+
}
|
|
2912
|
+
}
|
|
2913
|
+
/** Copy for one child hand-off, built once so a deferred delivery matches. */
|
|
2914
|
+
handoffText(sessionId, reason) {
|
|
2915
|
+
const code = this.state(sessionId).lastFailure?.code ?? reason;
|
|
2916
|
+
return HANDOFF_COPY[this.sessionConfig(sessionId).locale](sessionId, code);
|
|
2917
|
+
}
|
|
2918
|
+
/**
|
|
2919
|
+
* Revive a disposed child through the host's cold resume and deliver the
|
|
2920
|
+
* continuation to it. Falls back to the main-conversation hand-off when the
|
|
2921
|
+
* host cannot resume (no persistence, no live parent, not a direct child).
|
|
2922
|
+
* The child's own recovery mode decides; the parent only has to be alive to
|
|
2923
|
+
* authorize the call.
|
|
2924
|
+
*/
|
|
2925
|
+
async reviveChild(sessionId, reason, text, force) {
|
|
2926
|
+
if (this.disposed || this.getConfig().paused) return;
|
|
2927
|
+
if (!this.subagentRecoveryEnabled(sessionId)) return;
|
|
2928
|
+
const state = this.state(sessionId);
|
|
2929
|
+
if (state.reviveInFlight === true) {
|
|
2930
|
+
this.log(`冷恢复跳过 ${sessionId}: 已有请求在途中`);
|
|
2931
|
+
return;
|
|
2932
|
+
}
|
|
2933
|
+
const config = this.sessionConfig(sessionId);
|
|
2934
|
+
if (!force) {
|
|
2935
|
+
if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) {
|
|
2936
|
+
this.log(`冷恢复跳过 ${sessionId}: 处于冷却期`);
|
|
2937
|
+
return;
|
|
2938
|
+
}
|
|
2939
|
+
if (state.consecutive >= config.maxConsecutive) {
|
|
2940
|
+
this.log(`冷恢复跳过 ${sessionId}: 已连续自动继续 ${state.consecutive} 次`);
|
|
2941
|
+
return;
|
|
2942
|
+
}
|
|
2943
|
+
}
|
|
2944
|
+
const parent = this.parentOf(sessionId);
|
|
2945
|
+
if (parent === void 0 || parent === "") return;
|
|
2946
|
+
const handoff = this.handoffText(sessionId, reason);
|
|
2947
|
+
const parentAgent = this.ctx.agents.get(parent);
|
|
2948
|
+
if (parentAgent === void 0) {
|
|
2949
|
+
this.deferHandoff(parent, sessionId, handoff);
|
|
2950
|
+
return;
|
|
2951
|
+
}
|
|
2952
|
+
const prompts = this.subagentPrompts();
|
|
2953
|
+
if (typeof prompts?.prompt !== "function") {
|
|
2954
|
+
this.handOffToParent(sessionId, reason, handoff);
|
|
2955
|
+
return;
|
|
2956
|
+
}
|
|
2957
|
+
state.lastAttemptAt = Date.now();
|
|
2958
|
+
state.consecutive += 1;
|
|
2959
|
+
state.reviveInFlight = true;
|
|
2960
|
+
const controller = new AbortController();
|
|
2961
|
+
this.reviveControllers.add(controller);
|
|
2962
|
+
let timedOut = false;
|
|
2963
|
+
const timeout = setTimeout(() => {
|
|
2964
|
+
timedOut = true;
|
|
2965
|
+
controller.abort();
|
|
2966
|
+
}, REVIVE_TIMEOUT_MS);
|
|
2967
|
+
try {
|
|
2968
|
+
await prompts.prompt(
|
|
2969
|
+
{
|
|
2970
|
+
parentSessionId: parent,
|
|
2971
|
+
childSessionId: sessionId,
|
|
2972
|
+
mode: "continuable",
|
|
2973
|
+
requestId: randomUUID2(),
|
|
2974
|
+
content: [{ type: "text", text }],
|
|
2975
|
+
delivery: "queue"
|
|
2976
|
+
},
|
|
2977
|
+
controller.signal
|
|
2978
|
+
);
|
|
2979
|
+
this.log(`已冷恢复子代理 ${sessionId}`);
|
|
2980
|
+
} catch (error) {
|
|
2981
|
+
if (this.disposed) return;
|
|
2982
|
+
this.log(`冷恢复 ${sessionId} 失败${timedOut ? "(超时)" : ""}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2983
|
+
this.handOffToParent(sessionId, reason, handoff);
|
|
2984
|
+
} finally {
|
|
2985
|
+
clearTimeout(timeout);
|
|
2986
|
+
this.reviveControllers.delete(controller);
|
|
2987
|
+
state.reviveInFlight = false;
|
|
2988
|
+
}
|
|
2989
|
+
}
|
|
2990
|
+
/** Existing state of a session, without materializing one just to read it. */
|
|
2991
|
+
parentState(sessionId) {
|
|
2992
|
+
return this.states.get(sessionId);
|
|
2993
|
+
}
|
|
2994
|
+
/** Whether this session already has a continuation on the way. */
|
|
2995
|
+
hasPendingSend(state) {
|
|
2996
|
+
return state.pendingTimer !== void 0 || state.cooldownRetryTimer !== void 0 || state.loopRetryTimer !== void 0 || state.offlineWait !== void 0 || state.offlineTimer !== void 0;
|
|
2997
|
+
}
|
|
2998
|
+
/**
|
|
2999
|
+
* Ask the child's main conversation to take over a failure the plugin cannot
|
|
3000
|
+
* repair itself: the child handle is gone, so only the root can continue it.
|
|
3001
|
+
* The main conversation's Off is respected because this writes a user message
|
|
3002
|
+
* into it; a child's own mode is never overridden by that Off for cold resume.
|
|
3003
|
+
*/
|
|
3004
|
+
handOffToParent(sessionId, reason, text) {
|
|
3005
|
+
if (this.disposed || this.getConfig().paused) return;
|
|
3006
|
+
if (!this.subagentRecoveryEnabled(sessionId)) return;
|
|
3007
|
+
const parent = this.parentOf(sessionId);
|
|
3008
|
+
if (parent === void 0 || parent === "") return;
|
|
3009
|
+
if (this.explicitMode(parent) === "off") return;
|
|
3010
|
+
const state = this.state(sessionId);
|
|
3011
|
+
const now = Date.now();
|
|
3012
|
+
if (state.handedOffAt !== void 0 && now - state.handedOffAt < HANDOFF_COOLDOWN_MS) return;
|
|
3013
|
+
const handoff = text ?? this.handoffText(sessionId, reason);
|
|
3014
|
+
const parentAgent = this.ctx.agents.get(parent);
|
|
3015
|
+
if (parentAgent === void 0) {
|
|
3016
|
+
this.deferHandoff(parent, sessionId, handoff);
|
|
3017
|
+
return;
|
|
3018
|
+
}
|
|
3019
|
+
const parentState = this.parentState(parent);
|
|
3020
|
+
if (parentState !== void 0 && (parentState.recovering === true || this.hasPendingSend(parentState))) {
|
|
3021
|
+
this.log(`移交跳过 ${sessionId}: 主会话 ${parent} 正在自行恢复`);
|
|
3022
|
+
return;
|
|
3023
|
+
}
|
|
3024
|
+
try {
|
|
3025
|
+
this.sendHandoff(parent, parentAgent, handoff);
|
|
3026
|
+
state.handedOffAt = now;
|
|
3027
|
+
this.log(`已将子代理 ${sessionId} 的失败移交主会话 ${parent}`);
|
|
3028
|
+
} catch (error) {
|
|
3029
|
+
this.log(`移交 ${sessionId} 失败: ${error instanceof Error ? error.message : String(error)}`);
|
|
3030
|
+
}
|
|
3031
|
+
}
|
|
3032
|
+
/**
|
|
3033
|
+
* Post a hand-off into the main conversation the same way a continuation is
|
|
3034
|
+
* sent: with the configured message source, and registered as our own echo so
|
|
3035
|
+
* the parent does not read it as the user stepping in (which would reset its
|
|
3036
|
+
* retry and loop counters and cancel whatever it had queued).
|
|
3037
|
+
*/
|
|
3038
|
+
sendHandoff(parent, parentAgent, text) {
|
|
3039
|
+
const parentState = this.state(parent);
|
|
3040
|
+
const message = createUserMessage({
|
|
3041
|
+
content: [{ type: "text", text }],
|
|
3042
|
+
source: { kind: this.getConfig().usePluginSource ? AUTO_CONTINUE_SOURCE_KIND : "user" }
|
|
3043
|
+
});
|
|
3044
|
+
trackPendingEcho(parentState, message.id);
|
|
3045
|
+
try {
|
|
3046
|
+
parentAgent.followup(message);
|
|
3047
|
+
} catch (error) {
|
|
3048
|
+
forgetPendingEcho(parentState, message.id);
|
|
3049
|
+
throw error;
|
|
3050
|
+
}
|
|
3051
|
+
}
|
|
3052
|
+
/** Keep one hand-off until its main conversation has a live agent again. */
|
|
3053
|
+
deferHandoff(parent, sessionId, text) {
|
|
3054
|
+
if (!this.getConfig().resumeSubagentSessions) return;
|
|
3055
|
+
const state = this.state(sessionId);
|
|
3056
|
+
const now = Date.now();
|
|
3057
|
+
if (state.handedOffAt !== void 0 && now - state.handedOffAt < HANDOFF_COOLDOWN_MS) return;
|
|
3058
|
+
let pending = this.deferredHandoffs.get(parent);
|
|
3059
|
+
if (pending === void 0) {
|
|
3060
|
+
pending = /* @__PURE__ */ new Map();
|
|
3061
|
+
this.deferredHandoffs.set(parent, pending);
|
|
3062
|
+
}
|
|
3063
|
+
pending.set(sessionId, text);
|
|
3064
|
+
this.log(`移交暂存 ${sessionId}: 主会话 ${parent} 无 live agent`);
|
|
3065
|
+
}
|
|
3066
|
+
/** Deliver queued hand-offs once their main conversation is live again. */
|
|
3067
|
+
flushDeferredHandoffs(parent) {
|
|
3068
|
+
const pending = this.deferredHandoffs.get(parent);
|
|
3069
|
+
if (pending === void 0 || pending.size === 0) return;
|
|
3070
|
+
if (this.explicitMode(parent) === "off") {
|
|
3071
|
+
this.deferredHandoffs.delete(parent);
|
|
3072
|
+
return;
|
|
3073
|
+
}
|
|
3074
|
+
const parentAgent = this.ctx.agents.get(parent);
|
|
3075
|
+
if (parentAgent === void 0) return;
|
|
3076
|
+
this.deferredHandoffs.delete(parent);
|
|
3077
|
+
const now = Date.now();
|
|
3078
|
+
for (const [child, text] of pending) {
|
|
3079
|
+
if (!this.subagentRecoveryEnabled(child)) continue;
|
|
3080
|
+
const state = this.state(child);
|
|
3081
|
+
if (state.handedOffAt !== void 0 && now - state.handedOffAt < HANDOFF_COOLDOWN_MS) continue;
|
|
3082
|
+
try {
|
|
3083
|
+
this.sendHandoff(parent, parentAgent, text);
|
|
3084
|
+
state.handedOffAt = now;
|
|
3085
|
+
this.log(`已移交暂存子代理 ${child} 给主会话 ${parent}`);
|
|
3086
|
+
} catch (error) {
|
|
3087
|
+
this.log(`暂存移交 ${child} 失败: ${error instanceof Error ? error.message : String(error)}`);
|
|
3088
|
+
}
|
|
3089
|
+
}
|
|
3090
|
+
}
|
|
2667
3091
|
fire(sessionId, reason, force = false) {
|
|
2668
3092
|
if (this.disposed) return;
|
|
2669
3093
|
const state = this.state(sessionId);
|
|
@@ -2671,12 +3095,18 @@ var AutoContinueRunner = class {
|
|
|
2671
3095
|
const manualResume = force && reason === MANUAL_NOTIFICATION_REASON;
|
|
2672
3096
|
if (reason.endsWith(":silent") && !config.resumeSilentTurns) return;
|
|
2673
3097
|
if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
|
|
2674
|
-
if (this.
|
|
3098
|
+
if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) {
|
|
3099
|
+
const parent = this.parentOf(sessionId);
|
|
3100
|
+
if (parent !== void 0 && parent !== "" && this.ctx.agents.get(parent) === void 0) {
|
|
3101
|
+
this.deferHandoff(parent, sessionId, this.handoffText(sessionId, reason));
|
|
3102
|
+
}
|
|
3103
|
+
return;
|
|
3104
|
+
}
|
|
2675
3105
|
if (config.paused && !manualResume) {
|
|
2676
3106
|
this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
|
|
2677
3107
|
return;
|
|
2678
3108
|
}
|
|
2679
|
-
if (!manualResume && Date.now() <
|
|
3109
|
+
if (!manualResume && Date.now() < this.effectivePauseUntil(sessionId)) {
|
|
2680
3110
|
this.log(`跳过 ${sessionId}(${reason}): 会话暂停中`);
|
|
2681
3111
|
return;
|
|
2682
3112
|
}
|
|
@@ -2692,6 +3122,9 @@ var AutoContinueRunner = class {
|
|
|
2692
3122
|
const text = this.buildContinueText(config, state, template);
|
|
2693
3123
|
const agent = this.ctx.agents.get(sessionId);
|
|
2694
3124
|
if (agent === void 0) {
|
|
3125
|
+
if (this.isSubagentSession(sessionId) && this.subagentRecoveryEnabled(sessionId)) {
|
|
3126
|
+
void this.reviveChild(sessionId, reason, text, manualResume);
|
|
3127
|
+
}
|
|
2695
3128
|
this.log(`跳过 ${sessionId}(${reason}): 无 live agent`);
|
|
2696
3129
|
return;
|
|
2697
3130
|
}
|
|
@@ -2712,6 +3145,7 @@ var AutoContinueRunner = class {
|
|
|
2712
3145
|
this.prioritizedFollowups.delete(message.id);
|
|
2713
3146
|
}
|
|
2714
3147
|
const now = Date.now();
|
|
3148
|
+
state.recovering = true;
|
|
2715
3149
|
this.rearmGoal(sessionId, config);
|
|
2716
3150
|
if (reason !== LOOP_COMPLETED_REASON) state.consecutive += 1;
|
|
2717
3151
|
if (isLoopReason(reason)) state.loopIterations += 1;
|
|
@@ -2801,6 +3235,7 @@ var AutoContinueRunner = class {
|
|
|
2801
3235
|
const token = {};
|
|
2802
3236
|
state.offlineWait = token;
|
|
2803
3237
|
state.pendingReason = reason;
|
|
3238
|
+
state.recovering = true;
|
|
2804
3239
|
void this.checkConnectivity().then((online) => {
|
|
2805
3240
|
if (this.disposed || state.offlineWait !== token) return;
|
|
2806
3241
|
if (online) {
|
|
@@ -2923,7 +3358,8 @@ var AutoContinueRunner = class {
|
|
|
2923
3358
|
break;
|
|
2924
3359
|
}
|
|
2925
3360
|
}
|
|
2926
|
-
|
|
3361
|
+
let reasonKind = readReasonKind(lastEnd?.data.reason);
|
|
3362
|
+
if (reasonKind === "aborted" && isHostCancel(lastEnd?.data.reason)) reasonKind = "interrupted";
|
|
2927
3363
|
const lastStart = latestTurnStart(events);
|
|
2928
3364
|
const maintenance = lastStart?.data.turn === lastEnd?.data.turn && isMaintenanceTurnStart(lastStart);
|
|
2929
3365
|
const silent = reasonKind === "no-visible-output" && config.resumeSilentTurns;
|
|
@@ -3066,7 +3502,7 @@ var AutoContinueRunner = class {
|
|
|
3066
3502
|
continue;
|
|
3067
3503
|
}
|
|
3068
3504
|
const sessionId = record2.header.id;
|
|
3069
|
-
if (this.
|
|
3505
|
+
if (this.ownSessionConfig(sessionId).paused || Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) continue;
|
|
3070
3506
|
if (record2.header.origin === "subagent") {
|
|
3071
3507
|
if (config.resumeInterruptedChildren) {
|
|
3072
3508
|
await this.sweepChild(record2, headersById, config, deadline);
|
|
@@ -3106,6 +3542,7 @@ var AutoContinueRunner = class {
|
|
|
3106
3542
|
freshAt = events[events.length - 1]?.time ?? 0;
|
|
3107
3543
|
} else {
|
|
3108
3544
|
reasonKind = readReasonKind(lastEnd?.data.reason);
|
|
3545
|
+
if (reasonKind === "aborted" && isHostCancel(lastEnd?.data.reason)) reasonKind = "interrupted";
|
|
3109
3546
|
freshAt = lastEnd?.time ?? 0;
|
|
3110
3547
|
}
|
|
3111
3548
|
if (reasonKind === void 0 || freshAt < Date.now() - config.freshMs) continue;
|
|
@@ -3173,7 +3610,7 @@ var AutoContinueRunner = class {
|
|
|
3173
3610
|
if (this.childSwept.has(sessionId)) return;
|
|
3174
3611
|
if (this.ctx.agents.get(sessionId) !== void 0) return;
|
|
3175
3612
|
if (this.childScanned >= CHILD_SWEEP_LIMIT) return;
|
|
3176
|
-
if (this.
|
|
3613
|
+
if (this.ownSessionConfig(sessionId).paused) return;
|
|
3177
3614
|
const rootId = resolveRootHeader(header, headersById);
|
|
3178
3615
|
if (rootId === void 0 || rootId === sessionId) {
|
|
3179
3616
|
if (!this.childDirtyLogged.has(sessionId)) {
|
|
@@ -3303,10 +3740,7 @@ var AutoContinueRunner = class {
|
|
|
3303
3740
|
if (end === void 0) return false;
|
|
3304
3741
|
const kind = readReasonKind(end.data.reason);
|
|
3305
3742
|
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
|
-
}
|
|
3743
|
+
if (kind === "aborted") return isHostCancel(end.data.reason);
|
|
3310
3744
|
return false;
|
|
3311
3745
|
}
|
|
3312
3746
|
/** 发送需要 live agent; 存储会话沿既有物化路径拉起, 复用 preset 与模型回装。 */
|
|
@@ -9714,7 +10148,7 @@ function migrateLegacySettings(ctx, config, fields, validate) {
|
|
|
9714
10148
|
});
|
|
9715
10149
|
const failed = () => {
|
|
9716
10150
|
if (disposed) return;
|
|
9717
|
-
migration.logger.error("[auto-continue] Could not import settings-legacy.yaml
|
|
10151
|
+
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
10152
|
};
|
|
9719
10153
|
void (async () => {
|
|
9720
10154
|
try {
|
|
@@ -9781,6 +10215,7 @@ function migrateLegacySettings(ctx, config, fields, validate) {
|
|
|
9781
10215
|
|
|
9782
10216
|
// src/index.ts
|
|
9783
10217
|
var AUTO_CONTINUE_NS = "auto-continue";
|
|
10218
|
+
var BRIDGE_HEARTBEAT_MS = 2e4;
|
|
9784
10219
|
var settingsFields = {
|
|
9785
10220
|
/** Active browser/UI locale mirrored by the client. */
|
|
9786
10221
|
locale: z2.string().default("en"),
|
|
@@ -9792,6 +10227,8 @@ var settingsFields = {
|
|
|
9792
10227
|
continueTextMaxTokens: z2.string().default(""),
|
|
9793
10228
|
/** Resume observed model activity that completes without visible output. */
|
|
9794
10229
|
resumeSilentTurns: z2.boolean().default(true),
|
|
10230
|
+
/** Resume interrupted subagent sessions when their main conversation has auto-continue enabled. Subagents never enter the autonomous loop. */
|
|
10231
|
+
resumeSubagentSessions: z2.boolean().default(false),
|
|
9795
10232
|
/** 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
10233
|
resumeCompletedTurns: z2.boolean().default(false),
|
|
9797
10234
|
/** Text sent to resume a silent turn (same placeholders as `continueText`). */
|
|
@@ -9891,6 +10328,12 @@ function apply(ctx, config) {
|
|
|
9891
10328
|
disposeEngine?.();
|
|
9892
10329
|
const readConfig = () => resolveConfig(legacyConfig?.() ?? readEntry());
|
|
9893
10330
|
const runner = new AutoContinueRunner(engineCtx, readConfig);
|
|
10331
|
+
engineCtx.inject(["subagents"], (subagentCtx) => {
|
|
10332
|
+
runner.setSubagentPromptProvider(
|
|
10333
|
+
() => subagentCtx.subagents
|
|
10334
|
+
);
|
|
10335
|
+
subagentCtx.effect(() => () => runner.setSubagentPromptProvider(void 0));
|
|
10336
|
+
});
|
|
9894
10337
|
const writableSettings = () => {
|
|
9895
10338
|
const settings = engineCtx.get("settings");
|
|
9896
10339
|
return settings?.writable && typeof settings.mutate === "function" ? settings : void 0;
|
|
@@ -9915,6 +10358,7 @@ function apply(ctx, config) {
|
|
|
9915
10358
|
recoveryAttempts: runner.recentRecoveryAttempts(),
|
|
9916
10359
|
sessionPolicy: {
|
|
9917
10360
|
modes: config2.sessionModes,
|
|
10361
|
+
inheritedModes: runner.inheritedSubagentModes(),
|
|
9918
10362
|
defaultMode: config2.resumeCompletedTurns ? "loop" : "recover",
|
|
9919
10363
|
paused: config2.paused,
|
|
9920
10364
|
writable: writableSettings() !== void 0
|
|
@@ -9952,11 +10396,20 @@ function apply(ctx, config) {
|
|
|
9952
10396
|
res.write(data);
|
|
9953
10397
|
};
|
|
9954
10398
|
sseClients.add(send);
|
|
10399
|
+
const heartbeat = setInterval(() => {
|
|
10400
|
+
try {
|
|
10401
|
+
res.write(": ping\n\n");
|
|
10402
|
+
} catch {
|
|
10403
|
+
}
|
|
10404
|
+
}, BRIDGE_HEARTBEAT_MS);
|
|
10405
|
+
heartbeat.unref?.();
|
|
9955
10406
|
const close = () => {
|
|
10407
|
+
clearInterval(heartbeat);
|
|
9956
10408
|
res.end();
|
|
9957
10409
|
};
|
|
9958
10410
|
closeClients.add(close);
|
|
9959
10411
|
req.on("close", () => {
|
|
10412
|
+
clearInterval(heartbeat);
|
|
9960
10413
|
sseClients.delete(send);
|
|
9961
10414
|
closeClients.delete(close);
|
|
9962
10415
|
});
|