dsh-client-auto-continue 0.20.2 → 0.21.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
@@ -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;
@@ -1939,6 +1945,50 @@ function isLoopGuardCancelReason(value) {
1939
1945
  const cause = value;
1940
1946
  return cause.kind === LOOP_GUARD_CANCEL_CAUSE.kind && cause.reason === LOOP_GUARD_CANCEL_CAUSE.reason;
1941
1947
  }
1948
+ var TEMPLATE_PLACEHOLDER = /\{(?:code|message|status|tool|turn|errorCount|sessionTitle|elapsed|result)\}/;
1949
+ function templateParts(template) {
1950
+ const parts = template.split(TEMPLATE_PLACEHOLDER);
1951
+ return parts.join("").trim() === "" ? void 0 : parts;
1952
+ }
1953
+ function matchesParts(text, parts) {
1954
+ const first = parts[0] ?? "";
1955
+ if (parts.length === 1) return text === first;
1956
+ const last = parts[parts.length - 1] ?? "";
1957
+ if (text.length < first.length + last.length || !text.startsWith(first) || !text.endsWith(last)) return false;
1958
+ const end = text.length - last.length;
1959
+ let at = first.length;
1960
+ for (let i = 1; i < parts.length - 1; i += 1) {
1961
+ const part = parts[i] ?? "";
1962
+ const found = text.indexOf(part, at);
1963
+ if (found < 0 || found + part.length > end) return false;
1964
+ at = found + part.length;
1965
+ }
1966
+ return true;
1967
+ }
1968
+ function joinParts(left, separator, right) {
1969
+ return [...left.slice(0, -1), `${left[left.length - 1] ?? ""}${separator}${right[0] ?? ""}`, ...right.slice(1)];
1970
+ }
1971
+ var definedParts = (templates) => templates.map(templateParts).filter((parts) => parts !== void 0);
1972
+ var HANDOFF_SHAPES = definedParts(Object.values(HANDOFF_COPY).map((copy) => copy("{code}", "{code}")));
1973
+ var isHandoffText = (text) => HANDOFF_SHAPES.some((parts) => matchesParts(text, parts));
1974
+ function continueTextMatcher(config) {
1975
+ const texts = definedParts([
1976
+ config.continueText,
1977
+ config.continueTextMaxTokens,
1978
+ config.continueTextSilent,
1979
+ config.continueTextLoop,
1980
+ config.continueTextInterrupted,
1981
+ config.continueTextQuestion,
1982
+ config.loopText
1983
+ ]);
1984
+ const guards = definedParts([config.guardPendingText, config.guardDoneText]);
1985
+ const shapes = texts.flatMap((text) => [text, ...guards.map((guard) => joinParts(text, " ", guard))]);
1986
+ return (text) => shapes.some((parts) => matchesParts(text, parts));
1987
+ }
1988
+ function messageText(content) {
1989
+ if (!Array.isArray(content)) return "";
1990
+ return content.map((block) => block?.type === "text" && typeof block.text === "string" ? block.text : "").join("");
1991
+ }
1942
1992
  var LINEAGE_CACHE_LIMIT = 2e3;
1943
1993
  var AutoContinueRunner = class {
1944
1994
  /**
@@ -2346,8 +2396,7 @@ var AutoContinueRunner = class {
2346
2396
  const state = this.state(sessionId);
2347
2397
  if (this.tracksOutput(state, event)) {
2348
2398
  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";
2399
+ if (this.chunkVisible(chunk)) state.turnOutput = "visible";
2351
2400
  else if (state.turnOutput === "empty" && chunk.type !== "usage" && chunk.type !== "finish") state.turnOutput = "silent";
2352
2401
  }
2353
2402
  this.onAssistantChunk(sessionId, state, event);
@@ -2364,6 +2413,9 @@ var AutoContinueRunner = class {
2364
2413
  tracksOutput(state, event) {
2365
2414
  return state.running === true && state.outputTurn === event.data.turn && event.seq > state.outputStartSeq;
2366
2415
  }
2416
+ chunkVisible(chunk) {
2417
+ 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";
2418
+ }
2367
2419
  /** Treat unknown block kinds conservatively: only reasoning and blank text are silent. */
2368
2420
  hasVisibleContent(content) {
2369
2421
  if (!Array.isArray(content)) return false;
@@ -2962,7 +3014,7 @@ var AutoContinueRunner = class {
2962
3014
  * The child's own recovery mode decides; the parent only has to be alive to
2963
3015
  * authorize the call.
2964
3016
  */
2965
- async reviveChild(sessionId, reason, text, force) {
3017
+ async reviveChild(sessionId, reason, text, force, checkGoal) {
2966
3018
  if (this.disposed || this.getConfig().paused) return;
2967
3019
  if (!this.subagentRecoveryEnabled(sessionId)) return;
2968
3020
  const state = this.state(sessionId);
@@ -2981,6 +3033,21 @@ var AutoContinueRunner = class {
2981
3033
  return;
2982
3034
  }
2983
3035
  }
3036
+ if (checkGoal) {
3037
+ state.reviveInFlight = true;
3038
+ let held;
3039
+ try {
3040
+ held = await this.storedGoalHold(sessionId, config);
3041
+ } finally {
3042
+ state.reviveInFlight = false;
3043
+ }
3044
+ if (this.disposed) return;
3045
+ if (held !== void 0) {
3046
+ state.recovering = false;
3047
+ this.log(`冷恢复跳过 ${sessionId}: goal 处于 ${held}, 不替用户续跑`);
3048
+ return;
3049
+ }
3050
+ }
2984
3051
  const parent = this.parentOf(sessionId);
2985
3052
  if (parent === void 0 || parent === "") return;
2986
3053
  const handoff = this.handoffText(sessionId, reason);
@@ -3160,14 +3227,21 @@ var AutoContinueRunner = class {
3160
3227
  }
3161
3228
  const template = this.templateFor(config, reason);
3162
3229
  const text = this.buildContinueText(config, state, template);
3230
+ const resumesInterruption = !manualResume && !isLoopReason(reason) && !reason.startsWith("loop:") && !reason.endsWith(":silent") && !reason.includes("max-tokens");
3163
3231
  const agent = this.ctx.agents.get(sessionId);
3164
3232
  if (agent === void 0) {
3165
3233
  if (this.isSubagentSession(sessionId) && this.subagentRecoveryEnabled(sessionId)) {
3166
- void this.reviveChild(sessionId, reason, text, manualResume);
3234
+ void this.reviveChild(sessionId, reason, text, manualResume, resumesInterruption);
3167
3235
  }
3168
3236
  this.log(`跳过 ${sessionId}(${reason}): 无 live agent`);
3169
3237
  return;
3170
3238
  }
3239
+ const heldGoal = resumesInterruption ? this.heldGoalPhase(agent, config) : void 0;
3240
+ if (heldGoal !== void 0) {
3241
+ state.recovering = false;
3242
+ this.log(`跳过 ${sessionId}(${reason}): goal 处于 ${heldGoal}, 不替用户续跑`);
3243
+ return;
3244
+ }
3171
3245
  state.lastAttemptAt = Date.now();
3172
3246
  try {
3173
3247
  const message = createUserMessage({
@@ -3313,15 +3387,16 @@ var AutoContinueRunner = class {
3313
3387
  * - 已失败 → 不加护栏(重试工具本来就是目的)
3314
3388
  */
3315
3389
  buildContinueText(config, state, template) {
3316
- let text = fillTemplate(template, {
3390
+ const guard = this.currentGuard(state);
3391
+ const unanswered = (guard.kind === "pending" || guard.kind === "failed") && guard.tool === ASK_USER_QUESTION_TOOL;
3392
+ let text = fillTemplate(unanswered ? config.continueTextQuestion : template, {
3317
3393
  facts: state.lastFailure,
3318
3394
  tool: state.tools.lastTool(),
3319
3395
  turn: state.lastTurn,
3320
3396
  errorCount: state.consecutive + 1,
3321
3397
  elapsedMs: state.lastFailureAt > 0 ? Date.now() - state.lastFailureAt : void 0
3322
3398
  });
3323
- if (!config.guardTools) return text;
3324
- const guard = this.currentGuard(state);
3399
+ if (unanswered || !config.guardTools) return text;
3325
3400
  if (guard.kind === "pending") {
3326
3401
  text += ` ${fillTemplate(config.guardPendingText, { tool: guard.tool, result: guard.result })}`;
3327
3402
  } else if (guard.kind === "done") {
@@ -3424,6 +3499,12 @@ var AutoContinueRunner = class {
3424
3499
  continue;
3425
3500
  }
3426
3501
  }
3502
+ state.consecutive = Math.max(state.consecutive, this.continuationsInLog(events, config));
3503
+ if (state.consecutive >= config.maxConsecutive) {
3504
+ this.bootScannedSessions.add(session);
3505
+ this.log(`跳过 ${sessionId}(启动扫描): 重启前已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`);
3506
+ continue;
3507
+ }
3427
3508
  candidates.push({
3428
3509
  session,
3429
3510
  sessionId,
@@ -3718,6 +3799,11 @@ var AutoContinueRunner = class {
3718
3799
  if (events.length === 0) return;
3719
3800
  const cause = classifyChildInterruption(events, config);
3720
3801
  if (cause === void 0) return;
3802
+ const held = this.goalHold(stored.projections?.values.goal?.goal?.phase, config);
3803
+ if (held !== void 0) {
3804
+ this.log(`子会话 ${sessionId} 的 goal 处于 ${held}, 不列入 root ${rootId} 的唤醒`);
3805
+ return;
3806
+ }
3721
3807
  const tail = events[events.length - 1];
3722
3808
  const list = this.childInterrupts.get(rootId) ?? [];
3723
3809
  list.push({
@@ -3773,9 +3859,14 @@ var AutoContinueRunner = class {
3773
3859
  if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) return false;
3774
3860
  const batch = children.map((child) => `${child.id}:${child.cause}`).sort().join(",");
3775
3861
  if (this.childWoken.get(rootId) === batch) return true;
3776
- if (!await this.rootAcceptsWake(rootId, deadline)) return true;
3862
+ if (!await this.rootAcceptsWake(rootId, config, deadline)) return true;
3777
3863
  const agent = await this.ensureLiveAgent(rootId, deadline);
3778
3864
  if (agent === void 0 || this.disposed) return false;
3865
+ const heldGoal = this.heldGoalPhase(agent, config);
3866
+ if (heldGoal !== void 0) {
3867
+ this.log(`跳过唤醒 ${rootId}: goal 处于 ${heldGoal}, 不替用户续跑`);
3868
+ return true;
3869
+ }
3779
3870
  const text = this.buildChildResumeText(config, children);
3780
3871
  const message = createUserMessage({
3781
3872
  content: [{ type: "text", text }],
@@ -3791,7 +3882,7 @@ var AutoContinueRunner = class {
3791
3882
  return true;
3792
3883
  }
3793
3884
  /** 父会话只在"干净结束"或"被宿主关闭"时接受唤醒; 用户手动停止的绝不复活。 */
3794
- async rootAcceptsWake(sessionId, deadline) {
3885
+ async rootAcceptsWake(sessionId, config, deadline) {
3795
3886
  const query = this.ctx.get("sessionQuery");
3796
3887
  if (query === void 0) return false;
3797
3888
  let events;
@@ -3822,9 +3913,14 @@ var AutoContinueRunner = class {
3822
3913
  if (lastStart !== void 0 && (end === void 0 || lastStart.seq > end.seq)) return false;
3823
3914
  if (end === void 0) return false;
3824
3915
  const kind = readReasonKind(end.data.reason);
3825
- if (kind === "completed") return true;
3826
- if (kind === "aborted") return isHostCancel(end.data.reason);
3827
- return false;
3916
+ if (kind !== "completed" && !(kind === "aborted" && isHostCancel(end.data.reason))) return false;
3917
+ const state = this.state(sessionId);
3918
+ state.consecutive = Math.max(state.consecutive, this.continuationsInLog(events, config));
3919
+ if (state.consecutive >= config.maxConsecutive) {
3920
+ this.log(`跳过唤醒 ${sessionId}: 重启前已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`);
3921
+ return false;
3922
+ }
3923
+ return true;
3828
3924
  }
3829
3925
  /** 发送需要 live agent; 存储会话沿既有物化路径拉起, 复用 preset 与模型回装。 */
3830
3926
  async ensureLiveAgent(sessionId, deadline) {
@@ -3871,7 +3967,7 @@ var AutoContinueRunner = class {
3871
3967
  */
3872
3968
  rearmGoal(sessionId, config) {
3873
3969
  if (!config.resumeGoals) return;
3874
- const goals = this.ctx.get(GOALS_SERVICE_KEY);
3970
+ const goals = this.goals();
3875
3971
  if (goals === void 0) return;
3876
3972
  const agent = this.ctx.agents.get(sessionId);
3877
3973
  if (agent === void 0) return;
@@ -3899,6 +3995,95 @@ var AutoContinueRunner = class {
3899
3995
  );
3900
3996
  }
3901
3997
  }
3998
+ goals() {
3999
+ return this.ctx.get(GOALS_SERVICE_KEY);
4000
+ }
4001
+ /**
4002
+ * A paused or blocked goal is a decision to stop and wait; a continue sent anyway reads as the
4003
+ * user resuming it. `resumePausedGoals` is the user's standing permission to resume paused
4004
+ * goals, so it lets those through.
4005
+ */
4006
+ heldGoalPhase(agent, config) {
4007
+ let phase;
4008
+ try {
4009
+ const goals = this.goals();
4010
+ if (goals === void 0) return void 0;
4011
+ phase = goals.get(agent)?.phase;
4012
+ } catch {
4013
+ return "unreadable";
4014
+ }
4015
+ return this.goalHold(phase, config);
4016
+ }
4017
+ goalHold(phase, config) {
4018
+ if (phase === "blocked") return phase;
4019
+ if (phase === "paused" && !(config.resumeGoals && config.resumePausedGoals)) return phase;
4020
+ return void 0;
4021
+ }
4022
+ /** `heldGoalPhase` for a session without a live agent, read from its stored goal projection. */
4023
+ async storedGoalHold(sessionId, config) {
4024
+ if (this.goals() === void 0) return void 0;
4025
+ const query = this.ctx.get("sessionQuery");
4026
+ if (query === void 0) return "unreadable";
4027
+ let stored;
4028
+ try {
4029
+ const observation = await this.readStored(
4030
+ (signal) => query.observeSession(sessionId, { projectionMode: "all", signal }),
4031
+ Date.now() + STORED_READ_TIMEOUT_MS
4032
+ );
4033
+ stored = observation;
4034
+ return this.goalHold(observation.projections?.values.goal?.goal?.phase, config);
4035
+ } catch (error) {
4036
+ if (error?.code === "SESSION_QUERY_SESSION_NOT_FOUND") return void 0;
4037
+ return "unreadable";
4038
+ } finally {
4039
+ stored?.[Symbol.dispose]?.();
4040
+ }
4041
+ }
4042
+ /**
4043
+ * Continuations this plugin sent since the last message from the user, manual stop or turn
4044
+ * with visible output, read from the log so the consecutive cap survives a host restart.
4045
+ * Mirrors the in-memory count: a continuation right after a visible completion is a loop
4046
+ * round and does not count. With `usePluginSource` off a continuation is a `user` message
4047
+ * matching one of the configured continue texts, so a user message identical to one of them
4048
+ * is counted too; that can only stop recovery earlier, never later.
4049
+ */
4050
+ continuationsInLog(events, config) {
4051
+ const ours = continueTextMatcher(config);
4052
+ let count = 0;
4053
+ let visible = false;
4054
+ let maintenance = false;
4055
+ let afterSuccess = false;
4056
+ for (const event of events) {
4057
+ if (event.type === "turn/start") {
4058
+ visible = false;
4059
+ maintenance = isMaintenanceTurnStart(event);
4060
+ } else if (event.type === "tool/call") {
4061
+ visible = true;
4062
+ } else if (event.type === "assistant/chunk") {
4063
+ if (this.chunkVisible(event.data.chunk)) visible = true;
4064
+ } else if (event.type === "assistant/message") {
4065
+ if (this.hasVisibleContent(event.data.message?.content)) visible = true;
4066
+ } else if (event.type === "turn/end") {
4067
+ if (maintenance) continue;
4068
+ const reason = event.data.reason;
4069
+ const kind = readReasonKind(reason);
4070
+ afterSuccess = kind === "completed" && visible;
4071
+ const userStop = kind === "aborted" && !isHostCancel(reason) && !isLoopGuardCancelReason(reason.reason);
4072
+ if (afterSuccess || userStop) count = 0;
4073
+ } else if (event.type === "user/message") {
4074
+ const source = event.data.source?.kind;
4075
+ const text = messageText(event.data.content);
4076
+ if (isHandoffText(text)) continue;
4077
+ if (source === AUTO_CONTINUE_SOURCE_KIND || source === "user" && ours(text)) {
4078
+ if (!afterSuccess) count += 1;
4079
+ } else if (source === "user") {
4080
+ count = 0;
4081
+ }
4082
+ if (source === AUTO_CONTINUE_SOURCE_KIND || source === "user") afterSuccess = false;
4083
+ }
4084
+ }
4085
+ return count;
4086
+ }
3902
4087
  /**
3903
4088
  * 按会话记录的 preset 组合把存储会话恢复为 live agent(镜像会话控制
3904
4089
  * 器的 adopt 路径: preset 挂载 + 会话已记录的模型选择回装)。模型选择
@@ -10320,6 +10505,8 @@ var settingsFields = {
10320
10505
  continueTextLoop: z2.string().default(""),
10321
10506
  /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
10322
10507
  continueTextInterrupted: z2.string().default(""),
10508
+ /** Text sent instead of a continue text (and its guard note) while the user has not answered the last `ask_user_question`. */
10509
+ continueTextQuestion: z2.string().default(""),
10323
10510
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
10324
10511
  guardTools: z2.boolean().default(true),
10325
10512
  /** 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.0",
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