dsh-client-auto-continue 0.5.2 → 0.5.4
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.
- package/README.md +1 -0
- package/README.zh.md +1 -0
- package/package.json +7 -3
- package/src/client/engine.ts +1116 -0
- package/src/client/index.ts +91 -0
- package/src/client/locales.ts +140 -0
- package/src/client/settings-card.tsx +547 -0
- package/src/client/settings-form.ts +293 -0
- package/src/client/styles.ts +172 -0
- package/src/index.ts +62 -0
- package/tsconfig.build.json +11 -0
- package/tsconfig.json +29 -0
|
@@ -0,0 +1,1116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auto-continue engine — browser half core.
|
|
3
|
+
*
|
|
4
|
+
* Watches the two live event streams of the dsh web GUI (mux + host):
|
|
5
|
+
* - turns ended for a non-human reason (`turn/end` reason ∈ error / interrupted / max-tokens)
|
|
6
|
+
* - host-reported agent failures with no turn position (`host/agent-error`)
|
|
7
|
+
* After a grace period it sends a queued prompt (default 「继续」) to that
|
|
8
|
+
* session — exactly equivalent to the user typing it manually.
|
|
9
|
+
*
|
|
10
|
+
* All behavior is driven by the `auto-continue` settings namespace (see the
|
|
11
|
+
* plugin's settings card); every knob below is user-configurable there.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type {
|
|
15
|
+
HostFrame,
|
|
16
|
+
IApiClient,
|
|
17
|
+
MuxFrame,
|
|
18
|
+
SessionId,
|
|
19
|
+
SessionSummary,
|
|
20
|
+
} from '@deepseek-ai/dsh-client-connection/client';
|
|
21
|
+
import type { SessionEvent } from '@deepseek-ai/dsh-session/types';
|
|
22
|
+
|
|
23
|
+
/** The `auto-continue` settings section (all fields optional on the wire; the host schema carries defaults). */
|
|
24
|
+
export interface AutoContinueSettings {
|
|
25
|
+
/** Text automatically sent after an interruption. */
|
|
26
|
+
continueText?: string;
|
|
27
|
+
/** Text sent when the output token ceiling is reached (same placeholders as `continueText`). */
|
|
28
|
+
continueTextMaxTokens?: string;
|
|
29
|
+
/** Grace period after an interruption before auto-sending (ms). */
|
|
30
|
+
graceMs?: number;
|
|
31
|
+
/** Minimum interval between two auto-continues per session (ms). */
|
|
32
|
+
cooldownMs?: number;
|
|
33
|
+
/** Max consecutive auto-continues per session before stopping. */
|
|
34
|
+
maxConsecutive?: number;
|
|
35
|
+
/** Scan recently interrupted sessions on page load / reconnect. */
|
|
36
|
+
scanOnBoot?: boolean;
|
|
37
|
+
/** Max sessions the scan checks (most recently updated). */
|
|
38
|
+
scanLimit?: number;
|
|
39
|
+
/** Scan only considers interruptions inside this window (ms). */
|
|
40
|
+
freshMs?: number;
|
|
41
|
+
/** Delay before scanning after a reconnect (ms). */
|
|
42
|
+
reconnectScanDelayMs?: number;
|
|
43
|
+
/** SSE reconnect backoff (ms). */
|
|
44
|
+
reconnectBackoffMs?: number;
|
|
45
|
+
/** Log `[auto-continue]` lines to the browser console. */
|
|
46
|
+
verbose?: boolean;
|
|
47
|
+
/** Classify failures: auto-continue transient errors only; permanent ones (auth/balance/model) are skipped and notified. */
|
|
48
|
+
classify?: boolean;
|
|
49
|
+
/** Cooldown multiplier per consecutive failure (adaptive backoff). */
|
|
50
|
+
backoffFactor?: number;
|
|
51
|
+
/** Cap on the effective backoff interval (ms). */
|
|
52
|
+
backoffMaxMs?: number;
|
|
53
|
+
/** Show browser notifications for auto-continue events. */
|
|
54
|
+
notify?: boolean;
|
|
55
|
+
/** Globally pause auto-continue: no live or scan send, queued pending sends cancelled. */
|
|
56
|
+
paused?: boolean;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Fully resolved configuration (built-in defaults + user overrides). */
|
|
60
|
+
export type AutoContinueConfig = Required<AutoContinueSettings>;
|
|
61
|
+
|
|
62
|
+
/** Built-in defaults — must match the host schema defaults in src/index.ts. */
|
|
63
|
+
export const DEFAULT_CONFIG: AutoContinueConfig = {
|
|
64
|
+
continueText: '继续',
|
|
65
|
+
continueTextMaxTokens: '继续',
|
|
66
|
+
graceMs: 3000,
|
|
67
|
+
cooldownMs: 20000,
|
|
68
|
+
maxConsecutive: 3,
|
|
69
|
+
scanOnBoot: true,
|
|
70
|
+
scanLimit: 8,
|
|
71
|
+
freshMs: 15 * 60 * 1000,
|
|
72
|
+
reconnectScanDelayMs: 5000,
|
|
73
|
+
reconnectBackoffMs: 3000,
|
|
74
|
+
verbose: true,
|
|
75
|
+
classify: true,
|
|
76
|
+
backoffFactor: 2,
|
|
77
|
+
backoffMaxMs: 300000,
|
|
78
|
+
notify: false,
|
|
79
|
+
paused: false,
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
function numberOr(value: unknown, fallback: number): number {
|
|
83
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function booleanOr(value: unknown, fallback: boolean): boolean {
|
|
87
|
+
return typeof value === 'boolean' ? value : fallback;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Resolve a (possibly partial / not-yet-loaded) settings section to a full config. */
|
|
91
|
+
export function resolveConfig(section: AutoContinueSettings | undefined): AutoContinueConfig {
|
|
92
|
+
const value = section ?? {};
|
|
93
|
+
const text =
|
|
94
|
+
typeof value.continueText === 'string' && value.continueText.trim() !== ''
|
|
95
|
+
? value.continueText
|
|
96
|
+
: DEFAULT_CONFIG.continueText;
|
|
97
|
+
const maxTokensText =
|
|
98
|
+
typeof value.continueTextMaxTokens === 'string' && value.continueTextMaxTokens.trim() !== ''
|
|
99
|
+
? value.continueTextMaxTokens
|
|
100
|
+
: DEFAULT_CONFIG.continueTextMaxTokens;
|
|
101
|
+
return {
|
|
102
|
+
continueText: text,
|
|
103
|
+
continueTextMaxTokens: maxTokensText,
|
|
104
|
+
graceMs: numberOr(value.graceMs, DEFAULT_CONFIG.graceMs),
|
|
105
|
+
cooldownMs: numberOr(value.cooldownMs, DEFAULT_CONFIG.cooldownMs),
|
|
106
|
+
maxConsecutive: Math.max(1, numberOr(value.maxConsecutive, DEFAULT_CONFIG.maxConsecutive)),
|
|
107
|
+
scanOnBoot: booleanOr(value.scanOnBoot, DEFAULT_CONFIG.scanOnBoot),
|
|
108
|
+
scanLimit: Math.max(1, numberOr(value.scanLimit, DEFAULT_CONFIG.scanLimit)),
|
|
109
|
+
freshMs: numberOr(value.freshMs, DEFAULT_CONFIG.freshMs),
|
|
110
|
+
reconnectScanDelayMs: numberOr(value.reconnectScanDelayMs, DEFAULT_CONFIG.reconnectScanDelayMs),
|
|
111
|
+
reconnectBackoffMs: numberOr(value.reconnectBackoffMs, DEFAULT_CONFIG.reconnectBackoffMs),
|
|
112
|
+
verbose: booleanOr(value.verbose, DEFAULT_CONFIG.verbose),
|
|
113
|
+
classify: booleanOr(value.classify, DEFAULT_CONFIG.classify),
|
|
114
|
+
backoffFactor: Math.max(1, numberOr(value.backoffFactor, DEFAULT_CONFIG.backoffFactor)),
|
|
115
|
+
backoffMaxMs: numberOr(value.backoffMaxMs, DEFAULT_CONFIG.backoffMaxMs),
|
|
116
|
+
notify: booleanOr(value.notify, DEFAULT_CONFIG.notify),
|
|
117
|
+
paused: booleanOr(value.paused, DEFAULT_CONFIG.paused),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* 视为「非人为中断」的回合结束原因, 用于启动/重连扫描。
|
|
123
|
+
* - `interrupted` 只由崩溃修复在宿主重载时写入(loop 永不实时发出), 因此仅在扫描路径处理;
|
|
124
|
+
* - 实时事件路径只对 `error` / `max-tokens` 自动续跑;
|
|
125
|
+
* - `aborted`(用户停止)与 `blocked`(策略拒绝)永不自动继续。
|
|
126
|
+
*/
|
|
127
|
+
type NonHumanReason = 'error' | 'interrupted' | 'max-tokens';
|
|
128
|
+
|
|
129
|
+
function isNonHumanReason(kind: string): kind is NonHumanReason {
|
|
130
|
+
return kind === 'error' || kind === 'interrupted' || kind === 'max-tokens';
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 一次回合失败的机器可读事实(turn/end error 的 LlmFailure 载荷)。 */
|
|
134
|
+
export interface FailureFacts {
|
|
135
|
+
/** 稳定机器路由码(如 UPSTREAM、RATE_LIMIT_EXCEEDED、INVALID_API_KEY)。 */
|
|
136
|
+
code: string;
|
|
137
|
+
/** 人类可读的失败描述。 */
|
|
138
|
+
message: string;
|
|
139
|
+
/** 供应商 HTTP 状态码(可用时)。 */
|
|
140
|
+
status?: number;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* 错误分类: 该失败是否值得自动继续。
|
|
145
|
+
* 永久性失败(认证/余额/模型不存在/上下文超限等)重试也不会成功, 应跳过并通知用户;
|
|
146
|
+
* 其余(网络、超时、5xx、429 等)视为临时性失败, 允许自动恢复。
|
|
147
|
+
*/
|
|
148
|
+
export function isTransientFailure(failure: FailureFacts): boolean {
|
|
149
|
+
const haystack = `${failure.code} ${failure.message}`.toLowerCase();
|
|
150
|
+
const status = failure.status;
|
|
151
|
+
if (status !== undefined && (status === 401 || status === 403)) return false;
|
|
152
|
+
const permanent =
|
|
153
|
+
/auth|unauthor|forbidden|credential|api[_-]?key|permission/i.test(haystack) ||
|
|
154
|
+
/insufficient.*(balance|quota)|billing|payment|quota.*exceeded.*(?!retry)/i.test(haystack) ||
|
|
155
|
+
/model.*not[_-]?found|unknown[_-]?model|model[_-]?not[_-]?found|not.*support.*model/i.test(haystack) ||
|
|
156
|
+
/context.*(length|limit|overflow|exceed)|token.*limit|max.*context/i.test(haystack) ||
|
|
157
|
+
/invalid[_-]?request|bad[_-]?request/i.test(haystack);
|
|
158
|
+
return !permanent;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* host/agent-error 消息分类: 仅明确属于网络/传输类的临时错误才自动继续。
|
|
163
|
+
* 其余(序列化失败、配置/宿主内部错误等)视为永久性——重试无益, 且用户停止导致的
|
|
164
|
+
* 序列化失败(如 Windows 下 abort 的 DOMException reason)绝不能自动续跑。
|
|
165
|
+
*/
|
|
166
|
+
export function isTransientAgentError(message: string): boolean {
|
|
167
|
+
return /network|timeout|timed ?out|econn|etimedout|socket|5\d\d|\b429\b|upstream|temporar/i.test(message);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** 通知上的一个操作按钮(action 标识 + 显示文案)。 */
|
|
171
|
+
export interface NotifyAction {
|
|
172
|
+
/** 稳定动作标识, 点击时经 onAction 回调传出。 */
|
|
173
|
+
action: string;
|
|
174
|
+
/** 按钮显示文案。 */
|
|
175
|
+
title: string;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** 通知的可选行为: 操作按钮列表与点击回调。 */
|
|
179
|
+
export interface NotifyOptions {
|
|
180
|
+
actions?: NotifyAction[];
|
|
181
|
+
onAction?: (action: string) => void;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** 浏览器通知(不可用时静默跳过); 点击通知聚焦窗口, 操作按钮走 onAction。 */
|
|
185
|
+
function notify(title: string, body: string, options?: NotifyOptions): void {
|
|
186
|
+
try {
|
|
187
|
+
const N = (globalThis as { Notification?: unknown }).Notification as
|
|
188
|
+
| (new (t: string, o: { body: string; actions?: NotifyAction[] }) => unknown)
|
|
189
|
+
| undefined;
|
|
190
|
+
if (typeof N === 'undefined') return;
|
|
191
|
+
const permission = (N as unknown as { permission?: string }).permission;
|
|
192
|
+
const create = (): void => {
|
|
193
|
+
const instance = new N(title, {
|
|
194
|
+
body,
|
|
195
|
+
...(options?.actions !== undefined && options.actions.length > 0
|
|
196
|
+
? { actions: options.actions }
|
|
197
|
+
: {}),
|
|
198
|
+
});
|
|
199
|
+
const target = instance as {
|
|
200
|
+
onclick?: (() => void) | null;
|
|
201
|
+
onaction?: ((event: { action: string }) => void) | null;
|
|
202
|
+
};
|
|
203
|
+
target.onclick = () => {
|
|
204
|
+
try {
|
|
205
|
+
(globalThis as { focus?: () => void }).focus?.();
|
|
206
|
+
} catch {
|
|
207
|
+
/* ignore */
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
if (options?.onAction !== undefined) {
|
|
211
|
+
target.onaction = (event) => options.onAction?.(event.action);
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
if (permission === 'granted') {
|
|
215
|
+
create();
|
|
216
|
+
} else if (permission === 'default') {
|
|
217
|
+
// 首次使用时请求一次权限, 用户拒绝后不再打扰。
|
|
218
|
+
void (N as unknown as { requestPermission?: () => Promise<string> }).requestPermission?.()
|
|
219
|
+
.then((result) => {
|
|
220
|
+
if (result === 'granted') create();
|
|
221
|
+
})
|
|
222
|
+
.catch(() => {});
|
|
223
|
+
}
|
|
224
|
+
} catch {
|
|
225
|
+
/* 通知失败不影响核心逻辑 */
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** 把毫秒格式化为人类可读的经过时长(如 65s → 1m5s)。 */
|
|
230
|
+
function formatElapsed(ms: number | undefined): string {
|
|
231
|
+
if (ms === undefined || !Number.isFinite(ms) || ms < 0) return '';
|
|
232
|
+
if (ms < 1000) return `${Math.round(ms)}ms`;
|
|
233
|
+
const s = Math.round(ms / 1000);
|
|
234
|
+
if (s < 60) return `${s}s`;
|
|
235
|
+
return `${Math.floor(s / 60)}m${s % 60 > 0 ? `${s % 60}s` : ''}`;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** 模板填充所需的上下文(全部可选, 缺失的占位符填为空串)。 */
|
|
239
|
+
export interface TemplateContext {
|
|
240
|
+
/** 失败事实(错误码/消息/HTTP 状态), 对应 {code}/{message}/{status}。 */
|
|
241
|
+
facts?: FailureFacts;
|
|
242
|
+
/** 失败前最后一次工具调用的名称, 对应 {tool}。 */
|
|
243
|
+
tool?: string;
|
|
244
|
+
/** 失败回合的编号, 对应 {turn}。 */
|
|
245
|
+
turn?: number;
|
|
246
|
+
/** 连续失败次数(含本次), 对应 {errorCount}。 */
|
|
247
|
+
errorCount?: number;
|
|
248
|
+
/** 会话标题(来自 session.list 投影, 可用时), 对应 {sessionTitle}。 */
|
|
249
|
+
sessionTitle?: string;
|
|
250
|
+
/** 自失败发生以来的毫秒数, 对应 {elapsed}。 */
|
|
251
|
+
elapsedMs?: number;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** 用失败事实与回合信息填充 continueText 模板占位符({code}/{message}/{status}/{tool}/{turn}/{errorCount}/{sessionTitle}/{elapsed})。 */
|
|
255
|
+
export function fillTemplate(template: string, ctx: TemplateContext): string {
|
|
256
|
+
return template
|
|
257
|
+
.replace(/\{code\}/g, ctx.facts?.code ?? '')
|
|
258
|
+
.replace(/\{message\}/g, ctx.facts?.message ?? '')
|
|
259
|
+
.replace(/\{status\}/g, ctx.facts?.status !== undefined ? String(ctx.facts.status) : '')
|
|
260
|
+
.replace(/\{tool\}/g, ctx.tool ?? '')
|
|
261
|
+
.replace(/\{turn\}/g, ctx.turn !== undefined ? String(ctx.turn) : '')
|
|
262
|
+
.replace(/\{errorCount\}/g, ctx.errorCount !== undefined ? String(ctx.errorCount) : '')
|
|
263
|
+
.replace(/\{sessionTitle\}/g, ctx.sessionTitle ?? '')
|
|
264
|
+
.replace(/\{elapsed\}/g, formatElapsed(ctx.elapsedMs));
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** 自适应退避: 同一会话连续失败时的有效冷却间隔。 */
|
|
268
|
+
export function effectiveCooldown(
|
|
269
|
+
consecutive: number,
|
|
270
|
+
base: number,
|
|
271
|
+
factor: number,
|
|
272
|
+
max: number,
|
|
273
|
+
): number {
|
|
274
|
+
// consecutive = 已连续自动继续的次数; 第 1 次后开始按 factor 递增
|
|
275
|
+
const multiplier = Math.pow(factor, consecutive);
|
|
276
|
+
return Math.min(Math.max(base, base * multiplier), Math.max(base, max));
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function sleep(ms: number): Promise<void> {
|
|
280
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** 浏览器当前 IANA 时区; 不可用时省略(宿主允许省略)。 */
|
|
284
|
+
function clientTimeZone(): string | undefined {
|
|
285
|
+
try {
|
|
286
|
+
return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined;
|
|
287
|
+
} catch {
|
|
288
|
+
return undefined;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** 跨标签页互斥与冷却记录(仅浏览器本地, 不落盘到宿主)。 */
|
|
293
|
+
const lockPrefix = 'dsh-auto-continue:';
|
|
294
|
+
const lockKey = (sessionId: SessionId) => `${lockPrefix}lock:${sessionId}`;
|
|
295
|
+
const stampKey = (sessionId: SessionId) => `${lockPrefix}last:${sessionId}`;
|
|
296
|
+
|
|
297
|
+
/** 尝试独占本次发送: 两个标签页同时触发时只有一个成功。 */
|
|
298
|
+
function claimSend(sessionId: SessionId): boolean {
|
|
299
|
+
try {
|
|
300
|
+
const token = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
301
|
+
localStorage.setItem(lockKey(sessionId), token);
|
|
302
|
+
return localStorage.getItem(lockKey(sessionId)) === token;
|
|
303
|
+
} catch {
|
|
304
|
+
return true; // 存储不可用(隐私模式等)时放行
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function releaseSend(sessionId: SessionId): void {
|
|
309
|
+
try {
|
|
310
|
+
localStorage.removeItem(lockKey(sessionId));
|
|
311
|
+
} catch {
|
|
312
|
+
/* ignore */
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** 读/写「上次自动发送」时间戳(跨标签页冷却)。 */
|
|
317
|
+
function readLastSend(sessionId: SessionId): number {
|
|
318
|
+
try {
|
|
319
|
+
return Number(localStorage.getItem(stampKey(sessionId)) ?? 0) || 0;
|
|
320
|
+
} catch {
|
|
321
|
+
return 0;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function writeLastSend(sessionId: SessionId, at: number): void {
|
|
326
|
+
try {
|
|
327
|
+
localStorage.setItem(stampKey(sessionId), String(at));
|
|
328
|
+
} catch {
|
|
329
|
+
/* ignore */
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// ---------- 会话级暂停(仅浏览器本地, 跨标签页共享) ----------
|
|
334
|
+
|
|
335
|
+
const pauseKey = (sessionId: SessionId) => `${lockPrefix}pause:${sessionId}`;
|
|
336
|
+
|
|
337
|
+
/** 暂停某会话: 到 `until` 之前, 引擎不会为该会话自动继续(通知按钮等调用)。 */
|
|
338
|
+
export function pauseSession(sessionId: SessionId, ms: number): void {
|
|
339
|
+
try {
|
|
340
|
+
localStorage.setItem(pauseKey(sessionId), String(Date.now() + ms));
|
|
341
|
+
} catch {
|
|
342
|
+
/* ignore */
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** 解除某会话的暂停。 */
|
|
347
|
+
export function unpauseSession(sessionId: SessionId): void {
|
|
348
|
+
try {
|
|
349
|
+
localStorage.removeItem(pauseKey(sessionId));
|
|
350
|
+
} catch {
|
|
351
|
+
/* ignore */
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** 会话暂停的截止时间戳; 0 表示未暂停。 */
|
|
356
|
+
export function sessionPauseUntil(sessionId: SessionId): number {
|
|
357
|
+
try {
|
|
358
|
+
return Number(localStorage.getItem(pauseKey(sessionId)) ?? 0) || 0;
|
|
359
|
+
} catch {
|
|
360
|
+
return 0;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** 当前生效(未过期)的暂停会话列表; 顺带清理过期条目。 */
|
|
365
|
+
export function pausedSessions(): { sessionId: SessionId; until: number }[] {
|
|
366
|
+
const out: { sessionId: SessionId; until: number }[] = [];
|
|
367
|
+
const now = Date.now();
|
|
368
|
+
try {
|
|
369
|
+
for (let i = 0; i < localStorage.length; i += 1) {
|
|
370
|
+
const key = localStorage.key(i);
|
|
371
|
+
if (key === null || !key.startsWith(`${lockPrefix}pause:`)) continue;
|
|
372
|
+
const sessionId = key.slice(lockPrefix.length + 'pause:'.length) as SessionId;
|
|
373
|
+
const until = Number(localStorage.getItem(key) ?? 0) || 0;
|
|
374
|
+
if (until > now) out.push({ sessionId, until });
|
|
375
|
+
else localStorage.removeItem(key);
|
|
376
|
+
}
|
|
377
|
+
} catch {
|
|
378
|
+
/* ignore */
|
|
379
|
+
}
|
|
380
|
+
return out;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// ---------- 统计(仅浏览器本地; 按本地日期分桶, 最多保留 90 天) ----------
|
|
384
|
+
|
|
385
|
+
/** 一天的自动继续统计。 */
|
|
386
|
+
export interface DayStats {
|
|
387
|
+
/** 本地日期 YYYY-MM-DD。 */
|
|
388
|
+
date: string;
|
|
389
|
+
/** 自动发送次数。 */
|
|
390
|
+
sent: number;
|
|
391
|
+
/** 因永久性错误跳过的次数。 */
|
|
392
|
+
skipped: number;
|
|
393
|
+
/** 发送后回合成功完成(恢复成功)的次数。 */
|
|
394
|
+
recovered: number;
|
|
395
|
+
/** 发送后再次失败的次数。 */
|
|
396
|
+
failed: number;
|
|
397
|
+
/** 达到连续上限而停止的次数(按停止事件计)。 */
|
|
398
|
+
gaveUp: number;
|
|
399
|
+
/** 按错误码计数的失败分布。 */
|
|
400
|
+
byCode: Record<string, number>;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
const statsKey = `${lockPrefix}stats`;
|
|
404
|
+
const STATS_MAX_DAYS = 90;
|
|
405
|
+
|
|
406
|
+
function todayKey(): string {
|
|
407
|
+
const d = new Date();
|
|
408
|
+
const mm = String(d.getMonth() + 1).padStart(2, '0');
|
|
409
|
+
const dd = String(d.getDate()).padStart(2, '0');
|
|
410
|
+
return `${d.getFullYear()}-${mm}-${dd}`;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
function readStats(): DayStats[] {
|
|
414
|
+
try {
|
|
415
|
+
const raw = localStorage.getItem(statsKey);
|
|
416
|
+
if (raw === null) return [];
|
|
417
|
+
const parsed = JSON.parse(raw);
|
|
418
|
+
if (!Array.isArray(parsed)) return [];
|
|
419
|
+
return parsed.filter(
|
|
420
|
+
(item): item is DayStats =>
|
|
421
|
+
typeof item === 'object' && item !== null && typeof item.date === 'string',
|
|
422
|
+
);
|
|
423
|
+
} catch {
|
|
424
|
+
return [];
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function writeStats(list: DayStats[]): void {
|
|
429
|
+
try {
|
|
430
|
+
localStorage.setItem(statsKey, JSON.stringify(list));
|
|
431
|
+
} catch {
|
|
432
|
+
/* ignore */
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** 累加今日统计(引擎内部记账)。 */
|
|
437
|
+
function bumpStat(delta: {
|
|
438
|
+
sent?: number;
|
|
439
|
+
skipped?: number;
|
|
440
|
+
recovered?: number;
|
|
441
|
+
failed?: number;
|
|
442
|
+
gaveUp?: number;
|
|
443
|
+
code?: string;
|
|
444
|
+
}): void {
|
|
445
|
+
const list = readStats();
|
|
446
|
+
let day = list.find((item) => item.date === todayKey());
|
|
447
|
+
if (day === undefined) {
|
|
448
|
+
day = { date: todayKey(), sent: 0, skipped: 0, recovered: 0, failed: 0, gaveUp: 0, byCode: {} };
|
|
449
|
+
list.unshift(day);
|
|
450
|
+
}
|
|
451
|
+
if (delta.sent !== undefined) day.sent += delta.sent;
|
|
452
|
+
if (delta.skipped !== undefined) day.skipped += delta.skipped;
|
|
453
|
+
if (delta.recovered !== undefined) day.recovered += delta.recovered;
|
|
454
|
+
if (delta.failed !== undefined) day.failed += delta.failed;
|
|
455
|
+
if (delta.gaveUp !== undefined) day.gaveUp += delta.gaveUp;
|
|
456
|
+
if (delta.code !== undefined) day.byCode[delta.code] = (day.byCode[delta.code] ?? 0) + 1;
|
|
457
|
+
writeStats(list.slice(0, STATS_MAX_DAYS));
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** 今日统计(设置卡片展示用)。 */
|
|
461
|
+
export function readTodayStats(): DayStats {
|
|
462
|
+
const today = todayKey();
|
|
463
|
+
const found = readStats().find((item) => item.date === today);
|
|
464
|
+
return (
|
|
465
|
+
found ?? { date: today, sent: 0, skipped: 0, recovered: 0, failed: 0, gaveUp: 0, byCode: {} }
|
|
466
|
+
);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** 清零今日统计。 */
|
|
470
|
+
export function resetTodayStats(): void {
|
|
471
|
+
writeStats(readStats().filter((item) => item.date !== todayKey()));
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** 每会话运行时状态。 */
|
|
475
|
+
interface SessionState {
|
|
476
|
+
/** 连续自动「继续」次数; 成功回合或用户手动介入后归零。 */
|
|
477
|
+
consecutive: number;
|
|
478
|
+
/** 上次自动「继续」时间戳。 */
|
|
479
|
+
lastAutoAt: number;
|
|
480
|
+
/** 上次自动「继续」尝试(成功或失败)时间戳; 防止失败场景下的快速重试循环。 */
|
|
481
|
+
lastAttemptAt: number;
|
|
482
|
+
/** 我们上次自动发送的文本(用于识别自己的回显)。 */
|
|
483
|
+
lastSentText: string;
|
|
484
|
+
/** 宽限期定时器(进行中的待发送)。 */
|
|
485
|
+
pendingTimer: number | undefined;
|
|
486
|
+
/** 宿主权威 running 位(来自 host/session-status 与回合事件)。 */
|
|
487
|
+
running: boolean | undefined;
|
|
488
|
+
/** 当前排队消息数(来自 session/queue 帧)。 */
|
|
489
|
+
queued: number;
|
|
490
|
+
/** 子代理会话(host/session-added 带 parentSessionId)。 */
|
|
491
|
+
subagent: boolean;
|
|
492
|
+
/** 最近一次回合失败的事实(用于分类与模板填充)。 */
|
|
493
|
+
lastFailure: FailureFacts | undefined;
|
|
494
|
+
/** 最近一次失败的发生时间(模板 {elapsed} 与恢复统计用)。 */
|
|
495
|
+
lastFailureAt: number;
|
|
496
|
+
/** 失败前最后一次工具调用的名称(模板 {tool})。 */
|
|
497
|
+
lastTool: string | undefined;
|
|
498
|
+
/** 失败回合的编号(模板 {turn})。 */
|
|
499
|
+
lastTurn: number | undefined;
|
|
500
|
+
/** 我们最近一次自动发送的时间戳; 0 = 没有待确认的恢复。 */
|
|
501
|
+
pendingRecoveryAt: number;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
const freshState = (): SessionState => ({
|
|
505
|
+
consecutive: 0,
|
|
506
|
+
lastAutoAt: 0,
|
|
507
|
+
lastAttemptAt: 0,
|
|
508
|
+
lastSentText: '',
|
|
509
|
+
pendingTimer: undefined,
|
|
510
|
+
running: undefined,
|
|
511
|
+
queued: 0,
|
|
512
|
+
subagent: false,
|
|
513
|
+
lastFailure: undefined,
|
|
514
|
+
lastFailureAt: 0,
|
|
515
|
+
lastTool: undefined,
|
|
516
|
+
lastTurn: undefined,
|
|
517
|
+
pendingRecoveryAt: 0,
|
|
518
|
+
});
|
|
519
|
+
|
|
520
|
+
/** 自动发送后, 在该窗口内出现的回合结束才计入恢复统计。 */
|
|
521
|
+
const RECOVERY_WINDOW_MS = 10 * 60 * 1000;
|
|
522
|
+
|
|
523
|
+
/** 判定一条 user/message 是否是我们自己自动发送的回显。 */
|
|
524
|
+
function isOurEcho(state: SessionState, event: SessionEvent): boolean {
|
|
525
|
+
if (event.type !== 'user/message') return false;
|
|
526
|
+
const message = event.data;
|
|
527
|
+
if (message.source.kind !== 'user') return false;
|
|
528
|
+
if (state.lastSentText === '') return false;
|
|
529
|
+
if (Date.now() - state.lastAutoAt > 30000) return false;
|
|
530
|
+
const text = message.content
|
|
531
|
+
.filter((part): part is { type: 'text'; text: string } => part.type === 'text')
|
|
532
|
+
.map((part) => part.text)
|
|
533
|
+
.join('');
|
|
534
|
+
return text === state.lastSentText;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/** SSE 帧外壳: `{ rpcId, payload }`。 */
|
|
538
|
+
type FrameEnvelope<T> = { payload: T };
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* 事件流泵: 带指数退避的 SSE 重连循环。
|
|
542
|
+
* - 从未收到任何帧(宿主未就绪): 退避重试, 不触发扫描
|
|
543
|
+
* - 曾连上后断开: 重连, 并通过 onReconnect 通知外层(宿主可能崩溃重启过)
|
|
544
|
+
*/
|
|
545
|
+
async function pumpStream<T>(
|
|
546
|
+
open: (signal: AbortSignal) => AsyncIterable<FrameEnvelope<T>>,
|
|
547
|
+
onFrame: (payload: T) => void,
|
|
548
|
+
onReconnect: () => void,
|
|
549
|
+
getBackoff: () => number,
|
|
550
|
+
log: (message: string) => void,
|
|
551
|
+
signal: AbortSignal,
|
|
552
|
+
): Promise<void> {
|
|
553
|
+
let backoff = getBackoff();
|
|
554
|
+
while (!signal.aborted) {
|
|
555
|
+
let connected = false;
|
|
556
|
+
try {
|
|
557
|
+
for await (const envelope of open(signal)) {
|
|
558
|
+
connected = true;
|
|
559
|
+
onFrame(envelope.payload);
|
|
560
|
+
}
|
|
561
|
+
if (signal.aborted) return;
|
|
562
|
+
} catch (error) {
|
|
563
|
+
if (signal.aborted) return;
|
|
564
|
+
log(`stream error: ${error instanceof Error ? error.message : String(error)}`);
|
|
565
|
+
}
|
|
566
|
+
if (!connected) {
|
|
567
|
+
// 从未连上(宿主未就绪): 指数退避重试
|
|
568
|
+
await sleep(backoff);
|
|
569
|
+
backoff = Math.min(backoff * 2, 15000);
|
|
570
|
+
continue;
|
|
571
|
+
}
|
|
572
|
+
// 曾连上后断开 → 重连并触发外层扫描
|
|
573
|
+
backoff = getBackoff();
|
|
574
|
+
onReconnect();
|
|
575
|
+
await sleep(backoff);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/** 插件主体: 一条 mux 流 + 一条 host 流 + 启动/重连扫描。 */
|
|
580
|
+
export class AutoContinueRunner {
|
|
581
|
+
private readonly states = new Map<SessionId, SessionState>();
|
|
582
|
+
private readonly muxAbort = new AbortController();
|
|
583
|
+
private readonly hostAbort = new AbortController();
|
|
584
|
+
private disposed = false;
|
|
585
|
+
private reconnectScans = 0;
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* @param api - shared wire client (ctx.connection.api).
|
|
589
|
+
* @param getConfig - read the current resolved configuration (settings scope).
|
|
590
|
+
*/
|
|
591
|
+
constructor(
|
|
592
|
+
private readonly api: IApiClient,
|
|
593
|
+
private readonly getConfig: () => AutoContinueConfig,
|
|
594
|
+
) {
|
|
595
|
+
const config = this.getConfig();
|
|
596
|
+
void this.runMux();
|
|
597
|
+
void this.runHost();
|
|
598
|
+
if (config.scanOnBoot) {
|
|
599
|
+
// 启动时连接可能尚未建立, 循环重试直到成功。
|
|
600
|
+
void this.bootScanLoop();
|
|
601
|
+
}
|
|
602
|
+
this.log(
|
|
603
|
+
`已启动(文本="${config.continueText}", 宽限 ${config.graceMs}ms, ` +
|
|
604
|
+
`冷却 ${config.cooldownMs}ms, 最多连续 ${config.maxConsecutive} 次)`,
|
|
605
|
+
);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
private log(message: string): void {
|
|
609
|
+
if (this.getConfig().verbose) console.info(`[auto-continue] ${message}`);
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
dispose(): void {
|
|
613
|
+
this.disposed = true;
|
|
614
|
+
this.muxAbort.abort();
|
|
615
|
+
this.hostAbort.abort();
|
|
616
|
+
for (const state of this.states.values()) {
|
|
617
|
+
if (state.pendingTimer !== undefined) clearTimeout(state.pendingTimer);
|
|
618
|
+
}
|
|
619
|
+
this.states.clear();
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
private state(sessionId: SessionId): SessionState {
|
|
623
|
+
let state = this.states.get(sessionId);
|
|
624
|
+
if (state === undefined) {
|
|
625
|
+
state = freshState();
|
|
626
|
+
this.states.set(sessionId, state);
|
|
627
|
+
}
|
|
628
|
+
return state;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
private runMux(): Promise<void> {
|
|
632
|
+
return pumpStream<MuxFrame>(
|
|
633
|
+
(signal) => this.api.events.mux({}, signal),
|
|
634
|
+
(payload) => this.onMuxFrame(payload),
|
|
635
|
+
() => this.scheduleReconnectScan(),
|
|
636
|
+
() => this.getConfig().reconnectBackoffMs,
|
|
637
|
+
(m) => this.log(m),
|
|
638
|
+
this.muxAbort.signal,
|
|
639
|
+
);
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
private runHost(): Promise<void> {
|
|
643
|
+
return pumpStream<HostFrame>(
|
|
644
|
+
(signal) => this.api.events.host({}, signal),
|
|
645
|
+
(payload) => this.onHostFrame(payload),
|
|
646
|
+
() => this.scheduleReconnectScan(),
|
|
647
|
+
() => this.getConfig().reconnectBackoffMs,
|
|
648
|
+
(m) => this.log(m),
|
|
649
|
+
this.hostAbort.signal,
|
|
650
|
+
);
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// ---------- mux 帧 ----------
|
|
654
|
+
|
|
655
|
+
private onMuxFrame(frame: MuxFrame): void {
|
|
656
|
+
switch (frame.type) {
|
|
657
|
+
case 'session/event':
|
|
658
|
+
if (frame.event.type === 'tool/call') {
|
|
659
|
+
const name = frame.event.data.name;
|
|
660
|
+
if (typeof name === 'string') this.state(frame.sessionId).lastTool = name;
|
|
661
|
+
}
|
|
662
|
+
this.onSessionEvent(frame.sessionId, frame.event);
|
|
663
|
+
break;
|
|
664
|
+
case 'session/queue':
|
|
665
|
+
this.state(frame.sessionId).queued = frame.items.length;
|
|
666
|
+
if (frame.items.length > 0) this.cancelPending(frame.sessionId, '出现排队消息');
|
|
667
|
+
break;
|
|
668
|
+
case 'stream/error':
|
|
669
|
+
this.log(`mux stream/error: ${frame.error.code} ${frame.error.message}`);
|
|
670
|
+
break;
|
|
671
|
+
default:
|
|
672
|
+
break; // session/subscribed、approval/*、question/*、session/jobs、session/projection 与本插件无关
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
private onSessionEvent(sessionId: SessionId, event: SessionEvent): void {
|
|
677
|
+
const state = this.state(sessionId);
|
|
678
|
+
switch (event.type) {
|
|
679
|
+
case 'turn/start':
|
|
680
|
+
state.running = true;
|
|
681
|
+
this.cancelPending(sessionId, '宿主自行开启新回合');
|
|
682
|
+
break;
|
|
683
|
+
case 'turn/end': {
|
|
684
|
+
state.running = false;
|
|
685
|
+
this.cancelPending(sessionId, '收到新的 turn/end');
|
|
686
|
+
const reason = event.data.reason;
|
|
687
|
+
if (reason.kind === 'completed') {
|
|
688
|
+
// 成功回合: 恢复健康状态, 并确认上一次自动发送的效果
|
|
689
|
+
state.consecutive = 0;
|
|
690
|
+
state.lastFailure = undefined;
|
|
691
|
+
this.noteRecovery(sessionId, 'completed');
|
|
692
|
+
} else if (reason.kind === 'aborted') {
|
|
693
|
+
// 用户主动停止: 不自动继续, 视为用户介入
|
|
694
|
+
state.consecutive = 0;
|
|
695
|
+
state.pendingRecoveryAt = 0;
|
|
696
|
+
} else if (reason.kind === 'blocked') {
|
|
697
|
+
// 策略拒绝: 不自动继续
|
|
698
|
+
} else if (reason.kind === 'interrupted') {
|
|
699
|
+
// 实时路径的 interrupted 仅来自崩溃修复重载(loop 从不实时发出);
|
|
700
|
+
// 用户手动停止在 DSH 中标记为 aborted, 不走到这里。实时流里出现
|
|
701
|
+
// interrupted 视为异常中断, 不自动继续——宿主崩溃孤儿回合由扫描恢复。
|
|
702
|
+
state.consecutive = 0;
|
|
703
|
+
state.pendingRecoveryAt = 0;
|
|
704
|
+
} else if (reason.kind === 'error') {
|
|
705
|
+
// 记录失败事实(分类与模板填充用), 然后按类型处理
|
|
706
|
+
const error = reason.error;
|
|
707
|
+
state.lastFailure = {
|
|
708
|
+
code: typeof error.code === 'string' ? error.code : 'UNKNOWN',
|
|
709
|
+
message: typeof error.message === 'string' ? error.message : String(error),
|
|
710
|
+
...(typeof error.status === 'number' ? { status: error.status } : {}),
|
|
711
|
+
};
|
|
712
|
+
state.lastTurn = event.data.turn;
|
|
713
|
+
state.lastFailureAt = Date.now();
|
|
714
|
+
this.noteRecovery(sessionId, 'error');
|
|
715
|
+
this.onTurnFailure(sessionId, 'turn/end:error', state.lastFailure);
|
|
716
|
+
} else if (reason.kind === 'max-tokens') {
|
|
717
|
+
state.lastFailureAt = Date.now();
|
|
718
|
+
this.noteRecovery(sessionId, 'error');
|
|
719
|
+
this.schedule(sessionId, 'turn/end:max-tokens');
|
|
720
|
+
}
|
|
721
|
+
break;
|
|
722
|
+
}
|
|
723
|
+
case 'user/message':
|
|
724
|
+
if (isOurEcho(state, event)) break; // 我们自己的回显
|
|
725
|
+
if (event.data.source.kind === 'user') {
|
|
726
|
+
// 用户手动介入
|
|
727
|
+
state.consecutive = 0;
|
|
728
|
+
this.cancelPending(sessionId, '用户手动发送消息');
|
|
729
|
+
}
|
|
730
|
+
break;
|
|
731
|
+
default:
|
|
732
|
+
break;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// ---------- host 帧 ----------
|
|
737
|
+
|
|
738
|
+
private onHostFrame(frame: HostFrame): void {
|
|
739
|
+
switch (frame.type) {
|
|
740
|
+
case 'host/session-status':
|
|
741
|
+
this.state(frame.sessionId).running = frame.running;
|
|
742
|
+
if (frame.running) this.cancelPending(frame.sessionId, '宿主报告会话开始运行');
|
|
743
|
+
break;
|
|
744
|
+
case 'host/session-added':
|
|
745
|
+
this.state(frame.sessionId).subagent = frame.parentSessionId !== undefined;
|
|
746
|
+
break;
|
|
747
|
+
case 'host/agent-error':
|
|
748
|
+
if (this.state(frame.sessionId).subagent) break;
|
|
749
|
+
this.log(`host/agent-error(${frame.sessionId}): ${frame.message}`);
|
|
750
|
+
if (this.getConfig().classify && !isTransientAgentError(frame.message)) {
|
|
751
|
+
// 永久性 agent 错误(序列化失败/配置错误等): 跳过并通知, 避免把用户停止等
|
|
752
|
+
// 场景误判为可恢复中断后自动续跑。
|
|
753
|
+
this.log(`跳过 ${frame.sessionId}: 永久性 agent 错误 — ${frame.message}`);
|
|
754
|
+
bumpStat({ skipped: 1 });
|
|
755
|
+
if (this.getConfig().notify) {
|
|
756
|
+
notify(
|
|
757
|
+
'dsh-auto-continue: 未自动继续',
|
|
758
|
+
`${frame.sessionId}: 永久性 agent 错误 ${frame.message.slice(0, 120)}`,
|
|
759
|
+
this.notifyOptions(frame.sessionId),
|
|
760
|
+
);
|
|
761
|
+
}
|
|
762
|
+
break;
|
|
763
|
+
}
|
|
764
|
+
this.schedule(frame.sessionId, 'host/agent-error');
|
|
765
|
+
break;
|
|
766
|
+
case 'host/session-removed':
|
|
767
|
+
this.cancelPending(frame.sessionId, '会话已移除');
|
|
768
|
+
this.states.delete(frame.sessionId);
|
|
769
|
+
break;
|
|
770
|
+
default:
|
|
771
|
+
break;
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// ---------- 调度 ----------
|
|
776
|
+
|
|
777
|
+
/** 回合失败入口: 先做错误分类, 永久性失败跳过并通知, 临时性失败走正常调度。 */
|
|
778
|
+
private onTurnFailure(sessionId: SessionId, reason: string, failure: FailureFacts): void {
|
|
779
|
+
const config = this.getConfig();
|
|
780
|
+
if (config.classify && !isTransientFailure(failure)) {
|
|
781
|
+
const summary = `${failure.code}${failure.status !== undefined ? ` (HTTP ${failure.status})` : ''}`;
|
|
782
|
+
this.log(`跳过 ${sessionId}(${reason}): 永久性失败 ${summary} — ${failure.message}`);
|
|
783
|
+
bumpStat({ skipped: 1, code: failure.code });
|
|
784
|
+
if (config.notify) {
|
|
785
|
+
notify(
|
|
786
|
+
'dsh-auto-continue: 未自动继续',
|
|
787
|
+
`${sessionId}: 永久性错误 ${summary},需要人工处理`,
|
|
788
|
+
this.notifyOptions(sessionId),
|
|
789
|
+
);
|
|
790
|
+
}
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
this.schedule(sessionId, reason);
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/** 通知操作按钮与回调(「立即续跑」/「暂停该会话 1 小时」)。 */
|
|
797
|
+
private notifyOptions(sessionId: SessionId): NotifyOptions {
|
|
798
|
+
return {
|
|
799
|
+
actions: [
|
|
800
|
+
{ action: 'resume', title: '立即续跑' },
|
|
801
|
+
{ action: 'pause1h', title: '暂停该会话 1 小时' },
|
|
802
|
+
],
|
|
803
|
+
onAction: (action) => this.onNotifyAction(sessionId, action),
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
private onNotifyAction(sessionId: SessionId, action: string): void {
|
|
808
|
+
if (action === 'resume') {
|
|
809
|
+
this.log(`通知按钮: 立即续跑 ${sessionId}`);
|
|
810
|
+
void this.resumeNow(sessionId);
|
|
811
|
+
} else if (action === 'pause1h') {
|
|
812
|
+
this.log(`通知按钮: 暂停 ${sessionId} 1 小时`);
|
|
813
|
+
pauseSession(sessionId, 60 * 60 * 1000);
|
|
814
|
+
this.cancelPending(sessionId, '通知按钮暂停该会话');
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/** 恢复结果记账: 自动发送后窗口内的回合结束, 判定恢复成功或失败。 */
|
|
819
|
+
private noteRecovery(sessionId: SessionId, outcome: 'completed' | 'error'): void {
|
|
820
|
+
const state = this.state(sessionId);
|
|
821
|
+
if (state.pendingRecoveryAt === 0) return;
|
|
822
|
+
if (Date.now() - state.pendingRecoveryAt > RECOVERY_WINDOW_MS) {
|
|
823
|
+
state.pendingRecoveryAt = 0; // 窗口过期, 不再归属这次发送
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
state.pendingRecoveryAt = 0;
|
|
827
|
+
bumpStat(outcome === 'completed' ? { recovered: 1 } : { failed: 1 });
|
|
828
|
+
this.log(`恢复结果(${sessionId}): ${outcome === 'completed' ? '成功' : '失败'}`);
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
/** 立即为该会话发送一次自动继续(无视冷却与连续上限; 由通知按钮触发)。 */
|
|
832
|
+
async resumeNow(sessionId: SessionId): Promise<void> {
|
|
833
|
+
if (this.disposed) return;
|
|
834
|
+
const state = this.state(sessionId);
|
|
835
|
+
if (state.subagent) return;
|
|
836
|
+
if (state.pendingTimer !== undefined) {
|
|
837
|
+
clearTimeout(state.pendingTimer);
|
|
838
|
+
state.pendingTimer = undefined;
|
|
839
|
+
}
|
|
840
|
+
await this.fire(sessionId, 'manual:notification', true);
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/** 本会话当前生效的冷却间隔(自适应退避)。 */
|
|
844
|
+
private cooldownFor(state: SessionState): number {
|
|
845
|
+
const config = this.getConfig();
|
|
846
|
+
return effectiveCooldown(
|
|
847
|
+
state.consecutive,
|
|
848
|
+
config.cooldownMs,
|
|
849
|
+
config.backoffFactor,
|
|
850
|
+
config.backoffMaxMs,
|
|
851
|
+
);
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
private schedule(sessionId: SessionId, reason: string): void {
|
|
855
|
+
const state = this.state(sessionId);
|
|
856
|
+
const config = this.getConfig();
|
|
857
|
+
if (state.subagent) return; // 子代理会话由父代理处理, 不抢跑
|
|
858
|
+
if (config.paused) {
|
|
859
|
+
this.log(`跳过 ${sessionId}(${reason}): 全局暂停中`);
|
|
860
|
+
return;
|
|
861
|
+
}
|
|
862
|
+
if (Date.now() < sessionPauseUntil(sessionId)) {
|
|
863
|
+
this.log(`跳过 ${sessionId}(${reason}): 会话暂停中`);
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
if (state.pendingTimer !== undefined) return; // 已有待发送
|
|
867
|
+
if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) return; // 冷却期(含失败尝试, 自适应退避)
|
|
868
|
+
if (state.consecutive >= config.maxConsecutive) {
|
|
869
|
+
this.log(
|
|
870
|
+
`跳过 ${sessionId}(${reason}): 已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`,
|
|
871
|
+
);
|
|
872
|
+
return;
|
|
873
|
+
}
|
|
874
|
+
if (state.queued > 0) return; // 已有排队消息, 宿主会自行唤醒
|
|
875
|
+
const timer = setTimeout(() => {
|
|
876
|
+
if (state.pendingTimer !== timer) return;
|
|
877
|
+
state.pendingTimer = undefined;
|
|
878
|
+
void this.fire(sessionId, reason);
|
|
879
|
+
}, config.graceMs);
|
|
880
|
+
state.pendingTimer = timer;
|
|
881
|
+
const template = reason.includes('max-tokens') ? config.continueTextMaxTokens : config.continueText;
|
|
882
|
+
this.log(
|
|
883
|
+
`检测到非人为中断 ${sessionId}(${reason}), ${config.graceMs}ms 后自动发送「${template}」`,
|
|
884
|
+
);
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
private cancelPending(sessionId: SessionId, why: string): void {
|
|
888
|
+
const state = this.state(sessionId);
|
|
889
|
+
if (state.pendingTimer === undefined) return;
|
|
890
|
+
clearTimeout(state.pendingTimer);
|
|
891
|
+
state.pendingTimer = undefined;
|
|
892
|
+
this.log(`取消 ${sessionId} 的自动继续(${why})`);
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
private async fire(sessionId: SessionId, reason: string, force = false): Promise<void> {
|
|
896
|
+
if (this.disposed) return;
|
|
897
|
+
const state = this.state(sessionId);
|
|
898
|
+
const config = this.getConfig();
|
|
899
|
+
// 权威 running 检查: 优先用 host 帧, 未知时回退到 session.list
|
|
900
|
+
if (state.running === undefined) {
|
|
901
|
+
const running = await this.runningViaList(sessionId);
|
|
902
|
+
if (running === undefined || running) {
|
|
903
|
+
this.log(`跳过 ${sessionId}: 无法确认空闲(${running === undefined ? '未知' : '运行中'})`);
|
|
904
|
+
return;
|
|
905
|
+
}
|
|
906
|
+
} else if (state.running) {
|
|
907
|
+
this.log(`跳过 ${sessionId}: 会话仍在运行`);
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
if (state.queued > 0) {
|
|
911
|
+
this.log(`跳过 ${sessionId}: 已有排队消息`);
|
|
912
|
+
return;
|
|
913
|
+
}
|
|
914
|
+
// 跨标签页冷却(自适应退避); 通知按钮的强制续跑不受冷却约束
|
|
915
|
+
if (!force && Date.now() - readLastSend(sessionId) < this.cooldownFor(state)) {
|
|
916
|
+
this.log(`跳过 ${sessionId}: 其他标签页刚发送过`);
|
|
917
|
+
return;
|
|
918
|
+
}
|
|
919
|
+
if (!claimSend(sessionId)) {
|
|
920
|
+
this.log(`跳过 ${sessionId}: 其他标签页正在发送`);
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
923
|
+
// 模板填充: continueText 可含 {code}/{message}/{status}/{tool}/{turn}/{errorCount}/{sessionTitle}/{elapsed} 占位符
|
|
924
|
+
const template = reason.includes('max-tokens') ? config.continueTextMaxTokens : config.continueText;
|
|
925
|
+
let sessionTitle: string | undefined;
|
|
926
|
+
if (template.includes('{sessionTitle}')) {
|
|
927
|
+
sessionTitle = this.titles.get(sessionId);
|
|
928
|
+
if (sessionTitle === undefined) {
|
|
929
|
+
const info = await this.fetchSessionInfo(sessionId);
|
|
930
|
+
sessionTitle = info?.title;
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
const text = fillTemplate(template, {
|
|
934
|
+
facts: state.lastFailure,
|
|
935
|
+
tool: state.lastTool,
|
|
936
|
+
turn: state.lastTurn,
|
|
937
|
+
errorCount: state.consecutive + 1,
|
|
938
|
+
sessionTitle,
|
|
939
|
+
elapsedMs: state.lastFailureAt > 0 ? Date.now() - state.lastFailureAt : undefined,
|
|
940
|
+
});
|
|
941
|
+
const zone = clientTimeZone();
|
|
942
|
+
state.lastAttemptAt = Date.now(); // 先记账: 无论成败, 本次尝试都进入冷却
|
|
943
|
+
try {
|
|
944
|
+
const response = await this.api.sessions.prompt({
|
|
945
|
+
sessionId,
|
|
946
|
+
mode: 'queue',
|
|
947
|
+
content: [{ type: 'text', text }],
|
|
948
|
+
...(zone === undefined ? {} : { clientTimeZone: zone }),
|
|
949
|
+
});
|
|
950
|
+
if (response.result.ok) {
|
|
951
|
+
const now = Date.now();
|
|
952
|
+
state.consecutive += 1;
|
|
953
|
+
state.lastAutoAt = now;
|
|
954
|
+
state.lastSentText = text;
|
|
955
|
+
state.pendingRecoveryAt = now; // 等待窗口内的下一个回合结束来判定恢复结果
|
|
956
|
+
writeLastSend(sessionId, now);
|
|
957
|
+
bumpStat({ sent: 1, ...(state.lastFailure !== undefined ? { code: state.lastFailure.code } : {}) });
|
|
958
|
+
this.log(`已自动发送「${text}」到 ${sessionId}(${reason}), 第 ${state.consecutive} 次连续`);
|
|
959
|
+
if (config.notify) {
|
|
960
|
+
notify(
|
|
961
|
+
'dsh-auto-continue: 已自动继续',
|
|
962
|
+
`${sessionId}: 已发送「${text}」(第 ${state.consecutive} 次连续)`,
|
|
963
|
+
this.notifyOptions(sessionId),
|
|
964
|
+
);
|
|
965
|
+
}
|
|
966
|
+
if (state.consecutive >= config.maxConsecutive) {
|
|
967
|
+
bumpStat({ gaveUp: 1 });
|
|
968
|
+
this.log(`达到连续上限 ${config.maxConsecutive} 次, 停止自动继续 ${sessionId}`);
|
|
969
|
+
if (config.notify) {
|
|
970
|
+
notify(
|
|
971
|
+
'dsh-auto-continue: 已停止自动继续',
|
|
972
|
+
`${sessionId}: 连续失败 ${state.consecutive} 次, 需要人工介入`,
|
|
973
|
+
this.notifyOptions(sessionId),
|
|
974
|
+
);
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
} else {
|
|
978
|
+
this.log(
|
|
979
|
+
`发送失败 ${sessionId}: ${response.result.error.code} ${response.result.error.message}`,
|
|
980
|
+
);
|
|
981
|
+
}
|
|
982
|
+
} catch (error) {
|
|
983
|
+
this.log(`发送异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
984
|
+
} finally {
|
|
985
|
+
releaseSend(sessionId);
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
/** 会话标题缓存(来自 session.list 投影, {sessionTitle} 占位符用)。 */
|
|
990
|
+
private readonly titles = new Map<SessionId, string>();
|
|
991
|
+
|
|
992
|
+
/** 查一次 session.list, 顺带缓存该会话的标题。 */
|
|
993
|
+
private async fetchSessionInfo(
|
|
994
|
+
sessionId: SessionId,
|
|
995
|
+
): Promise<{ running: boolean | undefined; title: string | undefined } | undefined> {
|
|
996
|
+
try {
|
|
997
|
+
const response = await this.api.sessions.list({});
|
|
998
|
+
if (!response.result.ok) return undefined;
|
|
999
|
+
const item = response.result.value.items.find(
|
|
1000
|
+
(summary: SessionSummary) => summary.sessionId === sessionId,
|
|
1001
|
+
);
|
|
1002
|
+
if (item === undefined) return undefined;
|
|
1003
|
+
// `title` 投影由 @deepseek-ai/dsh-session-title 声明; 此处用局部断言避免引入额外依赖。
|
|
1004
|
+
const title = (item.projections?.values as { title?: string | null } | undefined)?.title;
|
|
1005
|
+
if (typeof title === 'string' && title !== '') this.titles.set(sessionId, title);
|
|
1006
|
+
return { running: item.running, title: typeof title === 'string' ? title : undefined };
|
|
1007
|
+
} catch {
|
|
1008
|
+
return undefined;
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
private async runningViaList(sessionId: SessionId): Promise<boolean | undefined> {
|
|
1013
|
+
const info = await this.fetchSessionInfo(sessionId);
|
|
1014
|
+
return info?.running;
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
// ---------- 启动/重连扫描 ----------
|
|
1018
|
+
|
|
1019
|
+
private scheduleReconnectScan(): void {
|
|
1020
|
+
this.reconnectScans += 1;
|
|
1021
|
+
const scan = this.reconnectScans;
|
|
1022
|
+
setTimeout(() => {
|
|
1023
|
+
if (scan !== this.reconnectScans || this.disposed) return;
|
|
1024
|
+
void this.scanLoop(6, this.getConfig().reconnectScanDelayMs);
|
|
1025
|
+
}, this.getConfig().reconnectScanDelayMs);
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
private async bootScanLoop(): Promise<void> {
|
|
1029
|
+
await this.scanLoop(Infinity, 3000);
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
/** 反复尝试扫描, 直到成功(宿主就绪)或达到次数上限。 */
|
|
1033
|
+
private async scanLoop(attempts: number, delayMs: number): Promise<void> {
|
|
1034
|
+
for (let attempt = 0; attempt < attempts && !this.disposed; attempt += 1) {
|
|
1035
|
+
try {
|
|
1036
|
+
if (await this.scanInterrupted()) return;
|
|
1037
|
+
} catch (error) {
|
|
1038
|
+
if (this.disposed) return;
|
|
1039
|
+
// 宿主未就绪时每 3s 重试; 只节流记录日志, 避免刷屏。
|
|
1040
|
+
if (attempt % 10 === 0) {
|
|
1041
|
+
this.log(
|
|
1042
|
+
`扫描失败(${attempt + 1}/${attempts === Infinity ? '∞' : attempts}): ${
|
|
1043
|
+
error instanceof Error ? error.message : String(error)
|
|
1044
|
+
}`,
|
|
1045
|
+
);
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
if (attempt + 1 < attempts) await sleep(delayMs);
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
/**
|
|
1053
|
+
* 扫描最近中断过的会话: 最后回合以非人为原因结束, 且其后没有新回合或用户消息。
|
|
1054
|
+
* @returns 是否成功完成一次扫描(宿主就绪)。
|
|
1055
|
+
*/
|
|
1056
|
+
private async scanInterrupted(): Promise<boolean> {
|
|
1057
|
+
const config = this.getConfig();
|
|
1058
|
+
if (config.paused) return true; // 全局暂停: 不做任何扫描
|
|
1059
|
+
const response = await this.api.sessions.list({});
|
|
1060
|
+
if (!response.result.ok) return false;
|
|
1061
|
+
const items = response.result.value.items;
|
|
1062
|
+
for (const summary of items) {
|
|
1063
|
+
const title = (summary.projections?.values as { title?: string | null } | undefined)?.title;
|
|
1064
|
+
if (typeof title === 'string' && title !== '') this.titles.set(summary.sessionId, title);
|
|
1065
|
+
}
|
|
1066
|
+
const candidates = items
|
|
1067
|
+
.filter((summary) => !summary.running && summary.parentSessionId === undefined)
|
|
1068
|
+
.slice(0, config.scanLimit);
|
|
1069
|
+
const now = Date.now();
|
|
1070
|
+
for (const summary of candidates) {
|
|
1071
|
+
if (this.disposed) return true;
|
|
1072
|
+
const state = this.state(summary.sessionId);
|
|
1073
|
+
if (state.pendingTimer !== undefined) continue;
|
|
1074
|
+
if (state.consecutive >= config.maxConsecutive) continue;
|
|
1075
|
+
if (now - state.lastAttemptAt < this.cooldownFor(state)) continue;
|
|
1076
|
+
if (now < sessionPauseUntil(summary.sessionId)) continue; // 会话暂停中
|
|
1077
|
+
let events;
|
|
1078
|
+
try {
|
|
1079
|
+
const page = await this.api.sessions.history({
|
|
1080
|
+
sessionId: summary.sessionId,
|
|
1081
|
+
maxMessages: 30,
|
|
1082
|
+
});
|
|
1083
|
+
if (!page.result.ok) continue;
|
|
1084
|
+
events = page.result.value.events;
|
|
1085
|
+
} catch {
|
|
1086
|
+
continue; // 会话可能刚被移除
|
|
1087
|
+
}
|
|
1088
|
+
// 从尾部找最后一个 turn/end(在分支内完成收窄)
|
|
1089
|
+
let lastEnd: SessionEvent<'turn/end'> | undefined;
|
|
1090
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
1091
|
+
const event = events[i]?.event;
|
|
1092
|
+
if (event !== undefined && event.type === 'turn/end') {
|
|
1093
|
+
lastEnd = event;
|
|
1094
|
+
break;
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
if (lastEnd === undefined) continue;
|
|
1098
|
+
const reason = lastEnd.data.reason;
|
|
1099
|
+
if (!isNonHumanReason(reason.kind)) continue;
|
|
1100
|
+
if (lastEnd.time < now - config.freshMs) continue; // 太久远, 不翻旧账
|
|
1101
|
+
// 该 turn/end 之后不能有新回合或用户消息(说明已被处理)
|
|
1102
|
+
let superseded = false;
|
|
1103
|
+
for (const entry of events) {
|
|
1104
|
+
const event = entry.event;
|
|
1105
|
+
if (event.seq <= lastEnd.seq) continue;
|
|
1106
|
+
if (event.type === 'turn/start') superseded = true;
|
|
1107
|
+
if (event.type === 'user/message' && event.data.source.kind === 'user') superseded = true;
|
|
1108
|
+
if (superseded) break;
|
|
1109
|
+
}
|
|
1110
|
+
if (superseded) continue;
|
|
1111
|
+
this.log(`扫描发现中断 ${summary.sessionId}(turn/end:${reason.kind}), 安排自动继续`);
|
|
1112
|
+
this.schedule(summary.sessionId, `scan:turn/end:${reason.kind}`);
|
|
1113
|
+
}
|
|
1114
|
+
return true;
|
|
1115
|
+
}
|
|
1116
|
+
}
|