dsh-client-auto-continue 0.15.0 → 0.17.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +37 -21
  3. package/README.zh.md +34 -21
  4. package/docs/releases/v0.16.0.md +75 -0
  5. package/docs/releases/v0.17.0.md +62 -0
  6. package/docs/screenshots/01-settings-section.png +0 -0
  7. package/docs/screenshots/01-settings-section.zh.png +0 -0
  8. package/docs/screenshots/02-settings-card.png +0 -0
  9. package/docs/screenshots/02-settings-card.zh.png +0 -0
  10. package/docs/screenshots/07-card-panels.png +0 -0
  11. package/docs/screenshots/07-card-panels.zh.png +0 -0
  12. package/docs/screenshots/08-composer-toggle.png +0 -0
  13. package/docs/screenshots/08-composer-toggle.zh.png +0 -0
  14. package/docs/screenshots/README.md +8 -8
  15. package/docs/third-party-notices.md +19 -0
  16. package/lib/client.js +474 -133
  17. package/lib/client.js.map +4 -4
  18. package/lib/index.js +7560 -117
  19. package/lib/types/client/auto-continue-icon.d.ts +1 -0
  20. package/lib/types/client/bridge.d.ts +3 -1
  21. package/lib/types/client/composer-toggle.d.ts +6 -4
  22. package/lib/types/client/index.d.ts +1 -1
  23. package/lib/types/client/locales.d.ts +11 -8
  24. package/lib/types/client/mode-menu.d.ts +19 -0
  25. package/lib/types/client/native-toast.d.ts +17 -0
  26. package/lib/types/client/settings-card.d.ts +6 -5
  27. package/lib/types/host/engine.d.ts +2 -0
  28. package/lib/types/host/settings-migration.d.ts +14 -0
  29. package/lib/types/index.d.ts +14 -8
  30. package/lib/types/shared/core.d.ts +13 -1
  31. package/locale/en.json +6 -0
  32. package/locale/zh.json +6 -0
  33. package/package.json +24 -14
  34. package/src/client/auto-continue-icon.tsx +35 -0
  35. package/src/client/bridge.ts +35 -4
  36. package/src/client/composer-toggle.tsx +66 -14
  37. package/src/client/index.ts +4 -2
  38. package/src/client/locales.ts +32 -26
  39. package/src/client/mode-menu.tsx +110 -0
  40. package/src/client/native-toast.tsx +44 -0
  41. package/src/client/settings-card.tsx +156 -41
  42. package/src/client/styles.ts +61 -37
  43. package/src/host/engine.ts +54 -12
  44. package/src/host/settings-migration.ts +117 -0
  45. package/src/index.ts +63 -12
  46. package/src/shared/core.ts +23 -1
@@ -6,13 +6,39 @@
6
6
  */
7
7
 
8
8
  const css = `
9
- .dshAcComposer { display: inline-flex; align-items: center; gap: 7px; min-height: 32px; flex: 0 0 auto; font: inherit; }
10
- .dshAcComposerLabel { color: var(--dsw-alias-label-secondary); font-size: 12px; white-space: nowrap; }
11
- .dshAcSwitchTarget { display: inline-flex; align-items: center; min-height: 32px; }
9
+ .dshAcComposer { display: inline-flex; align-items: center; flex-wrap: wrap; gap: 6px; min-width: 0; min-height: 32px; max-width: 100%; font: inherit; }
10
+ .dshAcComposerCore { display: inline-flex; align-items: center; gap: 6px; min-width: 0; max-width: 100%; }
11
+ .dshAcComposerCore > span { min-width: 0; }
12
+ .dshAcModeTrigger { display: inline-flex; align-items: center; gap: 3px; min-width: 0; max-width: 132px; height: 28px; margin-left: -1px; padding: 0 4px 0 7px; border: 0; border-radius: var(--dsw-radius-sm, 6px); background: none; color: var(--dsw-alias-label-secondary); font: inherit; font-size: 13px; font-weight: 500; line-height: 20px; cursor: pointer; }
13
+ .dshAcModeTrigger:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); }
14
+ .dshAcModeTrigger:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); }
15
+ .dshAcModeTrigger:disabled { color: var(--dsw-alias-label-dimmed, var(--dsw-alias-label-tertiary)); cursor: default; }
16
+ .dshAcModeTriggerLabel { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
17
+ .dshAcModeChevron { display: inline-flex; flex: none; color: var(--dsw-alias-label-caption, var(--dsw-alias-label-tertiary)); transition: transform .12s ease; }
18
+ .dshAcModeChevron > svg { display: block; width: 14px; height: 14px; }
19
+ .dshAcModeChevronFallback { fill: none; stroke: currentColor; stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; }
20
+ .dshAcModeChevron[data-open=true] { transform: rotate(180deg); }
21
+ .dshAcModeMenu { position: relative; display: inline-flex; align-items: center; gap: 3px; min-width: 0; max-width: 132px; height: 28px; margin-left: -1px; padding: 0 4px 0 7px; border-radius: var(--dsw-radius-sm, 6px); color: var(--dsw-alias-label-secondary); font-size: 13px; font-weight: 500; line-height: 20px; }
22
+ .dshAcModeMenu:hover:not([data-disabled=true]) { color: var(--dsw-alias-label-primary); background: var(--dsw-alias-interactive-bg-hover); }
23
+ .dshAcModeMenu[data-disabled=true] { color: var(--dsw-alias-label-dimmed, var(--dsw-alias-label-tertiary)); }
24
+ .dshAcComposerSelect { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); font: inherit; font-size: 12px; }
25
+ .dshAcComposerSelect:disabled { cursor: default; }
26
+ /* Settings-card select (default session mode); kept scoped so the composer's
27
+ invisible overlay cannot stretch it over the whole app. */
28
+ .dshAcCard .dshAcMode { min-height: 32px; max-width: 100%; padding: 4px 6px; border: 1px solid var(--dsh-ac-line); border-radius: 6px; background: var(--dsh-ac-bg); color: var(--dsh-ac-text); font: inherit; font-size: 12px; }
29
+ .dshAcCard .dshAcMode:disabled { opacity: .5; }
30
+ .dshAcCard .dshAcMode:focus-visible { outline: 2px solid var(--dsh-ac-text); outline-offset: 3px; }
31
+ .dshAcComposerLabel { display: inline-flex; align-items: center; gap: 5px; flex: none; color: var(--dsw-alias-label-secondary); font-size: 12px; white-space: nowrap; }
32
+ .dshAcComposerText { display: inline; }
33
+ .dshAcComposerIcon { display: inline-flex; flex: none; color: var(--dsw-alias-label-secondary); }
34
+ .dshAcComposerIcon > svg { display: block; width: 14px; height: 14px; }
35
+ .dshAcComposerIconFallback { fill: none; stroke: currentColor; stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; }
36
+ .dshAcSwitchTarget { display: inline-flex; align-items: center; flex: none; min-height: 32px; }
12
37
  .dshAcSwitchTarget > button { position: relative; }
13
38
  .dshAcSwitchTarget > button::before { content: ''; position: absolute; inset: -6px -3px; }
14
39
  .dshAcComposerError { color: var(--dsw-alias-state-error-primary, var(--dsw-alias-label-secondary)); font-size: 12px; max-width: 160px; }
15
40
  .dshAcComposerError:empty { display: none; }
41
+ .dshAcToastIcon { display: block; width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; }
16
42
  .dshAcSwitch { position: relative; box-sizing: border-box; flex: none; width: 36px; height: 20px; padding: 2px; border: 0; border-radius: 999px; background: var(--dsw-alias-border-l3); cursor: pointer; }
17
43
  .dshAcSwitch[aria-checked='true'] { background: var(--dsw-alias-brand-primary); }
18
44
  .dshAcSwitch > span { display: block; width: 16px; height: 16px; border-radius: 50%; background: var(--dsw-alias-label-primary-foreground); }
@@ -39,27 +65,28 @@ const css = `
39
65
  .dshAcCard button { cursor: pointer; }
40
66
  .dshAcCard button:disabled { opacity: .4; cursor: default; }
41
67
  .dshAcCard :is(a,button,input,textarea):focus-visible { outline: 2px solid var(--dsh-ac-text); outline-offset: 3px; }
42
- .dshAcHeaderFrame { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.6fr); align-items: center; gap: 24px; margin: 20px 0; padding: 16px 18px; border-radius: 9px; color: #f9fafb; background: #23262c; }
43
- .dshAcIntroduction { min-width: 0; }
44
- .dshAcTitleLine { display: flex; align-items: center; gap: 10px; }
45
- .dshAcTitleLine h2 { font-size: 17px; font-weight: 620; line-height: 1.4; white-space: nowrap; }
46
- .dshAcStatus { white-space: nowrap; font-size: 11px; color: #dce0e6; background: #ffffff14; border-radius: 5px; padding: 2px 7px; }
47
- .dshAcIntroduction p { margin-top: 5px; color: #b9bec8; font-size: 12px; line-height: 1.6; }
48
- .dshAcRepository { display: flex; align-items: center; gap: 12px; min-width: 0; }
49
- .dshAcStar { display: grid; place-items: center; flex: none; width: 34px; height: 34px; border: 1px solid #625032; border-radius: 50%; background: #302c25; color: #e9be6d; }
50
- .dshAcStar svg { width: 18px; height: 18px; fill: #e9be6d12; stroke: currentColor; stroke-width: 1.5; stroke-linejoin: round; }
51
- .dshAcRepositoryCopy { display: flex; flex: 1; min-width: 0; flex-direction: column; gap: 5px; }
52
- .dshAcRepositoryCopy strong { font-size: 13px; font-weight: 560; line-height: 1.5; }
53
- .dshAcRepositoryCopy > span { color: #b9bec8; font-size: 10px; line-height: 1.6; }
54
- .dshAcRepositoryCopy > * { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
55
- .dshAcCard a.dshAcGithub { display: inline-flex; align-items: center; justify-content: center; gap: 8px; flex: none; min-height: 38px; padding: 9px 11px; border: 1px solid transparent; border-radius: 6px; color: #202329; background: #f4f5f7; text-decoration: none; font-size: 12px; font-weight: 550; white-space: nowrap; transition: background-color 140ms ease, box-shadow 140ms ease; }
56
- .dshAcCard a.dshAcGithub:hover { background: #fff; box-shadow: 0 0 0 3px #ffffff18; }
57
- .dshAcCard a.dshAcGithub:focus-visible { outline-color: #e9be6d; }
58
- .dshAcGithub > svg { flex: none; width: 17px; height: 17px; fill: currentColor; }
59
- .dshAcGithub > svg.dshAcExternal { width: 12px; height: 12px; fill: none; stroke: currentColor; stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; margin-left: 2px; }
60
- .dshAcGithubShort { display: none; }
68
+ .dshAcInvite { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 10px; margin: 0 0 18px; color: var(--dsh-ac-muted); font-size: 12px; line-height: 1.6; }
69
+ .dshAcInviteStar { color: #e9be6d; font-size: 13px; line-height: 1; }
70
+ .dshAcRepoLink { display: inline-flex; align-items: center; gap: 5px; color: var(--dsh-ac-text); text-decoration: none; }
71
+ .dshAcRepoLink:hover { text-decoration: underline; }
72
+ .dshAcRepoLink > svg:first-child { width: 14px; height: 14px; fill: currentColor; }
73
+ .dshAcRepoLink > svg.dshAcExternal { width: 11px; height: 11px; fill: none; stroke: currentColor; stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; }
74
+ .dshAcNativeFields { display: flex; flex-direction: column; min-width: 0; }
75
+ .dshAcNativeField { display: flex; flex-direction: column; gap: 6px; min-width: 0; padding: 12px 0; }
76
+ .dshAcNativeHead { display: flex; align-items: center; justify-content: space-between; gap: 12px; min-width: 0; }
77
+ .dshAcNativeLabel { color: var(--dsh-ac-text); font-size: 13px; font-weight: 500; line-height: 19.5px; }
78
+ .dshAcNativeHint { color: var(--dsh-ac-muted); font-size: 12px; line-height: 18px; }
79
+ .dshAcNativeToggleRow { display: flex; align-items: center; justify-content: space-between; gap: 16px; min-width: 0; }
80
+ .dshAcNativeActions { display: inline-flex; align-items: center; flex: none; gap: 10px; }
81
+ .dshAcNativeReset { padding: 0; border: 0; background: none; color: var(--dsh-ac-muted); font-size: 11px; white-space: nowrap; }
82
+ .dshAcNativeReset:hover:not(:disabled) { color: var(--dsh-ac-text); text-decoration: underline; }
83
+ .dshAcNativeSegment { display: block; min-width: 0; }
84
+ .dshAcNativeSegment[data-disabled=true] { opacity: .5; pointer-events: none; }
85
+ .dshAcNativeTextarea { box-sizing: border-box; width: 100%; min-height: 66px; resize: vertical; padding: 8px 12px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 12px; background: var(--dsw-alias-bg-layer-2, #353638); color: var(--dsh-ac-text); font: inherit; font-size: 13px; line-height: 19.5px; }
86
+ .dshAcNativeTextarea::placeholder { color: var(--dsh-ac-muted); opacity: .7; }
87
+ .dshAcNativeTextarea[aria-invalid=true] { border-color: var(--dsw-alias-state-error-primary); }
61
88
  .dshAcReadOnly { padding: 10px 0; color: var(--dsh-ac-muted); }
62
- .dshAcLayout { display: grid; grid-template-columns: 164px minmax(0, 1fr); border-top: 1px solid var(--dsh-ac-line); min-height: 462px; }
89
+ .dshAcLayout { display: grid; grid-template-columns: 164px minmax(0, 1fr); min-height: 462px; }
63
90
  .dshAcNav { display: flex; flex-direction: column; gap: 4px; padding: 16px 18px 16px 0; position: sticky; top: 16px; align-self: start; }
64
91
  .dshAcNav > button { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-height: 37px; padding: 8px 11px; border: 0; border-radius: 6px; text-align: left; background: none; color: var(--dsw-alias-label-secondary); }
65
92
  .dshAcNav > button:hover, .dshAcNav > button[aria-selected=true] { color: var(--dsh-ac-text); background: var(--dsw-alias-interactive-bg-hover); }
@@ -106,9 +133,6 @@ const css = `
106
133
  .dshAcPauseId { flex: 1; font: 12px ui-monospace, SFMono-Regular, monospace; }
107
134
  .dshAcRecovery { display: grid; gap: 4px; min-width: 0; overflow-wrap: anywhere; }
108
135
  @container auto-continue-settings (max-width: 760px) {
109
- .dshAcHeaderFrame { grid-template-columns: minmax(0, 1fr) auto; gap: 16px; }
110
- .dshAcRepositoryCopy { display: none; }
111
- .dshAcRepository { gap: 10px; }
112
136
  .dshAcLayout { grid-template-columns: 136px minmax(0, 1fr); }
113
137
  .dshAcCategory { padding-left: 20px; }
114
138
  .dshAcFieldControl { flex-direction: column-reverse; align-items: flex-end; gap: 6px; }
@@ -124,18 +148,18 @@ const css = `
124
148
  .dshAcFooter { align-items: flex-start; flex-direction: column; gap: 10px; }
125
149
  .dshAcFooter > div { width: 100%; justify-content: flex-end; }
126
150
  }
127
- @container auto-continue-settings (max-width: 440px) {
128
- .dshAcHeaderFrame { gap: 12px; padding: 14px; }
129
- .dshAcTitleLine { gap: 6px; }
130
- .dshAcTitleLine h2 { font-size: 15px; white-space: normal; }
131
- .dshAcStatus { padding: 2px 5px; font-size: 10px; }
132
- .dshAcIntroduction p { font-size: 11px; }
133
- .dshAcStar, .dshAcGithubLong { display: none; }
134
- .dshAcGithubShort { display: inline; }
135
- .dshAcCard a.dshAcGithub { gap: 6px; padding: 8px; font-size: 11px; }
136
- .dshAcGithub > svg.dshAcExternal { display: none; }
151
+ /* Match the composer's own pickers (permission/mode) instead of the viewport:
152
+ the nearest query container is the composer row, so the label collapses at
153
+ the same 460px threshold as the native permission picker. */
154
+ @container (width <= 640px) {
155
+ .dshAcComposerCore { gap: 5px; }
156
+ .dshAcModeTrigger, .dshAcModeMenu { max-width: 104px; padding: 0 3px 0 6px; }
157
+ }
158
+ @container (width <= 460px) {
159
+ .dshAcComposerText { display: none; }
160
+ .dshAcModeTrigger, .dshAcModeMenu { max-width: 28px; padding: 0 2px; }
161
+ .dshAcModeTriggerLabel { display: none; }
137
162
  }
138
- @media (prefers-reduced-motion: reduce) { .dshAcCard a.dshAcGithub { transition: none; } }
139
163
 
140
164
  `;
141
165
 
@@ -31,6 +31,7 @@ import {
31
31
  isTransientAgentError,
32
32
  isTransientFailure,
33
33
  resolveConfig,
34
+ sessionMode,
34
35
  sleep,
35
36
  todayKey,
36
37
  trackPendingEcho,
@@ -377,6 +378,28 @@ export class AutoContinueRunner {
377
378
  for (const listener of this.stateListeners) listener();
378
379
  }
379
380
 
381
+ private sessionConfig(sessionId: SessionId): AutoContinueConfig {
382
+ const config = this.getConfig();
383
+ const mode = sessionMode(config.sessionModes, sessionId);
384
+ return {
385
+ ...config,
386
+ paused: config.paused || mode === 'off',
387
+ resumeCompletedTurns: mode === 'default' ? config.resumeCompletedTurns : mode === 'loop',
388
+ loopGuard: config.loopGuard && mode !== 'off',
389
+ };
390
+ }
391
+
392
+ configurationChanged(): void {
393
+ if (this.disposed) return;
394
+ for (const [sessionId, state] of this.states) {
395
+ const config = this.sessionConfig(sessionId);
396
+ if (config.paused || (isLoopReason(state.pendingReason ?? '') && !config.resumeCompletedTurns)) {
397
+ this.cancelPending(sessionId, '会话模式或全局设置已更改');
398
+ }
399
+ }
400
+ this.emitState();
401
+ }
402
+
380
403
  /** 对外(状态桥): 消费待展示的通知。 */
381
404
  drainNotices(): HostNotice[] {
382
405
  return this.notices.splice(0, this.notices.length);
@@ -616,7 +639,7 @@ export class AutoContinueRunner {
616
639
  state: SessionState,
617
640
  event: SessionEvent<'assistant/chunk'>,
618
641
  ): void {
619
- if (!this.getConfig().loopGuard || !state.running || state.loopFired) return;
642
+ if (!this.sessionConfig(sessionId).loopGuard || !state.running || state.loopFired) return;
620
643
  const chunk = this.assistantChunkText(event);
621
644
  if (chunk === '') return;
622
645
  const merged = `${state.streamTail}${chunk}`.replace(/\r/g, '');
@@ -639,7 +662,7 @@ export class AutoContinueRunner {
639
662
  state: SessionState,
640
663
  event: SessionEvent<'assistant/message'>,
641
664
  ): void {
642
- if (!this.getConfig().loopGuard) return;
665
+ if (!this.sessionConfig(sessionId).loopGuard) return;
643
666
  const text = this.assistantText(event);
644
667
  const trimmed = visibleText(text);
645
668
  // 相同文本重复(不限长度): 模型反复输出完全相同的消息是最强的循环信号,
@@ -676,7 +699,7 @@ export class AutoContinueRunner {
676
699
  state: SessionState,
677
700
  toolRepeat?: ToolRepeatSignal,
678
701
  ): void {
679
- if (!this.getConfig().loopGuard) return;
702
+ if (!this.sessionConfig(sessionId).loopGuard) return;
680
703
  if (state.loopFired) return;
681
704
  if (!state.running) return; // 只干预运行中的回合
682
705
  const config = this.getConfig();
@@ -769,11 +792,11 @@ export class AutoContinueRunner {
769
792
  state.lastTurn = event.data.turn;
770
793
  state.lastFailureAt = Date.now();
771
794
  this.noteRecovery(sessionId, 'error');
772
- if (this.getConfig().resumeCompletedTurns) {
795
+ if (this.sessionConfig(sessionId).resumeCompletedTurns) {
773
796
  // 自主循环覆盖无可见输出的回合, 但这类回合是「失败」而非成功:
774
797
  // 不 force, 否则会绕过连续上限与冷却, 让卡住的模型无限重试。
775
798
  this.schedule(sessionId, LOOP_SILENT_REASON);
776
- } else if (this.getConfig().resumeSilentTurns) {
799
+ } else if (this.sessionConfig(sessionId).resumeSilentTurns) {
777
800
  this.schedule(sessionId, `turn/end:${reasonKind}:silent`);
778
801
  }
779
802
  break;
@@ -784,7 +807,7 @@ export class AutoContinueRunner {
784
807
  // 自主循环的例外只在于「是否续跑」, 不在于「是否清零预算」: 循环对每个
785
808
  // completed 回合都强制续跑, 但失败预算依旧只在可见输出时清零, 否则
786
809
  // 空回合/未观察到的回合会不断抹掉连续计数, 令连续上限永远无法生效。
787
- if (this.getConfig().resumeCompletedTurns) {
810
+ if (this.sessionConfig(sessionId).resumeCompletedTurns) {
788
811
  if (turnOutput === 'visible') {
789
812
  state.consecutive = 0;
790
813
  state.lastFailure = undefined;
@@ -798,6 +821,7 @@ export class AutoContinueRunner {
798
821
  }
799
822
  } else if (reasonKind === 'aborted') {
800
823
  if (isLoopGuardCancelReason((reason as { reason?: unknown }).reason)) {
824
+ if (this.sessionConfig(sessionId).paused) break;
801
825
  // 我们自己的 loop guard 打断: 视为可恢复中断, 用循环提示文本重启回合。
802
826
  // 不清 consecutive / lastAttemptAt: 冷却与连续上限在 loop 路径同样生效,
803
827
  // 防止无限打断重发(issue #13); 打断本身受冷却约束, 重启也要等冷却。
@@ -877,6 +901,7 @@ export class AutoContinueRunner {
877
901
 
878
902
  private onTurnFailure(sessionId: SessionId, reason: string, failure: FailureFacts): void {
879
903
  const config = this.getConfig();
904
+ if (sessionMode(config.sessionModes, sessionId) === 'off') return;
880
905
  if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
881
906
  const copy = NOTICE_COPY[config.locale];
882
907
  const summary = `${failure.code}${failure.status !== undefined ? ` (HTTP ${failure.status})` : ''}`;
@@ -1011,10 +1036,11 @@ export class AutoContinueRunner {
1011
1036
 
1012
1037
  private schedule(sessionId: SessionId, reason: string, force = false): void {
1013
1038
  const state = this.state(sessionId);
1014
- const config = this.getConfig();
1039
+ const config = this.sessionConfig(sessionId);
1040
+ if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
1015
1041
  if (this.isSubagent(sessionId, state)) return; // 子代理会话由父代理处理, 不抢跑
1016
1042
  if (config.paused) {
1017
- this.log(`跳过 ${sessionId}(${reason}): 全局暂停中`);
1043
+ this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
1018
1044
  return;
1019
1045
  }
1020
1046
  if (Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) {
@@ -1042,6 +1068,7 @@ export class AutoContinueRunner {
1042
1068
  const timer = setTimeout(() => {
1043
1069
  if (state.pendingTimer !== timer) return;
1044
1070
  state.pendingTimer = undefined;
1071
+ state.pendingReason = undefined;
1045
1072
  // 保险丝: 定时器回调内任何异常(含 inactive context)都不得成为未捕获异常炸掉进程。
1046
1073
  try {
1047
1074
  void this.fire(sessionId, reason, force);
@@ -1050,6 +1077,7 @@ export class AutoContinueRunner {
1050
1077
  }
1051
1078
  }, config.graceMs);
1052
1079
  state.pendingTimer = timer;
1080
+ state.pendingReason = reason;
1053
1081
  const template = this.templateFor(config, reason);
1054
1082
  this.log(
1055
1083
  `检测到非人为中断 ${sessionId}(${reason}), ${config.graceMs}ms 后自动发送「${template}」`,
@@ -1063,8 +1091,10 @@ export class AutoContinueRunner {
1063
1091
  private deferCooldownRetry(sessionId: SessionId, reason: string, remaining: number): void {
1064
1092
  const state = this.state(sessionId);
1065
1093
  if (state.cooldownRetryTimer !== undefined) clearTimeout(state.cooldownRetryTimer);
1094
+ state.pendingReason = reason;
1066
1095
  state.cooldownRetryTimer = setTimeout(() => {
1067
1096
  state.cooldownRetryTimer = undefined;
1097
+ state.pendingReason = undefined;
1068
1098
  try {
1069
1099
  this.schedule(sessionId, reason);
1070
1100
  } catch (error) {
@@ -1087,6 +1117,7 @@ export class AutoContinueRunner {
1087
1117
 
1088
1118
  private cancelPending(sessionId: SessionId, why: string): void {
1089
1119
  const state = this.state(sessionId);
1120
+ state.pendingReason = undefined;
1090
1121
  let cancelled = false;
1091
1122
  if (state.pendingTimer !== undefined) {
1092
1123
  clearTimeout(state.pendingTimer);
@@ -1099,13 +1130,18 @@ export class AutoContinueRunner {
1099
1130
  state.cooldownRetryTimer = undefined;
1100
1131
  cancelled = true;
1101
1132
  }
1133
+ if (state.loopRetryTimer !== undefined) {
1134
+ clearTimeout(state.loopRetryTimer);
1135
+ state.loopRetryTimer = undefined;
1136
+ cancelled = true;
1137
+ }
1102
1138
  if (cancelled) this.log(`取消 ${sessionId} 的自动继续(${why})`);
1103
1139
  }
1104
1140
 
1105
1141
  private fire(sessionId: SessionId, reason: string, force = false): void {
1106
1142
  if (this.disposed) return;
1107
1143
  const state = this.state(sessionId);
1108
- const config = this.getConfig();
1144
+ const config = this.sessionConfig(sessionId);
1109
1145
  const manualResume = force && reason === MANUAL_NOTIFICATION_REASON;
1110
1146
  if (reason.endsWith(':silent') && !config.resumeSilentTurns) return;
1111
1147
  // 宽限期内循环被关闭: 发送前必须重新检查开关, 与 :silent 恢复同样处理。
@@ -1113,7 +1149,7 @@ export class AutoContinueRunner {
1113
1149
  if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
1114
1150
  if (this.isSubagent(sessionId, state)) return; // 子代理会话由父代理处理, 不抢跑
1115
1151
  if (config.paused && !manualResume) {
1116
- this.log(`跳过 ${sessionId}(${reason}): 全局暂停中`);
1152
+ this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
1117
1153
  return;
1118
1154
  }
1119
1155
  if (!manualResume && Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) {
@@ -1302,6 +1338,7 @@ export class AutoContinueRunner {
1302
1338
  if (this.bootScannedSessions.has(session) || session.header?.origin === 'subagent') continue;
1303
1339
  sessionId = session.id;
1304
1340
  if (typeof sessionId !== 'string' || sessionId === '') throw new TypeError('session id is unavailable');
1341
+ if (this.sessionConfig(sessionId).paused) continue;
1305
1342
  const state = this.state(sessionId);
1306
1343
  if (state.pendingTimer !== undefined || state.consecutive >= config.maxConsecutive) continue;
1307
1344
  if (now - state.lastAttemptAt < this.cooldownFor(state)) continue;
@@ -1434,6 +1471,7 @@ export class AutoContinueRunner {
1434
1471
  continue;
1435
1472
  }
1436
1473
  const sessionId = record.header.id;
1474
+ if (this.sessionConfig(sessionId).paused || Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) continue;
1437
1475
  if (record.live || this.storedSwept.has(sessionId)) continue;
1438
1476
  this.storedSwept.add(sessionId);
1439
1477
  if (record.header.origin === 'subagent') continue;
@@ -1443,6 +1481,10 @@ export class AutoContinueRunner {
1443
1481
  const stored: StoredObservation = await this.readStored(signal => query.observeSession(sessionId, { projectionMode: 'all', signal }), deadline);
1444
1482
  observation = stored;
1445
1483
  if (this.disposed) return;
1484
+ if (this.sessionConfig(sessionId).paused) {
1485
+ this.storedSwept.delete(sessionId);
1486
+ continue;
1487
+ }
1446
1488
  const events = validateSessionEvents(stored.events);
1447
1489
  if (events.length === 0) continue;
1448
1490
  // 快照之后客户端可能已打开该会话: 归还 live 扫描, 避免与 live 路径
@@ -1544,7 +1586,7 @@ export class AutoContinueRunner {
1544
1586
  presetId: string | undefined,
1545
1587
  logged: { provider: string; model: string } | undefined,
1546
1588
  ): Promise<boolean> {
1547
- if (this.disposed || this.getConfig().paused || !this.getConfig().scanOnBoot) return false;
1589
+ if (this.disposed || this.sessionConfig(sessionId).paused || !this.getConfig().scanOnBoot) return false;
1548
1590
  const presets = this.ctx.get('agentPresets');
1549
1591
  // Mirrors session-controller's adopt: without agent options the agent has no
1550
1592
  // provider/model, so prompt variables like {{model}} have no value and the
@@ -1559,7 +1601,7 @@ export class AutoContinueRunner {
1559
1601
  return true;
1560
1602
  }
1561
1603
  const resolvedId = (await presets.resolve(presetId)).id;
1562
- if (this.disposed || this.getConfig().paused || !this.getConfig().scanOnBoot) return false;
1604
+ if (this.disposed || this.sessionConfig(sessionId).paused || !this.getConfig().scanOnBoot) return false;
1563
1605
  if (this.ctx.agents.get(sessionId) !== undefined) return true;
1564
1606
  await this.ctx.agents.resume({
1565
1607
  resumeSessionId: sessionId,
@@ -0,0 +1,117 @@
1
+ import { readFile, writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import type { Context } from '@deepseek-ai/cordis';
4
+ import { parse } from 'yaml';
5
+ import type { AutoContinueSettings } from '../shared/core.ts';
6
+
7
+ /** Recover an import interrupted between the profile save and completion file. */
8
+ export const LEGACY_SETTINGS_IMPORTED = '_legacySettingsImported';
9
+ export type EntrySettings = AutoContinueSettings & { _legacySettingsImported?: boolean };
10
+ export type LiveEntrySettings = { get(): EntrySettings | undefined };
11
+
12
+ interface ProfileEntry {
13
+ fiber?: unknown;
14
+ }
15
+
16
+ interface MigrationContext extends Context {
17
+ profileContext: { home: string; dir: string };
18
+ configEditor: {
19
+ entries(): ProfileEntry[];
20
+ edit(entry: ProfileEntry, change: (current: Record<string, unknown>) => Record<string, unknown>): Promise<void>;
21
+ };
22
+ loader: { await(): Promise<void> };
23
+ }
24
+
25
+ function record(value: unknown): value is Record<string, unknown> {
26
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
27
+ }
28
+
29
+ /** Import the mixed desktop host's legacy document through the profile editor.
30
+ * The original file stays untouched, including other plugins' settings.
31
+ */
32
+ export function migrateLegacySettings(
33
+ ctx: Context,
34
+ config: LiveEntrySettings,
35
+ fields: readonly string[],
36
+ validate: (value: AutoContinueSettings) => unknown,
37
+ ): () => EntrySettings | undefined {
38
+ // A profile may compose its editor after this entry. Hold recovery from the
39
+ // outset in that case; standalone hosts without a profile still work.
40
+ let pending = ctx.get('profileContext') !== undefined;
41
+
42
+ ctx.inject(['profileContext'], (injected) => {
43
+ const migration = injected as MigrationContext;
44
+ const completedPath = join(migration.profileContext.dir, '.auto-continue-settings-imported');
45
+ let disposed = false;
46
+ pending = true;
47
+ migration.effect(() => () => { disposed = true; });
48
+ const failed = () => {
49
+ if (disposed) return;
50
+ // YAML errors may quote other plugins' secrets, so do not log the source
51
+ // or parser exception. Leave the original document available for repair.
52
+ migration.logger.error('[auto-continue] Could not import settings-legacy.yaml; automatic recovery and loop guard are held until the file/profile can be read and saved, then restart the host');
53
+ };
54
+ // Do not return this task to Cordis: profile edits require the owning entry
55
+ // to be active, and Loader.await() must not wait for this migration itself.
56
+ void (async () => {
57
+ try {
58
+ const completed = await readFile(completedPath, 'utf8');
59
+ if (completed.trim() === '1') return;
60
+ if (config.get()?._legacySettingsImported !== true) throw new Error('Invalid settings migration record');
61
+ } catch (error) {
62
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
63
+ }
64
+ if (disposed) return;
65
+ if (config.get()?._legacySettingsImported === true) {
66
+ await writeFile(completedPath, '1\n', { mode: 0o600 });
67
+ return;
68
+ }
69
+ let source: string;
70
+ try {
71
+ source = await readFile(join(migration.profileContext.home, 'settings-legacy.yaml'), 'utf8');
72
+ } catch (error) {
73
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
74
+ throw error;
75
+ }
76
+ // Parser warnings can include source lines from unrelated namespaces.
77
+ const document: unknown = parse(source, { logLevel: 'silent' });
78
+ if (document === null || document === undefined) return;
79
+ if (!record(document)) throw new Error('Legacy settings must be a mapping');
80
+ const section = document['auto-continue'];
81
+ if (section === undefined) return;
82
+ if (!record(section)) throw new Error('Legacy auto-continue settings must be a mapping');
83
+ const values = Object.fromEntries(fields.filter(key => Object.prototype.hasOwnProperty.call(section, key)).map(key => [key, section[key]]));
84
+ validate(values);
85
+ return values;
86
+ })().then(values => {
87
+ if (disposed) return;
88
+ // Hosts without an editor can still run when there is nothing to import.
89
+ if (values === undefined) { pending = false; return; }
90
+ migration.inject(['configEditor', 'loader'], (ready) => {
91
+ const editor = ready as MigrationContext;
92
+ let cancelled = false;
93
+ editor.effect(() => () => { cancelled = true; });
94
+ void (async () => {
95
+ await editor.loader.await();
96
+ if (disposed || cancelled) return;
97
+ const entry = editor.configEditor.entries().find(candidate => candidate.fiber === ctx.fiber);
98
+ if (entry === undefined) throw new Error('Auto-continue profile entry is unavailable');
99
+ await editor.configEditor.edit(entry, current => {
100
+ if (disposed || cancelled) throw new Error('Auto-continue was unloaded during settings migration');
101
+ if (current[LEGACY_SETTINGS_IMPORTED] === true) return current;
102
+ // Explicit profile values, including concurrent edits, take precedence.
103
+ return { ...values, ...current, [LEGACY_SETTINGS_IMPORTED]: true };
104
+ });
105
+ // Keep completion outside resettable Config. The Config marker above
106
+ // repairs this file on restart if the process stops between writes.
107
+ if (!disposed && !cancelled) await writeFile(completedPath, '1\n', { mode: 0o600 });
108
+ })().then(() => {
109
+ if (!disposed && !cancelled) pending = false;
110
+ }, () => { if (!cancelled) failed(); });
111
+ });
112
+ }, failed);
113
+ });
114
+
115
+ // Startup recovery must not run with defaults while a stored pause is loading.
116
+ return () => pending ? { ...config.get(), paused: true, loopGuard: false } : config.get();
117
+ }
package/src/index.ts CHANGED
@@ -13,17 +13,19 @@
13
13
  import type { Context } from '@deepseek-ai/cordis';
14
14
  import z from '@deepseek-ai/schemastery';
15
15
  import { AutoContinueRunner } from './host/engine.ts';
16
- import { resolveConfig, type AutoContinueSettings } from './shared/core.ts';
16
+ import { LEGACY_SETTINGS_IMPORTED, migrateLegacySettings, type EntrySettings, type LiveEntrySettings } from './host/settings-migration.ts';
17
+ import { isSessionMode, resolveConfig, type AutoContinueSettings } from './shared/core.ts';
17
18
  // Type-only: pulls the `ctx.webServer` Context augmentation.
18
19
  import type {} from '@deepseek-ai/dsh-host-webserver';
19
20
  import type {} from '@deepseek-ai/dsh-agent';
20
21
  import type {} from '@deepseek-ai/dsh-session';
22
+ import type {} from '@deepseek-ai/dsh-settings';
21
23
 
22
24
  /** Settings namespace of the auto-continue plugin (lowercase kebab-case). */
23
25
  export const AUTO_CONTINUE_NS = 'auto-continue';
24
26
 
25
27
  /** Wire schema; blank localized text fields tell resolveConfig() to select the active locale's defaults. */
26
- export const AutoContinueSchema = z.object({
28
+ const settingsFields = {
27
29
  /** Active browser/UI locale mirrored by the client. */
28
30
  locale: z.string().default('zh'),
29
31
  /** Text automatically sent after an interruption. */
@@ -76,7 +78,9 @@ export const AutoContinueSchema = z.object({
76
78
  notify: z.boolean().default(false),
77
79
  /** Globally pause auto-continue: no live or scan send. */
78
80
  paused: z.boolean().default(false),
79
- /** Show the global auto-continue switch in the conversation composer. */
81
+ /** Persist choices by session, including an explicit return to the profile default. */
82
+ sessionModes: z.dict(z.union(['default', 'off', 'recover', 'loop'])).default({}).hidden(),
83
+ /** Show the session mode selector in the conversation composer. */
80
84
  showComposerToggle: z.boolean().default(true),
81
85
  /** Loop guard: detect a running turn spinning in place and restart it. */
82
86
  loopGuard: z.boolean().default(true),
@@ -94,14 +98,18 @@ export const AutoContinueSchema = z.object({
94
98
  loopText: z
95
99
  .string()
96
100
  .default(''),
97
- });
101
+ };
102
+ export const AutoContinueSchema = z.object(settingsFields);
98
103
 
99
104
  /** Loader config is a live reference on DSH 0.1.7, and a plain object on older hosts. */
100
- export type AutoContinueEntryConfig = AutoContinueSettings | { get(): AutoContinueSettings | undefined };
105
+ export type AutoContinueEntryConfig = EntrySettings | LiveEntrySettings;
101
106
 
102
107
  // Keep the wire schema usable by legacy Settings while exposing the live root
103
108
  // to current Loaders. Older Schemastery releases do not have volatile().
104
- const entrySchema = AutoContinueSchema as typeof AutoContinueSchema & {
109
+ const entrySchema = z.object({
110
+ ...settingsFields,
111
+ [LEGACY_SETTINGS_IMPORTED]: z.boolean().default(false).hidden(),
112
+ }) as typeof AutoContinueSchema & {
105
113
  volatile?: () => z<AutoContinueSettings, AutoContinueEntryConfig>;
106
114
  };
107
115
  export const Config = entrySchema.volatile?.() ?? AutoContinueSchema;
@@ -122,6 +130,10 @@ function entryConfig(config: AutoContinueEntryConfig | undefined): AutoContinueS
122
130
  */
123
131
  export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
124
132
  let legacyConfig: (() => AutoContinueSettings | undefined) | undefined;
133
+ const modern = config !== undefined && 'get' in config && typeof config.get === 'function';
134
+ const readEntry = modern
135
+ ? migrateLegacySettings(ctx, config, Object.keys(settingsFields), AutoContinueSchema)
136
+ : () => entryConfig(config);
125
137
  // Settings is optional: it must never prevent the engine or bridge starting.
126
138
  // Hosts predating Config-derived forms still own a separate settings document.
127
139
  ctx.inject(['settings'], (settingsCtx) => {
@@ -129,7 +141,9 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
129
141
  register?: (ns: string, schema: typeof AutoContinueSchema, options: { applies: string }) => unknown;
130
142
  get?: (ns: string) => AutoContinueSettings | undefined;
131
143
  } }).settings;
132
- if (typeof settings.register !== 'function' || typeof settings.get !== 'function') return;
144
+ // Some desktop hosts expose both APIs. A live Config already owns this
145
+ // namespace, so registering it again splits reads and writes across stores.
146
+ if (modern || typeof settings.register !== 'function' || typeof settings.get !== 'function') return;
133
147
  settings.register(AUTO_CONTINUE_NS, AutoContinueSchema, { applies: 'live' });
134
148
  const read = () => settings.get!(AUTO_CONTINUE_NS);
135
149
  legacyConfig = read;
@@ -146,7 +160,12 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
146
160
  ctx.inject(['agents', 'webServer'], (engineCtx) => {
147
161
  // 回调重入时先清理旧引擎, 避免定时器与监听器叠加。
148
162
  disposeEngine?.();
149
- const runner = new AutoContinueRunner(engineCtx, () => resolveConfig(legacyConfig?.() ?? entryConfig(config)));
163
+ const readConfig = () => resolveConfig(legacyConfig?.() ?? readEntry());
164
+ const runner = new AutoContinueRunner(engineCtx, readConfig);
165
+ const writableSettings = () => {
166
+ const settings = engineCtx.get('settings');
167
+ return settings?.writable && typeof settings.mutate === 'function' ? settings : undefined;
168
+ };
150
169
 
151
170
  // 状态桥: browser 侧订阅通知与运行时状态(SSE)。
152
171
  const sseClients = new Set<(data: string) => void>();
@@ -160,13 +179,21 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
160
179
  }
161
180
  }
162
181
  };
163
- const statePayload = (): string =>
164
- JSON.stringify({
182
+ const statePayload = (): string => {
183
+ const config = readConfig();
184
+ return JSON.stringify({
165
185
  type: 'state',
166
186
  stats: runner.todayStats(),
167
187
  paused: runner.activePauses(),
168
188
  recoveryAttempts: runner.recentRecoveryAttempts(),
189
+ sessionPolicy: {
190
+ modes: config.sessionModes,
191
+ defaultMode: config.resumeCompletedTurns ? 'loop' : 'recover',
192
+ paused: config.paused,
193
+ writable: writableSettings() !== undefined,
194
+ },
169
195
  });
196
+ };
170
197
 
171
198
  runner.subscribeNotices(() => {
172
199
  for (const notice of runner.drainNotices()) {
@@ -176,6 +203,10 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
176
203
  runner.subscribeState(() => {
177
204
  pushToAll(`data: ${statePayload()}\n\n`);
178
205
  });
206
+ // Event names differ across the legacy Settings and live Config hosts.
207
+ const stopSettings = ['settings/updated', 'settings/document-updated', 'app-boot/config-reload'].map(event =>
208
+ (engineCtx.on as (event: string, listener: () => void) => () => void)(event, () => runner.configurationChanged()),
209
+ );
179
210
 
180
211
  const stopBridge = engineCtx.webServer.register({
181
212
  kind: 'exact',
@@ -210,9 +241,28 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
210
241
  body += chunk.toString('utf8');
211
242
  if (body.length > 4096) req.destroy();
212
243
  });
213
- req.on('end', () => {
244
+ req.on('end', async () => {
214
245
  try {
215
- const parsed = JSON.parse(body) as { sessionId?: string; action?: string };
246
+ const parsed = JSON.parse(body) as { sessionId?: string; action?: string; mode?: unknown };
247
+ if (parsed.action === 'set-session-mode') {
248
+ const { sessionId, mode } = parsed;
249
+ if (typeof sessionId !== 'string' || sessionId.trim() === '' || sessionId.length > 256 ||
250
+ ['__proto__', 'prototype', 'constructor'].includes(sessionId) || !isSessionMode(mode)) {
251
+ throw new TypeError('Invalid session mode');
252
+ }
253
+ const settings = writableSettings();
254
+ if (settings === undefined) {
255
+ res.writeHead(503, { 'content-type': 'application/json' });
256
+ res.end(JSON.stringify({ ok: false }));
257
+ return;
258
+ }
259
+ // Path mutations preserve choices written concurrently by other tabs.
260
+ await settings.mutate(AUTO_CONTINUE_NS, [{ op: 'set', path: ['sessionModes', sessionId], value: mode }]);
261
+ runner.configurationChanged();
262
+ res.writeHead(200, { 'content-type': 'application/json' });
263
+ res.end(JSON.stringify({ ok: true, sessionId, mode }));
264
+ return;
265
+ }
216
266
  if (typeof parsed.action === 'string') {
217
267
  runner.handleNoticeAction((parsed.sessionId as never) ?? undefined, parsed.action);
218
268
  res.writeHead(200, { 'content-type': 'application/json' });
@@ -233,6 +283,7 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
233
283
  if (disposed) return;
234
284
  disposed = true;
235
285
  runner.dispose();
286
+ for (const stop of stopSettings) stop();
236
287
  stopBridge();
237
288
  stopActions();
238
289
  for (const close of closeClients) close();