dsh-client-auto-continue 0.17.4 → 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.
- package/CHANGELOG.md +47 -0
- package/README.md +230 -281
- package/README.ru.md +382 -0
- package/README.zh.md +229 -279
- 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.18.0.md +58 -0
- package/docs/releases/v0.19.0.md +62 -0
- package/docs/social-preview.png +0 -0
- package/docs/social-preview.svg +30 -1
- package/lib/client.js +347 -100
- package/lib/client.js.map +3 -3
- package/lib/index.js +790 -49
- 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 +19 -0
- package/lib/types/client/settings-card.d.ts +8 -0
- package/lib/types/host/connectivity.d.ts +4 -0
- package/lib/types/host/engine.d.ts +97 -5
- package/lib/types/index.d.ts +64 -0
- package/lib/types/shared/core.d.ts +54 -1
- package/locale/ru.json +6 -0
- package/package.json +6 -4
- 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 +241 -38
- package/src/client/settings-card.tsx +31 -4
- package/src/client/settings-notifications.ts +3 -2
- package/src/client/styles.ts +17 -19
- package/src/host/connectivity.ts +54 -0
- package/src/host/engine.ts +852 -40
- package/src/host/settings-migration.ts +1 -1
- package/src/index.ts +26 -1
- package/src/shared/core.ts +94 -3
package/lib/index.js
CHANGED
|
@@ -1119,8 +1119,12 @@ 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
|
+
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";
|
|
1124
1128
|
}
|
|
1125
1129
|
var isSessionMode = (value) => value === "default" || value === "off" || value === "recover" || value === "loop";
|
|
1126
1130
|
function sessionMode(modes, sessionId) {
|
|
@@ -1146,12 +1150,24 @@ var LOCALIZED_TEXT_DEFAULTS = {
|
|
|
1146
1150
|
guardPendingText: '(The previous tool "{tool}" may not have completed. Check its state before continuing and do not run it again.)',
|
|
1147
1151
|
guardDoneText: '(The previous tool "{tool}" completed successfully. Result: {result}; do not run it again. Continue from there.)',
|
|
1148
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: "(Похоже, ты застрял в цикле. Перестань повторять последнее действие и продолжай другим способом.)"
|
|
1149
1163
|
}
|
|
1150
1164
|
};
|
|
1151
1165
|
var DEFAULT_CONFIG = {
|
|
1152
1166
|
locale: "en",
|
|
1153
1167
|
...LOCALIZED_TEXT_DEFAULTS.en,
|
|
1168
|
+
usePluginSource: false,
|
|
1154
1169
|
resumeSilentTurns: true,
|
|
1170
|
+
resumeSubagentSessions: false,
|
|
1155
1171
|
resumeCompletedTurns: false,
|
|
1156
1172
|
continueTextLoop: "",
|
|
1157
1173
|
guardTools: true,
|
|
@@ -1175,7 +1191,13 @@ var DEFAULT_CONFIG = {
|
|
|
1175
1191
|
loopWindowMs: 3e4,
|
|
1176
1192
|
loopShortCount: 12,
|
|
1177
1193
|
loopRepeatText: 4,
|
|
1178
|
-
loopToolRepeat: 5
|
|
1194
|
+
loopToolRepeat: 5,
|
|
1195
|
+
resumeInterruptedChildren: false,
|
|
1196
|
+
resumeGoals: false,
|
|
1197
|
+
resumePausedGoals: false,
|
|
1198
|
+
pauseWhenOffline: true,
|
|
1199
|
+
offlineCheckMs: 15e3,
|
|
1200
|
+
loopMaxIterations: 0
|
|
1179
1201
|
};
|
|
1180
1202
|
function numberOr(value, fallback) {
|
|
1181
1203
|
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fallback;
|
|
@@ -1196,9 +1218,11 @@ function resolveConfig(section) {
|
|
|
1196
1218
|
const guardDoneText = typeof value.guardDoneText === "string" && value.guardDoneText.trim() !== "" ? value.guardDoneText : localized.guardDoneText;
|
|
1197
1219
|
return {
|
|
1198
1220
|
locale,
|
|
1221
|
+
usePluginSource: booleanOr(value.usePluginSource, DEFAULT_CONFIG.usePluginSource),
|
|
1199
1222
|
continueText: text,
|
|
1200
1223
|
continueTextMaxTokens: maxTokensText,
|
|
1201
1224
|
resumeSilentTurns: booleanOr(value.resumeSilentTurns, DEFAULT_CONFIG.resumeSilentTurns),
|
|
1225
|
+
resumeSubagentSessions: booleanOr(value.resumeSubagentSessions, DEFAULT_CONFIG.resumeSubagentSessions),
|
|
1202
1226
|
resumeCompletedTurns: booleanOr(value.resumeCompletedTurns, DEFAULT_CONFIG.resumeCompletedTurns),
|
|
1203
1227
|
continueTextSilent: silentText,
|
|
1204
1228
|
continueTextLoop: loopText,
|
|
@@ -1227,7 +1251,16 @@ function resolveConfig(section) {
|
|
|
1227
1251
|
loopShortCount: Math.max(2, numberOr(value.loopShortCount, DEFAULT_CONFIG.loopShortCount)),
|
|
1228
1252
|
loopRepeatText: Math.max(2, numberOr(value.loopRepeatText, DEFAULT_CONFIG.loopRepeatText)),
|
|
1229
1253
|
loopToolRepeat: Math.max(2, numberOr(value.loopToolRepeat, DEFAULT_CONFIG.loopToolRepeat)),
|
|
1230
|
-
loopText: typeof value.loopText === "string" && value.loopText.trim() !== "" ? value.loopText : localized.loopText
|
|
1254
|
+
loopText: typeof value.loopText === "string" && value.loopText.trim() !== "" ? value.loopText : localized.loopText,
|
|
1255
|
+
resumeInterruptedChildren: booleanOr(
|
|
1256
|
+
value.resumeInterruptedChildren,
|
|
1257
|
+
DEFAULT_CONFIG.resumeInterruptedChildren
|
|
1258
|
+
),
|
|
1259
|
+
resumeGoals: booleanOr(value.resumeGoals, DEFAULT_CONFIG.resumeGoals),
|
|
1260
|
+
resumePausedGoals: booleanOr(value.resumePausedGoals, DEFAULT_CONFIG.resumePausedGoals),
|
|
1261
|
+
pauseWhenOffline: booleanOr(value.pauseWhenOffline, DEFAULT_CONFIG.pauseWhenOffline),
|
|
1262
|
+
offlineCheckMs: Math.max(1e3, numberOr(value.offlineCheckMs, DEFAULT_CONFIG.offlineCheckMs)),
|
|
1263
|
+
loopMaxIterations: Math.floor(numberOr(value.loopMaxIterations, DEFAULT_CONFIG.loopMaxIterations))
|
|
1231
1264
|
};
|
|
1232
1265
|
}
|
|
1233
1266
|
function isNonHumanReason(kind) {
|
|
@@ -1243,6 +1276,10 @@ function isTransientFailure(failure, retryableErrorPatterns = "") {
|
|
|
1243
1276
|
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
1277
|
return !permanent;
|
|
1245
1278
|
}
|
|
1279
|
+
function isNetworkFailure(failure) {
|
|
1280
|
+
if (/^(TRANSPORT|TIMEOUT|NETWORK|E(CONN|NET|HOST|AI_|NOTFOUND|TIMEDOUT|PIPE))/i.test(failure.code)) return true;
|
|
1281
|
+
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);
|
|
1282
|
+
}
|
|
1246
1283
|
function formatElapsed(ms) {
|
|
1247
1284
|
if (ms === void 0 || !Number.isFinite(ms) || ms < 0) return "";
|
|
1248
1285
|
if (ms < 1e3) return `${Math.round(ms)}ms`;
|
|
@@ -1607,7 +1644,13 @@ var freshState = () => ({
|
|
|
1607
1644
|
streamRepeatRun: 0,
|
|
1608
1645
|
loopFired: false,
|
|
1609
1646
|
loopRetryTimer: void 0,
|
|
1610
|
-
cooldownRetryTimer: void 0
|
|
1647
|
+
cooldownRetryTimer: void 0,
|
|
1648
|
+
offlineWait: void 0,
|
|
1649
|
+
offlineTimer: void 0,
|
|
1650
|
+
offlineSince: 0,
|
|
1651
|
+
loopIterations: 0,
|
|
1652
|
+
loopCapNotified: false,
|
|
1653
|
+
loopEnabled: void 0
|
|
1611
1654
|
});
|
|
1612
1655
|
var RECOVERY_WINDOW_MS = 10 * 60 * 1e3;
|
|
1613
1656
|
var ECHO_WINDOW_MS = 10 * 60 * 1e3;
|
|
@@ -1633,34 +1676,99 @@ function forgetPendingEcho(state, messageId) {
|
|
|
1633
1676
|
function isOurEcho(state, event) {
|
|
1634
1677
|
if (event.type !== "user/message") return false;
|
|
1635
1678
|
const message = event.data;
|
|
1636
|
-
if (message.source.kind !== "user") return false;
|
|
1679
|
+
if (message.source.kind !== "user" && message.source.kind !== AUTO_CONTINUE_SOURCE_KIND) return false;
|
|
1637
1680
|
if (state.pendingEchoMessageIds.size === 0) return false;
|
|
1638
1681
|
const now = Date.now();
|
|
1639
1682
|
prunePendingEchoMessageIds(state, now);
|
|
1640
1683
|
return state.pendingEchoMessageIds.delete(message.id);
|
|
1641
1684
|
}
|
|
1642
1685
|
|
|
1686
|
+
// src/host/connectivity.ts
|
|
1687
|
+
import dns from "node:dns";
|
|
1688
|
+
import os from "node:os";
|
|
1689
|
+
var PROBE_HOSTS = ["api.deepseek.com", "www.baidu.com", "one.one.one.one"];
|
|
1690
|
+
var PROBE_TIMEOUT_MS = 3e3;
|
|
1691
|
+
function hasExternalInterface() {
|
|
1692
|
+
try {
|
|
1693
|
+
return Object.values(os.networkInterfaces()).some((list) => list?.some((entry) => !entry.internal) ?? false);
|
|
1694
|
+
} catch {
|
|
1695
|
+
return true;
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
function usesExplicitProxy() {
|
|
1699
|
+
const env = process.env;
|
|
1700
|
+
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() !== "");
|
|
1701
|
+
}
|
|
1702
|
+
function lookupWithin(host, ms) {
|
|
1703
|
+
return new Promise((resolve, reject) => {
|
|
1704
|
+
const timer = setTimeout(() => reject(new Error(`dns lookup timed out: ${host}`)), ms);
|
|
1705
|
+
timer.unref?.();
|
|
1706
|
+
dns.promises.lookup(host).then(
|
|
1707
|
+
(value) => {
|
|
1708
|
+
clearTimeout(timer);
|
|
1709
|
+
resolve(value);
|
|
1710
|
+
},
|
|
1711
|
+
(error) => {
|
|
1712
|
+
clearTimeout(timer);
|
|
1713
|
+
reject(error);
|
|
1714
|
+
}
|
|
1715
|
+
);
|
|
1716
|
+
});
|
|
1717
|
+
}
|
|
1718
|
+
var probeConnectivity = async () => {
|
|
1719
|
+
if (!hasExternalInterface()) return false;
|
|
1720
|
+
if (usesExplicitProxy()) return true;
|
|
1721
|
+
return new Promise((resolve) => {
|
|
1722
|
+
let pending = PROBE_HOSTS.length;
|
|
1723
|
+
for (const host of PROBE_HOSTS) {
|
|
1724
|
+
lookupWithin(host, PROBE_TIMEOUT_MS).then(
|
|
1725
|
+
() => resolve(true),
|
|
1726
|
+
() => {
|
|
1727
|
+
pending -= 1;
|
|
1728
|
+
if (pending === 0) resolve(false);
|
|
1729
|
+
}
|
|
1730
|
+
);
|
|
1731
|
+
}
|
|
1732
|
+
});
|
|
1733
|
+
};
|
|
1734
|
+
|
|
1643
1735
|
// src/host/engine.ts
|
|
1644
1736
|
var NOTICE_COPY = {
|
|
1645
1737
|
zh: {
|
|
1646
|
-
notContinuedTitle: "dsh-auto-continue:
|
|
1647
|
-
permanentErrorBody: (sessionId, summary) => `${sessionId}:
|
|
1738
|
+
notContinuedTitle: "dsh-auto-continue: 请处理会话错误",
|
|
1739
|
+
permanentErrorBody: (sessionId, summary) => `${sessionId}: ${summary}。请处理此错误后再继续。`,
|
|
1648
1740
|
resumeAction: "立即续跑",
|
|
1649
1741
|
pauseAction: "暂停该会话 1 小时",
|
|
1650
|
-
continuedTitle: "dsh-auto-continue:
|
|
1651
|
-
continuedBody: (sessionId, text, count) => `${sessionId}: 已发送「${text}
|
|
1652
|
-
stoppedTitle: "dsh-auto-continue:
|
|
1653
|
-
stoppedBody: (sessionId, count) => `${sessionId}:
|
|
1742
|
+
continuedTitle: "dsh-auto-continue: 已发送继续消息",
|
|
1743
|
+
continuedBody: (sessionId, text, count) => `${sessionId}: 已发送「${text}」(连续尝试 ${count} 次)`,
|
|
1744
|
+
stoppedTitle: "dsh-auto-continue: 已达到重试上限",
|
|
1745
|
+
stoppedBody: (sessionId, count) => `${sessionId}: 已连续尝试恢复 ${count} 次。请检查会话后再继续。`,
|
|
1746
|
+
loopCapTitle: "dsh-auto-continue: 自主循环已到上限",
|
|
1747
|
+
loopCapBody: (sessionId, count) => `${sessionId}: 已自主续跑 ${count} 轮, 循环暂停; 发一条消息或重新开启循环即可继续`
|
|
1654
1748
|
},
|
|
1655
1749
|
en: {
|
|
1656
|
-
notContinuedTitle: "dsh-auto-continue:
|
|
1657
|
-
permanentErrorBody: (sessionId, summary) => `${sessionId}:
|
|
1750
|
+
notContinuedTitle: "dsh-auto-continue: Review session error",
|
|
1751
|
+
permanentErrorBody: (sessionId, summary) => `${sessionId}: ${summary}. Resolve this error before continuing.`,
|
|
1658
1752
|
resumeAction: "Resume now",
|
|
1659
1753
|
pauseAction: "Pause this session for 1 hour",
|
|
1660
|
-
continuedTitle: "dsh-auto-continue:
|
|
1661
|
-
continuedBody: (sessionId, text, count) => `${sessionId}: Sent "${text}" (consecutive
|
|
1662
|
-
stoppedTitle: "dsh-auto-continue:
|
|
1663
|
-
stoppedBody: (sessionId, count) => `${sessionId}: ${count}
|
|
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.`,
|
|
1758
|
+
loopCapTitle: "dsh-auto-continue: Autonomous loop limit reached",
|
|
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} автономных раундов; отправьте сообщение или включите цикл снова, чтобы продолжить`
|
|
1664
1772
|
}
|
|
1665
1773
|
};
|
|
1666
1774
|
var LOOP_GUARD_CANCEL_CAUSE = {
|
|
@@ -1673,6 +1781,34 @@ var MANUAL_NOTIFICATION_REASON = "manual:notification";
|
|
|
1673
1781
|
var SWEEP_OBSERVE_BATCH = 16;
|
|
1674
1782
|
var STORED_READ_TIMEOUT_MS = 5e3;
|
|
1675
1783
|
var SWEEP_MAX_FAILURES = 3;
|
|
1784
|
+
var RESTART_CANCEL_CAUSES = /* @__PURE__ */ new Set(["disposed", "legacy"]);
|
|
1785
|
+
var DECISION_CANCEL_CAUSES = /* @__PURE__ */ new Set(["user", "parent", "hook"]);
|
|
1786
|
+
var CHILD_SWEEP_LIMIT = 8;
|
|
1787
|
+
var CHILD_ROOT_MAX_DEPTH = 8;
|
|
1788
|
+
var GOALS_SERVICE_KEY = "goals";
|
|
1789
|
+
var CHILD_CAUSE_COPY = {
|
|
1790
|
+
zh: {
|
|
1791
|
+
"open-turn": "回合开始后中断",
|
|
1792
|
+
disposed: "宿主销毁",
|
|
1793
|
+
interrupted: "崩溃恢复标记",
|
|
1794
|
+
"max-tokens": "输出长度耗尽",
|
|
1795
|
+
error: "可重试错误"
|
|
1796
|
+
},
|
|
1797
|
+
en: {
|
|
1798
|
+
"open-turn": "turn cut off after start",
|
|
1799
|
+
disposed: "host disposed the agent",
|
|
1800
|
+
interrupted: "closed by crash recovery",
|
|
1801
|
+
"max-tokens": "output ceiling reached",
|
|
1802
|
+
error: "retryable error"
|
|
1803
|
+
},
|
|
1804
|
+
ru: {
|
|
1805
|
+
"open-turn": "ход прерван после начала",
|
|
1806
|
+
disposed: "хост уничтожил агента",
|
|
1807
|
+
interrupted: "закрыт восстановлением после сбоя",
|
|
1808
|
+
"max-tokens": "достигнут лимит вывода",
|
|
1809
|
+
error: "повторяемая ошибка"
|
|
1810
|
+
}
|
|
1811
|
+
};
|
|
1676
1812
|
var isLoopReason = (reason) => reason === LOOP_COMPLETED_REASON || reason === LOOP_SILENT_REASON;
|
|
1677
1813
|
var STREAM_NEAR_DUPLICATE_MAX_CHARS = 2048;
|
|
1678
1814
|
var STREAM_TAIL_MAX_CHARS = 4096;
|
|
@@ -1721,20 +1857,88 @@ function readReasonKind(value) {
|
|
|
1721
1857
|
const kind = value.kind;
|
|
1722
1858
|
return typeof kind === "string" && kind.trim() !== "" ? kind : void 0;
|
|
1723
1859
|
}
|
|
1860
|
+
function readCancelCause(value) {
|
|
1861
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
1862
|
+
const reason = value;
|
|
1863
|
+
if (reason.kind !== "aborted") return void 0;
|
|
1864
|
+
return readReasonKind(reason.reason);
|
|
1865
|
+
}
|
|
1866
|
+
function isHostCancel(value) {
|
|
1867
|
+
const cause = readCancelCause(value);
|
|
1868
|
+
return cause !== void 0 && RESTART_CANCEL_CAUSES.has(cause);
|
|
1869
|
+
}
|
|
1870
|
+
function classifyChildInterruption(events, config) {
|
|
1871
|
+
let lastEnd;
|
|
1872
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
1873
|
+
const event = events[i];
|
|
1874
|
+
if (event?.type === "turn/end") {
|
|
1875
|
+
lastEnd = event;
|
|
1876
|
+
break;
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
const lastStart = latestTurnStart(events);
|
|
1880
|
+
if (lastStart !== void 0 && (lastEnd === void 0 || lastStart.seq > lastEnd.seq)) {
|
|
1881
|
+
if (isMaintenanceTurnStart(lastStart)) return void 0;
|
|
1882
|
+
if ((events[events.length - 1]?.time ?? 0) < Date.now() - config.freshMs) return void 0;
|
|
1883
|
+
return "open-turn";
|
|
1884
|
+
}
|
|
1885
|
+
const end = lastEnd;
|
|
1886
|
+
if (end === void 0) return void 0;
|
|
1887
|
+
if (end.time < Date.now() - config.freshMs) return void 0;
|
|
1888
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
1889
|
+
const event = events[i];
|
|
1890
|
+
if (event === void 0 || event.seq <= end.seq) break;
|
|
1891
|
+
if (event.type === "user/message") return void 0;
|
|
1892
|
+
}
|
|
1893
|
+
const reason = end.data.reason;
|
|
1894
|
+
const kind = readReasonKind(reason);
|
|
1895
|
+
if (kind === void 0) return void 0;
|
|
1896
|
+
if (kind === "aborted") {
|
|
1897
|
+
const cause = readCancelCause(reason);
|
|
1898
|
+
if (cause === void 0 || DECISION_CANCEL_CAUSES.has(cause)) return void 0;
|
|
1899
|
+
return RESTART_CANCEL_CAUSES.has(cause) ? "disposed" : void 0;
|
|
1900
|
+
}
|
|
1901
|
+
if (kind === "interrupted") return "interrupted";
|
|
1902
|
+
if (kind === "max-tokens") return "max-tokens";
|
|
1903
|
+
if (kind === "error") {
|
|
1904
|
+
const failure = parseFailureFacts(reason.error);
|
|
1905
|
+
if (failure === void 0) return void 0;
|
|
1906
|
+
if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) return void 0;
|
|
1907
|
+
return "error";
|
|
1908
|
+
}
|
|
1909
|
+
return void 0;
|
|
1910
|
+
}
|
|
1911
|
+
function resolveRootHeader(header, byId) {
|
|
1912
|
+
let current = header;
|
|
1913
|
+
for (let depth = 0; depth <= CHILD_ROOT_MAX_DEPTH; depth += 1) {
|
|
1914
|
+
const parentId = current.parentSession;
|
|
1915
|
+
if (parentId === void 0 || parentId === "") return current.id;
|
|
1916
|
+
const parent = byId.get(parentId);
|
|
1917
|
+
if (parent === void 0) return void 0;
|
|
1918
|
+
current = parent;
|
|
1919
|
+
}
|
|
1920
|
+
return void 0;
|
|
1921
|
+
}
|
|
1724
1922
|
function isLoopGuardCancelReason(value) {
|
|
1725
1923
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
1726
1924
|
const cause = value;
|
|
1727
1925
|
return cause.kind === LOOP_GUARD_CANCEL_CAUSE.kind && cause.reason === LOOP_GUARD_CANCEL_CAUSE.reason;
|
|
1728
1926
|
}
|
|
1927
|
+
var LINEAGE_CACHE_LIMIT = 2e3;
|
|
1729
1928
|
var AutoContinueRunner = class {
|
|
1730
1929
|
/**
|
|
1731
1930
|
* @param ctx - host plugin context (agents registry, session events).
|
|
1732
1931
|
* @param getConfig - read the current resolved configuration (entry config).
|
|
1733
1932
|
*/
|
|
1734
|
-
constructor(ctx, getConfig) {
|
|
1933
|
+
constructor(ctx, getConfig, probe = probeConnectivity) {
|
|
1735
1934
|
this.ctx = ctx;
|
|
1736
1935
|
this.getConfig = getConfig;
|
|
1936
|
+
this.probe = probe;
|
|
1737
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();
|
|
1738
1942
|
this.pauseUntil = /* @__PURE__ */ new Map();
|
|
1739
1943
|
this.dayStats = emptyDayStats();
|
|
1740
1944
|
this.recoveryAttempts = [];
|
|
@@ -1748,6 +1952,16 @@ var AutoContinueRunner = class {
|
|
|
1748
1952
|
this.bootScanErrors = /* @__PURE__ */ new WeakSet();
|
|
1749
1953
|
/** 存储扫描已裁决的会话 id, 避免每轮重复冷读大日志。 */
|
|
1750
1954
|
this.storedSwept = /* @__PURE__ */ new Set();
|
|
1955
|
+
/** 子会话裁决独立记账: storedSwept 在 origin 判断之前就已标记, 不能复用。 */
|
|
1956
|
+
this.childSwept = /* @__PURE__ */ new Set();
|
|
1957
|
+
/** 本轮已花掉的子会话观察配额(每轮重置, 子会话日志与主会话同等昂贵)。 */
|
|
1958
|
+
this.childScanned = 0;
|
|
1959
|
+
/** 本轮收集到的子会话中断, 按 root 主会话 id 归组。 */
|
|
1960
|
+
this.childInterrupts = /* @__PURE__ */ new Map();
|
|
1961
|
+
/** 已唤醒过的 root 会话 → 上次唤醒覆盖的子会话签名, 防止每轮重复催同一批。 */
|
|
1962
|
+
this.childWoken = /* @__PURE__ */ new Map();
|
|
1963
|
+
/** 已打印过「父链不可解析」的子会话, 避免 15 分钟扫描窗口内每轮重扫把日志刷爆。 */
|
|
1964
|
+
this.childDirtyLogged = /* @__PURE__ */ new Set();
|
|
1751
1965
|
/** 存储会话的连续观察/物化失败次数, 触达 SWEEP_MAX_FAILURES 后不再重试。 */
|
|
1752
1966
|
this.storedSweepFailures = /* @__PURE__ */ new Map();
|
|
1753
1967
|
this.storedSweepAnnounced = false;
|
|
@@ -1790,7 +2004,7 @@ var AutoContinueRunner = class {
|
|
|
1790
2004
|
void this.bootScanLoop();
|
|
1791
2005
|
}
|
|
1792
2006
|
this.log(
|
|
1793
|
-
`已启动(
|
|
2007
|
+
`已启动(文本="${config.continueText}", 宽限 ${config.graceMs}ms, 冷却 ${config.cooldownMs}ms, 最多连续 ${config.maxConsecutive} 次)`
|
|
1794
2008
|
);
|
|
1795
2009
|
}
|
|
1796
2010
|
log(message) {
|
|
@@ -1832,6 +2046,24 @@ var AutoContinueRunner = class {
|
|
|
1832
2046
|
for (const listener of this.stateListeners) listener();
|
|
1833
2047
|
}
|
|
1834
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) {
|
|
1835
2067
|
const config = this.getConfig();
|
|
1836
2068
|
const mode = sessionMode(config.sessionModes, sessionId);
|
|
1837
2069
|
return {
|
|
@@ -1845,6 +2077,8 @@ var AutoContinueRunner = class {
|
|
|
1845
2077
|
if (this.disposed) return;
|
|
1846
2078
|
for (const [sessionId, state] of this.states) {
|
|
1847
2079
|
const config = this.sessionConfig(sessionId);
|
|
2080
|
+
if (config.resumeCompletedTurns && state.loopEnabled === false) this.resetLoopIterations(state);
|
|
2081
|
+
state.loopEnabled = config.resumeCompletedTurns;
|
|
1848
2082
|
if (config.paused || isLoopReason(state.pendingReason ?? "") && !config.resumeCompletedTurns) {
|
|
1849
2083
|
this.cancelPending(sessionId, "会话模式或全局设置已更改");
|
|
1850
2084
|
}
|
|
@@ -1883,8 +2117,12 @@ var AutoContinueRunner = class {
|
|
|
1883
2117
|
if (state.pendingTimer !== void 0) clearTimeout(state.pendingTimer);
|
|
1884
2118
|
if (state.loopRetryTimer !== void 0) clearTimeout(state.loopRetryTimer);
|
|
1885
2119
|
if (state.cooldownRetryTimer !== void 0) clearTimeout(state.cooldownRetryTimer);
|
|
2120
|
+
if (state.offlineTimer !== void 0) clearTimeout(state.offlineTimer);
|
|
2121
|
+
state.offlineWait = void 0;
|
|
1886
2122
|
}
|
|
1887
2123
|
this.states.clear();
|
|
2124
|
+
this.parents.clear();
|
|
2125
|
+
this.subagentSessions.clear();
|
|
1888
2126
|
}
|
|
1889
2127
|
state(sessionId) {
|
|
1890
2128
|
let state = this.states.get(sessionId);
|
|
@@ -1894,19 +2132,157 @@ var AutoContinueRunner = class {
|
|
|
1894
2132
|
}
|
|
1895
2133
|
return state;
|
|
1896
2134
|
}
|
|
1897
|
-
/**
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
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
|
+
}
|
|
1901
2143
|
}
|
|
1902
2144
|
/** Read durable origin from the live agent for direct action paths as well. */
|
|
1903
2145
|
isSubagent(sessionId, state) {
|
|
1904
2146
|
if (state.subagent) return true;
|
|
1905
|
-
const
|
|
1906
|
-
if (
|
|
1907
|
-
|
|
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);
|
|
1908
2161
|
return true;
|
|
1909
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
|
+
}
|
|
1910
2286
|
/**
|
|
1911
2287
|
* 事件入口(host 单实例): 预处理工具调用/结果/模型消息(护栏与循环信号),
|
|
1912
2288
|
* 然后交给回合状态机。
|
|
@@ -1915,10 +2291,10 @@ var AutoContinueRunner = class {
|
|
|
1915
2291
|
const sessionId = session.id;
|
|
1916
2292
|
const sessionState = this.states.get(sessionId);
|
|
1917
2293
|
if (session.header?.origin === "subagent") {
|
|
1918
|
-
this.markSubagent(sessionId, sessionState ?? this.state(sessionId));
|
|
1919
|
-
|
|
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));
|
|
1920
2297
|
}
|
|
1921
|
-
if (sessionState?.subagent) return;
|
|
1922
2298
|
if (sessionState?.maintenanceTurn !== void 0 && sessionState.maintenanceTurn === event.data.turn && event.type !== "turn/start" && event.type !== "turn/end") return;
|
|
1923
2299
|
if ((event.type === "user/message" || event.type === "assistant/message") && typeof event.surfaceOp === "object" && event.surfaceOp !== null) {
|
|
1924
2300
|
this.state(sessionId).tools.recordSurfaceReplacement(event.seq);
|
|
@@ -2273,6 +2649,7 @@ var AutoContinueRunner = class {
|
|
|
2273
2649
|
if (isOurEcho(state, event)) break;
|
|
2274
2650
|
if (event.data.source.kind === "user") {
|
|
2275
2651
|
state.consecutive = 0;
|
|
2652
|
+
this.resetLoopIterations(state);
|
|
2276
2653
|
this.cancelPending(sessionId, "用户手动发送消息");
|
|
2277
2654
|
}
|
|
2278
2655
|
break;
|
|
@@ -2283,7 +2660,9 @@ var AutoContinueRunner = class {
|
|
|
2283
2660
|
// ---------- host 帧 ----------
|
|
2284
2661
|
onTurnFailure(sessionId, reason, failure) {
|
|
2285
2662
|
const config = this.getConfig();
|
|
2286
|
-
if (
|
|
2663
|
+
if (this.isSubagentSession(sessionId)) {
|
|
2664
|
+
if (!this.subagentRecoveryEnabled(sessionId)) return;
|
|
2665
|
+
} else if (sessionMode(config.sessionModes, sessionId) === "off") return;
|
|
2287
2666
|
if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
|
|
2288
2667
|
const copy = NOTICE_COPY[config.locale];
|
|
2289
2668
|
const summary = `${failure.code}${failure.status !== void 0 ? ` (HTTP ${failure.status})` : ""}`;
|
|
@@ -2318,6 +2697,11 @@ var AutoContinueRunner = class {
|
|
|
2318
2697
|
this.log(`通知按钮: 暂停 ${sessionId} 1 小时`);
|
|
2319
2698
|
this.pauseUntil.set(sessionId, Date.now() + 60 * 60 * 1e3);
|
|
2320
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
|
+
}
|
|
2321
2705
|
}
|
|
2322
2706
|
}
|
|
2323
2707
|
/** 内存统计(host 单实例): 按今日桶累计。 */
|
|
@@ -2364,12 +2748,8 @@ var AutoContinueRunner = class {
|
|
|
2364
2748
|
/** 立即为该会话发送一次自动继续(无视冷却与连续上限; 由通知按钮触发)。 */
|
|
2365
2749
|
async resumeNow(sessionId) {
|
|
2366
2750
|
if (this.disposed) return;
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
if (state.pendingTimer !== void 0) {
|
|
2370
|
-
clearTimeout(state.pendingTimer);
|
|
2371
|
-
state.pendingTimer = void 0;
|
|
2372
|
-
}
|
|
2751
|
+
if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) return;
|
|
2752
|
+
this.cancelPending(sessionId, "手动续跑");
|
|
2373
2753
|
try {
|
|
2374
2754
|
await this.fire(sessionId, MANUAL_NOTIFICATION_REASON, true);
|
|
2375
2755
|
} catch (error) {
|
|
@@ -2390,16 +2770,17 @@ var AutoContinueRunner = class {
|
|
|
2390
2770
|
const state = this.state(sessionId);
|
|
2391
2771
|
const config = this.sessionConfig(sessionId);
|
|
2392
2772
|
if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
|
|
2393
|
-
if (this.isSubagent(sessionId, state)) return;
|
|
2394
2773
|
if (config.paused) {
|
|
2395
2774
|
this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
|
|
2396
2775
|
return;
|
|
2397
2776
|
}
|
|
2398
|
-
if (Date.now() <
|
|
2777
|
+
if (Date.now() < this.effectivePauseUntil(sessionId)) {
|
|
2399
2778
|
this.log(`跳过 ${sessionId}(${reason}): 会话暂停中`);
|
|
2400
2779
|
return;
|
|
2401
2780
|
}
|
|
2402
2781
|
if (state.pendingTimer !== void 0) return;
|
|
2782
|
+
if (state.offlineWait !== void 0 || state.offlineTimer !== void 0) return;
|
|
2783
|
+
if (isLoopReason(reason) && this.loopCapReached(sessionId, state, config)) return;
|
|
2403
2784
|
if (!force && state.consecutive >= config.maxConsecutive) {
|
|
2404
2785
|
this.log(
|
|
2405
2786
|
`跳过 ${sessionId}(${reason}): 已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`
|
|
@@ -2418,7 +2799,7 @@ var AutoContinueRunner = class {
|
|
|
2418
2799
|
state.pendingTimer = void 0;
|
|
2419
2800
|
state.pendingReason = void 0;
|
|
2420
2801
|
try {
|
|
2421
|
-
|
|
2802
|
+
this.fireWhenOnline(sessionId, reason, force);
|
|
2422
2803
|
} catch (error) {
|
|
2423
2804
|
console.error(`[auto-continue] 定时发送异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2424
2805
|
}
|
|
@@ -2477,6 +2858,13 @@ var AutoContinueRunner = class {
|
|
|
2477
2858
|
state.loopRetryTimer = void 0;
|
|
2478
2859
|
cancelled = true;
|
|
2479
2860
|
}
|
|
2861
|
+
if (state.offlineWait !== void 0 || state.offlineTimer !== void 0) {
|
|
2862
|
+
if (state.offlineTimer !== void 0) clearTimeout(state.offlineTimer);
|
|
2863
|
+
state.offlineTimer = void 0;
|
|
2864
|
+
state.offlineWait = void 0;
|
|
2865
|
+
state.offlineSince = 0;
|
|
2866
|
+
cancelled = true;
|
|
2867
|
+
}
|
|
2480
2868
|
if (cancelled) this.log(`取消 ${sessionId} 的自动继续(${why})`);
|
|
2481
2869
|
}
|
|
2482
2870
|
fire(sessionId, reason, force = false) {
|
|
@@ -2486,12 +2874,12 @@ var AutoContinueRunner = class {
|
|
|
2486
2874
|
const manualResume = force && reason === MANUAL_NOTIFICATION_REASON;
|
|
2487
2875
|
if (reason.endsWith(":silent") && !config.resumeSilentTurns) return;
|
|
2488
2876
|
if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
|
|
2489
|
-
if (this.
|
|
2877
|
+
if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) return;
|
|
2490
2878
|
if (config.paused && !manualResume) {
|
|
2491
2879
|
this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
|
|
2492
2880
|
return;
|
|
2493
2881
|
}
|
|
2494
|
-
if (!manualResume && Date.now() <
|
|
2882
|
+
if (!manualResume && Date.now() < this.effectivePauseUntil(sessionId)) {
|
|
2495
2883
|
this.log(`跳过 ${sessionId}(${reason}): 会话暂停中`);
|
|
2496
2884
|
return;
|
|
2497
2885
|
}
|
|
@@ -2514,7 +2902,7 @@ var AutoContinueRunner = class {
|
|
|
2514
2902
|
try {
|
|
2515
2903
|
const message = createUserMessage({
|
|
2516
2904
|
content: [{ type: "text", text }],
|
|
2517
|
-
source: { kind: "user" }
|
|
2905
|
+
source: { kind: config.usePluginSource ? AUTO_CONTINUE_SOURCE_KIND : "user" }
|
|
2518
2906
|
});
|
|
2519
2907
|
trackPendingEcho(state, message.id);
|
|
2520
2908
|
if (agent.inbox.nextTurn.length > 0) this.prioritizedFollowups.add(message.id);
|
|
@@ -2527,7 +2915,9 @@ var AutoContinueRunner = class {
|
|
|
2527
2915
|
this.prioritizedFollowups.delete(message.id);
|
|
2528
2916
|
}
|
|
2529
2917
|
const now = Date.now();
|
|
2918
|
+
this.rearmGoal(sessionId, config);
|
|
2530
2919
|
if (reason !== LOOP_COMPLETED_REASON) state.consecutive += 1;
|
|
2920
|
+
if (isLoopReason(reason)) state.loopIterations += 1;
|
|
2531
2921
|
state.pendingRecoveryAt = now;
|
|
2532
2922
|
if (reason !== LOOP_COMPLETED_REASON) {
|
|
2533
2923
|
this.recoveryAttempts.unshift({
|
|
@@ -2566,6 +2956,83 @@ var AutoContinueRunner = class {
|
|
|
2566
2956
|
this.log(`发送异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2567
2957
|
}
|
|
2568
2958
|
}
|
|
2959
|
+
resetLoopIterations(state) {
|
|
2960
|
+
state.loopIterations = 0;
|
|
2961
|
+
state.loopCapNotified = false;
|
|
2962
|
+
}
|
|
2963
|
+
/** 自主循环轮数上限: 触顶后静默停下, 每次触顶只提示一次。 */
|
|
2964
|
+
loopCapReached(sessionId, state, config) {
|
|
2965
|
+
const cap = config.loopMaxIterations;
|
|
2966
|
+
if (cap <= 0 || state.loopIterations < cap) return false;
|
|
2967
|
+
if (!state.loopCapNotified) {
|
|
2968
|
+
state.loopCapNotified = true;
|
|
2969
|
+
this.log(`自主循环已续跑 ${state.loopIterations} 轮, 达到上限 ${cap}, 停止 ${sessionId}; 用户发消息或重新开启循环后重新计数`);
|
|
2970
|
+
if (config.notify) {
|
|
2971
|
+
const copy = NOTICE_COPY[config.locale];
|
|
2972
|
+
this.notify(
|
|
2973
|
+
sessionId,
|
|
2974
|
+
copy.loopCapTitle,
|
|
2975
|
+
copy.loopCapBody(sessionId, state.loopIterations),
|
|
2976
|
+
this.notifyOptions(sessionId, config.locale)
|
|
2977
|
+
);
|
|
2978
|
+
}
|
|
2979
|
+
}
|
|
2980
|
+
return true;
|
|
2981
|
+
}
|
|
2982
|
+
checkConnectivity() {
|
|
2983
|
+
if (this.connectivityCheck === void 0) {
|
|
2984
|
+
const check = this.probe().catch(() => true).finally(() => {
|
|
2985
|
+
if (this.connectivityCheck === check) this.connectivityCheck = void 0;
|
|
2986
|
+
});
|
|
2987
|
+
this.connectivityCheck = check;
|
|
2988
|
+
}
|
|
2989
|
+
return this.connectivityCheck;
|
|
2990
|
+
}
|
|
2991
|
+
/**
|
|
2992
|
+
* 网络类失败的续跑先过连通性检测: 断网时发出去必然再失败一次, 白白吃掉连续上限,
|
|
2993
|
+
* 等网络恢复时预算已耗尽。挂起期间不计次数, 每 offlineCheckMs 复检一次, 恢复后
|
|
2994
|
+
* 重新走 schedule(宽限、冷却照常)。手动续跑和非网络原因不受影响。
|
|
2995
|
+
*/
|
|
2996
|
+
fireWhenOnline(sessionId, reason, force) {
|
|
2997
|
+
const state = this.state(sessionId);
|
|
2998
|
+
const config = this.sessionConfig(sessionId);
|
|
2999
|
+
const gated = config.pauseWhenOffline && reason !== MANUAL_NOTIFICATION_REASON && !isLoopReason(reason) && state.lastFailure !== void 0 && isNetworkFailure(state.lastFailure);
|
|
3000
|
+
if (!gated) {
|
|
3001
|
+
this.fire(sessionId, reason, force);
|
|
3002
|
+
return;
|
|
3003
|
+
}
|
|
3004
|
+
const token = {};
|
|
3005
|
+
state.offlineWait = token;
|
|
3006
|
+
state.pendingReason = reason;
|
|
3007
|
+
void this.checkConnectivity().then((online) => {
|
|
3008
|
+
if (this.disposed || state.offlineWait !== token) return;
|
|
3009
|
+
if (online) {
|
|
3010
|
+
state.offlineWait = void 0;
|
|
3011
|
+
state.pendingReason = void 0;
|
|
3012
|
+
if (state.offlineSince !== 0) {
|
|
3013
|
+
this.log(`网络已恢复 ${sessionId}, 断网挂起 ${Math.round((Date.now() - state.offlineSince) / 1e3)}s 后继续(${reason})`);
|
|
3014
|
+
state.offlineSince = 0;
|
|
3015
|
+
this.schedule(sessionId, reason, force);
|
|
3016
|
+
return;
|
|
3017
|
+
}
|
|
3018
|
+
this.fire(sessionId, reason, force);
|
|
3019
|
+
return;
|
|
3020
|
+
}
|
|
3021
|
+
if (state.offlineSince === 0) {
|
|
3022
|
+
state.offlineSince = Date.now();
|
|
3023
|
+
this.log(`网络不可用, 挂起 ${sessionId} 的自动继续(${reason}), 每 ${config.offlineCheckMs}ms 复检, 不消耗重试次数`);
|
|
3024
|
+
}
|
|
3025
|
+
state.offlineTimer = setTimeout(() => {
|
|
3026
|
+
state.offlineTimer = void 0;
|
|
3027
|
+
if (state.offlineWait !== token) return;
|
|
3028
|
+
try {
|
|
3029
|
+
this.fireWhenOnline(sessionId, reason, force);
|
|
3030
|
+
} catch (error) {
|
|
3031
|
+
console.error(`[auto-continue] 断网复检异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
3032
|
+
}
|
|
3033
|
+
}, config.offlineCheckMs);
|
|
3034
|
+
});
|
|
3035
|
+
}
|
|
2569
3036
|
/**
|
|
2570
3037
|
* 组装本次续跑消息: 模板填充 + 幂等护栏。
|
|
2571
3038
|
* 护栏依据上一步工具调用的执行状态附加指引, 防止重跑副作用操作:
|
|
@@ -2602,7 +3069,8 @@ var AutoContinueRunner = class {
|
|
|
2602
3069
|
if (await this.scanInterrupted()) return;
|
|
2603
3070
|
const config = this.getConfig();
|
|
2604
3071
|
if (!config.paused && config.scanOnBoot && this.storedSweep === void 0) {
|
|
2605
|
-
this.
|
|
3072
|
+
this.childScanned = 0;
|
|
3073
|
+
this.storedSweep = this.sweepStoredSessions(config, deadline).then(() => this.wakeInterruptedChildren(config, deadline)).catch((error) => {
|
|
2606
3074
|
if (!this.disposed) this.ctx.logger.error(`Stored session scan failed: ${String(error)}`);
|
|
2607
3075
|
}).finally(() => {
|
|
2608
3076
|
this.storedSweep = void 0;
|
|
@@ -2658,7 +3126,8 @@ var AutoContinueRunner = class {
|
|
|
2658
3126
|
break;
|
|
2659
3127
|
}
|
|
2660
3128
|
}
|
|
2661
|
-
|
|
3129
|
+
let reasonKind = readReasonKind(lastEnd?.data.reason);
|
|
3130
|
+
if (reasonKind === "aborted" && isHostCancel(lastEnd?.data.reason)) reasonKind = "interrupted";
|
|
2662
3131
|
const lastStart = latestTurnStart(events);
|
|
2663
3132
|
const maintenance = lastStart?.data.turn === lastEnd?.data.turn && isMaintenanceTurnStart(lastStart);
|
|
2664
3133
|
const silent = reasonKind === "no-visible-output" && config.resumeSilentTurns;
|
|
@@ -2773,7 +3242,25 @@ var AutoContinueRunner = class {
|
|
|
2773
3242
|
if (!Array.isArray(records)) throw new TypeError("stored session listing is not an array");
|
|
2774
3243
|
if (!this.storedSweepAnnounced) {
|
|
2775
3244
|
this.storedSweepAnnounced = true;
|
|
2776
|
-
|
|
3245
|
+
let children = 0;
|
|
3246
|
+
let otherOrigins = 0;
|
|
3247
|
+
let originMissing = 0;
|
|
3248
|
+
for (const record2 of records) {
|
|
3249
|
+
const origin = record2?.header?.origin;
|
|
3250
|
+
if (origin === "subagent") children += 1;
|
|
3251
|
+
else if (origin === void 0) originMissing += 1;
|
|
3252
|
+
else otherOrigins += 1;
|
|
3253
|
+
}
|
|
3254
|
+
this.ctx.logger.info(
|
|
3255
|
+
`存储扫描就绪: ${records.length} 个会话记录 (subagent ${children} / 无 origin ${originMissing} / 其它 origin ${otherOrigins})`
|
|
3256
|
+
);
|
|
3257
|
+
}
|
|
3258
|
+
const headersById = /* @__PURE__ */ new Map();
|
|
3259
|
+
for (const record2 of records) {
|
|
3260
|
+
const header = record2?.header;
|
|
3261
|
+
if (header !== void 0 && typeof header.id === "string" && header.id !== "") {
|
|
3262
|
+
headersById.set(header.id, header);
|
|
3263
|
+
}
|
|
2777
3264
|
}
|
|
2778
3265
|
let observed = 0;
|
|
2779
3266
|
for (const record2 of records) {
|
|
@@ -2783,10 +3270,15 @@ var AutoContinueRunner = class {
|
|
|
2783
3270
|
continue;
|
|
2784
3271
|
}
|
|
2785
3272
|
const sessionId = record2.header.id;
|
|
2786
|
-
if (this.
|
|
3273
|
+
if (this.ownSessionConfig(sessionId).paused || Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) continue;
|
|
3274
|
+
if (record2.header.origin === "subagent") {
|
|
3275
|
+
if (config.resumeInterruptedChildren) {
|
|
3276
|
+
await this.sweepChild(record2, headersById, config, deadline);
|
|
3277
|
+
}
|
|
3278
|
+
continue;
|
|
3279
|
+
}
|
|
2787
3280
|
if (record2.live || this.storedSwept.has(sessionId)) continue;
|
|
2788
3281
|
this.storedSwept.add(sessionId);
|
|
2789
|
-
if (record2.header.origin === "subagent") continue;
|
|
2790
3282
|
observed += 1;
|
|
2791
3283
|
let observation;
|
|
2792
3284
|
try {
|
|
@@ -2818,6 +3310,7 @@ var AutoContinueRunner = class {
|
|
|
2818
3310
|
freshAt = events[events.length - 1]?.time ?? 0;
|
|
2819
3311
|
} else {
|
|
2820
3312
|
reasonKind = readReasonKind(lastEnd?.data.reason);
|
|
3313
|
+
if (reasonKind === "aborted" && isHostCancel(lastEnd?.data.reason)) reasonKind = "interrupted";
|
|
2821
3314
|
freshAt = lastEnd?.time ?? 0;
|
|
2822
3315
|
}
|
|
2823
3316
|
if (reasonKind === void 0 || freshAt < Date.now() - config.freshMs) continue;
|
|
@@ -2870,6 +3363,227 @@ var AutoContinueRunner = class {
|
|
|
2870
3363
|
}
|
|
2871
3364
|
}
|
|
2872
3365
|
}
|
|
3366
|
+
/**
|
|
3367
|
+
* 子会话裁决。子会话本身永不直接续跑(父代理权威, 见 README), 但启动扫描要
|
|
3368
|
+
* 知道它是否在重启时被打断, 才能在自己的 root 会话上补一次带清单的唤醒。
|
|
3369
|
+
* 独立 `childSwept` 记账与独立配额: 主扫描的 `storedSwept` 在 origin 判断
|
|
3370
|
+
* 之前就已标记, 复用它会让子会话永远扫不到, 也会吃掉主扫描的观察预算。
|
|
3371
|
+
*/
|
|
3372
|
+
async sweepChild(record2, headersById, config, deadline) {
|
|
3373
|
+
const header = record2.header;
|
|
3374
|
+
const sessionId = header.id;
|
|
3375
|
+
const parentId = header.parentSession;
|
|
3376
|
+
if (parentId === void 0 || parentId === "") return;
|
|
3377
|
+
if (record2.persisted !== true) return;
|
|
3378
|
+
if (this.childSwept.has(sessionId)) return;
|
|
3379
|
+
if (this.ctx.agents.get(sessionId) !== void 0) return;
|
|
3380
|
+
if (this.childScanned >= CHILD_SWEEP_LIMIT) return;
|
|
3381
|
+
if (this.ownSessionConfig(sessionId).paused) return;
|
|
3382
|
+
const rootId = resolveRootHeader(header, headersById);
|
|
3383
|
+
if (rootId === void 0 || rootId === sessionId) {
|
|
3384
|
+
if (!this.childDirtyLogged.has(sessionId)) {
|
|
3385
|
+
this.childDirtyLogged.add(sessionId);
|
|
3386
|
+
this.log(`子会话 ${sessionId} 父链不可解析(脏引用或自环), 跳过(每会话只记一次)`);
|
|
3387
|
+
}
|
|
3388
|
+
return;
|
|
3389
|
+
}
|
|
3390
|
+
const query = this.ctx.get("sessionQuery");
|
|
3391
|
+
if (query === void 0) return;
|
|
3392
|
+
this.childSwept.add(sessionId);
|
|
3393
|
+
this.childScanned += 1;
|
|
3394
|
+
let observation;
|
|
3395
|
+
try {
|
|
3396
|
+
const stored = await this.readStored(
|
|
3397
|
+
(signal) => query.observeSession(sessionId, { projectionMode: "all", signal }),
|
|
3398
|
+
deadline
|
|
3399
|
+
);
|
|
3400
|
+
observation = stored;
|
|
3401
|
+
if (this.disposed) return;
|
|
3402
|
+
const events = validateSessionEvents(stored.events);
|
|
3403
|
+
if (events.length === 0) return;
|
|
3404
|
+
const cause = classifyChildInterruption(events, config);
|
|
3405
|
+
if (cause === void 0) return;
|
|
3406
|
+
const tail = events[events.length - 1];
|
|
3407
|
+
const list = this.childInterrupts.get(rootId) ?? [];
|
|
3408
|
+
list.push({
|
|
3409
|
+
id: sessionId,
|
|
3410
|
+
title: typeof header.title === "string" && header.title !== "" ? header.title : void 0,
|
|
3411
|
+
preset: header.agentPreset,
|
|
3412
|
+
cause,
|
|
3413
|
+
at: tail?.time ?? Date.now()
|
|
3414
|
+
});
|
|
3415
|
+
this.childInterrupts.set(rootId, list);
|
|
3416
|
+
this.log(`子会话 ${sessionId} 重启时被打断(${cause}), 记入 root ${rootId}`);
|
|
3417
|
+
} catch (error) {
|
|
3418
|
+
this.childSwept.delete(sessionId);
|
|
3419
|
+
if (!this.disposed) {
|
|
3420
|
+
this.ctx.logger.info(
|
|
3421
|
+
`子会话 ${sessionId} 冷读失败: ${error instanceof Error ? error.message : String(error)}`
|
|
3422
|
+
);
|
|
3423
|
+
}
|
|
3424
|
+
} finally {
|
|
3425
|
+
observation?.[Symbol.dispose]?.();
|
|
3426
|
+
}
|
|
3427
|
+
}
|
|
3428
|
+
/** 把本轮收集到的子会话中断转成 root 会话上的一次唤醒(同一批只催一次)。 */
|
|
3429
|
+
async wakeInterruptedChildren(config, deadline) {
|
|
3430
|
+
if (this.disposed || this.childInterrupts.size === 0) return;
|
|
3431
|
+
if (config.paused || !config.scanOnBoot || !config.resumeInterruptedChildren) return;
|
|
3432
|
+
for (const [rootId, children] of [...this.childInterrupts]) {
|
|
3433
|
+
if (this.disposed || Date.now() >= deadline) return;
|
|
3434
|
+
try {
|
|
3435
|
+
if (await this.wakeRoot(config, rootId, children, deadline)) {
|
|
3436
|
+
this.childInterrupts.delete(rootId);
|
|
3437
|
+
}
|
|
3438
|
+
} catch (error) {
|
|
3439
|
+
this.childInterrupts.delete(rootId);
|
|
3440
|
+
if (!this.disposed) {
|
|
3441
|
+
this.ctx.logger.info(
|
|
3442
|
+
`子会话唤醒 ${rootId} 失败: ${error instanceof Error ? error.message : String(error)}`
|
|
3443
|
+
);
|
|
3444
|
+
}
|
|
3445
|
+
}
|
|
3446
|
+
}
|
|
3447
|
+
}
|
|
3448
|
+
/**
|
|
3449
|
+
* 在 root 会话上唤醒一次。只有在 root 自己是"干净终态"时才动手: 它若被打断,
|
|
3450
|
+
* 主扫描本来就会续跑它; 它若被用户手动停止, 唤醒就是幽灵回合。
|
|
3451
|
+
*/
|
|
3452
|
+
async wakeRoot(config, rootId, children, deadline) {
|
|
3453
|
+
if (this.sessionConfig(rootId).paused) return false;
|
|
3454
|
+
if (Date.now() < (this.pauseUntil.get(rootId) ?? 0)) return false;
|
|
3455
|
+
const state = this.state(rootId);
|
|
3456
|
+
if (state.pendingTimer !== void 0) return false;
|
|
3457
|
+
if (state.consecutive >= config.maxConsecutive) return true;
|
|
3458
|
+
if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) return false;
|
|
3459
|
+
const batch = children.map((child) => `${child.id}:${child.cause}`).sort().join(",");
|
|
3460
|
+
if (this.childWoken.get(rootId) === batch) return true;
|
|
3461
|
+
if (!await this.rootAcceptsWake(rootId, deadline)) return true;
|
|
3462
|
+
const agent = await this.ensureLiveAgent(rootId, deadline);
|
|
3463
|
+
if (agent === void 0 || this.disposed) return false;
|
|
3464
|
+
const text = this.buildChildResumeText(config, children);
|
|
3465
|
+
const message = createUserMessage({
|
|
3466
|
+
content: [{ type: "text", text }],
|
|
3467
|
+
source: { kind: "user" }
|
|
3468
|
+
});
|
|
3469
|
+
state.lastAttemptAt = Date.now();
|
|
3470
|
+
agent.followup(message);
|
|
3471
|
+
this.childWoken.set(rootId, batch);
|
|
3472
|
+
this.log(
|
|
3473
|
+
`已唤醒 ${rootId}: ${children.length} 个子会话在重启时被打断, 清单已交给父会话处置`
|
|
3474
|
+
);
|
|
3475
|
+
this.rearmGoal(rootId, config);
|
|
3476
|
+
return true;
|
|
3477
|
+
}
|
|
3478
|
+
/** 父会话只在"干净结束"或"被宿主关闭"时接受唤醒; 用户手动停止的绝不复活。 */
|
|
3479
|
+
async rootAcceptsWake(sessionId, deadline) {
|
|
3480
|
+
const query = this.ctx.get("sessionQuery");
|
|
3481
|
+
if (query === void 0) return false;
|
|
3482
|
+
let events;
|
|
3483
|
+
let stored;
|
|
3484
|
+
try {
|
|
3485
|
+
const observation = await this.readStored(
|
|
3486
|
+
(signal) => query.observeSession(sessionId, { projectionMode: "all", signal }),
|
|
3487
|
+
deadline
|
|
3488
|
+
);
|
|
3489
|
+
stored = observation;
|
|
3490
|
+
events = validateSessionEvents(observation.events);
|
|
3491
|
+
} catch {
|
|
3492
|
+
return false;
|
|
3493
|
+
} finally {
|
|
3494
|
+
stored?.[Symbol.dispose]?.();
|
|
3495
|
+
}
|
|
3496
|
+
if (events.length === 0) return false;
|
|
3497
|
+
let lastEnd;
|
|
3498
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
3499
|
+
const event = events[i];
|
|
3500
|
+
if (event?.type === "turn/end") {
|
|
3501
|
+
lastEnd = event;
|
|
3502
|
+
break;
|
|
3503
|
+
}
|
|
3504
|
+
}
|
|
3505
|
+
const lastStart = latestTurnStart(events);
|
|
3506
|
+
const end = lastEnd;
|
|
3507
|
+
if (lastStart !== void 0 && (end === void 0 || lastStart.seq > end.seq)) return false;
|
|
3508
|
+
if (end === void 0) return false;
|
|
3509
|
+
const kind = readReasonKind(end.data.reason);
|
|
3510
|
+
if (kind === "completed") return true;
|
|
3511
|
+
if (kind === "aborted") return isHostCancel(end.data.reason);
|
|
3512
|
+
return false;
|
|
3513
|
+
}
|
|
3514
|
+
/** 发送需要 live agent; 存储会话沿既有物化路径拉起, 复用 preset 与模型回装。 */
|
|
3515
|
+
async ensureLiveAgent(sessionId, deadline) {
|
|
3516
|
+
const live = this.ctx.agents.get(sessionId);
|
|
3517
|
+
if (live !== void 0) return live;
|
|
3518
|
+
const query = this.ctx.get("sessionQuery");
|
|
3519
|
+
if (query === void 0) return void 0;
|
|
3520
|
+
let presetId;
|
|
3521
|
+
let model;
|
|
3522
|
+
let stored;
|
|
3523
|
+
try {
|
|
3524
|
+
const observation = await this.readStored(
|
|
3525
|
+
(signal) => query.observeSession(sessionId, { projectionMode: "all", signal }),
|
|
3526
|
+
deadline
|
|
3527
|
+
);
|
|
3528
|
+
stored = observation;
|
|
3529
|
+
presetId = observation.projections?.values.agentPreset ?? observation.header.agentPreset;
|
|
3530
|
+
const loggedConfig = foldRequestHeader(validateSessionEvents(observation.events))?.config;
|
|
3531
|
+
if (loggedConfig !== void 0) model = { provider: loggedConfig.provider, model: loggedConfig.model };
|
|
3532
|
+
} catch {
|
|
3533
|
+
return void 0;
|
|
3534
|
+
} finally {
|
|
3535
|
+
stored?.[Symbol.dispose]?.();
|
|
3536
|
+
}
|
|
3537
|
+
const ok = await this.materializeStored(sessionId, presetId, model);
|
|
3538
|
+
if (!ok || this.disposed) return void 0;
|
|
3539
|
+
return this.ctx.agents.get(sessionId);
|
|
3540
|
+
}
|
|
3541
|
+
/** 唤醒文本必须带会话级证据: 否则父会话看不到任何状态, 只会白跑一轮再回一句"都结束了"。 */
|
|
3542
|
+
buildChildResumeText(config, children) {
|
|
3543
|
+
const lines = children.map((child) => {
|
|
3544
|
+
const label = child.title !== void 0 ? `「${child.title}」` : "";
|
|
3545
|
+
const preset = child.preset !== void 0 ? ` (${child.preset})` : "";
|
|
3546
|
+
const cause = CHILD_CAUSE_COPY[config.locale][child.cause];
|
|
3547
|
+
return `- ${child.id} ${label}${preset} — ${cause}`;
|
|
3548
|
+
});
|
|
3549
|
+
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:";
|
|
3550
|
+
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.";
|
|
3551
|
+
return [header, ...lines, tail].join("\n");
|
|
3552
|
+
}
|
|
3553
|
+
/**
|
|
3554
|
+
* 重启会把 active goal 置为 disarmed(宿主卸载驱动的正常动作), 只有人类授权的
|
|
3555
|
+
* resume 能重新 arm; paused 则是人类的显式决定。两者都默认关闭。
|
|
3556
|
+
*/
|
|
3557
|
+
rearmGoal(sessionId, config) {
|
|
3558
|
+
if (!config.resumeGoals) return;
|
|
3559
|
+
const goals = this.ctx.get(GOALS_SERVICE_KEY);
|
|
3560
|
+
if (goals === void 0) return;
|
|
3561
|
+
const agent = this.ctx.agents.get(sessionId);
|
|
3562
|
+
if (agent === void 0) return;
|
|
3563
|
+
try {
|
|
3564
|
+
const view = goals.get(agent);
|
|
3565
|
+
if (view === void 0) return;
|
|
3566
|
+
const revision = view.revision;
|
|
3567
|
+
if (revision === void 0) {
|
|
3568
|
+
this.log(`会话 ${sessionId}: goal 视图缺 revision, 跳过重新武装(宿主会拒绝无 revision 的 resume)`);
|
|
3569
|
+
return;
|
|
3570
|
+
}
|
|
3571
|
+
const ref = view.ref ?? { id: view.id, revision };
|
|
3572
|
+
if (view.phase === "active" && view.activation === "disarmed") {
|
|
3573
|
+
goals.resume(agent, ref);
|
|
3574
|
+
this.log(`会话 ${sessionId}: goal 被重启失活, 已重新武装`);
|
|
3575
|
+
return;
|
|
3576
|
+
}
|
|
3577
|
+
if (view.phase === "paused" && config.resumePausedGoals) {
|
|
3578
|
+
goals.resume(agent, ref);
|
|
3579
|
+
this.log(`会话 ${sessionId}: 已恢复被暂停的 goal`);
|
|
3580
|
+
}
|
|
3581
|
+
} catch (error) {
|
|
3582
|
+
this.ctx.logger.info(
|
|
3583
|
+
`goal 恢复失败 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`
|
|
3584
|
+
);
|
|
3585
|
+
}
|
|
3586
|
+
}
|
|
2873
3587
|
/**
|
|
2874
3588
|
* 按会话记录的 preset 组合把存储会话恢复为 live agent(镜像会话控制
|
|
2875
3589
|
* 器的 adopt 路径: preset 挂载 + 会话已记录的模型选择回装)。模型选择
|
|
@@ -9202,7 +9916,7 @@ function migrateLegacySettings(ctx, config, fields, validate) {
|
|
|
9202
9916
|
});
|
|
9203
9917
|
const failed = () => {
|
|
9204
9918
|
if (disposed) return;
|
|
9205
|
-
migration.logger.error("[auto-continue] Could not import settings-legacy.yaml
|
|
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.");
|
|
9206
9920
|
};
|
|
9207
9921
|
void (async () => {
|
|
9208
9922
|
try {
|
|
@@ -9269,15 +9983,20 @@ function migrateLegacySettings(ctx, config, fields, validate) {
|
|
|
9269
9983
|
|
|
9270
9984
|
// src/index.ts
|
|
9271
9985
|
var AUTO_CONTINUE_NS = "auto-continue";
|
|
9986
|
+
var BRIDGE_HEARTBEAT_MS = 2e4;
|
|
9272
9987
|
var settingsFields = {
|
|
9273
9988
|
/** Active browser/UI locale mirrored by the client. */
|
|
9274
9989
|
locale: z2.string().default("en"),
|
|
9990
|
+
/** Send continue messages with the plugin source instead of the legacy user source. */
|
|
9991
|
+
usePluginSource: z2.boolean().default(false),
|
|
9275
9992
|
/** Text automatically sent after an interruption. */
|
|
9276
9993
|
continueText: z2.string().default(""),
|
|
9277
9994
|
/** Text sent when the output token ceiling is reached (same placeholders as `continueText`). */
|
|
9278
9995
|
continueTextMaxTokens: z2.string().default(""),
|
|
9279
9996
|
/** Resume observed model activity that completes without visible output. */
|
|
9280
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),
|
|
9281
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. */
|
|
9282
10001
|
resumeCompletedTurns: z2.boolean().default(false),
|
|
9283
10002
|
/** Text sent to resume a silent turn (same placeholders as `continueText`). */
|
|
@@ -9335,7 +10054,19 @@ var settingsFields = {
|
|
|
9335
10054
|
/** Consecutive identical tool calls with identical arguments AND results trip the loop guard. */
|
|
9336
10055
|
loopToolRepeat: z2.natural().min(2).default(5),
|
|
9337
10056
|
/** Text sent after the loop guard cancels and restarts a turn (supports {tool}). */
|
|
9338
|
-
loopText: z2.string().default("")
|
|
10057
|
+
loopText: z2.string().default(""),
|
|
10058
|
+
/** Recover child (subagent / Agent Teams) sessions a restart interrupted by waking their root session once. */
|
|
10059
|
+
resumeInterruptedChildren: z2.boolean().default(false),
|
|
10060
|
+
/** Re-arm a goal a restart left `active` but `disarmed`, when its own session is resumed. */
|
|
10061
|
+
resumeGoals: z2.boolean().default(false),
|
|
10062
|
+
/** Also resume goals the user explicitly paused. Off by default: pausing is a human decision. */
|
|
10063
|
+
resumePausedGoals: z2.boolean().default(false),
|
|
10064
|
+
/** Hold network-error recoveries while the host is offline; waiting does not consume the retry budget. */
|
|
10065
|
+
pauseWhenOffline: z2.boolean().default(true),
|
|
10066
|
+
/** How often (ms) a held recovery re-checks connectivity. */
|
|
10067
|
+
offlineCheckMs: z2.natural().min(1e3).default(15e3),
|
|
10068
|
+
/** Autonomous-loop round cap per session; 0 means unlimited. */
|
|
10069
|
+
loopMaxIterations: z2.natural().default(0)
|
|
9339
10070
|
};
|
|
9340
10071
|
var AutoContinueSchema = z2.object(settingsFields);
|
|
9341
10072
|
var entrySchema = z2.object({
|
|
@@ -9389,6 +10120,7 @@ function apply(ctx, config) {
|
|
|
9389
10120
|
recoveryAttempts: runner.recentRecoveryAttempts(),
|
|
9390
10121
|
sessionPolicy: {
|
|
9391
10122
|
modes: config2.sessionModes,
|
|
10123
|
+
inheritedModes: runner.inheritedSubagentModes(),
|
|
9392
10124
|
defaultMode: config2.resumeCompletedTurns ? "loop" : "recover",
|
|
9393
10125
|
paused: config2.paused,
|
|
9394
10126
|
writable: writableSettings() !== void 0
|
|
@@ -9426,11 +10158,20 @@ function apply(ctx, config) {
|
|
|
9426
10158
|
res.write(data);
|
|
9427
10159
|
};
|
|
9428
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?.();
|
|
9429
10168
|
const close = () => {
|
|
10169
|
+
clearInterval(heartbeat);
|
|
9430
10170
|
res.end();
|
|
9431
10171
|
};
|
|
9432
10172
|
closeClients.add(close);
|
|
9433
10173
|
req.on("close", () => {
|
|
10174
|
+
clearInterval(heartbeat);
|
|
9434
10175
|
sseClients.delete(send);
|
|
9435
10176
|
closeClients.delete(close);
|
|
9436
10177
|
});
|