dsh-client-auto-continue 0.11.8 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -101,6 +101,8 @@ var LOCALIZED_TEXT_DEFAULTS = {
101
101
  zh: {
102
102
  continueText: "继续",
103
103
  continueTextMaxTokens: "继续",
104
+ continueTextSilent: "继续。你上一轮只输出了内部推理, 既没有回复也没有调用工具, 用户什么都没看到。每一轮都要以工具调用或可见回复结束。",
105
+ continueTextLoop: "继续",
104
106
  guardPendingText: "(上一步工具「{tool}」可能未完成, 先确认状态再继续, 不要重复执行)",
105
107
  guardDoneText: "(上一步工具「{tool}」已完成, 结果: {result}; 不要重复执行, 直接继续)",
106
108
  loopText: "(检测到你可能陷入循环, 请停止重复刚才的动作, 换一种方式继续)"
@@ -108,6 +110,8 @@ var LOCALIZED_TEXT_DEFAULTS = {
108
110
  en: {
109
111
  continueText: "Continue",
110
112
  continueTextMaxTokens: "Continue",
113
+ 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
+ continueTextLoop: "Continue",
111
115
  guardPendingText: '(The previous tool "{tool}" may not have completed. Check its state before continuing and do not run it again.)',
112
116
  guardDoneText: '(The previous tool "{tool}" completed successfully. Result: {result}; do not run it again. Continue from there.)',
113
117
  loopText: "(You may be stuck in a loop. Stop repeating the last action and continue with a different approach.)"
@@ -116,6 +120,9 @@ var LOCALIZED_TEXT_DEFAULTS = {
116
120
  var DEFAULT_CONFIG = {
117
121
  locale: "zh",
118
122
  ...LOCALIZED_TEXT_DEFAULTS.zh,
123
+ resumeSilentTurns: true,
124
+ resumeCompletedTurns: false,
125
+ continueTextLoop: "",
119
126
  guardTools: true,
120
127
  graceMs: 3e3,
121
128
  cooldownMs: 2e4,
@@ -149,12 +156,18 @@ function resolveConfig(section) {
149
156
  const localized = LOCALIZED_TEXT_DEFAULTS[locale];
150
157
  const text = typeof value.continueText === "string" && value.continueText.trim() !== "" ? value.continueText : localized.continueText;
151
158
  const maxTokensText = typeof value.continueTextMaxTokens === "string" && value.continueTextMaxTokens.trim() !== "" ? value.continueTextMaxTokens : localized.continueTextMaxTokens;
159
+ const silentText = typeof value.continueTextSilent === "string" && value.continueTextSilent.trim() !== "" ? value.continueTextSilent : localized.continueTextSilent;
160
+ const loopText = typeof value.continueTextLoop === "string" && value.continueTextLoop.trim() !== "" ? value.continueTextLoop : localized.continueTextLoop;
152
161
  const guardPendingText = typeof value.guardPendingText === "string" && value.guardPendingText.trim() !== "" ? value.guardPendingText : localized.guardPendingText;
153
162
  const guardDoneText = typeof value.guardDoneText === "string" && value.guardDoneText.trim() !== "" ? value.guardDoneText : localized.guardDoneText;
154
163
  return {
155
164
  locale,
156
165
  continueText: text,
157
166
  continueTextMaxTokens: maxTokensText,
167
+ resumeSilentTurns: booleanOr(value.resumeSilentTurns, DEFAULT_CONFIG.resumeSilentTurns),
168
+ resumeCompletedTurns: booleanOr(value.resumeCompletedTurns, DEFAULT_CONFIG.resumeCompletedTurns),
169
+ continueTextSilent: silentText,
170
+ continueTextLoop: loopText,
158
171
  guardTools: booleanOr(value.guardTools, DEFAULT_CONFIG.guardTools),
159
172
  guardPendingText,
160
173
  guardDoneText,
@@ -522,9 +535,6 @@ function effectiveCooldown(consecutive, base, factor, max) {
522
535
  const multiplier = Math.pow(factor, consecutive);
523
536
  return Math.min(Math.max(base, base * multiplier), Math.max(base, max));
524
537
  }
525
- function sleep(ms) {
526
- return new Promise((resolve) => setTimeout(resolve, ms));
527
- }
528
538
  function todayKey() {
529
539
  const d = /* @__PURE__ */ new Date();
530
540
  const mm = String(d.getMonth() + 1).padStart(2, "0");
@@ -547,6 +557,9 @@ var freshState = () => ({
547
557
  tools: new ToolInvocationTracker(),
548
558
  lastTurn: void 0,
549
559
  pendingRecoveryAt: 0,
560
+ turnOutput: "unknown",
561
+ outputTurn: void 0,
562
+ outputStartSeq: 0,
550
563
  shortRun: 0,
551
564
  lastShortAt: 0,
552
565
  lastAssistantText: "",
@@ -555,7 +568,8 @@ var freshState = () => ({
555
568
  streamLastSegment: "",
556
569
  streamRepeatRun: 0,
557
570
  loopFired: false,
558
- loopRetryTimer: void 0
571
+ loopRetryTimer: void 0,
572
+ cooldownRetryTimer: void 0
559
573
  });
560
574
  var RECOVERY_WINDOW_MS = 10 * 60 * 1e3;
561
575
  var ECHO_WINDOW_MS = 10 * 60 * 1e3;
@@ -615,6 +629,9 @@ var LOOP_GUARD_CANCEL_CAUSE = {
615
629
  kind: "hook",
616
630
  reason: "dsh-auto-continue:loop-guard"
617
631
  };
632
+ var LOOP_COMPLETED_REASON = "turn/end:completed";
633
+ var LOOP_SILENT_REASON = "turn/end:loop-silent";
634
+ var isLoopReason = (reason) => reason === LOOP_COMPLETED_REASON || reason === LOOP_SILENT_REASON;
618
635
  var STREAM_NEAR_DUPLICATE_MAX_CHARS = 2048;
619
636
  var STREAM_TAIL_MAX_CHARS = 4096;
620
637
  function snapshotSessionEvents(session) {
@@ -648,8 +665,8 @@ function isLoopGuardCancelReason(value) {
648
665
  }
649
666
  var AutoContinueRunner = class {
650
667
  /**
651
- * @param ctx - host plugin context (agents registry, session events, settings).
652
- * @param getConfig - read the current resolved configuration (settings service).
668
+ * @param ctx - host plugin context (agents registry, session events).
669
+ * @param getConfig - read the current resolved configuration (entry config).
653
670
  */
654
671
  constructor(ctx, getConfig) {
655
672
  this.ctx = ctx;
@@ -662,6 +679,7 @@ var AutoContinueRunner = class {
662
679
  this.stateListeners = /* @__PURE__ */ new Set();
663
680
  this.prioritizedFollowups = /* @__PURE__ */ new Set();
664
681
  this.disposed = false;
682
+ this.bootScannedSessions = /* @__PURE__ */ new WeakSet();
665
683
  this.disposeSessionEvents = ctx.on("session/event", (session, event) => {
666
684
  try {
667
685
  this.onHostEvent(session, event);
@@ -758,12 +776,17 @@ var AutoContinueRunner = class {
758
776
  dispose() {
759
777
  if (this.disposed) return;
760
778
  this.disposed = true;
779
+ if (this.bootScanTimer !== void 0) clearTimeout(this.bootScanTimer);
780
+ this.bootScanTimer = void 0;
781
+ this.wakeBootScan?.();
782
+ this.wakeBootScan = void 0;
761
783
  this.disposeSessionEvents();
762
784
  this.disposeInboxEvents();
763
785
  this.prioritizedFollowups.clear();
764
786
  for (const state of this.states.values()) {
765
787
  if (state.pendingTimer !== void 0) clearTimeout(state.pendingTimer);
766
788
  if (state.loopRetryTimer !== void 0) clearTimeout(state.loopRetryTimer);
789
+ if (state.cooldownRetryTimer !== void 0) clearTimeout(state.cooldownRetryTimer);
767
790
  }
768
791
  this.states.clear();
769
792
  }
@@ -787,23 +810,51 @@ var AutoContinueRunner = class {
787
810
  }
788
811
  if (event.type === "tool/call") {
789
812
  const state = this.state(sessionId);
790
- if (state.tools.recordCall(event)) state.shortRun = 0;
813
+ if (state.tools.recordCall(event)) {
814
+ state.shortRun = 0;
815
+ if (this.tracksOutput(state, event)) state.turnOutput = "visible";
816
+ }
791
817
  } else if (event.type === "tool/result") {
792
818
  const state = this.state(sessionId);
793
819
  state.tools.recordResult(event);
794
820
  } else if (event.type === "step/start") {
795
821
  const state = this.state(sessionId);
822
+ if (this.tracksOutput(state, event) && state.turnOutput === "empty") state.turnOutput = "silent";
796
823
  const repeat = state.tools.confirmRepeatAtStep(event.seq);
797
824
  if (repeat !== void 0) this.checkLoop(sessionId, state, repeat);
798
825
  } else if (event.type === "assistant/chunk") {
799
826
  const state = this.state(sessionId);
827
+ if (this.tracksOutput(state, event)) {
828
+ const chunk = event.data.chunk;
829
+ const visible = chunk.type === "text-delta" && chunk.text.trim() !== "" || chunk.type === "tool-call-delta" || chunk.type === "block-end" && this.hasVisibleContent([chunk.block]) || chunk.type === "block-start" && chunk.blockType !== "reasoning" && chunk.blockType !== "text";
830
+ if (visible) state.turnOutput = "visible";
831
+ else if (state.turnOutput === "empty" && chunk.type !== "usage" && chunk.type !== "finish") state.turnOutput = "silent";
832
+ }
800
833
  this.onAssistantChunk(sessionId, state, event);
801
834
  } else if (event.type === "assistant/message") {
802
835
  const state = this.state(sessionId);
836
+ if (this.tracksOutput(state, event)) {
837
+ if (this.hasVisibleContent(event.data.message.content)) state.turnOutput = "visible";
838
+ else if (state.turnOutput === "empty") state.turnOutput = "silent";
839
+ }
803
840
  this.onAssistantMessage(sessionId, state, event);
804
841
  }
805
842
  this.onSessionEvent(sessionId, event);
806
843
  }
844
+ tracksOutput(state, event) {
845
+ return state.running === true && state.outputTurn === event.data.turn && event.seq > state.outputStartSeq;
846
+ }
847
+ /** Treat unknown block kinds conservatively: only reasoning and blank text are silent. */
848
+ hasVisibleContent(content) {
849
+ if (!Array.isArray(content)) return false;
850
+ return content.some((part) => {
851
+ if (part === null || typeof part !== "object") return true;
852
+ const block = part;
853
+ if (block.type === "reasoning") return false;
854
+ if (block.type === "text") return typeof block.text !== "string" || block.text.trim() !== "";
855
+ return true;
856
+ });
857
+ }
807
858
  /** 从 assistant/message 事件提取纯文本。 */
808
859
  assistantText(event) {
809
860
  const content = event.data.message.content;
@@ -988,6 +1039,9 @@ var AutoContinueRunner = class {
988
1039
  state.streamLastSegment = "";
989
1040
  state.streamRepeatRun = 0;
990
1041
  state.loopFired = false;
1042
+ state.turnOutput = "empty";
1043
+ state.outputTurn = event.data.turn;
1044
+ state.outputStartSeq = event.seq;
991
1045
  if (state.loopRetryTimer !== void 0) {
992
1046
  clearTimeout(state.loopRetryTimer);
993
1047
  state.loopRetryTimer = void 0;
@@ -999,16 +1053,40 @@ var AutoContinueRunner = class {
999
1053
  const loopCancelPending = state.loopFired;
1000
1054
  state.loopFired = false;
1001
1055
  this.cancelPending(sessionId, "收到新的 turn/end");
1056
+ const turnOutput = state.outputTurn === event.data.turn ? state.turnOutput : "unknown";
1057
+ state.turnOutput = "unknown";
1058
+ state.outputTurn = void 0;
1002
1059
  const reason = event.data.reason;
1003
1060
  const reasonKind = readReasonKind(reason);
1004
1061
  if (reasonKind === void 0) {
1005
1062
  console.error(`[auto-continue] 忽略畸形 turn/end ${sessionId}: reason 无法解释`);
1006
1063
  break;
1007
1064
  }
1008
- if (reasonKind === "completed") {
1009
- state.consecutive = 0;
1065
+ if (reasonKind === "no-visible-output" || reasonKind === "completed" && turnOutput === "silent") {
1010
1066
  state.lastFailure = void 0;
1011
- this.noteRecovery(sessionId, "completed");
1067
+ state.lastTurn = event.data.turn;
1068
+ state.lastFailureAt = Date.now();
1069
+ this.noteRecovery(sessionId, "error");
1070
+ if (this.getConfig().resumeCompletedTurns) {
1071
+ this.schedule(sessionId, LOOP_SILENT_REASON);
1072
+ } else if (this.getConfig().resumeSilentTurns) {
1073
+ this.schedule(sessionId, `turn/end:${reasonKind}:silent`);
1074
+ }
1075
+ break;
1076
+ }
1077
+ if (reasonKind === "completed") {
1078
+ if (this.getConfig().resumeCompletedTurns) {
1079
+ if (turnOutput === "visible") {
1080
+ state.consecutive = 0;
1081
+ state.lastFailure = void 0;
1082
+ this.noteRecovery(sessionId, "completed");
1083
+ }
1084
+ this.schedule(sessionId, LOOP_COMPLETED_REASON, true);
1085
+ } else if (turnOutput === "visible") {
1086
+ state.consecutive = 0;
1087
+ state.lastFailure = void 0;
1088
+ this.noteRecovery(sessionId, "completed");
1089
+ }
1012
1090
  } else if (reasonKind === "aborted") {
1013
1091
  if (isLoopGuardCancelReason(reason.reason)) {
1014
1092
  if (loopCancelPending) this.bumpStat({ looped: 1 });
@@ -1032,7 +1110,7 @@ var AutoContinueRunner = class {
1032
1110
  } catch (error) {
1033
1111
  console.error(`[auto-continue] loop 重启异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
1034
1112
  }
1035
- }, remaining);
1113
+ }, remaining + 10);
1036
1114
  this.log(`loop 重启延迟 ${remaining}ms(冷却期) ${sessionId}`);
1037
1115
  } else {
1038
1116
  this.schedule(sessionId, "loop:aborted");
@@ -1128,6 +1206,7 @@ var AutoContinueRunner = class {
1128
1206
  if (delta.code !== void 0) {
1129
1207
  this.dayStats.byCode[delta.code] = (this.dayStats.byCode[delta.code] ?? 0) + 1;
1130
1208
  }
1209
+ this.emitState();
1131
1210
  }
1132
1211
  /** 通知桥: 产生一条通知事件, SSE 端点推给 browser 侧展示。 */
1133
1212
  notify(sessionId, title, body, options) {
@@ -1180,7 +1259,7 @@ var AutoContinueRunner = class {
1180
1259
  config.backoffMaxMs
1181
1260
  );
1182
1261
  }
1183
- schedule(sessionId, reason) {
1262
+ schedule(sessionId, reason, force = false) {
1184
1263
  const state = this.state(sessionId);
1185
1264
  const config = this.getConfig();
1186
1265
  if (state.subagent) return;
@@ -1193,39 +1272,80 @@ var AutoContinueRunner = class {
1193
1272
  return;
1194
1273
  }
1195
1274
  if (state.pendingTimer !== void 0) return;
1196
- if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) return;
1197
- if (state.consecutive >= config.maxConsecutive) {
1275
+ if (!force && state.consecutive >= config.maxConsecutive) {
1198
1276
  this.log(
1199
1277
  `跳过 ${sessionId}(${reason}): 已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`
1200
1278
  );
1201
1279
  return;
1202
1280
  }
1281
+ if (!force) {
1282
+ const remaining = this.cooldownFor(state) - (Date.now() - state.lastAttemptAt);
1283
+ if (remaining > 0) {
1284
+ this.deferCooldownRetry(sessionId, reason, remaining);
1285
+ return;
1286
+ }
1287
+ }
1203
1288
  const timer = setTimeout(() => {
1204
1289
  if (state.pendingTimer !== timer) return;
1205
1290
  state.pendingTimer = void 0;
1206
1291
  try {
1207
- void this.fire(sessionId, reason);
1292
+ void this.fire(sessionId, reason, force);
1208
1293
  } catch (error) {
1209
1294
  console.error(`[auto-continue] 定时发送异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
1210
1295
  }
1211
1296
  }, config.graceMs);
1212
1297
  state.pendingTimer = timer;
1213
- const template = reason.startsWith("loop:") ? config.loopText : reason.includes("max-tokens") ? config.continueTextMaxTokens : config.continueText;
1298
+ const template = this.templateFor(config, reason);
1214
1299
  this.log(
1215
1300
  `检测到非人为中断 ${sessionId}(${reason}), ${config.graceMs}ms 后自动发送「${template}」`
1216
1301
  );
1217
1302
  }
1303
+ /**
1304
+ * 冷却期内的恢复: 等到冷却结束再重新调度。
1305
+ * 直接丢弃会让一次瞬时失败把会话搁置, 直到用户手动发消息才恢复。
1306
+ */
1307
+ deferCooldownRetry(sessionId, reason, remaining) {
1308
+ const state = this.state(sessionId);
1309
+ if (state.cooldownRetryTimer !== void 0) clearTimeout(state.cooldownRetryTimer);
1310
+ state.cooldownRetryTimer = setTimeout(() => {
1311
+ state.cooldownRetryTimer = void 0;
1312
+ try {
1313
+ this.schedule(sessionId, reason);
1314
+ } catch (error) {
1315
+ console.error(`[auto-continue] 冷却后重试异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
1316
+ }
1317
+ }, remaining + 10);
1318
+ this.log(`冷却中 ${sessionId}(${reason}), ${remaining}ms 后重试`);
1319
+ }
1320
+ /** 按调度原因选择续跑模板: loop 重启、无输出回合、max-tokens、自主循环, 其余用通用继续文本。 */
1321
+ templateFor(config, reason) {
1322
+ if (reason.startsWith("loop:")) return config.loopText;
1323
+ if (isLoopReason(reason)) return config.continueTextLoop;
1324
+ if (reason.endsWith(":silent")) return config.continueTextSilent;
1325
+ if (reason.includes("max-tokens")) return config.continueTextMaxTokens;
1326
+ return config.continueText;
1327
+ }
1218
1328
  cancelPending(sessionId, why) {
1219
1329
  const state = this.state(sessionId);
1220
- if (state.pendingTimer === void 0) return;
1221
- clearTimeout(state.pendingTimer);
1222
- state.pendingTimer = void 0;
1223
- this.log(`取消 ${sessionId} 的自动继续(${why})`);
1330
+ let cancelled = false;
1331
+ if (state.pendingTimer !== void 0) {
1332
+ clearTimeout(state.pendingTimer);
1333
+ state.pendingTimer = void 0;
1334
+ cancelled = true;
1335
+ }
1336
+ if (state.cooldownRetryTimer !== void 0) {
1337
+ clearTimeout(state.cooldownRetryTimer);
1338
+ state.cooldownRetryTimer = void 0;
1339
+ cancelled = true;
1340
+ }
1341
+ if (cancelled) this.log(`取消 ${sessionId} 的自动继续(${why})`);
1224
1342
  }
1225
1343
  fire(sessionId, reason, force = false) {
1226
1344
  if (this.disposed) return;
1227
1345
  const state = this.state(sessionId);
1228
1346
  const config = this.getConfig();
1347
+ if (reason.endsWith(":silent") && !config.resumeSilentTurns) return;
1348
+ if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
1229
1349
  if (state.subagent) return;
1230
1350
  if (config.paused) {
1231
1351
  this.log(`跳过 ${sessionId}(${reason}): 全局暂停中`);
@@ -1243,7 +1363,7 @@ var AutoContinueRunner = class {
1243
1363
  this.log(`跳过 ${sessionId}(${reason}): 已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`);
1244
1364
  return;
1245
1365
  }
1246
- const template = reason.startsWith("loop:") ? config.loopText : reason.includes("max-tokens") ? config.continueTextMaxTokens : config.continueText;
1366
+ const template = this.templateFor(config, reason);
1247
1367
  const text = this.buildContinueText(config, state, template);
1248
1368
  const agent = this.ctx.agents.get(sessionId);
1249
1369
  if (agent === void 0) {
@@ -1267,7 +1387,7 @@ var AutoContinueRunner = class {
1267
1387
  this.prioritizedFollowups.delete(message.id);
1268
1388
  }
1269
1389
  const now = Date.now();
1270
- state.consecutive += 1;
1390
+ if (reason !== LOOP_COMPLETED_REASON) state.consecutive += 1;
1271
1391
  state.pendingRecoveryAt = now;
1272
1392
  this.bumpStat({ sent: 1, ...state.lastFailure !== void 0 ? { code: state.lastFailure.code } : {} });
1273
1393
  this.log(`已自动发送「${text}」到 ${sessionId}(${reason}), 第 ${state.consecutive} 次连续`);
@@ -1326,98 +1446,111 @@ var AutoContinueRunner = class {
1326
1446
  return state.tools.guard();
1327
1447
  }
1328
1448
  async bootScanLoop() {
1329
- await this.scanLoop(Infinity, 3e3);
1330
- }
1331
- /** 反复尝试扫描, 直到成功(宿主就绪)或达到次数上限。 */
1332
- async scanLoop(attempts, delayMs) {
1333
- for (let attempt = 0; attempt < attempts && !this.disposed; attempt += 1) {
1449
+ const deadline = Date.now() + this.getConfig().freshMs;
1450
+ for (let attempt = 0; !this.disposed; attempt += 1) {
1451
+ if (attempt > 0 && Date.now() >= deadline) return;
1334
1452
  try {
1335
1453
  if (await this.scanInterrupted()) return;
1336
1454
  } catch (error) {
1337
1455
  if (this.disposed) return;
1338
1456
  if (attempt % 10 === 0) {
1339
1457
  this.log(
1340
- `扫描失败(${attempt + 1}/${attempts === Infinity ? "∞" : attempts}): ${error instanceof Error ? error.message : String(error)}`
1458
+ `扫描失败(${attempt + 1}): ${error instanceof Error ? error.message : String(error)}`
1341
1459
  );
1342
1460
  }
1343
1461
  }
1344
- if (attempt + 1 < attempts) await sleep(delayMs);
1462
+ const remaining = deadline - Date.now();
1463
+ if (this.disposed || remaining <= 0) return;
1464
+ await new Promise((resolve) => {
1465
+ this.wakeBootScan = resolve;
1466
+ this.bootScanTimer = setTimeout(() => {
1467
+ this.bootScanTimer = void 0;
1468
+ this.wakeBootScan = void 0;
1469
+ resolve();
1470
+ }, Math.min(3e3, remaining));
1471
+ });
1345
1472
  }
1346
1473
  }
1347
- /**
1348
- * 扫描最近中断过的会话: 最后回合以非人为原因结束, 且其后没有新回合或用户消息。
1349
- * @returns 是否成功完成一次扫描(宿主就绪)。
1350
- */
1474
+ /** Inspect newly available sessions; process each settled startup history once. */
1351
1475
  async scanInterrupted() {
1352
1476
  const config = this.getConfig();
1353
- if (config.paused) return true;
1477
+ if (config.paused || !config.scanOnBoot) return false;
1354
1478
  const now = Date.now();
1355
1479
  const candidates = [];
1356
1480
  for (const agent of this.ctx.agents.list()) {
1357
1481
  const session = agent.session;
1358
- if (session.header.origin === "subagent") continue;
1359
- const events = snapshotSessionEvents(session);
1360
- const lastActivityAt = events.reduce(
1361
- (latest, event) => Math.max(latest, event.time),
1362
- Number.isFinite(session.header.createdAt) ? session.header.createdAt : 0
1363
- );
1364
- candidates.push({
1365
- sessionId: session.id,
1366
- events,
1367
- lastActivityAt,
1368
- listIndex: candidates.length
1369
- });
1370
- }
1371
- candidates.sort(
1372
- (left, right) => right.lastActivityAt - left.lastActivityAt || left.listIndex - right.listIndex
1373
- );
1374
- for (const candidate of candidates.slice(0, config.scanLimit)) {
1375
- if (this.disposed) return true;
1376
- const state = this.state(candidate.sessionId);
1377
- if (state.pendingTimer !== void 0) continue;
1378
- if (state.consecutive >= config.maxConsecutive) continue;
1482
+ if (session.header.origin === "subagent" || this.bootScannedSessions.has(session)) continue;
1483
+ const state = this.state(session.id);
1484
+ if (state.pendingTimer !== void 0 || state.consecutive >= config.maxConsecutive) continue;
1379
1485
  if (now - state.lastAttemptAt < this.cooldownFor(state)) continue;
1380
- if (now < (this.pauseUntil.get(candidate.sessionId) ?? 0)) continue;
1381
- const events = candidate.events;
1486
+ if (now < (this.pauseUntil.get(session.id) ?? 0)) continue;
1487
+ const events = snapshotSessionEvents(session);
1488
+ if (events.length === 0) continue;
1382
1489
  let lastEnd;
1383
1490
  for (let i = events.length - 1; i >= 0; i -= 1) {
1384
1491
  const event = events[i];
1385
- if (event !== void 0 && event.type === "turn/end") {
1492
+ if (event?.type === "turn/end") {
1386
1493
  lastEnd = event;
1387
1494
  break;
1388
1495
  }
1389
1496
  }
1390
- if (lastEnd === void 0) continue;
1391
- const reason = lastEnd.data.reason;
1392
- const reasonKind = readReasonKind(reason);
1393
- if (reasonKind === void 0 || !isNonHumanReason(reasonKind)) continue;
1394
- if (lastEnd.time < now - config.freshMs) continue;
1395
- let superseded = false;
1396
- for (const event of events) {
1397
- if (event.seq <= lastEnd.seq) continue;
1398
- if (event.type === "turn/start") superseded = true;
1399
- if (event.type === "user/message" && event.data.source.kind === "user") superseded = true;
1400
- if (superseded) break;
1497
+ const reasonKind = readReasonKind(lastEnd?.data.reason);
1498
+ const silent = reasonKind === "no-visible-output" && config.resumeSilentTurns;
1499
+ const superseded = lastEnd !== void 0 && events.some(
1500
+ (event) => event.seq > lastEnd.seq && (event.type === "turn/start" || event.type === "user/message" && event.data.source.kind === "user")
1501
+ );
1502
+ if (lastEnd === void 0 || reasonKind === void 0 || !isNonHumanReason(reasonKind) && !silent || lastEnd.time < now - config.freshMs || superseded) {
1503
+ this.bootScannedSessions.add(session);
1504
+ continue;
1401
1505
  }
1402
- if (superseded) continue;
1403
- this.applyGuardFromEvents(state, events, lastEnd.seq);
1404
- const scanReason = `scan:turn/end:${reasonKind}`;
1405
- this.log(`扫描发现中断 ${candidate.sessionId}(turn/end:${reasonKind}), 交给恢复策略处理`);
1506
+ let failure;
1406
1507
  if (reasonKind === "error") {
1407
- const failure = parseFailureFacts(reason.error);
1508
+ failure = parseFailureFacts(lastEnd.data.reason.error);
1408
1509
  if (failure === void 0) {
1409
- console.error(`[auto-continue] 忽略畸形扫描 turn/end ${candidate.sessionId}: error details 无法解释`);
1510
+ this.bootScannedSessions.add(session);
1511
+ console.error(`[auto-continue] 忽略畸形扫描 turn/end ${session.id}: error details 无法解释`);
1512
+ continue;
1513
+ }
1514
+ if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
1515
+ this.bootScannedSessions.add(session);
1516
+ this.onTurnFailure(session.id, "scan:turn/end:error", failure);
1410
1517
  continue;
1411
1518
  }
1519
+ }
1520
+ candidates.push({
1521
+ session,
1522
+ events,
1523
+ lastEnd,
1524
+ reasonKind,
1525
+ failure,
1526
+ lastActivityAt: events.reduce((latest, event) => Math.max(latest, event.time), 0),
1527
+ listIndex: candidates.length
1528
+ });
1529
+ }
1530
+ candidates.sort((left, right) => right.lastActivityAt - left.lastActivityAt || left.listIndex - right.listIndex);
1531
+ for (const candidate of candidates.slice(0, config.scanLimit)) {
1532
+ if (this.disposed) return true;
1533
+ const { session, events, lastEnd, reasonKind, failure } = candidate;
1534
+ this.bootScannedSessions.add(session);
1535
+ const state = this.state(session.id);
1536
+ this.applyGuardFromEvents(state, events, lastEnd.seq);
1537
+ const scanReason = `scan:turn/end:${reasonKind}${reasonKind === "no-visible-output" ? ":silent" : ""}`;
1538
+ this.log(`扫描发现中断 ${session.id}(turn/end:${reasonKind}), 交给恢复策略处理`);
1539
+ if (failure !== void 0) {
1412
1540
  state.lastFailure = failure;
1413
1541
  state.lastTurn = lastEnd.data.turn;
1414
1542
  state.lastFailureAt = lastEnd.time;
1415
- this.onTurnFailure(candidate.sessionId, scanReason, state.lastFailure);
1543
+ this.onTurnFailure(session.id, scanReason, failure);
1416
1544
  } else {
1417
- this.schedule(candidate.sessionId, scanReason);
1545
+ if (reasonKind === "no-visible-output") {
1546
+ state.lastFailure = void 0;
1547
+ state.lastTurn = lastEnd.data.turn;
1548
+ state.lastFailureAt = lastEnd.time;
1549
+ }
1550
+ this.schedule(session.id, scanReason);
1418
1551
  }
1419
1552
  }
1420
- return true;
1553
+ return false;
1421
1554
  }
1422
1555
  /** 从历史事件恢复上一步工具调用状态(扫描路径的幂等护栏)。 */
1423
1556
  applyGuardFromEvents(state, events, untilSeq) {
@@ -1427,7 +1560,6 @@ var AutoContinueRunner = class {
1427
1560
 
1428
1561
  // src/index.ts
1429
1562
  var AUTO_CONTINUE_NS = "auto-continue";
1430
- var SETTINGS_NS = AUTO_CONTINUE_NS;
1431
1563
  var AutoContinueSchema = z2.object({
1432
1564
  /** Active browser/UI locale mirrored by the client. */
1433
1565
  locale: z2.string().default("zh"),
@@ -1435,6 +1567,14 @@ var AutoContinueSchema = z2.object({
1435
1567
  continueText: z2.string().default(""),
1436
1568
  /** Text sent when the output token ceiling is reached (same placeholders as `continueText`). */
1437
1569
  continueTextMaxTokens: z2.string().default(""),
1570
+ /** Resume observed model activity that completes without visible output. */
1571
+ resumeSilentTurns: z2.boolean().default(true),
1572
+ /** 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. */
1573
+ resumeCompletedTurns: z2.boolean().default(false),
1574
+ /** Text sent to resume a silent turn (same placeholders as `continueText`). */
1575
+ continueTextSilent: z2.string().default(""),
1576
+ /** Text sent for each autonomous-loop continuation (same placeholders as `continueText`). */
1577
+ continueTextLoop: z2.string().default(""),
1438
1578
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
1439
1579
  guardTools: z2.boolean().default(true),
1440
1580
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -1447,11 +1587,11 @@ var AutoContinueSchema = z2.object({
1447
1587
  cooldownMs: z2.natural().default(2e4),
1448
1588
  /** Max consecutive auto-continues per session before stopping. */
1449
1589
  maxConsecutive: z2.natural().min(1).default(3),
1450
- /** Scan recently interrupted sessions on page load / reconnect. */
1590
+ /** Recover delayed interrupted sessions during the host startup window. */
1451
1591
  scanOnBoot: z2.boolean().default(true),
1452
- /** Max sessions the scan checks (most recently updated). */
1592
+ /** Max eligible recoveries per scan pass (most recently active first). */
1453
1593
  scanLimit: z2.natural().min(1).default(8),
1454
- /** Scan only considers interruptions inside this window (ms). */
1594
+ /** Interruption freshness and duration of startup polling (ms). */
1455
1595
  freshMs: z2.natural().default(15 * 60 * 1e3),
1456
1596
  /** Log `[auto-continue]` lines to the browser console. */
1457
1597
  verbose: z2.boolean().default(true),
@@ -1482,21 +1622,29 @@ var AutoContinueSchema = z2.object({
1482
1622
  /** Text sent after the loop guard cancels and restarts a turn (supports {tool}). */
1483
1623
  loopText: z2.string().default("")
1484
1624
  });
1485
- function apply(ctx) {
1625
+ var entrySchema = AutoContinueSchema;
1626
+ var Config = entrySchema.volatile?.() ?? AutoContinueSchema;
1627
+ function entryConfig(config) {
1628
+ return config !== void 0 && "get" in config ? config.get() : config;
1629
+ }
1630
+ function apply(ctx, config) {
1631
+ let legacyConfig;
1486
1632
  ctx.inject(["settings"], (settingsCtx) => {
1487
- settingsCtx.settings.register(SETTINGS_NS, AutoContinueSchema, {
1488
- applies: "live"
1633
+ const settings = settingsCtx.settings;
1634
+ if (typeof settings.register !== "function" || typeof settings.get !== "function") return;
1635
+ settings.register(AUTO_CONTINUE_NS, AutoContinueSchema, { applies: "live" });
1636
+ const read = () => settings.get(AUTO_CONTINUE_NS);
1637
+ legacyConfig = read;
1638
+ settingsCtx.effect(() => () => {
1639
+ if (legacyConfig === read) legacyConfig = void 0;
1489
1640
  });
1490
1641
  });
1491
- let runnerRef;
1492
- ctx.inject(["settings", "agents", "webServer"], (engineCtx) => {
1493
- if (runnerRef !== void 0) runnerRef.dispose();
1494
- const runner = new AutoContinueRunner(
1495
- engineCtx,
1496
- () => resolveConfig(engineCtx.settings.get(SETTINGS_NS))
1497
- );
1498
- runnerRef = runner;
1642
+ let disposeEngine;
1643
+ ctx.inject(["agents", "webServer"], (engineCtx) => {
1644
+ disposeEngine?.();
1645
+ const runner = new AutoContinueRunner(engineCtx, () => resolveConfig(legacyConfig?.() ?? entryConfig(config)));
1499
1646
  const sseClients = /* @__PURE__ */ new Set();
1647
+ const closeClients = /* @__PURE__ */ new Set();
1500
1648
  const pushToAll = (data) => {
1501
1649
  for (const send of sseClients) {
1502
1650
  try {
@@ -1523,7 +1671,7 @@ function apply(ctx) {
1523
1671
 
1524
1672
  `);
1525
1673
  });
1526
- engineCtx.webServer.register({
1674
+ const stopBridge = engineCtx.webServer.register({
1527
1675
  kind: "exact",
1528
1676
  path: "/api/auto-continue-bridge",
1529
1677
  handler: (req, res) => {
@@ -1539,10 +1687,17 @@ function apply(ctx) {
1539
1687
  res.write(data);
1540
1688
  };
1541
1689
  sseClients.add(send);
1542
- req.on("close", () => sseClients.delete(send));
1690
+ const close = () => {
1691
+ res.end();
1692
+ };
1693
+ closeClients.add(close);
1694
+ req.on("close", () => {
1695
+ sseClients.delete(send);
1696
+ closeClients.delete(close);
1697
+ });
1543
1698
  }
1544
1699
  });
1545
- engineCtx.webServer.register({
1700
+ const stopActions = engineCtx.webServer.register({
1546
1701
  kind: "exact",
1547
1702
  path: "/api/auto-continue-action",
1548
1703
  handler: (req, res) => {
@@ -1569,15 +1724,29 @@ function apply(ctx) {
1569
1724
  });
1570
1725
  }
1571
1726
  });
1727
+ let disposed = false;
1728
+ const dispose = () => {
1729
+ if (disposed) return;
1730
+ disposed = true;
1731
+ runner.dispose();
1732
+ stopBridge();
1733
+ stopActions();
1734
+ for (const close of closeClients) close();
1735
+ closeClients.clear();
1736
+ sseClients.clear();
1737
+ };
1738
+ disposeEngine = dispose;
1739
+ engineCtx.effect(() => dispose);
1572
1740
  });
1573
1741
  ctx.effect(() => () => {
1574
- const runner = runnerRef;
1575
- runnerRef = void 0;
1576
- if (runner !== void 0) runner.dispose();
1742
+ const dispose = disposeEngine;
1743
+ disposeEngine = void 0;
1744
+ dispose?.();
1577
1745
  });
1578
1746
  }
1579
1747
  export {
1580
1748
  AUTO_CONTINUE_NS,
1581
1749
  AutoContinueSchema,
1750
+ Config,
1582
1751
  apply
1583
1752
  };