dsh-client-auto-continue 0.11.8 → 0.11.9

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.
@@ -6,10 +6,11 @@
6
6
  * bugs (issue #13) cannot exist by construction. Listens to the session event
7
7
  * firehose (`session/event`), sends through the agent registry
8
8
  * (`agent.followup`), cancels through `agent.cancel`, and reads configuration
9
- * from the settings service.
9
+ * injected by the entry (`apply`'s config argument, merged with schema
10
+ * defaults by `resolveConfig`).
10
11
  *
11
- * All behavior is driven by the `auto-continue` settings namespace (see the
12
- * plugin's settings card); every knob below is user-configurable there.
12
+ * All behavior is driven by the `auto-continue` entry config; every knob below
13
+ * is user-configurable there.
13
14
  */
14
15
 
15
16
  import type { Context } from '@deepseek-ai/cordis';
@@ -201,10 +202,13 @@ export class AutoContinueRunner {
201
202
  private readonly disposeSessionEvents: () => void;
202
203
  private readonly disposeInboxEvents: () => void;
203
204
  private disposed = false;
205
+ private readonly bootScannedSessions = new WeakSet<Session>();
206
+ private bootScanTimer: ReturnType<typeof setTimeout> | undefined;
207
+ private wakeBootScan: (() => void) | undefined;
204
208
 
205
209
  /**
206
- * @param ctx - host plugin context (agents registry, session events, settings).
207
- * @param getConfig - read the current resolved configuration (settings service).
210
+ * @param ctx - host plugin context (agents registry, session events).
211
+ * @param getConfig - read the current resolved configuration (entry config).
208
212
  */
209
213
  constructor(
210
214
  private readonly ctx: Context,
@@ -326,6 +330,10 @@ export class AutoContinueRunner {
326
330
  dispose(): void {
327
331
  if (this.disposed) return;
328
332
  this.disposed = true;
333
+ if (this.bootScanTimer !== undefined) clearTimeout(this.bootScanTimer);
334
+ this.bootScanTimer = undefined;
335
+ this.wakeBootScan?.();
336
+ this.wakeBootScan = undefined;
329
337
  this.disposeSessionEvents();
330
338
  this.disposeInboxEvents();
331
339
  this.prioritizedFollowups.clear();
@@ -363,24 +371,58 @@ export class AutoContinueRunner {
363
371
  if (event.type === 'tool/call') {
364
372
  const state = this.state(sessionId);
365
373
  // 任何新鲜调用都代表进展(即使缺关联 id);旧帧重放不能清短句 streak。
366
- if (state.tools.recordCall(event)) state.shortRun = 0;
374
+ if (state.tools.recordCall(event)) {
375
+ state.shortRun = 0;
376
+ if (this.tracksOutput(state, event)) state.turnOutput = 'visible';
377
+ }
367
378
  } else if (event.type === 'tool/result') {
368
379
  const state = this.state(sessionId);
369
380
  state.tools.recordResult(event);
370
381
  } else if (event.type === 'step/start') {
371
382
  const state = this.state(sessionId);
383
+ if (this.tracksOutput(state, event) && state.turnOutput === 'empty') state.turnOutput = 'silent';
372
384
  const repeat = state.tools.confirmRepeatAtStep(event.seq);
373
385
  if (repeat !== undefined) this.checkLoop(sessionId, state, repeat);
374
386
  } else if (event.type === 'assistant/chunk') {
375
387
  const state = this.state(sessionId);
388
+ if (this.tracksOutput(state, event)) {
389
+ const chunk = event.data.chunk;
390
+ const visible = (chunk.type === 'text-delta' && chunk.text.trim() !== '') ||
391
+ chunk.type === 'tool-call-delta' ||
392
+ (chunk.type === 'block-end' && this.hasVisibleContent([chunk.block])) ||
393
+ (chunk.type === 'block-start' && chunk.blockType !== 'reasoning' && chunk.blockType !== 'text');
394
+ if (visible) state.turnOutput = 'visible';
395
+ else if (state.turnOutput === 'empty' && chunk.type !== 'usage' && chunk.type !== 'finish') state.turnOutput = 'silent';
396
+ }
376
397
  this.onAssistantChunk(sessionId, state, event);
377
398
  } else if (event.type === 'assistant/message') {
378
399
  const state = this.state(sessionId);
400
+ if (this.tracksOutput(state, event)) {
401
+ if (this.hasVisibleContent(event.data.message.content)) state.turnOutput = 'visible';
402
+ else if (state.turnOutput === 'empty') state.turnOutput = 'silent';
403
+ }
379
404
  this.onAssistantMessage(sessionId, state, event);
380
405
  }
381
406
  this.onSessionEvent(sessionId, event);
382
407
  }
383
408
 
409
+ private tracksOutput(state: SessionState, event: SessionEvent): boolean {
410
+ return state.running === true && state.outputTurn === (event.data as { turn?: number }).turn &&
411
+ event.seq > state.outputStartSeq;
412
+ }
413
+
414
+ /** Treat unknown block kinds conservatively: only reasoning and blank text are silent. */
415
+ private hasVisibleContent(content: unknown): boolean {
416
+ if (!Array.isArray(content)) return false;
417
+ return content.some((part: unknown) => {
418
+ if (part === null || typeof part !== 'object') return true;
419
+ const block = part as { type?: unknown; text?: unknown };
420
+ if (block.type === 'reasoning') return false;
421
+ if (block.type === 'text') return typeof block.text !== 'string' || block.text.trim() !== '';
422
+ return true;
423
+ });
424
+ }
425
+
384
426
  /** 从 assistant/message 事件提取纯文本。 */
385
427
  private assistantText(event: SessionEvent<'assistant/message'>): string {
386
428
  const content = event.data.message.content;
@@ -601,6 +643,9 @@ export class AutoContinueRunner {
601
643
  state.streamLastSegment = '';
602
644
  state.streamRepeatRun = 0;
603
645
  state.loopFired = false;
646
+ state.turnOutput = 'empty';
647
+ state.outputTurn = event.data.turn;
648
+ state.outputStartSeq = event.seq;
604
649
  if (state.loopRetryTimer !== undefined) {
605
650
  clearTimeout(state.loopRetryTimer);
606
651
  state.loopRetryTimer = undefined;
@@ -612,17 +657,34 @@ export class AutoContinueRunner {
612
657
  const loopCancelPending = state.loopFired;
613
658
  state.loopFired = false;
614
659
  this.cancelPending(sessionId, '收到新的 turn/end');
660
+ const turnOutput = state.outputTurn === event.data.turn ? state.turnOutput : 'unknown';
661
+ state.turnOutput = 'unknown';
662
+ state.outputTurn = undefined;
615
663
  const reason = event.data.reason;
616
664
  const reasonKind = readReasonKind(reason);
617
665
  if (reasonKind === undefined) {
618
666
  console.error(`[auto-continue] 忽略畸形 turn/end ${sessionId}: reason 无法解释`);
619
667
  break;
620
668
  }
621
- if (reasonKind === 'completed') {
622
- // 成功回合: 恢复健康状态, 并确认上一次自动发送的效果
623
- state.consecutive = 0;
669
+ if (reasonKind === 'no-visible-output' || (reasonKind === 'completed' && turnOutput === 'silent')) {
670
+ // 已观察到模型活动但没有可见输出; 没有模型活动的空回合不属于此类。
671
+ // 不清零 consecutive: 每轮都卡住的模型仍受冷却与连续上限约束。
672
+ // `no-visible-output` 是 DSH 为同一种回合提议的结束原因, 按同样方式处理。
624
673
  state.lastFailure = undefined;
625
- this.noteRecovery(sessionId, 'completed');
674
+ state.lastTurn = event.data.turn;
675
+ state.lastFailureAt = Date.now();
676
+ this.noteRecovery(sessionId, 'error');
677
+ if (this.getConfig().resumeSilentTurns) this.schedule(sessionId, `turn/end:${reasonKind}:silent`);
678
+ break;
679
+ }
680
+ if (reasonKind === 'completed') {
681
+ // Only observed visible output proves recovery; no-op and unknown
682
+ // turns must not erase the retry budget or count as successful.
683
+ if (turnOutput === 'visible') {
684
+ state.consecutive = 0;
685
+ state.lastFailure = undefined;
686
+ this.noteRecovery(sessionId, 'completed');
687
+ }
626
688
  } else if (reasonKind === 'aborted') {
627
689
  if (isLoopGuardCancelReason((reason as { reason?: unknown }).reason)) {
628
690
  // 我们自己的 loop guard 打断: 视为可恢复中断, 用循环提示文本重启回合。
@@ -650,7 +712,7 @@ export class AutoContinueRunner {
650
712
  } catch (error) {
651
713
  console.error(`[auto-continue] loop 重启异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
652
714
  }
653
- }, remaining);
715
+ }, remaining + 10); // +10ms: the schedule re-check compares Date.now() against the cooldown; a 1ms wall-clock step can otherwise make it read just under, silently dropping the restart
654
716
  this.log(`loop 重启延迟 ${remaining}ms(冷却期) ${sessionId}`);
655
717
  } else {
656
718
  this.schedule(sessionId, 'loop:aborted');
@@ -862,16 +924,20 @@ export class AutoContinueRunner {
862
924
  }
863
925
  }, config.graceMs);
864
926
  state.pendingTimer = timer;
865
- const template = reason.startsWith('loop:')
866
- ? config.loopText
867
- : reason.includes('max-tokens')
868
- ? config.continueTextMaxTokens
869
- : config.continueText;
927
+ const template = this.templateFor(config, reason);
870
928
  this.log(
871
929
  `检测到非人为中断 ${sessionId}(${reason}), ${config.graceMs}ms 后自动发送「${template}」`,
872
930
  );
873
931
  }
874
932
 
933
+ /** 按调度原因选择续跑模板: loop 重启、无输出回合、max-tokens, 其余用通用继续文本。 */
934
+ private templateFor(config: AutoContinueConfig, reason: string): string {
935
+ if (reason.startsWith('loop:')) return config.loopText;
936
+ if (reason.endsWith(':silent')) return config.continueTextSilent;
937
+ if (reason.includes('max-tokens')) return config.continueTextMaxTokens;
938
+ return config.continueText;
939
+ }
940
+
875
941
  private cancelPending(sessionId: SessionId, why: string): void {
876
942
  const state = this.state(sessionId);
877
943
  if (state.pendingTimer === undefined) return;
@@ -884,6 +950,7 @@ export class AutoContinueRunner {
884
950
  if (this.disposed) return;
885
951
  const state = this.state(sessionId);
886
952
  const config = this.getConfig();
953
+ if (reason.endsWith(':silent') && !config.resumeSilentTurns) return;
887
954
  if (state.subagent) return; // 子代理会话由父代理处理, 不抢跑
888
955
  if (config.paused) {
889
956
  this.log(`跳过 ${sessionId}(${reason}): 全局暂停中`);
@@ -903,11 +970,7 @@ export class AutoContinueRunner {
903
970
  return;
904
971
  }
905
972
  // 模板填充: continueText 可含 {code}/{message}/{status}/{tool}/{turn}/{errorCount}/{sessionTitle}/{elapsed} 占位符
906
- const template = reason.startsWith('loop:')
907
- ? config.loopText
908
- : reason.includes('max-tokens')
909
- ? config.continueTextMaxTokens
910
- : config.continueText;
973
+ const template = this.templateFor(config, reason);
911
974
  const text = this.buildContinueText(config, state, template);
912
975
  // 发送: followup 负责唤醒; 同步 inbox 插入事件会在唤醒前把本消息移到已有队列之前。
913
976
  const agent = this.ctx.agents.get(sessionId);
@@ -1003,12 +1066,11 @@ export class AutoContinueRunner {
1003
1066
  }
1004
1067
 
1005
1068
  private async bootScanLoop(): Promise<void> {
1006
- await this.scanLoop(Infinity, 3000);
1007
- }
1008
-
1009
- /** 反复尝试扫描, 直到成功(宿主就绪)或达到次数上限。 */
1010
- private async scanLoop(attempts: number, delayMs: number): Promise<void> {
1011
- for (let attempt = 0; attempt < attempts && !this.disposed; attempt += 1) {
1069
+ // Sessions restored after this window are too old for startup recovery.
1070
+ // Keep polling only within that window, including while globally paused.
1071
+ const deadline = Date.now() + this.getConfig().freshMs;
1072
+ for (let attempt = 0; !this.disposed; attempt += 1) {
1073
+ if (attempt > 0 && Date.now() >= deadline) return;
1012
1074
  try {
1013
1075
  if (await this.scanInterrupted()) return;
1014
1076
  } catch (error) {
@@ -1016,100 +1078,110 @@ export class AutoContinueRunner {
1016
1078
  // 宿主未就绪时每 3s 重试; 只节流记录日志, 避免刷屏。
1017
1079
  if (attempt % 10 === 0) {
1018
1080
  this.log(
1019
- `扫描失败(${attempt + 1}/${attempts === Infinity ? '∞' : attempts}): ${
1081
+ `扫描失败(${attempt + 1}): ${
1020
1082
  error instanceof Error ? error.message : String(error)
1021
1083
  }`,
1022
1084
  );
1023
1085
  }
1024
1086
  }
1025
- if (attempt + 1 < attempts) await sleep(delayMs);
1087
+ const remaining = deadline - Date.now();
1088
+ if (this.disposed || remaining <= 0) return;
1089
+ await new Promise<void>((resolve) => {
1090
+ this.wakeBootScan = resolve;
1091
+ this.bootScanTimer = setTimeout(() => {
1092
+ this.bootScanTimer = undefined;
1093
+ this.wakeBootScan = undefined;
1094
+ resolve();
1095
+ }, Math.min(3000, remaining));
1096
+ });
1026
1097
  }
1027
1098
  }
1028
1099
 
1029
- /**
1030
- * 扫描最近中断过的会话: 最后回合以非人为原因结束, 且其后没有新回合或用户消息。
1031
- * @returns 是否成功完成一次扫描(宿主就绪)。
1032
- */
1100
+ /** Inspect newly available sessions; process each settled startup history once. */
1033
1101
  private async scanInterrupted(): Promise<boolean> {
1034
1102
  const config = this.getConfig();
1035
- if (config.paused) return true; // 全局暂停: 不做任何扫描
1036
- // 只扫 live agents(host 重启后 agent-loop 会 resume 崩溃会话, 冷会话无需处理)
1103
+ if (config.paused || !config.scanOnBoot) return false;
1037
1104
  const now = Date.now();
1038
1105
  const candidates: {
1039
- sessionId: SessionId;
1106
+ session: Session;
1040
1107
  events: readonly SessionEvent[];
1108
+ lastEnd: SessionEvent<'turn/end'>;
1109
+ reasonKind: string;
1110
+ failure?: FailureFacts;
1041
1111
  lastActivityAt: number;
1042
1112
  listIndex: number;
1043
1113
  }[] = [];
1044
1114
  for (const agent of this.ctx.agents.list()) {
1045
1115
  const session = agent.session;
1046
- if (session.header.origin === 'subagent') continue; // 子代理由父代理处理
1047
- const events = snapshotSessionEvents(session);
1048
- const lastActivityAt = events.reduce(
1049
- (latest, event) => Math.max(latest, event.time),
1050
- Number.isFinite(session.header.createdAt) ? session.header.createdAt : 0,
1051
- );
1052
- candidates.push({
1053
- sessionId: session.id,
1054
- events,
1055
- lastActivityAt,
1056
- listIndex: candidates.length,
1057
- });
1058
- }
1059
- candidates.sort(
1060
- (left, right) =>
1061
- right.lastActivityAt - left.lastActivityAt || left.listIndex - right.listIndex,
1062
- );
1063
- for (const candidate of candidates.slice(0, config.scanLimit)) {
1064
- if (this.disposed) return true;
1065
- const state = this.state(candidate.sessionId);
1066
- if (state.pendingTimer !== undefined) continue;
1067
- if (state.consecutive >= config.maxConsecutive) continue;
1116
+ if (session.header.origin === 'subagent' || this.bootScannedSessions.has(session)) continue;
1117
+ const state = this.state(session.id);
1118
+ if (state.pendingTimer !== undefined || state.consecutive >= config.maxConsecutive) continue;
1068
1119
  if (now - state.lastAttemptAt < this.cooldownFor(state)) continue;
1069
- if (now < (this.pauseUntil.get(candidate.sessionId) ?? 0)) continue; // 会话暂停中
1070
- const events = candidate.events;
1071
- // 从尾部找最后一个 turn/end
1120
+ if (now < (this.pauseUntil.get(session.id) ?? 0)) continue;
1121
+ const events = snapshotSessionEvents(session);
1122
+ // A published session may still be waiting for its first history snapshot.
1123
+ if (events.length === 0) continue;
1072
1124
  let lastEnd: SessionEvent<'turn/end'> | undefined;
1073
1125
  for (let i = events.length - 1; i >= 0; i -= 1) {
1074
1126
  const event = events[i];
1075
- if (event !== undefined && event.type === 'turn/end') {
1076
- lastEnd = event;
1077
- break;
1078
- }
1127
+ if (event?.type === 'turn/end') { lastEnd = event; break; }
1079
1128
  }
1080
- if (lastEnd === undefined) continue;
1081
- const reason = lastEnd.data.reason;
1082
- const reasonKind = readReasonKind(reason);
1083
- if (reasonKind === undefined || !isNonHumanReason(reasonKind)) continue;
1084
- if (lastEnd.time < now - config.freshMs) continue; // 太久远, 不翻旧账
1085
- // 该 turn/end 之后不能有新回合或用户消息(说明已被处理)
1086
- let superseded = false;
1087
- for (const event of events) {
1088
- if (event.seq <= lastEnd.seq) continue;
1089
- if (event.type === 'turn/start') superseded = true;
1090
- if (event.type === 'user/message' && event.data.source.kind === 'user') superseded = true;
1091
- if (superseded) break;
1129
+ const reasonKind = readReasonKind(lastEnd?.data.reason);
1130
+ const silent = reasonKind === 'no-visible-output' && config.resumeSilentTurns;
1131
+ const superseded = lastEnd !== undefined && events.some((event) =>
1132
+ event.seq > lastEnd!.seq && (event.type === 'turn/start' ||
1133
+ (event.type === 'user/message' && event.data.source.kind === 'user')),
1134
+ );
1135
+ if (lastEnd === undefined || reasonKind === undefined || (!isNonHumanReason(reasonKind) && !silent) ||
1136
+ lastEnd.time < now - config.freshMs || superseded) {
1137
+ this.bootScannedSessions.add(session);
1138
+ continue;
1092
1139
  }
1093
- if (superseded) continue;
1094
- // 幂等护栏: 从历史事件里重建上一步工具调用的执行状态
1095
- this.applyGuardFromEvents(state, events, lastEnd.seq);
1096
- const scanReason = `scan:turn/end:${reasonKind}`;
1097
- this.log(`扫描发现中断 ${candidate.sessionId}(turn/end:${reasonKind}), 交给恢复策略处理`);
1140
+ let failure: FailureFacts | undefined;
1098
1141
  if (reasonKind === 'error') {
1099
- const failure = parseFailureFacts((reason as { error?: unknown }).error);
1142
+ failure = parseFailureFacts((lastEnd.data.reason as { error?: unknown }).error);
1100
1143
  if (failure === undefined) {
1101
- console.error(`[auto-continue] 忽略畸形扫描 turn/end ${candidate.sessionId}: error details 无法解释`);
1144
+ this.bootScannedSessions.add(session);
1145
+ console.error(`[auto-continue] 忽略畸形扫描 turn/end ${session.id}: error details 无法解释`);
1146
+ continue;
1147
+ }
1148
+ if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
1149
+ this.bootScannedSessions.add(session);
1150
+ this.onTurnFailure(session.id, 'scan:turn/end:error', failure);
1102
1151
  continue;
1103
1152
  }
1153
+ }
1154
+ candidates.push({
1155
+ session, events, lastEnd, reasonKind, failure,
1156
+ lastActivityAt: events.reduce((latest, event) => Math.max(latest, event.time), 0),
1157
+ listIndex: candidates.length,
1158
+ });
1159
+ }
1160
+ // Limit recoveries, not healthy/permanent histories that cannot be resumed.
1161
+ candidates.sort((left, right) => right.lastActivityAt - left.lastActivityAt || left.listIndex - right.listIndex);
1162
+ for (const candidate of candidates.slice(0, config.scanLimit)) {
1163
+ if (this.disposed) return true;
1164
+ const { session, events, lastEnd, reasonKind, failure } = candidate;
1165
+ this.bootScannedSessions.add(session);
1166
+ const state = this.state(session.id);
1167
+ this.applyGuardFromEvents(state, events, lastEnd.seq);
1168
+ const scanReason = `scan:turn/end:${reasonKind}${reasonKind === 'no-visible-output' ? ':silent' : ''}`;
1169
+ this.log(`扫描发现中断 ${session.id}(turn/end:${reasonKind}), 交给恢复策略处理`);
1170
+ if (failure !== undefined) {
1104
1171
  state.lastFailure = failure;
1105
1172
  state.lastTurn = lastEnd.data.turn;
1106
1173
  state.lastFailureAt = lastEnd.time;
1107
- this.onTurnFailure(candidate.sessionId, scanReason, state.lastFailure);
1174
+ this.onTurnFailure(session.id, scanReason, failure);
1108
1175
  } else {
1109
- this.schedule(candidate.sessionId, scanReason);
1176
+ if (reasonKind === 'no-visible-output') {
1177
+ state.lastFailure = undefined;
1178
+ state.lastTurn = lastEnd.data.turn;
1179
+ state.lastFailureAt = lastEnd.time;
1180
+ }
1181
+ this.schedule(session.id, scanReason);
1110
1182
  }
1111
1183
  }
1112
- return true;
1184
+ return false;
1113
1185
  }
1114
1186
 
1115
1187
  /** 从历史事件恢复上一步工具调用状态(扫描路径的幂等护栏)。 */
package/src/index.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * Host half of the auto-continue plugin.
3
3
  *
4
- * - Registers the `auto-continue` settings namespace (the browser half's
5
- * settings card edits it; the host engine reads it).
4
+ * - Configuration is this entry's own Loader config: `apply(ctx, config)`
5
+ * injects it into the engine, where `resolveConfig` merges it with the
6
+ * schema defaults (the browser half's settings card writes the same values).
6
7
  * - Runs the single-instance auto-continue engine: listens to the session
7
8
  * event firehose, sends via `agent.followup`, cancels via `agent.cancel`.
8
9
  * - Serves a status bridge the browser half subscribes to: notifications and
@@ -11,10 +12,8 @@
11
12
  */
12
13
  import type { Context } from '@deepseek-ai/cordis';
13
14
  import z from '@deepseek-ai/schemastery';
14
- import type { SettingsNamespace } from '@deepseek-ai/dsh-settings';
15
15
  import { AutoContinueRunner } from './host/engine.ts';
16
16
  import { resolveConfig, type AutoContinueSettings } from './shared/core.ts';
17
- // The type-only settings import also pulls in the `ctx.settings` Context augmentation.
18
17
  // Type-only: pulls the `ctx.webServer` Context augmentation.
19
18
  import type {} from '@deepseek-ai/dsh-host-webserver';
20
19
  import type {} from '@deepseek-ai/dsh-agent';
@@ -22,7 +21,6 @@ import type {} from '@deepseek-ai/dsh-session';
22
21
 
23
22
  /** Settings namespace of the auto-continue plugin (lowercase kebab-case). */
24
23
  export const AUTO_CONTINUE_NS = 'auto-continue';
25
- const SETTINGS_NS = AUTO_CONTINUE_NS as SettingsNamespace;
26
24
 
27
25
  /** Wire schema; blank localized text fields tell resolveConfig() to select the active locale's defaults. */
28
26
  export const AutoContinueSchema = z.object({
@@ -32,6 +30,10 @@ export const AutoContinueSchema = z.object({
32
30
  continueText: z.string().default(''),
33
31
  /** Text sent when the output token ceiling is reached (same placeholders as `continueText`). */
34
32
  continueTextMaxTokens: z.string().default(''),
33
+ /** Resume observed model activity that completes without visible output. */
34
+ resumeSilentTurns: z.boolean().default(true),
35
+ /** Text sent to resume a silent turn (same placeholders as `continueText`). */
36
+ continueTextSilent: z.string().default(''),
35
37
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
36
38
  guardTools: z.boolean().default(true),
37
39
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -48,11 +50,11 @@ export const AutoContinueSchema = z.object({
48
50
  cooldownMs: z.natural().default(20000),
49
51
  /** Max consecutive auto-continues per session before stopping. */
50
52
  maxConsecutive: z.natural().min(1).default(3),
51
- /** Scan recently interrupted sessions on page load / reconnect. */
53
+ /** Recover delayed interrupted sessions during the host startup window. */
52
54
  scanOnBoot: z.boolean().default(true),
53
- /** Max sessions the scan checks (most recently updated). */
55
+ /** Max eligible recoveries per scan pass (most recently active first). */
54
56
  scanLimit: z.natural().min(1).default(8),
55
- /** Scan only considers interruptions inside this window (ms). */
57
+ /** Interruption freshness and duration of startup polling (ms). */
56
58
  freshMs: z.natural().default(15 * 60 * 1000),
57
59
  /** Log `[auto-continue]` lines to the browser console. */
58
60
  verbose: z.boolean().default(true),
@@ -86,34 +88,61 @@ export const AutoContinueSchema = z.object({
86
88
  .default(''),
87
89
  });
88
90
 
91
+ /** Loader config is a live reference on DSH 0.1.7, and a plain object on older hosts. */
92
+ export type AutoContinueEntryConfig = AutoContinueSettings | { get(): AutoContinueSettings | undefined };
93
+
94
+ // Keep the wire schema usable by legacy Settings while exposing the live root
95
+ // to current Loaders. Older Schemastery releases do not have volatile().
96
+ const entrySchema = AutoContinueSchema as typeof AutoContinueSchema & {
97
+ volatile?: () => z<AutoContinueSettings, AutoContinueEntryConfig>;
98
+ };
99
+ export const Config = entrySchema.volatile?.() ?? AutoContinueSchema;
100
+
101
+ function entryConfig(config: AutoContinueEntryConfig | undefined): AutoContinueSettings | undefined {
102
+ return config !== undefined && 'get' in config ? config.get() : config;
103
+ }
104
+
89
105
  /**
90
- * Plugin body: register the settings namespace, start the single-instance
91
- * engine, and serve the status bridge.
106
+ * Plugin body: start the single-instance engine and serve the status bridge.
107
+ *
108
+ * Configuration comes from this entry's own Loader config (merged with the
109
+ * schema defaults by `resolveConfig`); the current harness exposes entry
110
+ * config through the settings service instead of the legacy `register`/`get`
111
+ * namespace API this plugin was originally written against.
92
112
  * @param ctx - host plugin context.
113
+ * @param config - this entry's config (may be partial / absent → defaults).
93
114
  */
94
- export function apply(ctx: Context): void {
115
+ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
116
+ let legacyConfig: (() => AutoContinueSettings | undefined) | undefined;
117
+ // Settings is optional: it must never prevent the engine or bridge starting.
118
+ // Hosts predating Config-derived forms still own a separate settings document.
95
119
  ctx.inject(['settings'], (settingsCtx) => {
96
- settingsCtx.settings.register(SETTINGS_NS, AutoContinueSchema, {
97
- applies: 'live',
120
+ const settings = (settingsCtx as unknown as { settings: {
121
+ register?: (ns: string, schema: typeof AutoContinueSchema, options: { applies: string }) => unknown;
122
+ get?: (ns: string) => AutoContinueSettings | undefined;
123
+ } }).settings;
124
+ if (typeof settings.register !== 'function' || typeof settings.get !== 'function') return;
125
+ settings.register(AUTO_CONTINUE_NS, AutoContinueSchema, { applies: 'live' });
126
+ const read = () => settings.get!(AUTO_CONTINUE_NS);
127
+ legacyConfig = read;
128
+ settingsCtx.effect(() => () => {
129
+ if (legacyConfig === read) legacyConfig = undefined;
98
130
  });
99
131
  });
100
-
101
132
  // 引擎引用: inject 回调可能重入(依赖组合变化), 顶层 effect 在 fiber 卸载时必跑。
102
133
  // dispose 绑定必须挂在 apply 的顶层 ctx 上——挂 inject 派生 ctx 的 effect 在 config HMR
103
134
  // 替换行时不会执行, 悬空定时器会撞上 inactive context 炸掉整个进程。
104
- let runnerRef: AutoContinueRunner | undefined;
135
+ let disposeEngine: (() => void) | undefined;
105
136
 
106
137
  // 单实例引擎: host 进程内监听会话事件, 所有标签页共享同一个引擎。
107
- ctx.inject(['settings', 'agents', 'webServer'], (engineCtx) => {
138
+ ctx.inject(['agents', 'webServer'], (engineCtx) => {
108
139
  // 回调重入时先清理旧引擎, 避免定时器与监听器叠加。
109
- if (runnerRef !== undefined) runnerRef.dispose();
110
- const runner = new AutoContinueRunner(engineCtx, () =>
111
- resolveConfig(engineCtx.settings.get(SETTINGS_NS) as AutoContinueSettings | undefined),
112
- );
113
- runnerRef = runner;
140
+ disposeEngine?.();
141
+ const runner = new AutoContinueRunner(engineCtx, () => resolveConfig(legacyConfig?.() ?? entryConfig(config)));
114
142
 
115
143
  // 状态桥: browser 侧订阅通知与运行时状态(SSE)。
116
144
  const sseClients = new Set<(data: string) => void>();
145
+ const closeClients = new Set<() => void>();
117
146
  const pushToAll = (data: string): void => {
118
147
  for (const send of sseClients) {
119
148
  try {
@@ -139,7 +168,7 @@ export function apply(ctx: Context): void {
139
168
  pushToAll(`data: ${statePayload()}\n\n`);
140
169
  });
141
170
 
142
- engineCtx.webServer.register({
171
+ const stopBridge = engineCtx.webServer.register({
143
172
  kind: 'exact',
144
173
  path: '/api/auto-continue-bridge',
145
174
  handler: (req, res) => {
@@ -153,12 +182,17 @@ export function apply(ctx: Context): void {
153
182
  res.write(data);
154
183
  };
155
184
  sseClients.add(send);
156
- req.on('close', () => sseClients.delete(send));
185
+ const close = () => { res.end(); };
186
+ closeClients.add(close);
187
+ req.on('close', () => {
188
+ sseClients.delete(send);
189
+ closeClients.delete(close);
190
+ });
157
191
  },
158
192
  });
159
193
 
160
194
  // 通知按钮动作: browser 点击「立即续跑 / 暂停该会话」时 POST 到这里。
161
- engineCtx.webServer.register({
195
+ const stopActions = engineCtx.webServer.register({
162
196
  kind: 'exact',
163
197
  path: '/api/auto-continue-action',
164
198
  handler: (req, res) => {
@@ -185,13 +219,26 @@ export function apply(ctx: Context): void {
185
219
  });
186
220
  },
187
221
  });
222
+ let disposed = false;
223
+ const dispose = () => {
224
+ if (disposed) return;
225
+ disposed = true;
226
+ runner.dispose();
227
+ stopBridge();
228
+ stopActions();
229
+ for (const close of closeClients) close();
230
+ closeClients.clear();
231
+ sseClients.clear();
232
+ };
233
+ disposeEngine = dispose;
234
+ engineCtx.effect(() => dispose);
188
235
  });
189
236
 
190
237
  // 顶层生命周期绑定: fiber 卸载时清理引擎(定时器/监听器)。
191
238
  // 挂在 apply 的 ctx 上保证 Cordis 一定会调用, 防止 inactive context 崩溃。
192
239
  ctx.effect(() => () => {
193
- const runner = runnerRef;
194
- runnerRef = undefined;
195
- if (runner !== undefined) runner.dispose();
240
+ const dispose = disposeEngine;
241
+ disposeEngine = undefined;
242
+ dispose?.();
196
243
  });
197
244
  }