dsh-client-auto-continue 0.8.0 → 0.8.2

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.
@@ -9,7 +9,7 @@
9
9
  * action endpoint,
10
10
  * - feeds the card's stats / paused-sessions panels from the bridge state.
11
11
  */
12
- import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client';
12
+ import type { Context as ClientContext } from '@deepseek-ai/cordis';
13
13
  // Type-only: pulls the locale plugin's Context merge (ctx.locale).
14
14
  import type {} from '@deepseek-ai/dsh-client-locale/client';
15
15
  // Type-only: pulls the settings-surface SlotMap merge and ctx.settingsScope.
@@ -32,10 +32,6 @@ export const zh = {
32
32
  'field.scanLimitHint': '最多检查多少个最近更新的会话(不含运行中与子代理会话)。',
33
33
  'field.freshMs': '扫描时间窗 (ms)',
34
34
  'field.freshMsHint': '扫描只处理该时间窗内的中断。',
35
- 'field.reconnectScanDelayMs': '重连扫描延迟 (ms)',
36
- 'field.reconnectScanDelayMsHint': '重连后等待宿主完成恢复再扫描。',
37
- 'field.reconnectBackoffMs': '重连退避 (ms)',
38
- 'field.reconnectBackoffMsHint': '事件流断开后的重连间隔。',
39
35
  'field.verbose': '详细日志',
40
36
  'field.verboseHint': '在浏览器控制台输出 [auto-continue] 日志。',
41
37
  'field.classify': '错误分类',
@@ -122,10 +118,6 @@ export const en: Record<SettingsCardKey, string> = {
122
118
  'field.scanLimitHint': 'How many most-recently-updated sessions to check (running / subagent sessions excluded).',
123
119
  'field.freshMs': 'Scan window (ms)',
124
120
  'field.freshMsHint': 'Only interruptions inside this window are considered.',
125
- 'field.reconnectScanDelayMs': 'Reconnect scan delay (ms)',
126
- 'field.reconnectScanDelayMsHint': 'Wait for the host to finish recovering before scanning after a reconnect.',
127
- 'field.reconnectBackoffMs': 'Reconnect backoff (ms)',
128
- 'field.reconnectBackoffMsHint': 'Interval between event-stream reconnect attempts.',
129
121
  'field.verbose': 'Verbose logs',
130
122
  'field.verboseHint': 'Log [auto-continue] lines to the browser console.',
131
123
  'field.classify': 'Classify errors',
@@ -8,9 +8,9 @@
8
8
  * tokens so the card follows the active theme.
9
9
  */
10
10
  import { useEffect, useState, type ReactNode } from 'react';
11
- import { createSnapshotStore, type SettingsScope, type SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client';
12
11
  import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots';
13
12
  import { DEFAULT_CONFIG, type AutoContinueSettings } from './engine.ts';
13
+ import { createSnapshotStore, type SettingsScope, type SnapshotStore } from './dsh-store-compat.ts';
14
14
  import {
15
15
  pausedSessions,
16
16
  readTodayStats,
@@ -48,8 +48,6 @@ export interface AutoContinueSettingsCardState extends CardShell {
48
48
  scanOnBoot: CardFieldState;
49
49
  scanLimit: CardFieldState;
50
50
  freshMs: CardFieldState;
51
- reconnectScanDelayMs: CardFieldState;
52
- reconnectBackoffMs: CardFieldState;
53
51
  verbose: CardFieldState;
54
52
  classify: CardFieldState;
55
53
  backoffFactor: CardFieldState;
@@ -94,8 +92,6 @@ export class AutoContinueSettingsCardController {
94
92
  booleanField('scanOnBoot'),
95
93
  numberField('scanLimit', 1),
96
94
  numberField('freshMs', 0),
97
- numberField('reconnectScanDelayMs', 0),
98
- numberField('reconnectBackoffMs', 0),
99
95
  booleanField('verbose'),
100
96
  booleanField('classify'),
101
97
  numberField('backoffFactor', 1),
@@ -127,8 +123,6 @@ export class AutoContinueSettingsCardController {
127
123
  scanOnBoot: this.form.field('scanOnBoot'),
128
124
  scanLimit: this.form.field('scanLimit'),
129
125
  freshMs: this.form.field('freshMs'),
130
- reconnectScanDelayMs: this.form.field('reconnectScanDelayMs'),
131
- reconnectBackoffMs: this.form.field('reconnectBackoffMs'),
132
126
  verbose: this.form.field('verbose'),
133
127
  classify: this.form.field('classify'),
134
128
  backoffFactor: this.form.field('backoffFactor'),
@@ -542,26 +536,6 @@ export function AutoContinueSettingsCard(props: AutoContinueSettingsCardProps) {
542
536
  onEdit={(text) => props.edit('freshMs', text)}
543
537
  onReset={() => props.resetField('freshMs')}
544
538
  />
545
- <ValueField
546
- id="auto-continue-reconnect-scan-delay"
547
- label={t('field.reconnectScanDelayMs')}
548
- hint={t('field.reconnectScanDelayMsHint')}
549
- numeric
550
- {...shared}
551
- {...state.reconnectScanDelayMs}
552
- onEdit={(text) => props.edit('reconnectScanDelayMs', text)}
553
- onReset={() => props.resetField('reconnectScanDelayMs')}
554
- />
555
- <ValueField
556
- id="auto-continue-reconnect-backoff"
557
- label={t('field.reconnectBackoffMs')}
558
- hint={t('field.reconnectBackoffMsHint')}
559
- numeric
560
- {...shared}
561
- {...state.reconnectBackoffMs}
562
- onEdit={(text) => props.edit('reconnectBackoffMs', text)}
563
- onReset={() => props.resetField('reconnectBackoffMs')}
564
- />
565
539
  <BooleanField
566
540
  id="auto-continue-verbose"
567
541
  label={t('field.verbose')}
@@ -10,7 +10,7 @@
10
10
  * default — and whether the user layer carries it (presence, not value
11
11
  * equality, marks an override).
12
12
  */
13
- import type { SettingsScope, SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client';
13
+ import type { SettingsScope, SnapshotStore } from './dsh-store-compat.ts';
14
14
 
15
15
  /** The write one field's staged text performs when the card is saved. */
16
16
  export type FieldWrite = { kind: 'set'; value: unknown } | { kind: 'clear' };
@@ -17,360 +17,30 @@ import { createUserMessage } from '@deepseek-ai/dsh-llm';
17
17
  import type { Agent } from '@deepseek-ai/dsh-agent';
18
18
  import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types';
19
19
  import type { Session } from '@deepseek-ai/dsh-session';
20
-
21
- /** The `auto-continue` settings section (all fields optional on the wire; the host schema carries defaults). */
22
- export interface AutoContinueSettings {
23
- /** Text automatically sent after an interruption. */
24
- continueText?: string;
25
- /** Text sent when the output token ceiling is reached (same placeholders as `continueText`). */
26
- continueTextMaxTokens?: string;
27
- /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
28
- guardTools?: boolean;
29
- /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
30
- guardPendingText?: string;
31
- /** Guard text appended when the last tool call completed successfully (don't rerun it). */
32
- guardDoneText?: string;
33
- /** Grace period after an interruption before auto-sending (ms). */
34
- graceMs?: number;
35
- /** Minimum interval between two auto-continues per session (ms). */
36
- cooldownMs?: number;
37
- /** Max consecutive auto-continues per session before stopping. */
38
- maxConsecutive?: number;
39
- /** Scan recently interrupted sessions on page load / reconnect. */
40
- scanOnBoot?: boolean;
41
- /** Max sessions the scan checks (most recently updated). */
42
- scanLimit?: number;
43
- /** Scan only considers interruptions inside this window (ms). */
44
- freshMs?: number;
45
- /** Delay before scanning after a reconnect (ms). */
46
- reconnectScanDelayMs?: number;
47
- /** SSE reconnect backoff (ms). */
48
- reconnectBackoffMs?: number;
49
- /** Log `[auto-continue]` lines to the browser console. */
50
- verbose?: boolean;
51
- /** Classify failures: auto-continue transient errors only; permanent ones (auth/balance/model) are skipped and notified. */
52
- classify?: boolean;
53
- /** Cooldown multiplier per consecutive failure (adaptive backoff). */
54
- backoffFactor?: number;
55
- /** Cap on the effective backoff interval (ms). */
56
- backoffMaxMs?: number;
57
- /** Show browser notifications for auto-continue events. */
58
- notify?: boolean;
59
- /** Globally pause auto-continue: no live or scan send, queued pending sends cancelled. */
60
- paused?: boolean;
61
- /** Loop guard: detect a running turn spinning in place (short talk without tools, or the same tool repeating) and restart it. */
62
- loopGuard?: boolean;
63
- /** A model message shorter than this many chars counts as a "short sentence" (loop signal). */
64
- loopShortChars?: number;
65
- /** Consecutive short sentences within this window (ms) with no tool call in between trip the loop guard. */
66
- loopWindowMs?: number;
67
- /** Consecutive short sentences trip the loop guard. */
68
- loopShortCount?: number;
69
- /** Consecutive identical tool calls with identical arguments AND identical results trip the loop guard. */
70
- loopToolRepeat?: number;
71
- /** Consecutive identical short sentences trip the loop guard (strongest spinning signal). */
72
- loopRepeatText?: number;
73
- /** Text sent after the loop guard cancels and restarts a turn (supports {tool}). */
74
- loopText?: string;
75
- }
76
-
77
- /** Fully resolved configuration (built-in defaults + user overrides). */
78
- export type AutoContinueConfig = Required<AutoContinueSettings>;
79
-
80
- /** Built-in defaults — must match the host schema defaults in src/index.ts. */
81
- export const DEFAULT_CONFIG: AutoContinueConfig = {
82
- continueText: '继续',
83
- continueTextMaxTokens: '继续',
84
- guardTools: true,
85
- guardPendingText: '(上一步工具「{tool}」可能未完成, 先确认状态再继续, 不要重复执行)',
86
- guardDoneText: '(上一步工具「{tool}」已完成, 结果: {result}; 不要重复执行, 直接继续)',
87
- graceMs: 3000,
88
- cooldownMs: 20000,
89
- maxConsecutive: 3,
90
- scanOnBoot: true,
91
- scanLimit: 8,
92
- freshMs: 15 * 60 * 1000,
93
- reconnectScanDelayMs: 5000,
94
- reconnectBackoffMs: 3000,
95
- verbose: true,
96
- classify: true,
97
- backoffFactor: 2,
98
- backoffMaxMs: 300000,
99
- notify: false,
100
- paused: false,
101
- loopGuard: true,
102
- loopShortChars: 40,
103
- loopWindowMs: 30000,
104
- loopShortCount: 12,
105
- loopRepeatText: 4,
106
- loopToolRepeat: 5,
107
- loopText: '(检测到你可能陷入循环, 请停止重复刚才的动作, 换一种方式继续)',
108
- };
109
-
110
- function numberOr(value: unknown, fallback: number): number {
111
- return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback;
112
- }
113
-
114
- function booleanOr(value: unknown, fallback: boolean): boolean {
115
- return typeof value === 'boolean' ? value : fallback;
116
- }
117
-
118
- /** Resolve a (possibly partial / not-yet-loaded) settings section to a full config. */
119
- export function resolveConfig(section: AutoContinueSettings | undefined): AutoContinueConfig {
120
- const value = section ?? {};
121
- const text =
122
- typeof value.continueText === 'string' && value.continueText.trim() !== ''
123
- ? value.continueText
124
- : DEFAULT_CONFIG.continueText;
125
- const maxTokensText =
126
- typeof value.continueTextMaxTokens === 'string' && value.continueTextMaxTokens.trim() !== ''
127
- ? value.continueTextMaxTokens
128
- : DEFAULT_CONFIG.continueTextMaxTokens;
129
- const guardPendingText =
130
- typeof value.guardPendingText === 'string' && value.guardPendingText.trim() !== ''
131
- ? value.guardPendingText
132
- : DEFAULT_CONFIG.guardPendingText;
133
- const guardDoneText =
134
- typeof value.guardDoneText === 'string' && value.guardDoneText.trim() !== ''
135
- ? value.guardDoneText
136
- : DEFAULT_CONFIG.guardDoneText;
137
- return {
138
- continueText: text,
139
- continueTextMaxTokens: maxTokensText,
140
- guardTools: booleanOr(value.guardTools, DEFAULT_CONFIG.guardTools),
141
- guardPendingText,
142
- guardDoneText,
143
- graceMs: numberOr(value.graceMs, DEFAULT_CONFIG.graceMs),
144
- cooldownMs: numberOr(value.cooldownMs, DEFAULT_CONFIG.cooldownMs),
145
- maxConsecutive: Math.max(1, numberOr(value.maxConsecutive, DEFAULT_CONFIG.maxConsecutive)),
146
- scanOnBoot: booleanOr(value.scanOnBoot, DEFAULT_CONFIG.scanOnBoot),
147
- scanLimit: Math.max(1, numberOr(value.scanLimit, DEFAULT_CONFIG.scanLimit)),
148
- freshMs: numberOr(value.freshMs, DEFAULT_CONFIG.freshMs),
149
- reconnectScanDelayMs: numberOr(value.reconnectScanDelayMs, DEFAULT_CONFIG.reconnectScanDelayMs),
150
- reconnectBackoffMs: numberOr(value.reconnectBackoffMs, DEFAULT_CONFIG.reconnectBackoffMs),
151
- verbose: booleanOr(value.verbose, DEFAULT_CONFIG.verbose),
152
- classify: booleanOr(value.classify, DEFAULT_CONFIG.classify),
153
- backoffFactor: Math.max(1, numberOr(value.backoffFactor, DEFAULT_CONFIG.backoffFactor)),
154
- backoffMaxMs: numberOr(value.backoffMaxMs, DEFAULT_CONFIG.backoffMaxMs),
155
- notify: booleanOr(value.notify, DEFAULT_CONFIG.notify),
156
- paused: booleanOr(value.paused, DEFAULT_CONFIG.paused),
157
- loopGuard: booleanOr(value.loopGuard, DEFAULT_CONFIG.loopGuard),
158
- loopShortChars: Math.max(1, numberOr(value.loopShortChars, DEFAULT_CONFIG.loopShortChars)),
159
- loopWindowMs: Math.max(1000, numberOr(value.loopWindowMs, DEFAULT_CONFIG.loopWindowMs)),
160
- loopShortCount: Math.max(2, numberOr(value.loopShortCount, DEFAULT_CONFIG.loopShortCount)),
161
- loopRepeatText: Math.max(2, numberOr(value.loopRepeatText, DEFAULT_CONFIG.loopRepeatText)),
162
- loopToolRepeat: Math.max(2, numberOr(value.loopToolRepeat, DEFAULT_CONFIG.loopToolRepeat)),
163
- loopText:
164
- typeof value.loopText === 'string' && value.loopText.trim() !== ''
165
- ? value.loopText
166
- : DEFAULT_CONFIG.loopText,
167
- };
168
- }
169
-
170
- /**
171
- * 视为「非人为中断」的回合结束原因, 用于启动/重连扫描。
172
- * - `interrupted` 只由崩溃修复在宿主重载时写入(loop 永不实时发出), 因此仅在扫描路径处理;
173
- * - 实时事件路径只对 `error` / `max-tokens` 自动续跑;
174
- * - `aborted`(用户停止)与 `blocked`(策略拒绝)永不自动继续。
175
- */
176
- type NonHumanReason = 'error' | 'interrupted' | 'max-tokens';
177
-
178
- function isNonHumanReason(kind: string): kind is NonHumanReason {
179
- return kind === 'error' || kind === 'interrupted' || kind === 'max-tokens';
180
- }
181
-
182
- /** 一次回合失败的机器可读事实(turn/end error 的 LlmFailure 载荷)。 */
183
- export interface FailureFacts {
184
- /** 稳定机器路由码(如 UPSTREAM、RATE_LIMIT_EXCEEDED、INVALID_API_KEY)。 */
185
- code: string;
186
- /** 人类可读的失败描述。 */
187
- message: string;
188
- /** 供应商 HTTP 状态码(可用时)。 */
189
- status?: number;
190
- }
191
-
192
- /**
193
- * 错误分类: 该失败是否值得自动继续。
194
- * 永久性失败(认证/余额/模型不存在/上下文超限等)重试也不会成功, 应跳过并通知用户;
195
- * 其余(网络、超时、5xx、429 等)视为临时性失败, 允许自动恢复。
196
- */
197
- export function isTransientFailure(failure: FailureFacts): boolean {
198
- const haystack = `${failure.code} ${failure.message}`.toLowerCase();
199
- const status = failure.status;
200
- if (status !== undefined && (status === 401 || status === 403)) return false;
201
- const permanent =
202
- /auth|unauthor|forbidden|credential|api[_-]?key|permission/i.test(haystack) ||
203
- /insufficient.*(balance|quota)|billing|payment|quota.*exceeded.*(?!retry)/i.test(haystack) ||
204
- /model.*not[_-]?found|unknown[_-]?model|model[_-]?not[_-]?found|not.*support.*model/i.test(haystack) ||
205
- /context.*(length|limit|overflow|exceed)|token.*limit|max.*context/i.test(haystack) ||
206
- /invalid[_-]?request|bad[_-]?request/i.test(haystack);
207
- return !permanent;
208
- }
209
-
210
- /**
211
- * host/agent-error 消息分类: 仅明确属于网络/传输类的临时错误才自动继续。
212
- * 其余(序列化失败、配置/宿主内部错误等)视为永久性——重试无益, 且用户停止导致的
213
- * 序列化失败(如 Windows 下 abort 的 DOMException reason)绝不能自动续跑。
214
- */
215
- export function isTransientAgentError(message: string): boolean {
216
- return /network|timeout|timed ?out|econn|etimedout|socket|5\d\d|\b429\b|upstream|temporar/i.test(message);
217
- }
218
-
219
- /** 通知上的一个操作按钮(action 标识 + 显示文案)。 */
220
- export interface NotifyAction {
221
- /** 稳定动作标识, 点击时经 onAction 回调传出。 */
222
- action: string;
223
- /** 按钮显示文案。 */
224
- title: string;
225
- }
226
-
227
- /** 通知的可选行为: 操作按钮列表与点击回调。 */
228
- export interface NotifyOptions {
229
- actions?: NotifyAction[];
230
- onAction?: (action: string) => void;
231
- }
232
-
233
- /** 浏览器通知(不可用时静默跳过); 点击通知聚焦窗口, 操作按钮走 onAction。 */
234
- /** 把毫秒格式化为人类可读的经过时长(如 65s → 1m5s)。 */
235
- function formatElapsed(ms: number | undefined): string {
236
- if (ms === undefined || !Number.isFinite(ms) || ms < 0) return '';
237
- if (ms < 1000) return `${Math.round(ms)}ms`;
238
- const s = Math.round(ms / 1000);
239
- if (s < 60) return `${s}s`;
240
- return `${Math.floor(s / 60)}m${s % 60 > 0 ? `${s % 60}s` : ''}`;
241
- }
242
-
243
- /** 模板填充所需的上下文(全部可选, 缺失的占位符填为空串)。 */
244
- export interface TemplateContext {
245
- /** 失败事实(错误码/消息/HTTP 状态), 对应 {code}/{message}/{status}。 */
246
- facts?: FailureFacts;
247
- /** 失败前最后一次工具调用的名称, 对应 {tool}。 */
248
- tool?: string;
249
- /** 失败回合的编号, 对应 {turn}。 */
250
- turn?: number;
251
- /** 连续失败次数(含本次), 对应 {errorCount}。 */
252
- errorCount?: number;
253
- /** 会话标题(来自 session.list 投影, 可用时), 对应 {sessionTitle}。 */
254
- sessionTitle?: string;
255
- /** 自失败发生以来的毫秒数, 对应 {elapsed}。 */
256
- elapsedMs?: number;
257
- /** 上一步工具结果摘要(截断), 对应 {result}(护栏模板用)。 */
258
- result?: string;
259
- }
260
-
261
- /** 用失败事实与回合信息填充 continueText 模板占位符({code}/{message}/{status}/{tool}/{turn}/{errorCount}/{sessionTitle}/{elapsed}/{result})。 */
262
- export function fillTemplate(template: string, ctx: TemplateContext): string {
263
- return template
264
- .replace(/\{code\}/g, ctx.facts?.code ?? '')
265
- .replace(/\{message\}/g, ctx.facts?.message ?? '')
266
- .replace(/\{status\}/g, ctx.facts?.status !== undefined ? String(ctx.facts.status) : '')
267
- .replace(/\{tool\}/g, ctx.tool ?? '')
268
- .replace(/\{turn\}/g, ctx.turn !== undefined ? String(ctx.turn) : '')
269
- .replace(/\{errorCount\}/g, ctx.errorCount !== undefined ? String(ctx.errorCount) : '')
270
- .replace(/\{sessionTitle\}/g, ctx.sessionTitle ?? '')
271
- .replace(/\{elapsed\}/g, formatElapsed(ctx.elapsedMs))
272
- .replace(/\{result\}/g, ctx.result ?? '');
273
- }
274
-
275
- // ---------- 幂等护栏: 上一步工具调用的执行状态 ----------
276
-
277
- /** 工具结果摘要的最大长度(护栏模板 {result} 用)。 */
278
- const TOOL_RESULT_CAP = 160;
279
-
280
- /** 从任意内容块里递归收集文本(结果为模型可见的工具输出)。 */
281
- function extractText(blocks: unknown, cap: number): string {
282
- let out = '';
283
- const walk = (value: unknown): void => {
284
- if (out.length >= cap) return;
285
- if (Array.isArray(value)) {
286
- for (const item of value) walk(item);
287
- return;
288
- }
289
- if (typeof value !== 'object' || value === null) return;
290
- const record = value as Record<string, unknown>;
291
- if (record['type'] === 'text' && typeof record['text'] === 'string') {
292
- out += record['text'];
293
- return;
294
- }
295
- for (const child of Object.values(record)) walk(child);
296
- };
297
- walk(blocks);
298
- return out.slice(0, cap);
299
- }
300
-
301
- /** 上一步工具调用的判定结果: 是否已确认完成, 以及文本摘要。 */
302
- export interface ToolResultFacts {
303
- /** 工具是否成功完成(内部失败或 isError 视为未成功)。 */
304
- ok: boolean;
305
- /** 工具输出的文本摘要(截断)。 */
306
- excerpt: string;
307
- }
308
-
309
- /** 从 tool/result 事件载荷提取成功与否与文本摘要。 */
310
- function toolResultFacts(data: {
311
- error?: { name?: string; code?: string };
312
- message?: { content?: Array<{ type?: string; content?: unknown; isError?: boolean }> };
313
- }): ToolResultFacts {
314
- const failed = data.error !== undefined || data.message?.content?.[0]?.isError === true;
315
- return { ok: !failed, excerpt: extractText(data.message?.content?.[0]?.content, TOOL_RESULT_CAP) };
316
- }
317
-
318
- /** 自适应退避: 同一会话连续失败时的有效冷却间隔。 */
319
- export function effectiveCooldown(
320
- consecutive: number,
321
- base: number,
322
- factor: number,
323
- max: number,
324
- ): number {
325
- // consecutive = 已连续自动继续的次数; 第 1 次后开始按 factor 递增
326
- const multiplier = Math.pow(factor, consecutive);
327
- return Math.min(Math.max(base, base * multiplier), Math.max(base, max));
328
- }
329
-
330
- function sleep(ms: number): Promise<void> {
331
- return new Promise((resolve) => setTimeout(resolve, ms));
332
- }
333
-
334
- /** 浏览器当前 IANA 时区; 不可用时省略(宿主允许省略)。 */
335
- function clientTimeZone(): string | undefined {
336
- try {
337
- return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined;
338
- } catch {
339
- return undefined;
340
- }
341
- }
342
-
343
- /** 一天的自动继续统计(host 单实例内存态)。 */
344
- export interface DayStats {
345
- /** 本地日期 YYYY-MM-DD。 */
346
- date: string;
347
- /** 自动发送次数。 */
348
- sent: number;
349
- /** 因永久性错误跳过的次数。 */
350
- skipped: number;
351
- /** 发送后回合成功完成(恢复成功)的次数。 */
352
- recovered: number;
353
- /** 发送后再次失败的次数。 */
354
- failed: number;
355
- /** 达到连续上限而停止的次数(按停止事件计)。 */
356
- gaveUp: number;
357
- /** loop guard 打断并重启回合的次数。 */
358
- looped: number;
359
- /** 按错误码计数的失败分布。 */
360
- byCode: Record<string, number>;
361
- }
362
-
363
- function todayKey(): string {
364
- const d = new Date();
365
- const mm = String(d.getMonth() + 1).padStart(2, '0');
366
- const dd = String(d.getDate()).padStart(2, '0');
367
- return `${d.getFullYear()}-${mm}-${dd}`;
368
- }
369
-
370
- /** 空统计桶。 */
371
- function emptyDayStats(): DayStats {
372
- return { date: todayKey(), sent: 0, skipped: 0, recovered: 0, failed: 0, gaveUp: 0, looped: 0, byCode: {} };
373
- }
20
+ import {
21
+ DEFAULT_CONFIG,
22
+ ECHO_WINDOW_MS,
23
+ RECOVERY_WINDOW_MS,
24
+ effectiveCooldown,
25
+ emptyDayStats,
26
+ fillTemplate,
27
+ freshState,
28
+ isNonHumanReason,
29
+ isOurEcho,
30
+ isTransientAgentError,
31
+ isTransientFailure,
32
+ resolveConfig,
33
+ sleep,
34
+ todayKey,
35
+ toolResultFacts,
36
+ type AutoContinueConfig,
37
+ type DayStats,
38
+ type FailureFacts,
39
+ type SessionState,
40
+ type NotifyAction,
41
+ type NotifyOptions,
42
+ type TemplateContext,
43
+ } from '../shared/core.ts';
374
44
 
375
45
  /** 通知桥事件: host 引擎产生, browser 侧订阅展示(Notification / 动作按钮)。 */
376
46
  export interface HostNotice {
@@ -386,116 +56,13 @@ export interface HostNotice {
386
56
  }
387
57
 
388
58
  /** 自动发送后, 在该窗口内出现的回合结束才计入恢复统计。 */
389
- const RECOVERY_WINDOW_MS = 10 * 60 * 1000;
390
59
 
391
60
  /** 回显识别窗口: 排队消息可能几分钟后才被模型处理到, 窗口必须远大于排队延迟。 */
392
- const ECHO_WINDOW_MS = 10 * 60 * 1000;
393
61
 
394
62
  /**
395
63
  * 判定一条 user/message 是否是我们自己自动发送的回显。
396
64
  * 单实例引擎: 内存态即可; 排队消息可能几分钟后才被模型处理, 窗口保持 10 分钟。
397
65
  */
398
- /** 每会话运行时状态。 */
399
- interface SessionState {
400
- /** 连续自动「继续」次数; 成功回合或用户手动介入后归零。 */
401
- consecutive: number;
402
- /** 上次自动「继续」时间戳。 */
403
- lastAutoAt: number;
404
- /** 上次自动「继续」尝试(成功或失败)时间戳; 防止失败场景下的快速重试循环。 */
405
- lastAttemptAt: number;
406
- /** 我们上次自动发送的文本(用于识别自己的回显)。 */
407
- lastSentText: string;
408
- /** 宽限期定时器(进行中的待发送)。 */
409
- pendingTimer: ReturnType<typeof setTimeout> | undefined;
410
- /** 宿主权威 running 位(来自 host/session-status 与回合事件)。 */
411
- running: boolean | undefined;
412
- /** 当前排队消息数(来自 session/queue 帧)。 */
413
- queued: number;
414
- /** 子代理会话(host/session-added 带 parentSessionId)。 */
415
- subagent: boolean;
416
- /** 最近一次回合失败的事实(用于分类与模板填充)。 */
417
- lastFailure: FailureFacts | undefined;
418
- /** 最近一次失败的发生时间(模板 {elapsed} 与恢复统计用)。 */
419
- lastFailureAt: number;
420
- /** 失败前最后一次工具调用的名称(模板 {tool} 与幂等护栏用)。 */
421
- lastTool: string | undefined;
422
- /** 上一步工具调用的结果状态: 'pending' = 已发起未见结果(可能已部分执行)。 */
423
- lastToolResult: 'pending' | ToolResultFacts | undefined;
424
- /** 失败回合的编号(模板 {turn})。 */
425
- lastTurn: number | undefined;
426
- /** 我们最近一次自动发送的时间戳; 0 = 没有待确认的恢复。 */
427
- pendingRecoveryAt: number;
428
- /** 当前连续短句数(loop guard 信号 1: 空转)。 */
429
- shortRun: number;
430
- /** 最后一条短句的时间(时间窗判定用)。 */
431
- lastShortAt: number;
432
- /** 最后一条模型消息的文本(相同文本重复判定用)。 */
433
- lastAssistantText: string;
434
- /** 连续相同文本消息数(最强空转信号, 不限长度)。 */
435
- sameTextRun: number;
436
- /**
437
- * 工具重复信号(loop guard 信号 2: 死循环)。
438
- * 只有「同工具 + 同参数 + 同结果」的连续调用才累计; 参数或结果有变化视为有进展, 计数重置。
439
- */
440
- toolRun:
441
- | {
442
- /** 工具名 + 参数(用于判定是否同一调用)。 */
443
- key: string;
444
- /** 连续相同调用数(结果确认后更新)。 */
445
- count: number;
446
- /** 上次该调用的结果摘要(比较用)。 */
447
- lastResult: string | undefined;
448
- /** 本次调用等待结果确认。 */
449
- waiting: boolean;
450
- }
451
- | undefined;
452
- /** 本回合已触发过 loop guard(防重复打断)。 */
453
- loopFired: boolean;
454
- /** loop 重启的延迟定时器(冷却结束后再 schedule)。 */
455
- loopRetryTimer: ReturnType<typeof setTimeout> | undefined;
456
- /** 我们主动 cancel 过本回合(区分用户停止)。 */
457
- loopCancelled: boolean;
458
- }
459
-
460
- const freshState = (): SessionState => ({
461
- consecutive: 0,
462
- lastAutoAt: 0,
463
- lastAttemptAt: 0,
464
- lastSentText: '',
465
- pendingTimer: undefined,
466
- running: undefined,
467
- queued: 0,
468
- subagent: false,
469
- lastFailure: undefined,
470
- lastFailureAt: 0,
471
- lastTool: undefined,
472
- lastToolResult: undefined,
473
- lastTurn: undefined,
474
- pendingRecoveryAt: 0,
475
- shortRun: 0,
476
- lastShortAt: 0,
477
- lastAssistantText: '',
478
- sameTextRun: 0,
479
- toolRun: undefined,
480
- loopFired: false,
481
- loopCancelled: false,
482
- loopRetryTimer: undefined,
483
- });
484
-
485
-
486
- function isOurEcho(state: SessionState, event: SessionEvent): boolean {
487
- if (event.type !== 'user/message') return false;
488
- const message = event.data;
489
- if (message.source.kind !== 'user') return false;
490
- if (state.lastSentText === '') return false;
491
- if (Date.now() - state.lastAutoAt > ECHO_WINDOW_MS) return false;
492
- const text = message.content
493
- .filter((part): part is { type: 'text'; text: string } => part.type === 'text')
494
- .map((part) => part.text)
495
- .join('');
496
- return text === state.lastSentText;
497
- }
498
-
499
66
  /** SSE 帧外壳: `{ rpcId, payload }`。 */
500
67
  type FrameEnvelope<T> = { payload: T };
501
68
 
package/src/index.ts CHANGED
@@ -12,7 +12,8 @@
12
12
  import type { Context } from '@deepseek-ai/cordis';
13
13
  import z from '@deepseek-ai/schemastery';
14
14
  import { settingsNamespace } from '@deepseek-ai/dsh-settings';
15
- import { AutoContinueRunner, resolveConfig, type AutoContinueSettings } from './host/engine.ts';
15
+ import { AutoContinueRunner } from './host/engine.ts';
16
+ import { resolveConfig, type AutoContinueSettings } from './shared/core.ts';
16
17
  // Type-only: pulls the `ctx.settings` Context augmentation from dsh-settings.
17
18
  import type {} from '@deepseek-ai/dsh-settings';
18
19
  // Type-only: pulls the `ctx.webServer` Context augmentation.
@@ -51,10 +52,6 @@ export const AutoContinueSchema = z.object({
51
52
  scanLimit: z.natural().min(1).default(8),
52
53
  /** Scan only considers interruptions inside this window (ms). */
53
54
  freshMs: z.natural().default(15 * 60 * 1000),
54
- /** Delay before scanning after a reconnect (ms). */
55
- reconnectScanDelayMs: z.natural().default(5000),
56
- /** SSE reconnect backoff (ms). */
57
- reconnectBackoffMs: z.natural().default(3000),
58
55
  /** Log `[auto-continue]` lines to the browser console. */
59
56
  verbose: z.boolean().default(true),
60
57
  /** Classify failures: auto-continue transient errors only; permanent ones are skipped and notified. */