dsh-client-auto-continue 0.7.4 → 0.8.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.
- package/README.md +8 -12
- package/README.zh.md +8 -12
- package/lib/client.js +208 -1134
- package/lib/client.js.map +4 -4
- package/lib/index.js +993 -28
- package/lib/types/client/bridge.d.ts +39 -0
- package/lib/types/client/engine.d.ts +7 -2
- package/lib/types/client/index.d.ts +11 -14
- package/lib/types/host/engine.d.ts +258 -0
- package/lib/types/index.d.ts +11 -5
- package/package.json +4 -3
- package/src/client/bridge.ts +202 -0
- package/src/client/engine.ts +34 -4
- package/src/client/index.ts +19 -29
- package/src/client/settings-card.tsx +9 -4
- package/src/host/engine.ts +1270 -0
- package/src/index.ts +97 -5
- package/tsconfig.json +2 -1
|
@@ -0,0 +1,1270 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auto-continue engine — host half core (single instance).
|
|
3
|
+
*
|
|
4
|
+
* Runs inside the dsh host process, so there is exactly ONE engine regardless
|
|
5
|
+
* of how many browser tabs are open — the multi-tab duplicate-send class of
|
|
6
|
+
* bugs (issue #13) cannot exist by construction. Listens to the session event
|
|
7
|
+
* firehose (`session/event`), sends through the agent registry
|
|
8
|
+
* (`agent.followup`), cancels through `agent.cancel`, and reads configuration
|
|
9
|
+
* from the settings service.
|
|
10
|
+
*
|
|
11
|
+
* All behavior is driven by the `auto-continue` settings namespace (see the
|
|
12
|
+
* plugin's settings card); every knob below is user-configurable there.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
16
|
+
import { createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
17
|
+
import type { Agent } from '@deepseek-ai/dsh-agent';
|
|
18
|
+
import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types';
|
|
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
|
+
}
|
|
374
|
+
|
|
375
|
+
/** 通知桥事件: host 引擎产生, browser 侧订阅展示(Notification / 动作按钮)。 */
|
|
376
|
+
export interface HostNotice {
|
|
377
|
+
/** 稳定标识(供 browser 去重)。 */
|
|
378
|
+
id: string;
|
|
379
|
+
title: string;
|
|
380
|
+
body: string;
|
|
381
|
+
/** 会话 id(通知按钮「立即续跑 / 暂停该会话」作用于它)。 */
|
|
382
|
+
sessionId?: SessionId;
|
|
383
|
+
actions: NotifyAction[];
|
|
384
|
+
/** 产生时间。 */
|
|
385
|
+
at: number;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** 自动发送后, 在该窗口内出现的回合结束才计入恢复统计。 */
|
|
389
|
+
const RECOVERY_WINDOW_MS = 10 * 60 * 1000;
|
|
390
|
+
|
|
391
|
+
/** 回显识别窗口: 排队消息可能几分钟后才被模型处理到, 窗口必须远大于排队延迟。 */
|
|
392
|
+
const ECHO_WINDOW_MS = 10 * 60 * 1000;
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* 判定一条 user/message 是否是我们自己自动发送的回显。
|
|
396
|
+
* 单实例引擎: 内存态即可; 排队消息可能几分钟后才被模型处理, 窗口保持 10 分钟。
|
|
397
|
+
*/
|
|
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
|
+
/** SSE 帧外壳: `{ rpcId, payload }`。 */
|
|
500
|
+
type FrameEnvelope<T> = { payload: T };
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* 事件流泵: 带指数退避的 SSE 重连循环。
|
|
504
|
+
* - 从未收到任何帧(宿主未就绪): 退避重试, 不触发扫描
|
|
505
|
+
* - 曾连上后断开: 重连, 并通过 onReconnect 通知外层(宿主可能崩溃重启过)
|
|
506
|
+
*/
|
|
507
|
+
async function pumpStream<T>(
|
|
508
|
+
open: (signal: AbortSignal) => AsyncIterable<FrameEnvelope<T>>,
|
|
509
|
+
onFrame: (payload: T) => void,
|
|
510
|
+
onReconnect: () => void,
|
|
511
|
+
getBackoff: () => number,
|
|
512
|
+
log: (message: string) => void,
|
|
513
|
+
signal: AbortSignal,
|
|
514
|
+
): Promise<void> {
|
|
515
|
+
let backoff = getBackoff();
|
|
516
|
+
while (!signal.aborted) {
|
|
517
|
+
let connected = false;
|
|
518
|
+
try {
|
|
519
|
+
for await (const envelope of open(signal)) {
|
|
520
|
+
connected = true;
|
|
521
|
+
onFrame(envelope.payload);
|
|
522
|
+
}
|
|
523
|
+
if (signal.aborted) return;
|
|
524
|
+
} catch (error) {
|
|
525
|
+
if (signal.aborted) return;
|
|
526
|
+
log(`stream error: ${error instanceof Error ? error.message : String(error)}`);
|
|
527
|
+
}
|
|
528
|
+
if (!connected) {
|
|
529
|
+
// 从未连上(宿主未就绪): 指数退避重试
|
|
530
|
+
await sleep(backoff);
|
|
531
|
+
backoff = Math.min(backoff * 2, 15000);
|
|
532
|
+
continue;
|
|
533
|
+
}
|
|
534
|
+
// 曾连上后断开 → 重连并触发外层扫描
|
|
535
|
+
backoff = getBackoff();
|
|
536
|
+
onReconnect();
|
|
537
|
+
await sleep(backoff);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** 插件主体: 一条 mux 流 + 一条 host 流 + 启动/重连扫描。 */
|
|
542
|
+
export class AutoContinueRunner {
|
|
543
|
+
private readonly states = new Map<SessionId, SessionState>();
|
|
544
|
+
private readonly pauseUntil = new Map<SessionId, number>();
|
|
545
|
+
private dayStats: DayStats = emptyDayStats();
|
|
546
|
+
private readonly notices: HostNotice[] = [];
|
|
547
|
+
private readonly noticeListeners = new Set<() => void>();
|
|
548
|
+
private readonly stateListeners = new Set<() => void>();
|
|
549
|
+
private disposed = false;
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* @param ctx - host plugin context (agents registry, session events, settings).
|
|
553
|
+
* @param getConfig - read the current resolved configuration (settings service).
|
|
554
|
+
*/
|
|
555
|
+
constructor(
|
|
556
|
+
private readonly ctx: Context,
|
|
557
|
+
private readonly getConfig: () => AutoContinueConfig,
|
|
558
|
+
) {
|
|
559
|
+
// 单实例事件源: 宿主进程内的会话事件 firehose, 天然覆盖所有会话。
|
|
560
|
+
ctx.on('session/event', (session, event) => this.onHostEvent(session, event));
|
|
561
|
+
const config = this.getConfig();
|
|
562
|
+
if (config.scanOnBoot) {
|
|
563
|
+
void this.bootScanLoop();
|
|
564
|
+
}
|
|
565
|
+
this.log(
|
|
566
|
+
`已启动(host 单实例, 文本="${config.continueText}", 宽限 ${config.graceMs}ms, ` +
|
|
567
|
+
`冷却 ${config.cooldownMs}ms, 最多连续 ${config.maxConsecutive} 次)`,
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
private log(message: string): void {
|
|
572
|
+
if (this.getConfig().verbose) console.info(`[auto-continue] ${message}`);
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** 对外(状态桥): 今日统计快照。 */
|
|
576
|
+
todayStats(): DayStats {
|
|
577
|
+
const today = todayKey();
|
|
578
|
+
if (this.dayStats.date !== today) this.dayStats = emptyDayStats();
|
|
579
|
+
return { ...this.dayStats, byCode: { ...this.dayStats.byCode } };
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** 对外(状态桥): 当前生效的会话级暂停列表。 */
|
|
583
|
+
activePauses(): { sessionId: SessionId; until: number }[] {
|
|
584
|
+
const now = Date.now();
|
|
585
|
+
const out: { sessionId: SessionId; until: number }[] = [];
|
|
586
|
+
for (const [sessionId, until] of this.pauseUntil) {
|
|
587
|
+
if (until > now) out.push({ sessionId, until });
|
|
588
|
+
}
|
|
589
|
+
return out;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** 对外(状态桥): 订阅通知事件(SSE 端点推送)。 */
|
|
593
|
+
subscribeNotices(listener: () => void): () => void {
|
|
594
|
+
this.noticeListeners.add(listener);
|
|
595
|
+
return () => {
|
|
596
|
+
this.noticeListeners.delete(listener);
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/** 对外(状态桥): 订阅运行时状态变化(统计/暂停列表)。 */
|
|
601
|
+
subscribeState(listener: () => void): () => void {
|
|
602
|
+
this.stateListeners.add(listener);
|
|
603
|
+
return () => {
|
|
604
|
+
this.stateListeners.delete(listener);
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
private emitState(): void {
|
|
609
|
+
for (const listener of this.stateListeners) listener();
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/** 对外(状态桥): 消费待展示的通知。 */
|
|
613
|
+
drainNotices(): HostNotice[] {
|
|
614
|
+
return this.notices.splice(0, this.notices.length);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** 通知动作(browser 通知按钮回传): 立即续跑 / 暂停该会话 / 解除暂停 / 清零统计。 */
|
|
618
|
+
handleNoticeAction(sessionId: SessionId | undefined, action: string): void {
|
|
619
|
+
if (action === 'unpause') {
|
|
620
|
+
if (sessionId !== undefined) this.pauseUntil.delete(sessionId);
|
|
621
|
+
this.log(`解除暂停 ${sessionId ?? '?'}`);
|
|
622
|
+
} else if (action === 'reset-stats') {
|
|
623
|
+
this.dayStats = emptyDayStats();
|
|
624
|
+
this.log('清零今日统计');
|
|
625
|
+
} else if (sessionId !== undefined) {
|
|
626
|
+
this.onNotifyAction(sessionId, action);
|
|
627
|
+
}
|
|
628
|
+
this.emitState();
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
dispose(): void {
|
|
632
|
+
this.disposed = true;
|
|
633
|
+
for (const state of this.states.values()) {
|
|
634
|
+
if (state.pendingTimer !== undefined) clearTimeout(state.pendingTimer);
|
|
635
|
+
if (state.loopRetryTimer !== undefined) clearTimeout(state.loopRetryTimer);
|
|
636
|
+
}
|
|
637
|
+
this.states.clear();
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
private state(sessionId: SessionId): SessionState {
|
|
641
|
+
let state = this.states.get(sessionId);
|
|
642
|
+
if (state === undefined) {
|
|
643
|
+
state = freshState();
|
|
644
|
+
this.states.set(sessionId, state);
|
|
645
|
+
}
|
|
646
|
+
return state;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* 事件入口(host 单实例): 预处理工具调用/结果/模型消息(护栏与循环信号),
|
|
651
|
+
* 然后交给回合状态机。
|
|
652
|
+
*/
|
|
653
|
+
private onHostEvent(session: Session, event: SessionEvent): void {
|
|
654
|
+
const sessionId = session.id;
|
|
655
|
+
if (event.type === 'tool/call') {
|
|
656
|
+
const name = event.data.name;
|
|
657
|
+
if (typeof name === 'string') {
|
|
658
|
+
const state = this.state(sessionId);
|
|
659
|
+
state.lastTool = name;
|
|
660
|
+
state.lastToolResult = 'pending'; // 已发起, 尚未见结果
|
|
661
|
+
// loop guard 信号 2: 同工具+同参数才可能是循环; 参数变化 = 有进展
|
|
662
|
+
// (工具调用本身也重置短句信号)。计数在结果确认后才推进。
|
|
663
|
+
state.shortRun = 0;
|
|
664
|
+
const key = `${name}\n${event.data.arguments}`;
|
|
665
|
+
if (state.toolRun?.key === key) {
|
|
666
|
+
state.toolRun.waiting = true; // 结果到达时与上次结果比较
|
|
667
|
+
} else {
|
|
668
|
+
state.toolRun = { key, count: 1, lastResult: undefined, waiting: false };
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
} else if (event.type === 'tool/result') {
|
|
672
|
+
const state = this.state(sessionId);
|
|
673
|
+
if (state.lastToolResult === 'pending') {
|
|
674
|
+
const facts = toolResultFacts(event.data);
|
|
675
|
+
state.lastToolResult = facts;
|
|
676
|
+
// 结果确认: 与上次相同 → 计数推进; 不同 → 有进展, 重置
|
|
677
|
+
const run = state.toolRun;
|
|
678
|
+
if (run !== undefined && run.waiting) {
|
|
679
|
+
run.waiting = false;
|
|
680
|
+
if (run.lastResult !== undefined && run.lastResult === facts.excerpt) {
|
|
681
|
+
run.count += 1;
|
|
682
|
+
this.checkLoop(sessionId, state);
|
|
683
|
+
} else {
|
|
684
|
+
run.lastResult = facts.excerpt;
|
|
685
|
+
run.count = 1;
|
|
686
|
+
}
|
|
687
|
+
} else if (run !== undefined && !run.waiting) {
|
|
688
|
+
run.lastResult = facts.excerpt;
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
} else if (event.type === 'assistant/message') {
|
|
692
|
+
const state = this.state(sessionId);
|
|
693
|
+
this.onAssistantMessage(sessionId, state, event);
|
|
694
|
+
}
|
|
695
|
+
this.onSessionEvent(sessionId, event);
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/** 从 assistant/message 事件提取纯文本。 */
|
|
699
|
+
private assistantText(event: SessionEvent<'assistant/message'>): string {
|
|
700
|
+
const content = event.data.message.content;
|
|
701
|
+
if (!Array.isArray(content)) return '';
|
|
702
|
+
return content
|
|
703
|
+
.filter((part): part is { type: 'text'; text: string } => part.type === 'text')
|
|
704
|
+
.map((part) => part.text)
|
|
705
|
+
.join('');
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
private onAssistantMessage(
|
|
709
|
+
sessionId: SessionId,
|
|
710
|
+
state: SessionState,
|
|
711
|
+
event: SessionEvent<'assistant/message'>,
|
|
712
|
+
): void {
|
|
713
|
+
if (!this.getConfig().loopGuard) return;
|
|
714
|
+
const text = this.assistantText(event);
|
|
715
|
+
const trimmed = text.trim();
|
|
716
|
+
// 相同文本重复(不限长度): 模型反复输出完全相同的消息是最强的循环信号,
|
|
717
|
+
// 例如 "Let me test variants of the regex..." 连续 7 遍
|
|
718
|
+
if (trimmed !== '' && trimmed === state.lastAssistantText) {
|
|
719
|
+
state.sameTextRun += 1;
|
|
720
|
+
} else {
|
|
721
|
+
state.lastAssistantText = trimmed;
|
|
722
|
+
state.sameTextRun = 1;
|
|
723
|
+
}
|
|
724
|
+
// 短句计数(长度 < loopShortChars 且落在时间窗内): 空转信号
|
|
725
|
+
if (trimmed.length < this.getConfig().loopShortChars) {
|
|
726
|
+
const now = Date.now();
|
|
727
|
+
if (now - state.lastShortAt > this.getConfig().loopWindowMs) {
|
|
728
|
+
state.shortRun = 0; // 超过时间窗: 上一次短句太久远, 不算连续
|
|
729
|
+
}
|
|
730
|
+
state.shortRun += 1;
|
|
731
|
+
state.lastShortAt = now;
|
|
732
|
+
} else {
|
|
733
|
+
state.shortRun = 0; // 长句 = 有实际输出, 重置
|
|
734
|
+
state.lastShortAt = 0;
|
|
735
|
+
}
|
|
736
|
+
this.checkLoop(sessionId, state);
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/** 两个循环信号的公共检查; 命中且本回合未打断过则打断。 */
|
|
740
|
+
private checkLoop(sessionId: SessionId, state: SessionState): void {
|
|
741
|
+
if (!this.getConfig().loopGuard) return;
|
|
742
|
+
if (state.loopFired) return;
|
|
743
|
+
if (!state.running) return; // 只干预运行中的回合
|
|
744
|
+
const config = this.getConfig();
|
|
745
|
+
if (state.sameTextRun >= config.loopRepeatText) {
|
|
746
|
+
this.log(`检测到空转循环 ${sessionId}: 连续 ${state.sameTextRun} 条相同消息`);
|
|
747
|
+
void this.interruptLoop(sessionId, state);
|
|
748
|
+
} else if (state.shortRun >= config.loopShortCount) {
|
|
749
|
+
this.log(`检测到空转循环 ${sessionId}: 连续 ${state.shortRun} 条短句且无工具调用`);
|
|
750
|
+
void this.interruptLoop(sessionId, state);
|
|
751
|
+
} else if (state.toolRun !== undefined && state.toolRun.count >= config.loopToolRepeat) {
|
|
752
|
+
const toolName = state.toolRun.key.split('\n')[0] ?? '?';
|
|
753
|
+
this.log(`检测到工具死循环 ${sessionId}: 「${toolName}」连续 ${state.toolRun.count} 次(同参数同结果)`);
|
|
754
|
+
void this.interruptLoop(sessionId, state);
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/**
|
|
759
|
+
* 打断运行中的回合: cancel(带来源标记)+ 进冷却。
|
|
760
|
+
* 随后的 turn/end aborted 会因 loopCancelled 走「可恢复中断」路径,
|
|
761
|
+
* 用 loopText 重启回合——不会与用户手动停止混淆。
|
|
762
|
+
*/
|
|
763
|
+
private async interruptLoop(sessionId: SessionId, state: SessionState): Promise<void> {
|
|
764
|
+
if (state.loopFired) return;
|
|
765
|
+
// 打断本身受冷却约束: 距上次打断/发送太近时不再打断, 防止反复打断刷屏
|
|
766
|
+
if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) {
|
|
767
|
+
this.log(`跳过循环打断 ${sessionId}: 处于冷却期`);
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
state.loopFired = true;
|
|
771
|
+
state.loopCancelled = true;
|
|
772
|
+
state.lastAttemptAt = Date.now(); // 打断计入冷却, 防反复打断
|
|
773
|
+
this.bumpStat({ looped: 1 });
|
|
774
|
+
try {
|
|
775
|
+
const agent = this.ctx.agents.get(sessionId);
|
|
776
|
+
if (agent === undefined) {
|
|
777
|
+
this.log(`打断循环失败 ${sessionId}: 无 live agent`);
|
|
778
|
+
state.loopCancelled = false;
|
|
779
|
+
return;
|
|
780
|
+
}
|
|
781
|
+
agent.cancel({ kind: 'user' }, { keepInbox: true });
|
|
782
|
+
this.log(`已打断循环 ${sessionId}: cancel 已受理`);
|
|
783
|
+
} catch (error) {
|
|
784
|
+
this.log(`打断循环失败 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
785
|
+
state.loopCancelled = false;
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
private onSessionEvent(sessionId: SessionId, event: SessionEvent): void {
|
|
790
|
+
const state = this.state(sessionId);
|
|
791
|
+
switch (event.type) {
|
|
792
|
+
case 'turn/start':
|
|
793
|
+
state.running = true;
|
|
794
|
+
// 新回合开始: 清空上一步工具调用状态, 避免跨回合误用护栏
|
|
795
|
+
state.lastTool = undefined;
|
|
796
|
+
state.lastToolResult = undefined;
|
|
797
|
+
// loop guard 状态按回合重置
|
|
798
|
+
state.shortRun = 0;
|
|
799
|
+
state.lastShortAt = 0;
|
|
800
|
+
state.lastAssistantText = '';
|
|
801
|
+
state.sameTextRun = 0;
|
|
802
|
+
state.toolRun = undefined;
|
|
803
|
+
state.loopFired = false;
|
|
804
|
+
state.loopCancelled = false;
|
|
805
|
+
if (state.loopRetryTimer !== undefined) {
|
|
806
|
+
clearTimeout(state.loopRetryTimer);
|
|
807
|
+
state.loopRetryTimer = undefined;
|
|
808
|
+
}
|
|
809
|
+
this.cancelPending(sessionId, '宿主自行开启新回合');
|
|
810
|
+
break;
|
|
811
|
+
case 'turn/end': {
|
|
812
|
+
state.running = false;
|
|
813
|
+
this.cancelPending(sessionId, '收到新的 turn/end');
|
|
814
|
+
const reason = event.data.reason;
|
|
815
|
+
if (reason.kind === 'completed') {
|
|
816
|
+
// 成功回合: 恢复健康状态, 并确认上一次自动发送的效果
|
|
817
|
+
state.consecutive = 0;
|
|
818
|
+
state.lastFailure = undefined;
|
|
819
|
+
this.noteRecovery(sessionId, 'completed');
|
|
820
|
+
} else if (reason.kind === 'aborted') {
|
|
821
|
+
if (state.loopCancelled) {
|
|
822
|
+
// 我们自己的 loop guard 打断: 视为可恢复中断, 用循环提示文本重启回合。
|
|
823
|
+
// 不清 consecutive / lastAttemptAt: 冷却与连续上限在 loop 路径同样生效,
|
|
824
|
+
// 防止无限打断重发(issue #13); 打断本身受冷却约束, 重启也要等冷却。
|
|
825
|
+
state.loopCancelled = false;
|
|
826
|
+
state.loopFired = false;
|
|
827
|
+
state.pendingRecoveryAt = 0;
|
|
828
|
+
state.shortRun = 0;
|
|
829
|
+
state.lastShortAt = 0;
|
|
830
|
+
state.lastAssistantText = '';
|
|
831
|
+
state.sameTextRun = 0;
|
|
832
|
+
state.toolRun = undefined;
|
|
833
|
+
// 重启受冷却约束(防紧密打断循环): 等剩余冷却结束后再调度
|
|
834
|
+
const cooldown = this.cooldownFor(state);
|
|
835
|
+
const remaining = cooldown - (Date.now() - state.lastAttemptAt);
|
|
836
|
+
if (remaining > 0) {
|
|
837
|
+
if (state.loopRetryTimer !== undefined) clearTimeout(state.loopRetryTimer);
|
|
838
|
+
state.loopRetryTimer = setTimeout(() => {
|
|
839
|
+
state.loopRetryTimer = undefined;
|
|
840
|
+
this.schedule(sessionId, 'loop:aborted');
|
|
841
|
+
}, remaining);
|
|
842
|
+
this.log(`loop 重启延迟 ${remaining}ms(冷却期) ${sessionId}`);
|
|
843
|
+
} else {
|
|
844
|
+
this.schedule(sessionId, 'loop:aborted');
|
|
845
|
+
}
|
|
846
|
+
} else {
|
|
847
|
+
// 用户主动停止: 不自动继续, 视为用户介入
|
|
848
|
+
state.consecutive = 0;
|
|
849
|
+
state.pendingRecoveryAt = 0;
|
|
850
|
+
}
|
|
851
|
+
} else if (reason.kind === 'blocked') {
|
|
852
|
+
// 策略拒绝: 不自动继续
|
|
853
|
+
} else if (reason.kind === 'interrupted') {
|
|
854
|
+
// 实时路径的 interrupted 仅来自崩溃修复重载(loop 从不实时发出);
|
|
855
|
+
// 用户手动停止在 DSH 中标记为 aborted, 不走到这里。实时流里出现
|
|
856
|
+
// interrupted 视为异常中断, 不自动继续——宿主崩溃孤儿回合由扫描恢复。
|
|
857
|
+
state.consecutive = 0;
|
|
858
|
+
state.pendingRecoveryAt = 0;
|
|
859
|
+
} else if (reason.kind === 'error') {
|
|
860
|
+
// 记录失败事实(分类与模板填充用), 然后按类型处理
|
|
861
|
+
const error = reason.error;
|
|
862
|
+
state.lastFailure = {
|
|
863
|
+
code: typeof error.code === 'string' ? error.code : 'UNKNOWN',
|
|
864
|
+
message: typeof error.message === 'string' ? error.message : String(error),
|
|
865
|
+
...(typeof error.status === 'number' ? { status: error.status } : {}),
|
|
866
|
+
};
|
|
867
|
+
state.lastTurn = event.data.turn;
|
|
868
|
+
state.lastFailureAt = Date.now();
|
|
869
|
+
this.noteRecovery(sessionId, 'error');
|
|
870
|
+
this.onTurnFailure(sessionId, 'turn/end:error', state.lastFailure);
|
|
871
|
+
} else if (reason.kind === 'max-tokens') {
|
|
872
|
+
state.lastFailureAt = Date.now();
|
|
873
|
+
this.noteRecovery(sessionId, 'error');
|
|
874
|
+
this.schedule(sessionId, 'turn/end:max-tokens');
|
|
875
|
+
}
|
|
876
|
+
break;
|
|
877
|
+
}
|
|
878
|
+
case 'user/message':
|
|
879
|
+
if (isOurEcho(state, event)) break; // 我们自己的回显(跨标签页识别)
|
|
880
|
+
if (event.data.source.kind === 'user') {
|
|
881
|
+
// 用户手动介入: 清零上限与跨标签页发送计数
|
|
882
|
+
state.consecutive = 0;
|
|
883
|
+
this.cancelPending(sessionId, '用户手动发送消息');
|
|
884
|
+
}
|
|
885
|
+
break;
|
|
886
|
+
default:
|
|
887
|
+
break;
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
// ---------- host 帧 ----------
|
|
892
|
+
|
|
893
|
+
private onTurnFailure(sessionId: SessionId, reason: string, failure: FailureFacts): void {
|
|
894
|
+
const config = this.getConfig();
|
|
895
|
+
if (config.classify && !isTransientFailure(failure)) {
|
|
896
|
+
const summary = `${failure.code}${failure.status !== undefined ? ` (HTTP ${failure.status})` : ''}`;
|
|
897
|
+
this.log(`跳过 ${sessionId}(${reason}): 永久性失败 ${summary} — ${failure.message}`);
|
|
898
|
+
this.bumpStat({ skipped: 1, code: failure.code });
|
|
899
|
+
if (config.notify) {
|
|
900
|
+
this.notify(
|
|
901
|
+
'dsh-auto-continue: 未自动继续',
|
|
902
|
+
`${sessionId}: 永久性错误 ${summary},需要人工处理`,
|
|
903
|
+
this.notifyOptions(sessionId),
|
|
904
|
+
);
|
|
905
|
+
}
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
908
|
+
this.schedule(sessionId, reason);
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/** 通知操作按钮与回调(「立即续跑」/「暂停该会话 1 小时」)。 */
|
|
912
|
+
private notifyOptions(sessionId: SessionId): NotifyOptions {
|
|
913
|
+
return {
|
|
914
|
+
actions: [
|
|
915
|
+
{ action: 'resume', title: '立即续跑' },
|
|
916
|
+
{ action: 'pause1h', title: '暂停该会话 1 小时' },
|
|
917
|
+
],
|
|
918
|
+
onAction: (action) => this.onNotifyAction(sessionId, action),
|
|
919
|
+
};
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
private onNotifyAction(sessionId: SessionId, action: string): void {
|
|
923
|
+
if (action === 'resume') {
|
|
924
|
+
this.log(`通知按钮: 立即续跑 ${sessionId}`);
|
|
925
|
+
void this.resumeNow(sessionId);
|
|
926
|
+
} else if (action === 'pause1h') {
|
|
927
|
+
this.log(`通知按钮: 暂停 ${sessionId} 1 小时`);
|
|
928
|
+
this.pauseUntil.set(sessionId, Date.now() + 60 * 60 * 1000);
|
|
929
|
+
this.cancelPending(sessionId, '通知按钮暂停该会话');
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
|
|
934
|
+
/** 内存统计(host 单实例): 按今日桶累计。 */
|
|
935
|
+
private bumpStat(delta: {
|
|
936
|
+
sent?: number;
|
|
937
|
+
skipped?: number;
|
|
938
|
+
recovered?: number;
|
|
939
|
+
failed?: number;
|
|
940
|
+
gaveUp?: number;
|
|
941
|
+
looped?: number;
|
|
942
|
+
code?: string;
|
|
943
|
+
}): void {
|
|
944
|
+
const today = todayKey();
|
|
945
|
+
if (this.dayStats.date !== today) this.dayStats = emptyDayStats();
|
|
946
|
+
if (delta.sent !== undefined) this.dayStats.sent += delta.sent;
|
|
947
|
+
if (delta.skipped !== undefined) this.dayStats.skipped += delta.skipped;
|
|
948
|
+
if (delta.recovered !== undefined) this.dayStats.recovered += delta.recovered;
|
|
949
|
+
if (delta.failed !== undefined) this.dayStats.failed += delta.failed;
|
|
950
|
+
if (delta.gaveUp !== undefined) this.dayStats.gaveUp += delta.gaveUp;
|
|
951
|
+
if (delta.looped !== undefined) this.dayStats.looped += delta.looped;
|
|
952
|
+
if (delta.code !== undefined) {
|
|
953
|
+
this.dayStats.byCode[delta.code] = (this.dayStats.byCode[delta.code] ?? 0) + 1;
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/** 通知桥: 产生一条通知事件, SSE 端点推给 browser 侧展示。 */
|
|
958
|
+
private notify(title: string, body: string, options?: NotifyOptions): void {
|
|
959
|
+
const notice: HostNotice = {
|
|
960
|
+
id: `${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
961
|
+
title,
|
|
962
|
+
body,
|
|
963
|
+
...(options?.actions !== undefined && options.actions.length > 0
|
|
964
|
+
? { actions: options.actions }
|
|
965
|
+
: { actions: [] }),
|
|
966
|
+
at: Date.now(),
|
|
967
|
+
};
|
|
968
|
+
this.notices.push(notice);
|
|
969
|
+
for (const listener of this.noticeListeners) listener();
|
|
970
|
+
this.emitState();
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
/** 恢复结果记账: 自动发送后窗口内的回合结束, 判定恢复成功或失败。 */
|
|
974
|
+
private noteRecovery(sessionId: SessionId, outcome: 'completed' | 'error'): void {
|
|
975
|
+
const state = this.state(sessionId);
|
|
976
|
+
if (state.pendingRecoveryAt === 0) return;
|
|
977
|
+
if (Date.now() - state.pendingRecoveryAt > RECOVERY_WINDOW_MS) {
|
|
978
|
+
state.pendingRecoveryAt = 0; // 窗口过期, 不再归属这次发送
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
state.pendingRecoveryAt = 0;
|
|
982
|
+
this.bumpStat(outcome === 'completed' ? { recovered: 1 } : { failed: 1 });
|
|
983
|
+
this.log(`恢复结果(${sessionId}): ${outcome === 'completed' ? '成功' : '失败'}`);
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
/** 立即为该会话发送一次自动继续(无视冷却与连续上限; 由通知按钮触发)。 */
|
|
987
|
+
async resumeNow(sessionId: SessionId): Promise<void> {
|
|
988
|
+
if (this.disposed) return;
|
|
989
|
+
const state = this.state(sessionId);
|
|
990
|
+
if (state.subagent) return;
|
|
991
|
+
if (state.pendingTimer !== undefined) {
|
|
992
|
+
clearTimeout(state.pendingTimer);
|
|
993
|
+
state.pendingTimer = undefined;
|
|
994
|
+
}
|
|
995
|
+
await this.fire(sessionId, 'manual:notification', true);
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
/** 本会话当前生效的冷却间隔(自适应退避)。 */
|
|
999
|
+
private cooldownFor(state: SessionState): number {
|
|
1000
|
+
const config = this.getConfig();
|
|
1001
|
+
return effectiveCooldown(
|
|
1002
|
+
state.consecutive,
|
|
1003
|
+
config.cooldownMs,
|
|
1004
|
+
config.backoffFactor,
|
|
1005
|
+
config.backoffMaxMs,
|
|
1006
|
+
);
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
private schedule(sessionId: SessionId, reason: string): void {
|
|
1010
|
+
const state = this.state(sessionId);
|
|
1011
|
+
const config = this.getConfig();
|
|
1012
|
+
if (state.subagent) return; // 子代理会话由父代理处理, 不抢跑
|
|
1013
|
+
if (config.paused) {
|
|
1014
|
+
this.log(`跳过 ${sessionId}(${reason}): 全局暂停中`);
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
if (Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) {
|
|
1018
|
+
this.log(`跳过 ${sessionId}(${reason}): 会话暂停中`);
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
if (state.pendingTimer !== undefined) return; // 已有待发送
|
|
1022
|
+
if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) return; // 冷却期(含失败尝试, 自适应退避)
|
|
1023
|
+
if (state.consecutive >= config.maxConsecutive) {
|
|
1024
|
+
this.log(
|
|
1025
|
+
`跳过 ${sessionId}(${reason}): 已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`,
|
|
1026
|
+
);
|
|
1027
|
+
return;
|
|
1028
|
+
}
|
|
1029
|
+
const timer = setTimeout(() => {
|
|
1030
|
+
if (state.pendingTimer !== timer) return;
|
|
1031
|
+
state.pendingTimer = undefined;
|
|
1032
|
+
void this.fire(sessionId, reason);
|
|
1033
|
+
}, config.graceMs);
|
|
1034
|
+
state.pendingTimer = timer;
|
|
1035
|
+
const template = reason.startsWith('loop:')
|
|
1036
|
+
? config.loopText
|
|
1037
|
+
: reason.includes('max-tokens')
|
|
1038
|
+
? config.continueTextMaxTokens
|
|
1039
|
+
: config.continueText;
|
|
1040
|
+
this.log(
|
|
1041
|
+
`检测到非人为中断 ${sessionId}(${reason}), ${config.graceMs}ms 后自动发送「${template}」`,
|
|
1042
|
+
);
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
private cancelPending(sessionId: SessionId, why: string): void {
|
|
1046
|
+
const state = this.state(sessionId);
|
|
1047
|
+
if (state.pendingTimer === undefined) return;
|
|
1048
|
+
clearTimeout(state.pendingTimer);
|
|
1049
|
+
state.pendingTimer = undefined;
|
|
1050
|
+
this.log(`取消 ${sessionId} 的自动继续(${why})`);
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
private fire(sessionId: SessionId, reason: string, force = false): void {
|
|
1054
|
+
if (this.disposed) return;
|
|
1055
|
+
const state = this.state(sessionId);
|
|
1056
|
+
const config = this.getConfig();
|
|
1057
|
+
if (state.subagent) return; // 子代理会话由父代理处理, 不抢跑
|
|
1058
|
+
if (config.paused) {
|
|
1059
|
+
this.log(`跳过 ${sessionId}(${reason}): 全局暂停中`);
|
|
1060
|
+
return;
|
|
1061
|
+
}
|
|
1062
|
+
if (Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) {
|
|
1063
|
+
this.log(`跳过 ${sessionId}(${reason}): 会话暂停中`);
|
|
1064
|
+
return;
|
|
1065
|
+
}
|
|
1066
|
+
// 冷却(自适应退避)与连续上限; 通知按钮的强制续跑不受约束
|
|
1067
|
+
if (!force && Date.now() - state.lastAttemptAt < this.cooldownFor(state)) {
|
|
1068
|
+
this.log(`跳过 ${sessionId}(${reason}): 处于冷却期`);
|
|
1069
|
+
return;
|
|
1070
|
+
}
|
|
1071
|
+
if (!force && state.consecutive >= config.maxConsecutive) {
|
|
1072
|
+
this.log(`跳过 ${sessionId}(${reason}): 已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`);
|
|
1073
|
+
return;
|
|
1074
|
+
}
|
|
1075
|
+
// 模板填充: continueText 可含 {code}/{message}/{status}/{tool}/{turn}/{errorCount}/{sessionTitle}/{elapsed} 占位符
|
|
1076
|
+
const template = reason.startsWith('loop:')
|
|
1077
|
+
? config.loopText
|
|
1078
|
+
: reason.includes('max-tokens')
|
|
1079
|
+
? config.continueTextMaxTokens
|
|
1080
|
+
: config.continueText;
|
|
1081
|
+
const text = this.buildContinueText(config, state, template);
|
|
1082
|
+
// 发送: agent.followup 是排队语义(运行中会排入 inbox, 不会打断), 天然安全
|
|
1083
|
+
const agent = this.ctx.agents.get(sessionId);
|
|
1084
|
+
if (agent === undefined) {
|
|
1085
|
+
this.log(`跳过 ${sessionId}(${reason}): 无 live agent`);
|
|
1086
|
+
return;
|
|
1087
|
+
}
|
|
1088
|
+
state.lastAttemptAt = Date.now(); // 先记账: 无论成败, 本次尝试都进入冷却
|
|
1089
|
+
try {
|
|
1090
|
+
agent.followup(
|
|
1091
|
+
createUserMessage({
|
|
1092
|
+
content: [{ type: 'text', text }],
|
|
1093
|
+
source: { kind: 'user' },
|
|
1094
|
+
}),
|
|
1095
|
+
);
|
|
1096
|
+
const now = Date.now();
|
|
1097
|
+
state.consecutive += 1;
|
|
1098
|
+
state.lastAutoAt = now;
|
|
1099
|
+
state.lastSentText = text;
|
|
1100
|
+
state.pendingRecoveryAt = now; // 等待窗口内的下一个回合结束来判定恢复结果
|
|
1101
|
+
this.bumpStat({ sent: 1, ...(state.lastFailure !== undefined ? { code: state.lastFailure.code } : {}) });
|
|
1102
|
+
this.log(`已自动发送「${text}」到 ${sessionId}(${reason}), 第 ${state.consecutive} 次连续`);
|
|
1103
|
+
if (config.notify) {
|
|
1104
|
+
this.notify(
|
|
1105
|
+
'dsh-auto-continue: 已自动继续',
|
|
1106
|
+
`${sessionId}: 已发送「${text}」(第 ${state.consecutive} 次连续)`,
|
|
1107
|
+
this.notifyOptions(sessionId),
|
|
1108
|
+
);
|
|
1109
|
+
}
|
|
1110
|
+
if (state.consecutive >= config.maxConsecutive) {
|
|
1111
|
+
this.bumpStat({ gaveUp: 1 });
|
|
1112
|
+
this.log(`达到连续上限 ${config.maxConsecutive} 次, 停止自动继续 ${sessionId}`);
|
|
1113
|
+
if (config.notify) {
|
|
1114
|
+
this.notify(
|
|
1115
|
+
'dsh-auto-continue: 已停止自动继续',
|
|
1116
|
+
`${sessionId}: 连续失败 ${state.consecutive} 次, 需要人工介入`,
|
|
1117
|
+
this.notifyOptions(sessionId),
|
|
1118
|
+
);
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
} catch (error) {
|
|
1122
|
+
this.log(`发送异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
/**
|
|
1127
|
+
* 组装本次续跑消息: 模板填充 + 幂等护栏。
|
|
1128
|
+
* 护栏依据上一步工具调用的执行状态附加指引, 防止重跑副作用操作:
|
|
1129
|
+
* - 结果未确认(可能已部分执行)→ 提示先确认状态、不要重复执行
|
|
1130
|
+
* - 已确认成功 → 提示已完成、不要重复执行
|
|
1131
|
+
* - 已失败 → 不加护栏(重试工具本来就是目的)
|
|
1132
|
+
*/
|
|
1133
|
+
private buildContinueText(
|
|
1134
|
+
config: AutoContinueConfig,
|
|
1135
|
+
state: SessionState,
|
|
1136
|
+
template: string,
|
|
1137
|
+
): string {
|
|
1138
|
+
let text = fillTemplate(template, {
|
|
1139
|
+
facts: state.lastFailure,
|
|
1140
|
+
tool: state.lastTool,
|
|
1141
|
+
turn: state.lastTurn,
|
|
1142
|
+
errorCount: state.consecutive + 1,
|
|
1143
|
+
elapsedMs: state.lastFailureAt > 0 ? Date.now() - state.lastFailureAt : undefined,
|
|
1144
|
+
});
|
|
1145
|
+
if (!config.guardTools) return text;
|
|
1146
|
+
const guard = this.currentGuard(state);
|
|
1147
|
+
if (guard.kind === 'pending') {
|
|
1148
|
+
text += ` ${fillTemplate(config.guardPendingText, { tool: guard.tool, result: guard.result })}`;
|
|
1149
|
+
} else if (guard.kind === 'done') {
|
|
1150
|
+
text += ` ${fillTemplate(config.guardDoneText, { tool: guard.tool, result: guard.result })}`;
|
|
1151
|
+
}
|
|
1152
|
+
return text;
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
/** 上一步工具调用的护栏状态(实时路径, 由 mux 帧维护)。 */
|
|
1156
|
+
private currentGuard(state: SessionState): {
|
|
1157
|
+
kind: 'none' | 'pending' | 'done' | 'failed';
|
|
1158
|
+
tool?: string;
|
|
1159
|
+
result?: string;
|
|
1160
|
+
} {
|
|
1161
|
+
if (state.lastTool === undefined || state.lastToolResult === undefined) return { kind: 'none' };
|
|
1162
|
+
if (state.lastToolResult === 'pending') return { kind: 'pending', tool: state.lastTool };
|
|
1163
|
+
if (state.lastToolResult.ok) {
|
|
1164
|
+
return { kind: 'done', tool: state.lastTool, result: state.lastToolResult.excerpt };
|
|
1165
|
+
}
|
|
1166
|
+
return { kind: 'failed', tool: state.lastTool };
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
private async bootScanLoop(): Promise<void> {
|
|
1170
|
+
await this.scanLoop(Infinity, 3000);
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
/** 反复尝试扫描, 直到成功(宿主就绪)或达到次数上限。 */
|
|
1174
|
+
private async scanLoop(attempts: number, delayMs: number): Promise<void> {
|
|
1175
|
+
for (let attempt = 0; attempt < attempts && !this.disposed; attempt += 1) {
|
|
1176
|
+
try {
|
|
1177
|
+
if (await this.scanInterrupted()) return;
|
|
1178
|
+
} catch (error) {
|
|
1179
|
+
if (this.disposed) return;
|
|
1180
|
+
// 宿主未就绪时每 3s 重试; 只节流记录日志, 避免刷屏。
|
|
1181
|
+
if (attempt % 10 === 0) {
|
|
1182
|
+
this.log(
|
|
1183
|
+
`扫描失败(${attempt + 1}/${attempts === Infinity ? '∞' : attempts}): ${
|
|
1184
|
+
error instanceof Error ? error.message : String(error)
|
|
1185
|
+
}`,
|
|
1186
|
+
);
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
if (attempt + 1 < attempts) await sleep(delayMs);
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
/**
|
|
1194
|
+
* 扫描最近中断过的会话: 最后回合以非人为原因结束, 且其后没有新回合或用户消息。
|
|
1195
|
+
* @returns 是否成功完成一次扫描(宿主就绪)。
|
|
1196
|
+
*/
|
|
1197
|
+
private async scanInterrupted(): Promise<boolean> {
|
|
1198
|
+
const config = this.getConfig();
|
|
1199
|
+
if (config.paused) return true; // 全局暂停: 不做任何扫描
|
|
1200
|
+
// 只扫 live agents(host 重启后 agent-loop 会 resume 崩溃会话, 冷会话无需处理)
|
|
1201
|
+
const now = Date.now();
|
|
1202
|
+
const candidates: { sessionId: SessionId; events: readonly SessionEvent[] }[] = [];
|
|
1203
|
+
for (const agent of this.ctx.agents.list()) {
|
|
1204
|
+
const session = agent.session;
|
|
1205
|
+
if (session.header.origin === 'subagent') continue; // 子代理由父代理处理
|
|
1206
|
+
candidates.push({ sessionId: session.id, events: session.events });
|
|
1207
|
+
}
|
|
1208
|
+
for (const candidate of candidates.slice(0, config.scanLimit)) {
|
|
1209
|
+
if (this.disposed) return true;
|
|
1210
|
+
const state = this.state(candidate.sessionId);
|
|
1211
|
+
if (state.pendingTimer !== undefined) continue;
|
|
1212
|
+
if (state.consecutive >= config.maxConsecutive) continue;
|
|
1213
|
+
if (now - state.lastAttemptAt < this.cooldownFor(state)) continue;
|
|
1214
|
+
if (now < (this.pauseUntil.get(candidate.sessionId) ?? 0)) continue; // 会话暂停中
|
|
1215
|
+
const events = candidate.events;
|
|
1216
|
+
// 从尾部找最后一个 turn/end
|
|
1217
|
+
let lastEnd: SessionEvent<'turn/end'> | undefined;
|
|
1218
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
1219
|
+
const event = events[i];
|
|
1220
|
+
if (event !== undefined && event.type === 'turn/end') {
|
|
1221
|
+
lastEnd = event;
|
|
1222
|
+
break;
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
if (lastEnd === undefined) continue;
|
|
1226
|
+
const reason = lastEnd.data.reason;
|
|
1227
|
+
if (!isNonHumanReason(reason.kind)) continue;
|
|
1228
|
+
if (lastEnd.time < now - config.freshMs) continue; // 太久远, 不翻旧账
|
|
1229
|
+
// 该 turn/end 之后不能有新回合或用户消息(说明已被处理)
|
|
1230
|
+
let superseded = false;
|
|
1231
|
+
for (const event of events) {
|
|
1232
|
+
if (event.seq <= lastEnd.seq) continue;
|
|
1233
|
+
if (event.type === 'turn/start') superseded = true;
|
|
1234
|
+
if (event.type === 'user/message' && event.data.source.kind === 'user') superseded = true;
|
|
1235
|
+
if (superseded) break;
|
|
1236
|
+
}
|
|
1237
|
+
if (superseded) continue;
|
|
1238
|
+
// 幂等护栏: 从历史事件里重建上一步工具调用的执行状态
|
|
1239
|
+
this.applyGuardFromEvents(state, events, lastEnd.seq);
|
|
1240
|
+
this.log(`扫描发现中断 ${candidate.sessionId}(turn/end:${reason.kind}), 安排自动继续`);
|
|
1241
|
+
this.schedule(candidate.sessionId, `scan:turn/end:${reason.kind}`);
|
|
1242
|
+
}
|
|
1243
|
+
return true;
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
/** 从历史事件恢复上一步工具调用状态(扫描路径的幂等护栏)。 */
|
|
1247
|
+
private applyGuardFromEvents(
|
|
1248
|
+
state: SessionState,
|
|
1249
|
+
events: readonly SessionEvent[],
|
|
1250
|
+
untilSeq: number,
|
|
1251
|
+
): void {
|
|
1252
|
+
state.lastTool = undefined;
|
|
1253
|
+
state.lastToolResult = undefined;
|
|
1254
|
+
let call: SessionEvent<'tool/call'> | undefined;
|
|
1255
|
+
for (const event of events) {
|
|
1256
|
+
if (event.seq >= untilSeq) continue;
|
|
1257
|
+
if (event.type === 'tool/call') call = event;
|
|
1258
|
+
}
|
|
1259
|
+
if (call === undefined) return;
|
|
1260
|
+
state.lastTool = call.data.name;
|
|
1261
|
+
state.lastToolResult = 'pending';
|
|
1262
|
+
for (const event of events) {
|
|
1263
|
+
if (event.seq <= call.seq || event.seq >= untilSeq) continue;
|
|
1264
|
+
if (event.type === 'tool/result') {
|
|
1265
|
+
state.lastToolResult = toolResultFacts(event.data);
|
|
1266
|
+
break;
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
}
|