dsh-client-auto-continue 0.14.3 → 0.16.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.
@@ -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. */
@@ -38,6 +40,8 @@ export const AutoContinueSchema = z.object({
38
40
  continueTextSilent: z.string().default(''),
39
41
  /** Text sent for each autonomous-loop continuation (same placeholders as `continueText`). */
40
42
  continueTextLoop: z.string().default(''),
43
+ /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
44
+ continueTextInterrupted: z.string().default(''),
41
45
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
42
46
  guardTools: z.boolean().default(true),
43
47
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -74,7 +78,9 @@ export const AutoContinueSchema = z.object({
74
78
  notify: z.boolean().default(false),
75
79
  /** Globally pause auto-continue: no live or scan send. */
76
80
  paused: z.boolean().default(false),
77
- /** 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. */
78
84
  showComposerToggle: z.boolean().default(true),
79
85
  /** Loop guard: detect a running turn spinning in place and restart it. */
80
86
  loopGuard: z.boolean().default(true),
@@ -92,14 +98,18 @@ export const AutoContinueSchema = z.object({
92
98
  loopText: z
93
99
  .string()
94
100
  .default(''),
95
- });
101
+ };
102
+ export const AutoContinueSchema = z.object(settingsFields);
96
103
 
97
104
  /** Loader config is a live reference on DSH 0.1.7, and a plain object on older hosts. */
98
- export type AutoContinueEntryConfig = AutoContinueSettings | { get(): AutoContinueSettings | undefined };
105
+ export type AutoContinueEntryConfig = EntrySettings | LiveEntrySettings;
99
106
 
100
107
  // Keep the wire schema usable by legacy Settings while exposing the live root
101
108
  // to current Loaders. Older Schemastery releases do not have volatile().
102
- 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 & {
103
113
  volatile?: () => z<AutoContinueSettings, AutoContinueEntryConfig>;
104
114
  };
105
115
  export const Config = entrySchema.volatile?.() ?? AutoContinueSchema;
@@ -120,6 +130,10 @@ function entryConfig(config: AutoContinueEntryConfig | undefined): AutoContinueS
120
130
  */
121
131
  export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
122
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);
123
137
  // Settings is optional: it must never prevent the engine or bridge starting.
124
138
  // Hosts predating Config-derived forms still own a separate settings document.
125
139
  ctx.inject(['settings'], (settingsCtx) => {
@@ -127,7 +141,9 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
127
141
  register?: (ns: string, schema: typeof AutoContinueSchema, options: { applies: string }) => unknown;
128
142
  get?: (ns: string) => AutoContinueSettings | undefined;
129
143
  } }).settings;
130
- 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;
131
147
  settings.register(AUTO_CONTINUE_NS, AutoContinueSchema, { applies: 'live' });
132
148
  const read = () => settings.get!(AUTO_CONTINUE_NS);
133
149
  legacyConfig = read;
@@ -144,7 +160,12 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
144
160
  ctx.inject(['agents', 'webServer'], (engineCtx) => {
145
161
  // 回调重入时先清理旧引擎, 避免定时器与监听器叠加。
146
162
  disposeEngine?.();
147
- 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
+ };
148
169
 
149
170
  // 状态桥: browser 侧订阅通知与运行时状态(SSE)。
150
171
  const sseClients = new Set<(data: string) => void>();
@@ -158,12 +179,21 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
158
179
  }
159
180
  }
160
181
  };
161
- const statePayload = (): string =>
162
- JSON.stringify({
182
+ const statePayload = (): string => {
183
+ const config = readConfig();
184
+ return JSON.stringify({
163
185
  type: 'state',
164
186
  stats: runner.todayStats(),
165
187
  paused: runner.activePauses(),
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
+ },
166
195
  });
196
+ };
167
197
 
168
198
  runner.subscribeNotices(() => {
169
199
  for (const notice of runner.drainNotices()) {
@@ -173,6 +203,10 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
173
203
  runner.subscribeState(() => {
174
204
  pushToAll(`data: ${statePayload()}\n\n`);
175
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
+ );
176
210
 
177
211
  const stopBridge = engineCtx.webServer.register({
178
212
  kind: 'exact',
@@ -207,9 +241,28 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
207
241
  body += chunk.toString('utf8');
208
242
  if (body.length > 4096) req.destroy();
209
243
  });
210
- req.on('end', () => {
244
+ req.on('end', async () => {
211
245
  try {
212
- 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
+ }
213
266
  if (typeof parsed.action === 'string') {
214
267
  runner.handleNoticeAction((parsed.sessionId as never) ?? undefined, parsed.action);
215
268
  res.writeHead(200, { 'content-type': 'application/json' });
@@ -230,6 +283,7 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
230
283
  if (disposed) return;
231
284
  disposed = true;
232
285
  runner.dispose();
286
+ for (const stop of stopSettings) stop();
233
287
  stopBridge();
234
288
  stopActions();
235
289
  for (const close of closeClients) close();
@@ -9,6 +9,22 @@ import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types';
9
9
  /** Supported UI/config locales. Any unknown browser locale falls back to Chinese. */
10
10
  export type AutoContinueLocale = 'en' | 'zh';
11
11
 
12
+ export type SessionMode = 'default' | 'off' | 'recover' | 'loop';
13
+
14
+ export interface SessionPolicy {
15
+ modes: Record<string, SessionMode>;
16
+ defaultMode: 'recover' | 'loop';
17
+ paused: boolean;
18
+ writable: boolean;
19
+ }
20
+
21
+ export const isSessionMode = (value: unknown): value is SessionMode =>
22
+ value === 'default' || value === 'off' || value === 'recover' || value === 'loop';
23
+
24
+ export function sessionMode(modes: Record<string, SessionMode>, sessionId: string): SessionMode {
25
+ return Object.prototype.hasOwnProperty.call(modes, sessionId) && isSessionMode(modes[sessionId]) ? modes[sessionId]! : 'default';
26
+ }
27
+
12
28
  /** Locale-owned defaults for the user-editable text fields. */
13
29
  export const LOCALIZED_TEXT_DEFAULTS = {
14
30
  zh: {
@@ -17,6 +33,8 @@ export const LOCALIZED_TEXT_DEFAULTS = {
17
33
  continueTextSilent:
18
34
  '继续。你上一轮只输出了内部推理, 既没有回复也没有调用工具, 用户什么都没看到。每一轮都要以工具调用或可见回复结束。',
19
35
  continueTextLoop: '继续',
36
+ continueTextInterrupted:
37
+ '继续。宿主在你上一轮运行期间重启了; 重启时未完成的工具调用已按「结果未知」收尾。从中断处继续, 重试可能有副作用的操作前先核实外部状态。',
20
38
  guardPendingText: '(上一步工具「{tool}」可能未完成, 先确认状态再继续, 不要重复执行)',
21
39
  guardDoneText: '(上一步工具「{tool}」已完成, 结果: {result}; 不要重复执行, 直接继续)',
22
40
  loopText: '(检测到你可能陷入循环, 请停止重复刚才的动作, 换一种方式继续)',
@@ -27,6 +45,8 @@ export const LOCALIZED_TEXT_DEFAULTS = {
27
45
  continueTextSilent:
28
46
  '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
47
  continueTextLoop: 'Continue',
48
+ continueTextInterrupted:
49
+ '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.',
30
50
  guardPendingText:
31
51
  '(The previous tool "{tool}" may not have completed. Check its state before continuing and do not run it again.)',
32
52
  guardDoneText:
@@ -52,6 +72,8 @@ export interface AutoContinueSettings {
52
72
  continueTextSilent?: string;
53
73
  /** Text sent for each autonomous-loop continuation (same placeholders as `continueText`). */
54
74
  continueTextLoop?: string;
75
+ /** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
76
+ continueTextInterrupted?: string;
55
77
  /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
56
78
  guardTools?: boolean;
57
79
  /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
@@ -84,7 +106,9 @@ export interface AutoContinueSettings {
84
106
  notify?: boolean;
85
107
  /** Globally pause auto-continue: no live or scan send, queued pending sends cancelled. */
86
108
  paused?: boolean;
87
- /** Show the global auto-continue switch in the conversation composer. */
109
+ /** Persistent per-session overrides; default explicitly inherits the profile default. */
110
+ sessionModes?: Record<string, SessionMode>;
111
+ /** Show the session mode selector in the conversation composer. */
88
112
  showComposerToggle?: boolean;
89
113
  /** Loop guard: detect a running turn spinning in place (short talk without tools, or the same tool repeating) and restart it. */
90
114
  loopGuard?: boolean;
@@ -126,6 +150,7 @@ export const DEFAULT_CONFIG: AutoContinueConfig = {
126
150
  backoffMaxMs: 300000,
127
151
  notify: false,
128
152
  paused: false,
153
+ sessionModes: {},
129
154
  showComposerToggle: true,
130
155
  loopGuard: true,
131
156
  loopShortChars: 40,
@@ -164,6 +189,10 @@ export function resolveConfig(section: AutoContinueSettings | undefined): AutoCo
164
189
  typeof value.continueTextLoop === 'string' && value.continueTextLoop.trim() !== ''
165
190
  ? value.continueTextLoop
166
191
  : localized.continueTextLoop;
192
+ const interruptedText =
193
+ typeof value.continueTextInterrupted === 'string' && value.continueTextInterrupted.trim() !== ''
194
+ ? value.continueTextInterrupted
195
+ : localized.continueTextInterrupted;
167
196
  const guardPendingText =
168
197
  typeof value.guardPendingText === 'string' && value.guardPendingText.trim() !== ''
169
198
  ? value.guardPendingText
@@ -180,6 +209,7 @@ export function resolveConfig(section: AutoContinueSettings | undefined): AutoCo
180
209
  resumeCompletedTurns: booleanOr(value.resumeCompletedTurns, DEFAULT_CONFIG.resumeCompletedTurns),
181
210
  continueTextSilent: silentText,
182
211
  continueTextLoop: loopText,
212
+ continueTextInterrupted: interruptedText,
183
213
  guardTools: booleanOr(value.guardTools, DEFAULT_CONFIG.guardTools),
184
214
  guardPendingText,
185
215
  guardDoneText,
@@ -199,6 +229,8 @@ export function resolveConfig(section: AutoContinueSettings | undefined): AutoCo
199
229
  backoffMaxMs: numberOr(value.backoffMaxMs, DEFAULT_CONFIG.backoffMaxMs),
200
230
  notify: booleanOr(value.notify, DEFAULT_CONFIG.notify),
201
231
  paused: booleanOr(value.paused, DEFAULT_CONFIG.paused),
232
+ sessionModes: value.sessionModes !== null && typeof value.sessionModes === 'object' && !Array.isArray(value.sessionModes)
233
+ ? value.sessionModes : {},
202
234
  showComposerToggle: booleanOr(value.showComposerToggle, DEFAULT_CONFIG.showComposerToggle),
203
235
  loopGuard: booleanOr(value.loopGuard, DEFAULT_CONFIG.loopGuard),
204
236
  loopShortChars: Math.max(1, numberOr(value.loopShortChars, DEFAULT_CONFIG.loopShortChars)),
@@ -788,6 +820,14 @@ function clientTimeZone(): string | undefined {
788
820
  }
789
821
  }
790
822
 
823
+ /** A sent recovery prompt, not proof that the following turn succeeded. */
824
+ export interface RecoveryAttempt {
825
+ sessionId: string;
826
+ at: number;
827
+ reason: 'error' | 'max-tokens' | 'silent' | 'interrupted' | 'loop-guard' | 'manual';
828
+ consecutive: number;
829
+ }
830
+
791
831
  /** 一天的自动继续统计(host 单实例内存态)。 */
792
832
  export interface DayStats {
793
833
  /** 本地日期 YYYY-MM-DD。 */
@@ -830,6 +870,7 @@ export interface SessionState {
830
870
  pendingEchoMessageIds: Map<string, number>;
831
871
  /** 宽限期定时器(进行中的待发送)。 */
832
872
  pendingTimer: ReturnType<typeof setTimeout> | undefined;
873
+ pendingReason?: string;
833
874
  /** 宿主权威 running 位(来自 host/session-status 与回合事件)。 */
834
875
  running: boolean | undefined;
835
876
  /** 当前排队消息数(来自 session/queue 帧)。 */