dsh-client-auto-continue 0.11.9 → 0.12.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.
@@ -80,6 +80,21 @@ const LOOP_GUARD_CANCEL_CAUSE = {
80
80
  reason: 'dsh-auto-continue:loop-guard',
81
81
  } as const;
82
82
 
83
+ /**
84
+ * Autonomous-loop resume reasons.
85
+ * - `turn/end:completed` is a *successful* visible completion: the loop hands
86
+ * the thread back and the send is exempt from the failure budget.
87
+ * - `turn/end:loop-silent` is a loop-covered turn with no visible output. The
88
+ * loop still continues it, but it is a failure: it must consume the retry
89
+ * budget and obey backoff, or a stuck model retries forever.
90
+ * The silent reason must not end in `:silent` — `fire()` skips those when
91
+ * silent-turn resume is off, which would stall the loop (27j).
92
+ */
93
+ const LOOP_COMPLETED_REASON = 'turn/end:completed';
94
+ const LOOP_SILENT_REASON = 'turn/end:loop-silent';
95
+ const isLoopReason = (reason: string): boolean =>
96
+ reason === LOOP_COMPLETED_REASON || reason === LOOP_SILENT_REASON;
97
+
83
98
  /** Keep fuzzy matching off the unbounded host event path; exact repeats remain unlimited. */
84
99
  const STREAM_NEAR_DUPLICATE_MAX_CHARS = 2_048;
85
100
  /** Bound unfinished text copied between token chunks when a provider emits no paragraph break. */
@@ -340,6 +355,7 @@ export class AutoContinueRunner {
340
355
  for (const state of this.states.values()) {
341
356
  if (state.pendingTimer !== undefined) clearTimeout(state.pendingTimer);
342
357
  if (state.loopRetryTimer !== undefined) clearTimeout(state.loopRetryTimer);
358
+ if (state.cooldownRetryTimer !== undefined) clearTimeout(state.cooldownRetryTimer);
343
359
  }
344
360
  this.states.clear();
345
361
  }
@@ -674,13 +690,29 @@ export class AutoContinueRunner {
674
690
  state.lastTurn = event.data.turn;
675
691
  state.lastFailureAt = Date.now();
676
692
  this.noteRecovery(sessionId, 'error');
677
- if (this.getConfig().resumeSilentTurns) this.schedule(sessionId, `turn/end:${reasonKind}:silent`);
693
+ if (this.getConfig().resumeCompletedTurns) {
694
+ // 自主循环覆盖无可见输出的回合, 但这类回合是「失败」而非成功:
695
+ // 不 force, 否则会绕过连续上限与冷却, 让卡住的模型无限重试。
696
+ this.schedule(sessionId, LOOP_SILENT_REASON);
697
+ } else if (this.getConfig().resumeSilentTurns) {
698
+ this.schedule(sessionId, `turn/end:${reasonKind}:silent`);
699
+ }
678
700
  break;
679
701
  }
680
702
  if (reasonKind === 'completed') {
681
703
  // Only observed visible output proves recovery; no-op and unknown
682
704
  // turns must not erase the retry budget or count as successful.
683
- if (turnOutput === 'visible') {
705
+ // 自主循环的例外只在于「是否续跑」, 不在于「是否清零预算」: 循环对每个
706
+ // completed 回合都强制续跑, 但失败预算依旧只在可见输出时清零, 否则
707
+ // 空回合/未观察到的回合会不断抹掉连续计数, 令连续上限永远无法生效。
708
+ if (this.getConfig().resumeCompletedTurns) {
709
+ if (turnOutput === 'visible') {
710
+ state.consecutive = 0;
711
+ state.lastFailure = undefined;
712
+ this.noteRecovery(sessionId, 'completed');
713
+ }
714
+ this.schedule(sessionId, LOOP_COMPLETED_REASON, true);
715
+ } else if (turnOutput === 'visible') {
684
716
  state.consecutive = 0;
685
717
  state.lastFailure = undefined;
686
718
  this.noteRecovery(sessionId, 'completed');
@@ -829,6 +861,10 @@ export class AutoContinueRunner {
829
861
  if (delta.code !== undefined) {
830
862
  this.dayStats.byCode[delta.code] = (this.dayStats.byCode[delta.code] ?? 0) + 1;
831
863
  }
864
+ // Stats are only observable through the status bridge, so every bump must
865
+ // publish. Previously the panel only moved when a notification happened to
866
+ // fire (notify=false by default), leaving "Auto-continued" frozen at 0.
867
+ this.emitState();
832
868
  }
833
869
 
834
870
  /** 通知桥: 产生一条通知事件, SSE 端点推给 browser 侧展示。 */
@@ -893,7 +929,7 @@ export class AutoContinueRunner {
893
929
  );
894
930
  }
895
931
 
896
- private schedule(sessionId: SessionId, reason: string): void {
932
+ private schedule(sessionId: SessionId, reason: string, force = false): void {
897
933
  const state = this.state(sessionId);
898
934
  const config = this.getConfig();
899
935
  if (state.subagent) return; // 子代理会话由父代理处理, 不抢跑
@@ -906,19 +942,29 @@ export class AutoContinueRunner {
906
942
  return;
907
943
  }
908
944
  if (state.pendingTimer !== undefined) return; // 已有待发送
909
- if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) return; // 冷却期(含失败尝试, 自适应退避)
910
- if (state.consecutive >= config.maxConsecutive) {
945
+ // 连续上限优先于冷却: 已经放弃的会话不该再安排冷却后的重试。
946
+ // 自主循环的完成续跑(force)不受二者约束。
947
+ if (!force && state.consecutive >= config.maxConsecutive) {
911
948
  this.log(
912
949
  `跳过 ${sessionId}(${reason}): 已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`,
913
950
  );
914
951
  return;
915
952
  }
953
+ // 冷却(含失败尝试, 自适应退避): 不能直接丢弃这次恢复, 否则一次瞬时失败
954
+ // 会把会话搁置到用户手动介入为止。
955
+ if (!force) {
956
+ const remaining = this.cooldownFor(state) - (Date.now() - state.lastAttemptAt);
957
+ if (remaining > 0) {
958
+ this.deferCooldownRetry(sessionId, reason, remaining);
959
+ return;
960
+ }
961
+ }
916
962
  const timer = setTimeout(() => {
917
963
  if (state.pendingTimer !== timer) return;
918
964
  state.pendingTimer = undefined;
919
965
  // 保险丝: 定时器回调内任何异常(含 inactive context)都不得成为未捕获异常炸掉进程。
920
966
  try {
921
- void this.fire(sessionId, reason);
967
+ void this.fire(sessionId, reason, force);
922
968
  } catch (error) {
923
969
  console.error(`[auto-continue] 定时发送异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
924
970
  }
@@ -930,9 +976,29 @@ export class AutoContinueRunner {
930
976
  );
931
977
  }
932
978
 
933
- /** 按调度原因选择续跑模板: loop 重启、无输出回合、max-tokens, 其余用通用继续文本。 */
979
+ /**
980
+ * 冷却期内的恢复: 等到冷却结束再重新调度。
981
+ * 直接丢弃会让一次瞬时失败把会话搁置, 直到用户手动发消息才恢复。
982
+ */
983
+ private deferCooldownRetry(sessionId: SessionId, reason: string, remaining: number): void {
984
+ const state = this.state(sessionId);
985
+ if (state.cooldownRetryTimer !== undefined) clearTimeout(state.cooldownRetryTimer);
986
+ state.cooldownRetryTimer = setTimeout(() => {
987
+ state.cooldownRetryTimer = undefined;
988
+ try {
989
+ this.schedule(sessionId, reason);
990
+ } catch (error) {
991
+ console.error(`[auto-continue] 冷却后重试异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
992
+ }
993
+ }, remaining + 10); // +10ms: 同 loop 重启; 否则 1ms 抖动可能让重检仍判为冷却期而再次丢弃
994
+ this.log(`冷却中 ${sessionId}(${reason}), ${remaining}ms 后重试`);
995
+ }
996
+
997
+ /** 按调度原因选择续跑模板: loop 重启、无输出回合、max-tokens、自主循环, 其余用通用继续文本。 */
934
998
  private templateFor(config: AutoContinueConfig, reason: string): string {
935
999
  if (reason.startsWith('loop:')) return config.loopText;
1000
+ // 自主循环的两种原因都用循环文本(顺序在 `:silent` 之前: 循环模式决定文本)。
1001
+ if (isLoopReason(reason)) return config.continueTextLoop;
936
1002
  if (reason.endsWith(':silent')) return config.continueTextSilent;
937
1003
  if (reason.includes('max-tokens')) return config.continueTextMaxTokens;
938
1004
  return config.continueText;
@@ -940,10 +1006,19 @@ export class AutoContinueRunner {
940
1006
 
941
1007
  private cancelPending(sessionId: SessionId, why: string): void {
942
1008
  const state = this.state(sessionId);
943
- if (state.pendingTimer === undefined) return;
944
- clearTimeout(state.pendingTimer);
945
- state.pendingTimer = undefined;
946
- this.log(`取消 ${sessionId} 的自动继续(${why})`);
1009
+ let cancelled = false;
1010
+ if (state.pendingTimer !== undefined) {
1011
+ clearTimeout(state.pendingTimer);
1012
+ state.pendingTimer = undefined;
1013
+ cancelled = true;
1014
+ }
1015
+ // 冷却后的重试同样属于「待发送」: 新回合或用户介入必须让它作废。
1016
+ if (state.cooldownRetryTimer !== undefined) {
1017
+ clearTimeout(state.cooldownRetryTimer);
1018
+ state.cooldownRetryTimer = undefined;
1019
+ cancelled = true;
1020
+ }
1021
+ if (cancelled) this.log(`取消 ${sessionId} 的自动继续(${why})`);
947
1022
  }
948
1023
 
949
1024
  private fire(sessionId: SessionId, reason: string, force = false): void {
@@ -951,6 +1026,9 @@ export class AutoContinueRunner {
951
1026
  const state = this.state(sessionId);
952
1027
  const config = this.getConfig();
953
1028
  if (reason.endsWith(':silent') && !config.resumeSilentTurns) return;
1029
+ // 宽限期内循环被关闭: 发送前必须重新检查开关, 与 :silent 恢复同样处理。
1030
+ // 否则「关掉循环」后仍会多发出一次续跑。
1031
+ if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
954
1032
  if (state.subagent) return; // 子代理会话由父代理处理, 不抢跑
955
1033
  if (config.paused) {
956
1034
  this.log(`跳过 ${sessionId}(${reason}): 全局暂停中`);
@@ -996,7 +1074,8 @@ export class AutoContinueRunner {
996
1074
  this.prioritizedFollowups.delete(message.id);
997
1075
  }
998
1076
  const now = Date.now();
999
- state.consecutive += 1;
1077
+ // 自主循环的成功续跑不计入连续上限: 上限只约束失败(网络中断等)。
1078
+ if (reason !== LOOP_COMPLETED_REASON) state.consecutive += 1;
1000
1079
  state.pendingRecoveryAt = now; // 等待窗口内的下一个回合结束来判定恢复结果
1001
1080
  this.bumpStat({ sent: 1, ...(state.lastFailure !== undefined ? { code: state.lastFailure.code } : {}) });
1002
1081
  this.log(`已自动发送「${text}」到 ${sessionId}(${reason}), 第 ${state.consecutive} 次连续`);
package/src/index.ts CHANGED
@@ -32,8 +32,12 @@ export const AutoContinueSchema = z.object({
32
32
  continueTextMaxTokens: z.string().default(''),
33
33
  /** Resume observed model activity that completes without visible output. */
34
34
  resumeSilentTurns: z.boolean().default(true),
35
+ /** 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. */
36
+ resumeCompletedTurns: z.boolean().default(false),
35
37
  /** Text sent to resume a silent turn (same placeholders as `continueText`). */
36
38
  continueTextSilent: z.string().default(''),
39
+ /** Text sent for each autonomous-loop continuation (same placeholders as `continueText`). */
40
+ continueTextLoop: z.string().default(''),
37
41
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
38
42
  guardTools: z.boolean().default(true),
39
43
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -16,6 +16,7 @@ export const LOCALIZED_TEXT_DEFAULTS = {
16
16
  continueTextMaxTokens: '继续',
17
17
  continueTextSilent:
18
18
  '继续。你上一轮只输出了内部推理, 既没有回复也没有调用工具, 用户什么都没看到。每一轮都要以工具调用或可见回复结束。',
19
+ continueTextLoop: '继续',
19
20
  guardPendingText: '(上一步工具「{tool}」可能未完成, 先确认状态再继续, 不要重复执行)',
20
21
  guardDoneText: '(上一步工具「{tool}」已完成, 结果: {result}; 不要重复执行, 直接继续)',
21
22
  loopText: '(检测到你可能陷入循环, 请停止重复刚才的动作, 换一种方式继续)',
@@ -25,6 +26,7 @@ export const LOCALIZED_TEXT_DEFAULTS = {
25
26
  continueTextMaxTokens: 'Continue',
26
27
  continueTextSilent:
27
28
  '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.',
29
+ continueTextLoop: 'Continue',
28
30
  guardPendingText:
29
31
  '(The previous tool "{tool}" may not have completed. Check its state before continuing and do not run it again.)',
30
32
  guardDoneText:
@@ -44,8 +46,12 @@ export interface AutoContinueSettings {
44
46
  continueTextMaxTokens?: string;
45
47
  /** Resume observed model activity that completes without visible output. */
46
48
  resumeSilentTurns?: boolean;
49
+ /** 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. */
50
+ resumeCompletedTurns?: boolean;
47
51
  /** Text sent to resume a silent turn (same placeholders as `continueText`). */
48
52
  continueTextSilent?: string;
53
+ /** Text sent for each autonomous-loop continuation (same placeholders as `continueText`). */
54
+ continueTextLoop?: string;
49
55
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
50
56
  guardTools?: boolean;
51
57
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -102,6 +108,8 @@ export const DEFAULT_CONFIG: AutoContinueConfig = {
102
108
  locale: 'zh',
103
109
  ...LOCALIZED_TEXT_DEFAULTS.zh,
104
110
  resumeSilentTurns: true,
111
+ resumeCompletedTurns: false,
112
+ continueTextLoop: '',
105
113
  guardTools: true,
106
114
  graceMs: 3000,
107
115
  cooldownMs: 20000,
@@ -149,6 +157,10 @@ export function resolveConfig(section: AutoContinueSettings | undefined): AutoCo
149
157
  typeof value.continueTextSilent === 'string' && value.continueTextSilent.trim() !== ''
150
158
  ? value.continueTextSilent
151
159
  : localized.continueTextSilent;
160
+ const loopText =
161
+ typeof value.continueTextLoop === 'string' && value.continueTextLoop.trim() !== ''
162
+ ? value.continueTextLoop
163
+ : localized.continueTextLoop;
152
164
  const guardPendingText =
153
165
  typeof value.guardPendingText === 'string' && value.guardPendingText.trim() !== ''
154
166
  ? value.guardPendingText
@@ -162,7 +174,9 @@ export function resolveConfig(section: AutoContinueSettings | undefined): AutoCo
162
174
  continueText: text,
163
175
  continueTextMaxTokens: maxTokensText,
164
176
  resumeSilentTurns: booleanOr(value.resumeSilentTurns, DEFAULT_CONFIG.resumeSilentTurns),
177
+ resumeCompletedTurns: booleanOr(value.resumeCompletedTurns, DEFAULT_CONFIG.resumeCompletedTurns),
165
178
  continueTextSilent: silentText,
179
+ continueTextLoop: loopText,
166
180
  guardTools: booleanOr(value.guardTools, DEFAULT_CONFIG.guardTools),
167
181
  guardPendingText,
168
182
  guardDoneText,
@@ -850,6 +864,8 @@ export interface SessionState {
850
864
  loopFired: boolean;
851
865
  /** loop 重启的延迟定时器(冷却结束后再 schedule)。 */
852
866
  loopRetryTimer: ReturnType<typeof setTimeout> | undefined;
867
+ /** 冷却期恢复的延迟定时器(等到冷却结束再 schedule, 而不是丢弃这次恢复)。 */
868
+ cooldownRetryTimer: ReturnType<typeof setTimeout> | undefined;
853
869
  }
854
870
 
855
871
  export const freshState = (): SessionState => ({
@@ -877,6 +893,7 @@ export const freshState = (): SessionState => ({
877
893
  streamRepeatRun: 0,
878
894
  loopFired: false,
879
895
  loopRetryTimer: undefined,
896
+ cooldownRetryTimer: undefined,
880
897
  });
881
898
 
882
899