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