dsh-client-auto-continue 0.20.2 → 0.21.1

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
@@ -1140,6 +1140,7 @@ var LOCALIZED_TEXT_DEFAULTS = {
1140
1140
  continueTextSilent: "继续。你上一轮只输出了内部推理, 既没有回复也没有调用工具, 用户什么都没看到。每一轮都要以工具调用或可见回复结束。",
1141
1141
  continueTextLoop: "继续",
1142
1142
  continueTextInterrupted: "继续。宿主在你上一轮运行期间重启了; 重启时未完成的工具调用已按「结果未知」收尾。从中断处继续, 重试可能有副作用的操作前先核实外部状态。",
1143
+ continueTextQuestion: "这是宿主重启后插件自动发送的消息, 不是用户的回复。你上一步向用户提出的问题因重启中断, 用户还没有回答。请重新提出同一个问题并等待回答, 不要替用户做决定。",
1143
1144
  guardPendingText: "(上一步工具「{tool}」可能未完成, 先确认状态再继续, 不要重复执行)",
1144
1145
  guardDoneText: "(上一步工具「{tool}」已完成, 结果: {result}; 不要重复执行, 直接继续)",
1145
1146
  loopText: "(检测到你可能陷入循环, 请停止重复刚才的动作, 换一种方式继续)"
@@ -1150,6 +1151,7 @@ var LOCALIZED_TEXT_DEFAULTS = {
1150
1151
  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.",
1151
1152
  continueTextLoop: "Continue",
1152
1153
  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.",
1154
+ continueTextQuestion: "This message was sent automatically by the plugin after a harness restart; it is not the user's reply. The question you asked the user was cut off by the restart and has not been answered. Ask the same question again and wait for the answer; do not decide for the user.",
1153
1155
  guardPendingText: '(The previous tool "{tool}" may not have completed. Check its state before continuing and do not run it again.)',
1154
1156
  guardDoneText: '(The previous tool "{tool}" completed successfully. Result: {result}; do not run it again. Continue from there.)',
1155
1157
  loopText: "(You may be stuck in a loop. Stop repeating the last action and continue with a different approach.)"
@@ -1160,6 +1162,7 @@ var LOCALIZED_TEXT_DEFAULTS = {
1160
1162
  continueTextSilent: "Продолжай. Предыдущий ход закончился только внутренним рассуждением: ни ответа, ни вызова инструмента, поэтому пользователь ничего не увидел. Каждый ход должен заканчиваться вызовом инструмента или видимым ответом.",
1161
1163
  continueTextLoop: "Продолжай",
1162
1164
  continueTextInterrupted: "Продолжай. Хост перезапустился, пока предыдущий ход ещё выполнялся; вызовы инструментов, незавершённые на момент перезапуска, записаны с неизвестным результатом. Продолжай с места остановки, проверяя внешнее состояние перед повтором действий с возможными побочными эффектами.",
1165
+ continueTextQuestion: "Это сообщение плагин отправил автоматически после перезапуска хоста, это не ответ пользователя. Вопрос, который ты задал пользователю, прервался из-за перезапуска, и ответа на него ещё нет. Задай тот же вопрос снова и дождись ответа, не принимай решение за пользователя.",
1163
1166
  guardPendingText: "(Предыдущий инструмент «{tool}», возможно, не завершился. Проверь его состояние перед продолжением и не запускай его повторно.)",
1164
1167
  guardDoneText: "(Предыдущий инструмент «{tool}» завершился успешно. Результат: {result}; не запускай его повторно, продолжай с этого места.)",
1165
1168
  loopText: "(Похоже, ты застрял в цикле. Перестань повторять последнее действие и продолжай другим способом.)"
@@ -1217,6 +1220,7 @@ function resolveConfig(section) {
1217
1220
  const silentText = typeof value.continueTextSilent === "string" && value.continueTextSilent.trim() !== "" ? value.continueTextSilent : localized.continueTextSilent;
1218
1221
  const loopText = typeof value.continueTextLoop === "string" && value.continueTextLoop.trim() !== "" ? value.continueTextLoop : localized.continueTextLoop;
1219
1222
  const interruptedText = typeof value.continueTextInterrupted === "string" && value.continueTextInterrupted.trim() !== "" ? value.continueTextInterrupted : localized.continueTextInterrupted;
1223
+ const questionText = typeof value.continueTextQuestion === "string" && value.continueTextQuestion.trim() !== "" ? value.continueTextQuestion : localized.continueTextQuestion;
1220
1224
  const guardPendingText = typeof value.guardPendingText === "string" && value.guardPendingText.trim() !== "" ? value.guardPendingText : localized.guardPendingText;
1221
1225
  const guardDoneText = typeof value.guardDoneText === "string" && value.guardDoneText.trim() !== "" ? value.guardDoneText : localized.guardDoneText;
1222
1226
  return {
@@ -1230,6 +1234,7 @@ function resolveConfig(section) {
1230
1234
  continueTextSilent: silentText,
1231
1235
  continueTextLoop: loopText,
1232
1236
  continueTextInterrupted: interruptedText,
1237
+ continueTextQuestion: questionText,
1233
1238
  guardTools: booleanOr(value.guardTools, DEFAULT_CONFIG.guardTools),
1234
1239
  guardPendingText,
1235
1240
  guardDoneText,
@@ -1782,6 +1787,7 @@ var LOOP_GUARD_CANCEL_CAUSE = {
1782
1787
  var LOOP_COMPLETED_REASON = "turn/end:completed";
1783
1788
  var LOOP_SILENT_REASON = "turn/end:loop-silent";
1784
1789
  var MANUAL_NOTIFICATION_REASON = "manual:notification";
1790
+ var ASK_USER_QUESTION_TOOL = "ask_user_question";
1785
1791
  var SWEEP_OBSERVE_BATCH = 16;
1786
1792
  var STORED_READ_TIMEOUT_MS = 5e3;
1787
1793
  var SWEEP_MAX_FAILURES = 3;
@@ -1882,6 +1888,17 @@ function isHostCancel(value) {
1882
1888
  const cause = readCancelCause(value);
1883
1889
  return cause !== void 0 && RESTART_CANCEL_CAUSES.has(cause);
1884
1890
  }
1891
+ function goalStoppedByUser(events) {
1892
+ for (let index = events.length - 1; index >= 0; index -= 1) {
1893
+ const event = events[index];
1894
+ if (event.type === "goal/change") {
1895
+ if (event.data?.operation === "resume" || event.data?.operation === "create") return false;
1896
+ } else if (event.type === "turn/end" && readCancelCause(event.data?.reason) === "user") {
1897
+ return true;
1898
+ }
1899
+ }
1900
+ return false;
1901
+ }
1885
1902
  function classifyChildInterruption(events, config) {
1886
1903
  let lastEnd;
1887
1904
  for (let i = events.length - 1; i >= 0; i -= 1) {
@@ -1939,6 +1956,50 @@ function isLoopGuardCancelReason(value) {
1939
1956
  const cause = value;
1940
1957
  return cause.kind === LOOP_GUARD_CANCEL_CAUSE.kind && cause.reason === LOOP_GUARD_CANCEL_CAUSE.reason;
1941
1958
  }
1959
+ var TEMPLATE_PLACEHOLDER = /\{(?:code|message|status|tool|turn|errorCount|sessionTitle|elapsed|result)\}/;
1960
+ function templateParts(template) {
1961
+ const parts = template.split(TEMPLATE_PLACEHOLDER);
1962
+ return parts.join("").trim() === "" ? void 0 : parts;
1963
+ }
1964
+ function matchesParts(text, parts) {
1965
+ const first = parts[0] ?? "";
1966
+ if (parts.length === 1) return text === first;
1967
+ const last = parts[parts.length - 1] ?? "";
1968
+ if (text.length < first.length + last.length || !text.startsWith(first) || !text.endsWith(last)) return false;
1969
+ const end = text.length - last.length;
1970
+ let at = first.length;
1971
+ for (let i = 1; i < parts.length - 1; i += 1) {
1972
+ const part = parts[i] ?? "";
1973
+ const found = text.indexOf(part, at);
1974
+ if (found < 0 || found + part.length > end) return false;
1975
+ at = found + part.length;
1976
+ }
1977
+ return true;
1978
+ }
1979
+ function joinParts(left, separator, right) {
1980
+ return [...left.slice(0, -1), `${left[left.length - 1] ?? ""}${separator}${right[0] ?? ""}`, ...right.slice(1)];
1981
+ }
1982
+ var definedParts = (templates) => templates.map(templateParts).filter((parts) => parts !== void 0);
1983
+ var HANDOFF_SHAPES = definedParts(Object.values(HANDOFF_COPY).map((copy) => copy("{code}", "{code}")));
1984
+ var isHandoffText = (text) => HANDOFF_SHAPES.some((parts) => matchesParts(text, parts));
1985
+ function continueTextMatcher(config) {
1986
+ const texts = definedParts([
1987
+ config.continueText,
1988
+ config.continueTextMaxTokens,
1989
+ config.continueTextSilent,
1990
+ config.continueTextLoop,
1991
+ config.continueTextInterrupted,
1992
+ config.continueTextQuestion,
1993
+ config.loopText
1994
+ ]);
1995
+ const guards = definedParts([config.guardPendingText, config.guardDoneText]);
1996
+ const shapes = texts.flatMap((text) => [text, ...guards.map((guard) => joinParts(text, " ", guard))]);
1997
+ return (text) => shapes.some((parts) => matchesParts(text, parts));
1998
+ }
1999
+ function messageText(content) {
2000
+ if (!Array.isArray(content)) return "";
2001
+ return content.map((block) => block?.type === "text" && typeof block.text === "string" ? block.text : "").join("");
2002
+ }
1942
2003
  var LINEAGE_CACHE_LIMIT = 2e3;
1943
2004
  var AutoContinueRunner = class {
1944
2005
  /**
@@ -2346,8 +2407,7 @@ var AutoContinueRunner = class {
2346
2407
  const state = this.state(sessionId);
2347
2408
  if (this.tracksOutput(state, event)) {
2348
2409
  const chunk = event.data.chunk;
2349
- 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";
2350
- if (visible) state.turnOutput = "visible";
2410
+ if (this.chunkVisible(chunk)) state.turnOutput = "visible";
2351
2411
  else if (state.turnOutput === "empty" && chunk.type !== "usage" && chunk.type !== "finish") state.turnOutput = "silent";
2352
2412
  }
2353
2413
  this.onAssistantChunk(sessionId, state, event);
@@ -2364,6 +2424,9 @@ var AutoContinueRunner = class {
2364
2424
  tracksOutput(state, event) {
2365
2425
  return state.running === true && state.outputTurn === event.data.turn && event.seq > state.outputStartSeq;
2366
2426
  }
2427
+ chunkVisible(chunk) {
2428
+ return 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";
2429
+ }
2367
2430
  /** Treat unknown block kinds conservatively: only reasoning and blank text are silent. */
2368
2431
  hasVisibleContent(content) {
2369
2432
  if (!Array.isArray(content)) return false;
@@ -2962,7 +3025,7 @@ var AutoContinueRunner = class {
2962
3025
  * The child's own recovery mode decides; the parent only has to be alive to
2963
3026
  * authorize the call.
2964
3027
  */
2965
- async reviveChild(sessionId, reason, text, force) {
3028
+ async reviveChild(sessionId, reason, text, force, checkGoal) {
2966
3029
  if (this.disposed || this.getConfig().paused) return;
2967
3030
  if (!this.subagentRecoveryEnabled(sessionId)) return;
2968
3031
  const state = this.state(sessionId);
@@ -2981,6 +3044,21 @@ var AutoContinueRunner = class {
2981
3044
  return;
2982
3045
  }
2983
3046
  }
3047
+ if (checkGoal) {
3048
+ state.reviveInFlight = true;
3049
+ let held;
3050
+ try {
3051
+ held = await this.storedGoalHold(sessionId, config);
3052
+ } finally {
3053
+ state.reviveInFlight = false;
3054
+ }
3055
+ if (this.disposed) return;
3056
+ if (held !== void 0) {
3057
+ state.recovering = false;
3058
+ this.log(`冷恢复跳过 ${sessionId}: goal 处于 ${held}, 不替用户续跑`);
3059
+ return;
3060
+ }
3061
+ }
2984
3062
  const parent = this.parentOf(sessionId);
2985
3063
  if (parent === void 0 || parent === "") return;
2986
3064
  const handoff = this.handoffText(sessionId, reason);
@@ -3160,14 +3238,21 @@ var AutoContinueRunner = class {
3160
3238
  }
3161
3239
  const template = this.templateFor(config, reason);
3162
3240
  const text = this.buildContinueText(config, state, template);
3241
+ const resumesInterruption = !manualResume && !isLoopReason(reason) && !reason.startsWith("loop:") && !reason.endsWith(":silent") && !reason.includes("max-tokens");
3163
3242
  const agent = this.ctx.agents.get(sessionId);
3164
3243
  if (agent === void 0) {
3165
3244
  if (this.isSubagentSession(sessionId) && this.subagentRecoveryEnabled(sessionId)) {
3166
- void this.reviveChild(sessionId, reason, text, manualResume);
3245
+ void this.reviveChild(sessionId, reason, text, manualResume, resumesInterruption);
3167
3246
  }
3168
3247
  this.log(`跳过 ${sessionId}(${reason}): 无 live agent`);
3169
3248
  return;
3170
3249
  }
3250
+ const heldGoal = resumesInterruption ? this.heldGoalPhase(agent, config) : void 0;
3251
+ if (heldGoal !== void 0) {
3252
+ state.recovering = false;
3253
+ this.log(`跳过 ${sessionId}(${reason}): goal 处于 ${heldGoal}, 不替用户续跑`);
3254
+ return;
3255
+ }
3171
3256
  state.lastAttemptAt = Date.now();
3172
3257
  try {
3173
3258
  const message = createUserMessage({
@@ -3313,15 +3398,16 @@ var AutoContinueRunner = class {
3313
3398
  * - 已失败 → 不加护栏(重试工具本来就是目的)
3314
3399
  */
3315
3400
  buildContinueText(config, state, template) {
3316
- let text = fillTemplate(template, {
3401
+ const guard = this.currentGuard(state);
3402
+ const unanswered = (guard.kind === "pending" || guard.kind === "failed") && guard.tool === ASK_USER_QUESTION_TOOL;
3403
+ let text = fillTemplate(unanswered ? config.continueTextQuestion : template, {
3317
3404
  facts: state.lastFailure,
3318
3405
  tool: state.tools.lastTool(),
3319
3406
  turn: state.lastTurn,
3320
3407
  errorCount: state.consecutive + 1,
3321
3408
  elapsedMs: state.lastFailureAt > 0 ? Date.now() - state.lastFailureAt : void 0
3322
3409
  });
3323
- if (!config.guardTools) return text;
3324
- const guard = this.currentGuard(state);
3410
+ if (unanswered || !config.guardTools) return text;
3325
3411
  if (guard.kind === "pending") {
3326
3412
  text += ` ${fillTemplate(config.guardPendingText, { tool: guard.tool, result: guard.result })}`;
3327
3413
  } else if (guard.kind === "done") {
@@ -3424,6 +3510,12 @@ var AutoContinueRunner = class {
3424
3510
  continue;
3425
3511
  }
3426
3512
  }
3513
+ state.consecutive = Math.max(state.consecutive, this.continuationsInLog(events, config));
3514
+ if (state.consecutive >= config.maxConsecutive) {
3515
+ this.bootScannedSessions.add(session);
3516
+ this.log(`跳过 ${sessionId}(启动扫描): 重启前已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`);
3517
+ continue;
3518
+ }
3427
3519
  candidates.push({
3428
3520
  session,
3429
3521
  sessionId,
@@ -3718,6 +3810,11 @@ var AutoContinueRunner = class {
3718
3810
  if (events.length === 0) return;
3719
3811
  const cause = classifyChildInterruption(events, config);
3720
3812
  if (cause === void 0) return;
3813
+ const held = this.goalHold(stored.projections?.values.goal?.goal?.phase, config);
3814
+ if (held !== void 0) {
3815
+ this.log(`子会话 ${sessionId} 的 goal 处于 ${held}, 不列入 root ${rootId} 的唤醒`);
3816
+ return;
3817
+ }
3721
3818
  const tail = events[events.length - 1];
3722
3819
  const list = this.childInterrupts.get(rootId) ?? [];
3723
3820
  list.push({
@@ -3773,9 +3870,14 @@ var AutoContinueRunner = class {
3773
3870
  if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) return false;
3774
3871
  const batch = children.map((child) => `${child.id}:${child.cause}`).sort().join(",");
3775
3872
  if (this.childWoken.get(rootId) === batch) return true;
3776
- if (!await this.rootAcceptsWake(rootId, deadline)) return true;
3873
+ if (!await this.rootAcceptsWake(rootId, config, deadline)) return true;
3777
3874
  const agent = await this.ensureLiveAgent(rootId, deadline);
3778
3875
  if (agent === void 0 || this.disposed) return false;
3876
+ const heldGoal = this.heldGoalPhase(agent, config);
3877
+ if (heldGoal !== void 0) {
3878
+ this.log(`跳过唤醒 ${rootId}: goal 处于 ${heldGoal}, 不替用户续跑`);
3879
+ return true;
3880
+ }
3779
3881
  const text = this.buildChildResumeText(config, children);
3780
3882
  const message = createUserMessage({
3781
3883
  content: [{ type: "text", text }],
@@ -3791,7 +3893,7 @@ var AutoContinueRunner = class {
3791
3893
  return true;
3792
3894
  }
3793
3895
  /** 父会话只在"干净结束"或"被宿主关闭"时接受唤醒; 用户手动停止的绝不复活。 */
3794
- async rootAcceptsWake(sessionId, deadline) {
3896
+ async rootAcceptsWake(sessionId, config, deadline) {
3795
3897
  const query = this.ctx.get("sessionQuery");
3796
3898
  if (query === void 0) return false;
3797
3899
  let events;
@@ -3822,9 +3924,14 @@ var AutoContinueRunner = class {
3822
3924
  if (lastStart !== void 0 && (end === void 0 || lastStart.seq > end.seq)) return false;
3823
3925
  if (end === void 0) return false;
3824
3926
  const kind = readReasonKind(end.data.reason);
3825
- if (kind === "completed") return true;
3826
- if (kind === "aborted") return isHostCancel(end.data.reason);
3827
- return false;
3927
+ if (kind !== "completed" && !(kind === "aborted" && isHostCancel(end.data.reason))) return false;
3928
+ const state = this.state(sessionId);
3929
+ state.consecutive = Math.max(state.consecutive, this.continuationsInLog(events, config));
3930
+ if (state.consecutive >= config.maxConsecutive) {
3931
+ this.log(`跳过唤醒 ${sessionId}: 重启前已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`);
3932
+ return false;
3933
+ }
3934
+ return true;
3828
3935
  }
3829
3936
  /** 发送需要 live agent; 存储会话沿既有物化路径拉起, 复用 preset 与模型回装。 */
3830
3937
  async ensureLiveAgent(sessionId, deadline) {
@@ -3871,7 +3978,7 @@ var AutoContinueRunner = class {
3871
3978
  */
3872
3979
  rearmGoal(sessionId, config) {
3873
3980
  if (!config.resumeGoals) return;
3874
- const goals = this.ctx.get(GOALS_SERVICE_KEY);
3981
+ const goals = this.goals();
3875
3982
  if (goals === void 0) return;
3876
3983
  const agent = this.ctx.agents.get(sessionId);
3877
3984
  if (agent === void 0) return;
@@ -3885,6 +3992,10 @@ var AutoContinueRunner = class {
3885
3992
  }
3886
3993
  const ref = view.ref ?? { id: view.id, revision };
3887
3994
  if (view.phase === "active" && view.activation === "disarmed") {
3995
+ if (goalStoppedByUser(snapshotSessionEvents(agent.session))) {
3996
+ this.log(`会话 ${sessionId}: goal 是用户停下的, 不重新武装(等用户自己恢复)`);
3997
+ return;
3998
+ }
3888
3999
  goals.resume(agent, ref);
3889
4000
  this.log(`会话 ${sessionId}: goal 被重启失活, 已重新武装`);
3890
4001
  return;
@@ -3899,6 +4010,95 @@ var AutoContinueRunner = class {
3899
4010
  );
3900
4011
  }
3901
4012
  }
4013
+ goals() {
4014
+ return this.ctx.get(GOALS_SERVICE_KEY);
4015
+ }
4016
+ /**
4017
+ * A paused or blocked goal is a decision to stop and wait; a continue sent anyway reads as the
4018
+ * user resuming it. `resumePausedGoals` is the user's standing permission to resume paused
4019
+ * goals, so it lets those through.
4020
+ */
4021
+ heldGoalPhase(agent, config) {
4022
+ let phase;
4023
+ try {
4024
+ const goals = this.goals();
4025
+ if (goals === void 0) return void 0;
4026
+ phase = goals.get(agent)?.phase;
4027
+ } catch {
4028
+ return "unreadable";
4029
+ }
4030
+ return this.goalHold(phase, config);
4031
+ }
4032
+ goalHold(phase, config) {
4033
+ if (phase === "blocked") return phase;
4034
+ if (phase === "paused" && !(config.resumeGoals && config.resumePausedGoals)) return phase;
4035
+ return void 0;
4036
+ }
4037
+ /** `heldGoalPhase` for a session without a live agent, read from its stored goal projection. */
4038
+ async storedGoalHold(sessionId, config) {
4039
+ if (this.goals() === void 0) return void 0;
4040
+ const query = this.ctx.get("sessionQuery");
4041
+ if (query === void 0) return "unreadable";
4042
+ let stored;
4043
+ try {
4044
+ const observation = await this.readStored(
4045
+ (signal) => query.observeSession(sessionId, { projectionMode: "all", signal }),
4046
+ Date.now() + STORED_READ_TIMEOUT_MS
4047
+ );
4048
+ stored = observation;
4049
+ return this.goalHold(observation.projections?.values.goal?.goal?.phase, config);
4050
+ } catch (error) {
4051
+ if (error?.code === "SESSION_QUERY_SESSION_NOT_FOUND") return void 0;
4052
+ return "unreadable";
4053
+ } finally {
4054
+ stored?.[Symbol.dispose]?.();
4055
+ }
4056
+ }
4057
+ /**
4058
+ * Continuations this plugin sent since the last message from the user, manual stop or turn
4059
+ * with visible output, read from the log so the consecutive cap survives a host restart.
4060
+ * Mirrors the in-memory count: a continuation right after a visible completion is a loop
4061
+ * round and does not count. With `usePluginSource` off a continuation is a `user` message
4062
+ * matching one of the configured continue texts, so a user message identical to one of them
4063
+ * is counted too; that can only stop recovery earlier, never later.
4064
+ */
4065
+ continuationsInLog(events, config) {
4066
+ const ours = continueTextMatcher(config);
4067
+ let count = 0;
4068
+ let visible = false;
4069
+ let maintenance = false;
4070
+ let afterSuccess = false;
4071
+ for (const event of events) {
4072
+ if (event.type === "turn/start") {
4073
+ visible = false;
4074
+ maintenance = isMaintenanceTurnStart(event);
4075
+ } else if (event.type === "tool/call") {
4076
+ visible = true;
4077
+ } else if (event.type === "assistant/chunk") {
4078
+ if (this.chunkVisible(event.data.chunk)) visible = true;
4079
+ } else if (event.type === "assistant/message") {
4080
+ if (this.hasVisibleContent(event.data.message?.content)) visible = true;
4081
+ } else if (event.type === "turn/end") {
4082
+ if (maintenance) continue;
4083
+ const reason = event.data.reason;
4084
+ const kind = readReasonKind(reason);
4085
+ afterSuccess = kind === "completed" && visible;
4086
+ const userStop = kind === "aborted" && !isHostCancel(reason) && !isLoopGuardCancelReason(reason.reason);
4087
+ if (afterSuccess || userStop) count = 0;
4088
+ } else if (event.type === "user/message") {
4089
+ const source = event.data.source?.kind;
4090
+ const text = messageText(event.data.content);
4091
+ if (isHandoffText(text)) continue;
4092
+ if (source === AUTO_CONTINUE_SOURCE_KIND || source === "user" && ours(text)) {
4093
+ if (!afterSuccess) count += 1;
4094
+ } else if (source === "user") {
4095
+ count = 0;
4096
+ }
4097
+ if (source === AUTO_CONTINUE_SOURCE_KIND || source === "user") afterSuccess = false;
4098
+ }
4099
+ }
4100
+ return count;
4101
+ }
3902
4102
  /**
3903
4103
  * 按会话记录的 preset 组合把存储会话恢复为 live agent(镜像会话控制
3904
4104
  * 器的 adopt 路径: preset 挂载 + 会话已记录的模型选择回装)。模型选择
@@ -10320,6 +10520,8 @@ var settingsFields = {
10320
10520
  continueTextLoop: z2.string().default(""),
10321
10521
  /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
10322
10522
  continueTextInterrupted: z2.string().default(""),
10523
+ /** Text sent instead of a continue text (and its guard note) while the user has not answered the last `ask_user_question`. */
10524
+ continueTextQuestion: z2.string().default(""),
10323
10525
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
10324
10526
  guardTools: z2.boolean().default(true),
10325
10527
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -75,6 +75,9 @@ export declare const zh: {
75
75
  'field.continueTextInterrupted': string;
76
76
  'field.continueTextInterruptedHint': string;
77
77
  'default.continueTextInterrupted': "继续。宿主在你上一轮运行期间重启了; 重启时未完成的工具调用已按「结果未知」收尾。从中断处继续, 重试可能有副作用的操作前先核实外部状态。";
78
+ 'field.continueTextQuestion': string;
79
+ 'field.continueTextQuestionHint': string;
80
+ 'default.continueTextQuestion': "这是宿主重启后插件自动发送的消息, 不是用户的回复。你上一步向用户提出的问题因重启中断, 用户还没有回答。请重新提出同一个问题并等待回答, 不要替用户做决定。";
78
81
  'field.guardTools': string;
79
82
  'field.guardToolsHint': string;
80
83
  'field.guardPendingText': string;
@@ -27,6 +27,7 @@ export interface AutoContinueSettingsCardState extends CardShell {
27
27
  continueTextLoop: CardFieldState;
28
28
  continueTextSilent: CardFieldState;
29
29
  continueTextInterrupted: CardFieldState;
30
+ continueTextQuestion: CardFieldState;
30
31
  guardTools: CardFieldState;
31
32
  guardPendingText: CardFieldState;
32
33
  guardDoneText: CardFieldState;
@@ -155,6 +155,7 @@ export declare class AutoContinueRunner {
155
155
  */
156
156
  private onHostEvent;
157
157
  private tracksOutput;
158
+ private chunkVisible;
158
159
  /** Treat unknown block kinds conservatively: only reasoning and blank text are silent. */
159
160
  private hasVisibleContent;
160
161
  /** 从 assistant/message 事件提取纯文本。 */
@@ -305,6 +306,25 @@ export declare class AutoContinueRunner {
305
306
  * resume 能重新 arm; paused 则是人类的显式决定。两者都默认关闭。
306
307
  */
307
308
  private rearmGoal;
309
+ private goals;
310
+ /**
311
+ * A paused or blocked goal is a decision to stop and wait; a continue sent anyway reads as the
312
+ * user resuming it. `resumePausedGoals` is the user's standing permission to resume paused
313
+ * goals, so it lets those through.
314
+ */
315
+ private heldGoalPhase;
316
+ private goalHold;
317
+ /** `heldGoalPhase` for a session without a live agent, read from its stored goal projection. */
318
+ private storedGoalHold;
319
+ /**
320
+ * Continuations this plugin sent since the last message from the user, manual stop or turn
321
+ * with visible output, read from the log so the consecutive cap survives a host restart.
322
+ * Mirrors the in-memory count: a continuation right after a visible completion is a loop
323
+ * round and does not count. With `usePluginSource` off a continuation is a `user` message
324
+ * matching one of the configured continue texts, so a user message identical to one of them
325
+ * is counted too; that can only stop recovery earlier, never later.
326
+ */
327
+ private continuationsInLog;
308
328
  /**
309
329
  * 按会话记录的 preset 组合把存储会话恢复为 live agent(镜像会话控制
310
330
  * 器的 adopt 路径: preset 挂载 + 会话已记录的模型选择回装)。模型选择
@@ -37,6 +37,8 @@ export declare const AutoContinueSchema: z<Schemastery.ObjectS<{
37
37
  continueTextLoop: z<string, string>;
38
38
  /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
39
39
  continueTextInterrupted: z<string, string>;
40
+ /** Text sent instead of a continue text (and its guard note) while the user has not answered the last `ask_user_question`. */
41
+ continueTextQuestion: z<string, string>;
40
42
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
41
43
  guardTools: z<boolean, boolean>;
42
44
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -120,6 +122,8 @@ export declare const AutoContinueSchema: z<Schemastery.ObjectS<{
120
122
  continueTextLoop: z<string, string>;
121
123
  /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
122
124
  continueTextInterrupted: z<string, string>;
125
+ /** Text sent instead of a continue text (and its guard note) while the user has not answered the last `ask_user_question`. */
126
+ continueTextQuestion: z<string, string>;
123
127
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
124
128
  guardTools: z<boolean, boolean>;
125
129
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -206,6 +210,8 @@ export declare const Config: z<Schemastery.ObjectS<{
206
210
  continueTextLoop: z<string, string>;
207
211
  /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
208
212
  continueTextInterrupted: z<string, string>;
213
+ /** Text sent instead of a continue text (and its guard note) while the user has not answered the last `ask_user_question`. */
214
+ continueTextQuestion: z<string, string>;
209
215
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
210
216
  guardTools: z<boolean, boolean>;
211
217
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -289,6 +295,8 @@ export declare const Config: z<Schemastery.ObjectS<{
289
295
  continueTextLoop: z<string, string>;
290
296
  /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
291
297
  continueTextInterrupted: z<string, string>;
298
+ /** Text sent instead of a continue text (and its guard note) while the user has not answered the last `ask_user_question`. */
299
+ continueTextQuestion: z<string, string>;
292
300
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
293
301
  guardTools: z<boolean, boolean>;
294
302
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -35,6 +35,7 @@ export declare const LOCALIZED_TEXT_DEFAULTS: {
35
35
  readonly continueTextSilent: "继续。你上一轮只输出了内部推理, 既没有回复也没有调用工具, 用户什么都没看到。每一轮都要以工具调用或可见回复结束。";
36
36
  readonly continueTextLoop: "继续";
37
37
  readonly continueTextInterrupted: "继续。宿主在你上一轮运行期间重启了; 重启时未完成的工具调用已按「结果未知」收尾。从中断处继续, 重试可能有副作用的操作前先核实外部状态。";
38
+ readonly continueTextQuestion: "这是宿主重启后插件自动发送的消息, 不是用户的回复。你上一步向用户提出的问题因重启中断, 用户还没有回答。请重新提出同一个问题并等待回答, 不要替用户做决定。";
38
39
  readonly guardPendingText: "(上一步工具「{tool}」可能未完成, 先确认状态再继续, 不要重复执行)";
39
40
  readonly guardDoneText: "(上一步工具「{tool}」已完成, 结果: {result}; 不要重复执行, 直接继续)";
40
41
  readonly loopText: "(检测到你可能陷入循环, 请停止重复刚才的动作, 换一种方式继续)";
@@ -45,6 +46,7 @@ export declare const LOCALIZED_TEXT_DEFAULTS: {
45
46
  readonly 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.";
46
47
  readonly continueTextLoop: "Continue";
47
48
  readonly 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.";
49
+ readonly continueTextQuestion: "This message was sent automatically by the plugin after a harness restart; it is not the user's reply. The question you asked the user was cut off by the restart and has not been answered. Ask the same question again and wait for the answer; do not decide for the user.";
48
50
  readonly guardPendingText: "(The previous tool \"{tool}\" may not have completed. Check its state before continuing and do not run it again.)";
49
51
  readonly guardDoneText: "(The previous tool \"{tool}\" completed successfully. Result: {result}; do not run it again. Continue from there.)";
50
52
  readonly loopText: "(You may be stuck in a loop. Stop repeating the last action and continue with a different approach.)";
@@ -55,6 +57,7 @@ export declare const LOCALIZED_TEXT_DEFAULTS: {
55
57
  readonly continueTextSilent: "Продолжай. Предыдущий ход закончился только внутренним рассуждением: ни ответа, ни вызова инструмента, поэтому пользователь ничего не увидел. Каждый ход должен заканчиваться вызовом инструмента или видимым ответом.";
56
58
  readonly continueTextLoop: "Продолжай";
57
59
  readonly continueTextInterrupted: "Продолжай. Хост перезапустился, пока предыдущий ход ещё выполнялся; вызовы инструментов, незавершённые на момент перезапуска, записаны с неизвестным результатом. Продолжай с места остановки, проверяя внешнее состояние перед повтором действий с возможными побочными эффектами.";
60
+ readonly continueTextQuestion: "Это сообщение плагин отправил автоматически после перезапуска хоста, это не ответ пользователя. Вопрос, который ты задал пользователю, прервался из-за перезапуска, и ответа на него ещё нет. Задай тот же вопрос снова и дождись ответа, не принимай решение за пользователя.";
58
61
  readonly guardPendingText: "(Предыдущий инструмент «{tool}», возможно, не завершился. Проверь его состояние перед продолжением и не запускай его повторно.)";
59
62
  readonly guardDoneText: "(Предыдущий инструмент «{tool}» завершился успешно. Результат: {result}; не запускай его повторно, продолжай с этого места.)";
60
63
  readonly loopText: "(Похоже, ты застрял в цикле. Перестань повторять последнее действие и продолжай другим способом.)";
@@ -82,6 +85,8 @@ export interface AutoContinueSettings {
82
85
  continueTextLoop?: string;
83
86
  /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
84
87
  continueTextInterrupted?: string;
88
+ /** Text sent instead of a continue text (and its guard note) while the user has not answered the last `ask_user_question`. */
89
+ continueTextQuestion?: string;
85
90
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
86
91
  guardTools?: boolean;
87
92
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-client-auto-continue",
3
3
  "description": "Automatically resume interrupted DSH conversations, with an optional autonomous loop.",
4
- "version": "0.20.2",
4
+ "version": "0.21.1",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "types": "lib/types/index.d.ts",
@@ -52,7 +52,7 @@
52
52
  "typecheck": "tsc --noEmit",
53
53
  "docs:assets": "node scripts/build-docs-assets.mjs",
54
54
  "test:runtime": "node tests/settings-host-live.mjs 0.1.7 && node tests/settings-host-live.mjs 0.2.0 && node tests/settings-host-live.mjs 0.2.1 && node tests/profile-compatibility.mjs 0.2.0 && node tests/profile-compatibility.mjs 0.2.1 && node tests/client-settings-services.mjs 0.2.0 && node tests/client-settings-services.mjs 0.2.1 && node tests/boot-scan-host-live.mjs 0.2.0-rc.2 && node tests/boot-scan-host-live.mjs 0.2.1 && node tests/settings-host-live.mjs 0.2.1-rc.2 && node tests/profile-compatibility.mjs 0.2.1-rc.2 && node tests/boot-scan-restart-live.mjs 0.2.1-rc.2 && node tests/boot-scan-restart-live.mjs 0.2.2-rc.1 && node tests/boot-scan-restart-live.mjs 0.2.2-rc.1 dispose && node tests/settings-host-live.mjs 0.2.1-rc.2 mixed && node tests/settings-migration.mjs",
55
- "test": "node tests/echo-matching.mjs && node tests/boot-scan-stored-sweep.mjs && node tests/child-resume-scan.mjs && node tests/offline-and-loop-cap.mjs && node tests/loop-guard-progress.mjs && node tests/scan-on-boot.mjs && node tests/boot-scan-isolation.mjs && node tests/silent-turn-boundaries.mjs && node tests/autonomous-loop.mjs && node tests/session-modes.mjs && node tests/manual-resume-pauses.mjs && node tests/stats-freshness.mjs && node tests/failure-classification.mjs && node tests/simulate-host.mjs && node tests/settings-host-compat.mjs && node tests/simulate-client-loader.mjs && node tests/client-settings-services.mjs && node tests/client-settings-form.mjs && node tests/locale-mirror-bounded.mjs && node tests/settings-card-ui.mjs && node tests/settings-card-native.mjs && node tests/composer-toggle.mjs && node tests/settings-notifications.mjs && node tests/prepare-github-package.mjs && node tests/maintenance-turns.mjs && node tests/publish-prerelease.mjs",
55
+ "test": "node tests/echo-matching.mjs && node tests/boot-scan-stored-sweep.mjs && node tests/restart-resume-guards.mjs && node tests/child-resume-scan.mjs && node tests/offline-and-loop-cap.mjs && node tests/loop-guard-progress.mjs && node tests/scan-on-boot.mjs && node tests/boot-scan-isolation.mjs && node tests/silent-turn-boundaries.mjs && node tests/autonomous-loop.mjs && node tests/session-modes.mjs && node tests/manual-resume-pauses.mjs && node tests/stats-freshness.mjs && node tests/failure-classification.mjs && node tests/simulate-host.mjs && node tests/settings-host-compat.mjs && node tests/simulate-client-loader.mjs && node tests/client-settings-services.mjs && node tests/client-settings-form.mjs && node tests/locale-mirror-bounded.mjs && node tests/settings-card-ui.mjs && node tests/settings-card-native.mjs && node tests/composer-toggle.mjs && node tests/settings-notifications.mjs && node tests/prepare-github-package.mjs && node tests/maintenance-turns.mjs && node tests/publish-prerelease.mjs",
56
56
  "prepack": "npm run build"
57
57
  },
58
58
  "keywords": [
@@ -82,6 +82,9 @@ export const zh = {
82
82
  'field.continueTextInterrupted': '宿主重启后恢复的继续文本',
83
83
  'field.continueTextInterruptedHint': 'DSH 重启后恢复中断会话时发送的文本。',
84
84
  'default.continueTextInterrupted': LOCALIZED_TEXT_DEFAULTS.zh.continueTextInterrupted,
85
+ 'field.continueTextQuestion': '提问未获回答时的继续文本',
86
+ 'field.continueTextQuestionHint': '被打断的上一步是向用户提问(ask_user_question)且用户还没回答时, 改发这段文本, 不附护栏提示, 让模型重新提问并等待回答。',
87
+ 'default.continueTextQuestion': LOCALIZED_TEXT_DEFAULTS.zh.continueTextQuestion,
85
88
  'field.guardTools': '幂等护栏',
86
89
  'field.guardToolsHint': '继续前,工具结果未确认时提醒模型核实状态,已成功时提醒跳过该操作。',
87
90
  'field.guardPendingText': '结果未确认时的护栏文本',
@@ -254,6 +257,9 @@ export const en: Record<SettingsCardKey, string> = {
254
257
  'field.continueTextInterrupted': 'Continue text (after harness restart)',
255
258
  'field.continueTextInterruptedHint': 'Text sent when resuming an interrupted session after DSH restarts.',
256
259
  'default.continueTextInterrupted': LOCALIZED_TEXT_DEFAULTS.en.continueTextInterrupted,
260
+ 'field.continueTextQuestion': 'Continue text (unanswered question)',
261
+ 'field.continueTextQuestionHint': 'Sent instead, without a guard note, when the interrupted step was a question to the user (ask_user_question) that has not been answered, so the model asks again and waits.',
262
+ 'default.continueTextQuestion': LOCALIZED_TEXT_DEFAULTS.en.continueTextQuestion,
257
263
  'field.guardTools': 'Idempotency guard',
258
264
  'field.guardToolsHint': 'Before resuming, remind the model to check unconfirmed tool results or skip an action that already succeeded.',
259
265
  'field.guardPendingText': 'Guard text (unconfirmed result)',
@@ -409,6 +415,9 @@ export const ru: Record<SettingsCardKey, string> = {
409
415
  'field.continueTextInterrupted': 'Текст продолжения (после перезапуска хоста)',
410
416
  'field.continueTextInterruptedHint': 'Текст, отправляемый, когда сканирование при запуске продолжает сессию, прерванную перезапуском; по умолчанию объясняет перезапуск и просит сверять состояние перед повтором.',
411
417
  'default.continueTextInterrupted': LOCALIZED_TEXT_DEFAULTS.ru.continueTextInterrupted,
418
+ 'field.continueTextQuestion': 'Текст продолжения (вопрос без ответа)',
419
+ 'field.continueTextQuestionHint': 'Отправляется вместо обычного текста и без заметки защиты, если прерванным шагом был вопрос пользователю (ask_user_question), на который ещё нет ответа: модель задаёт вопрос снова и ждёт ответа.',
420
+ 'default.continueTextQuestion': LOCALIZED_TEXT_DEFAULTS.ru.continueTextQuestion,
412
421
  'field.guardTools': 'Защита от повторного выполнения',
413
422
  'field.guardToolsHint': 'Перед продолжением проверяет последний вызов инструмента: если результат не подтверждён, просит сначала проверить состояние; если вызов успешен — не повторять его. Помогает не дублировать коммиты и вызовы API.',
414
423
  'field.guardPendingText': 'Текст защиты (результат не подтверждён)',
@@ -100,6 +100,7 @@ export interface AutoContinueSettingsCardState extends CardShell {
100
100
  continueTextLoop: CardFieldState;
101
101
  continueTextSilent: CardFieldState;
102
102
  continueTextInterrupted: CardFieldState;
103
+ continueTextQuestion: CardFieldState;
103
104
  guardTools: CardFieldState;
104
105
  guardPendingText: CardFieldState;
105
106
  guardDoneText: CardFieldState;
@@ -169,6 +170,7 @@ export class AutoContinueSettingsCardController {
169
170
  textField('continueTextLoop'),
170
171
  textField('continueTextSilent'),
171
172
  textField('continueTextInterrupted'),
173
+ textField('continueTextQuestion'),
172
174
  booleanField('guardTools'),
173
175
  textField('guardPendingText'),
174
176
  textField('guardDoneText'),
@@ -219,6 +221,7 @@ export class AutoContinueSettingsCardController {
219
221
  continueTextLoop: this.form.field('continueTextLoop'),
220
222
  continueTextSilent: this.form.field('continueTextSilent'),
221
223
  continueTextInterrupted: this.form.field('continueTextInterrupted'),
224
+ continueTextQuestion: this.form.field('continueTextQuestion'),
222
225
  guardTools: this.form.field('guardTools'),
223
226
  guardPendingText: this.form.field('guardPendingText'),
224
227
  guardDoneText: this.form.field('guardDoneText'),
@@ -331,7 +334,7 @@ const groups = [
331
334
  { id: 'general', fields: ['paused', 'showComposerToggle', 'usePluginSource', 'resumeSilentTurns', 'resumeSubagentSessions', 'resumeCompletedTurns', 'loopMaxIterations', 'notify'] },
332
335
  { id: 'recovery', fields: ['graceMs', 'cooldownMs', 'maxConsecutive', 'classify', 'retryableErrorPatterns', 'backoffFactor', 'backoffMaxMs', 'pauseWhenOffline', 'offlineCheckMs', 'resumeGoals', 'resumePausedGoals'] },
333
336
  { id: 'startup', fields: ['scanOnBoot', 'resumeInterruptedChildren', 'scanLimit', 'freshMs'] },
334
- { id: 'prompts', fields: ['continueText', 'continueTextMaxTokens', 'continueTextSilent', 'continueTextInterrupted', 'continueTextLoop', 'guardPendingText', 'guardDoneText', 'loopText'] },
337
+ { id: 'prompts', fields: ['continueText', 'continueTextMaxTokens', 'continueTextSilent', 'continueTextInterrupted', 'continueTextQuestion', 'continueTextLoop', 'guardPendingText', 'guardDoneText', 'loopText'] },
335
338
  { id: 'safety', fields: ['guardTools', 'loopGuard', 'loopShortChars', 'loopWindowMs', 'loopShortCount', 'loopRepeatText', 'loopToolRepeat'] },
336
339
  { id: 'status', fields: ['verbose'] },
337
340
  ] as const satisfies ReadonlyArray<{ id: string; fields: readonly FieldName[] }>;
@@ -339,7 +342,7 @@ type Category = typeof groups[number]['id'];
339
342
  const textDefaults: Partial<Record<FieldName, SettingsCardKey>> = {
340
343
  continueText: 'default.continueText', continueTextMaxTokens: 'default.continueTextMaxTokens',
341
344
  continueTextSilent: 'default.continueTextSilent', continueTextLoop: 'default.continueTextLoop',
342
- continueTextInterrupted: 'default.continueTextInterrupted',
345
+ continueTextInterrupted: 'default.continueTextInterrupted', continueTextQuestion: 'default.continueTextQuestion',
343
346
  guardPendingText: 'default.guardPendingText', guardDoneText: 'default.guardDoneText', loopText: 'default.loopText',
344
347
  };
345
348