dsh-client-auto-continue 0.11.3 → 0.11.5
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 +2 -2
- package/README.zh.md +2 -2
- package/lib/client.js +4 -4
- package/lib/client.js.map +2 -2
- package/lib/index.js +564 -119
- package/lib/types/host/engine.d.ts +8 -2
- package/lib/types/index.d.ts +2 -2
- package/lib/types/shared/core.d.ts +90 -28
- package/package.json +1 -1
- package/src/client/locales.ts +4 -4
- package/src/host/engine.ts +303 -116
- package/src/index.ts +1 -1
- package/src/shared/core.ts +446 -46
package/src/host/engine.ts
CHANGED
|
@@ -19,11 +19,11 @@ import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types';
|
|
|
19
19
|
import type { Session } from '@deepseek-ai/dsh-session';
|
|
20
20
|
import {
|
|
21
21
|
DEFAULT_CONFIG,
|
|
22
|
-
ECHO_WINDOW_MS,
|
|
23
22
|
RECOVERY_WINDOW_MS,
|
|
24
23
|
effectiveCooldown,
|
|
25
24
|
emptyDayStats,
|
|
26
25
|
fillTemplate,
|
|
26
|
+
forgetPendingEcho,
|
|
27
27
|
freshState,
|
|
28
28
|
isNonHumanReason,
|
|
29
29
|
isOurEcho,
|
|
@@ -32,7 +32,7 @@ import {
|
|
|
32
32
|
resolveConfig,
|
|
33
33
|
sleep,
|
|
34
34
|
todayKey,
|
|
35
|
-
|
|
35
|
+
trackPendingEcho,
|
|
36
36
|
type AutoContinueConfig,
|
|
37
37
|
type AutoContinueLocale,
|
|
38
38
|
type DayStats,
|
|
@@ -41,6 +41,7 @@ import {
|
|
|
41
41
|
type NotifyAction,
|
|
42
42
|
type NotifyOptions,
|
|
43
43
|
type TemplateContext,
|
|
44
|
+
type ToolRepeatSignal,
|
|
44
45
|
} from '../shared/core.ts';
|
|
45
46
|
|
|
46
47
|
const NOTICE_COPY = {
|
|
@@ -72,6 +73,17 @@ const NOTICE_COPY = {
|
|
|
72
73
|
},
|
|
73
74
|
} as const satisfies Record<AutoContinueLocale, Record<string, unknown>>;
|
|
74
75
|
|
|
76
|
+
/** Durable cancel identity reserved for this plugin's loop guard. */
|
|
77
|
+
const LOOP_GUARD_CANCEL_CAUSE = {
|
|
78
|
+
kind: 'hook',
|
|
79
|
+
reason: 'dsh-auto-continue:loop-guard',
|
|
80
|
+
} as const;
|
|
81
|
+
|
|
82
|
+
/** Keep fuzzy matching off the unbounded host event path; exact repeats remain unlimited. */
|
|
83
|
+
const STREAM_NEAR_DUPLICATE_MAX_CHARS = 2_048;
|
|
84
|
+
/** Bound unfinished text copied between token chunks when a provider emits no paragraph break. */
|
|
85
|
+
const STREAM_TAIL_MAX_CHARS = 4_096;
|
|
86
|
+
|
|
75
87
|
/** 通知桥事件: host 引擎产生, browser 侧订阅展示(Notification / 动作按钮)。 */
|
|
76
88
|
export interface HostNotice {
|
|
77
89
|
/** 稳定标识(供 browser 去重)。 */
|
|
@@ -87,15 +99,57 @@ export interface HostNotice {
|
|
|
87
99
|
|
|
88
100
|
/** 自动发送后, 在该窗口内出现的回合结束才计入恢复统计。 */
|
|
89
101
|
|
|
90
|
-
/** 回显识别窗口: 排队消息可能几分钟后才被模型处理到, 窗口必须远大于排队延迟。 */
|
|
91
|
-
|
|
92
|
-
/**
|
|
93
|
-
* 判定一条 user/message 是否是我们自己自动发送的回显。
|
|
94
|
-
* 单实例引擎: 内存态即可; 排队消息可能几分钟后才被模型处理, 窗口保持 10 分钟。
|
|
95
|
-
*/
|
|
96
102
|
/** SSE 帧外壳: `{ rpcId, payload }`。 */
|
|
97
103
|
type FrameEnvelope<T> = { payload: T };
|
|
98
104
|
|
|
105
|
+
/** Session history APIs across the supported DSH host releases. */
|
|
106
|
+
type CompatibleSession = Session & {
|
|
107
|
+
readonly events?: readonly SessionEvent[];
|
|
108
|
+
snapshotEvents?: () => readonly SessionEvent[];
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
/** Read one stable event-log snapshot on both legacy and DSH 0.1.2 hosts. */
|
|
112
|
+
function snapshotSessionEvents(session: Session): readonly SessionEvent[] {
|
|
113
|
+
const compatible = session as CompatibleSession;
|
|
114
|
+
if (typeof compatible.snapshotEvents === 'function') return compatible.snapshotEvents();
|
|
115
|
+
if (compatible.events !== undefined) return compatible.events;
|
|
116
|
+
throw new TypeError('session exposes neither snapshotEvents() nor events');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Interpret host failure payloads without trusting persisted or plugin-provided event shapes. */
|
|
120
|
+
function parseFailureFacts(value: unknown): FailureFacts | undefined {
|
|
121
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;
|
|
122
|
+
const failure = value as { code?: unknown; message?: unknown; status?: unknown };
|
|
123
|
+
const code = typeof failure.code === 'string' && failure.code.trim() !== ''
|
|
124
|
+
? failure.code
|
|
125
|
+
: undefined;
|
|
126
|
+
const message = typeof failure.message === 'string' && failure.message.trim() !== ''
|
|
127
|
+
? failure.message
|
|
128
|
+
: undefined;
|
|
129
|
+
const status = typeof failure.status === 'number' && Number.isFinite(failure.status)
|
|
130
|
+
? failure.status
|
|
131
|
+
: undefined;
|
|
132
|
+
if (code === undefined && message === undefined && status === undefined) return undefined;
|
|
133
|
+
return {
|
|
134
|
+
code: code ?? 'UNKNOWN',
|
|
135
|
+
message: message ?? code ?? `HTTP ${status}`,
|
|
136
|
+
...(status !== undefined ? { status } : {}),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Read a reason discriminator defensively because session history can outlive its schema. */
|
|
141
|
+
function readReasonKind(value: unknown): string | undefined {
|
|
142
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;
|
|
143
|
+
const kind = (value as { kind?: unknown }).kind;
|
|
144
|
+
return typeof kind === 'string' && kind.trim() !== '' ? kind : undefined;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function isLoopGuardCancelReason(value: unknown): boolean {
|
|
148
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
|
|
149
|
+
const cause = value as { kind?: unknown; reason?: unknown };
|
|
150
|
+
return cause.kind === LOOP_GUARD_CANCEL_CAUSE.kind && cause.reason === LOOP_GUARD_CANCEL_CAUSE.reason;
|
|
151
|
+
}
|
|
152
|
+
|
|
99
153
|
/**
|
|
100
154
|
* 事件流泵: 带指数退避的 SSE 重连循环。
|
|
101
155
|
* - 从未收到任何帧(宿主未就绪): 退避重试, 不触发扫描
|
|
@@ -155,9 +209,17 @@ export class AutoContinueRunner {
|
|
|
155
209
|
private readonly getConfig: () => AutoContinueConfig,
|
|
156
210
|
) {
|
|
157
211
|
// 单实例事件源: 宿主进程内的会话事件 firehose, 天然覆盖所有会话。
|
|
158
|
-
this.disposeSessionEvents = ctx.on('session/event', (session, event) =>
|
|
159
|
-
|
|
160
|
-
|
|
212
|
+
this.disposeSessionEvents = ctx.on('session/event', (session, event) => {
|
|
213
|
+
try {
|
|
214
|
+
this.onHostEvent(session, event);
|
|
215
|
+
} catch (error) {
|
|
216
|
+
console.error(
|
|
217
|
+
`[auto-continue] 会话事件处理异常 ${session.id}: ${
|
|
218
|
+
error instanceof Error ? error.message : String(error)
|
|
219
|
+
}`,
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
});
|
|
161
223
|
const config = this.getConfig();
|
|
162
224
|
if (config.scanOnBoot) {
|
|
163
225
|
void this.bootScanLoop();
|
|
@@ -254,42 +316,29 @@ export class AutoContinueRunner {
|
|
|
254
316
|
*/
|
|
255
317
|
private onHostEvent(session: Session, event: SessionEvent): void {
|
|
256
318
|
const sessionId = session.id;
|
|
319
|
+
if (
|
|
320
|
+
(event.type === 'user/message' || event.type === 'assistant/message') &&
|
|
321
|
+
typeof event.surfaceOp === 'object' &&
|
|
322
|
+
event.surfaceOp !== null
|
|
323
|
+
) {
|
|
324
|
+
// Compaction replacement 不是新消息,也可能 shadow 整段工具结果。
|
|
325
|
+
this.state(sessionId).tools.recordSurfaceReplacement(event.seq);
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
257
328
|
if (event.type === 'tool/call') {
|
|
258
|
-
const
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
state.lastTool = name;
|
|
262
|
-
state.lastToolResult = 'pending'; // 已发起, 尚未见结果
|
|
263
|
-
// loop guard 信号 2: 同工具+同参数才可能是循环; 参数变化 = 有进展
|
|
264
|
-
// (工具调用本身也重置短句信号)。计数在结果确认后才推进。
|
|
265
|
-
state.shortRun = 0;
|
|
266
|
-
const key = `${name}\n${event.data.arguments}`;
|
|
267
|
-
if (state.toolRun?.key === key) {
|
|
268
|
-
state.toolRun.waiting = true; // 结果到达时与上次结果比较
|
|
269
|
-
} else {
|
|
270
|
-
state.toolRun = { key, count: 1, lastResult: undefined, waiting: false };
|
|
271
|
-
}
|
|
272
|
-
}
|
|
329
|
+
const state = this.state(sessionId);
|
|
330
|
+
// 任何新鲜调用都代表进展(即使缺关联 id);旧帧重放不能清短句 streak。
|
|
331
|
+
if (state.tools.recordCall(event)) state.shortRun = 0;
|
|
273
332
|
} else if (event.type === 'tool/result') {
|
|
274
333
|
const state = this.state(sessionId);
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
run.count += 1;
|
|
284
|
-
this.checkLoop(sessionId, state);
|
|
285
|
-
} else {
|
|
286
|
-
run.lastResult = facts.excerpt;
|
|
287
|
-
run.count = 1;
|
|
288
|
-
}
|
|
289
|
-
} else if (run !== undefined && !run.waiting) {
|
|
290
|
-
run.lastResult = facts.excerpt;
|
|
291
|
-
}
|
|
292
|
-
}
|
|
334
|
+
state.tools.recordResult(event);
|
|
335
|
+
} else if (event.type === 'step/start') {
|
|
336
|
+
const state = this.state(sessionId);
|
|
337
|
+
const repeat = state.tools.confirmRepeatAtStep(event.seq);
|
|
338
|
+
if (repeat !== undefined) this.checkLoop(sessionId, state, repeat);
|
|
339
|
+
} else if (event.type === 'assistant/chunk') {
|
|
340
|
+
const state = this.state(sessionId);
|
|
341
|
+
this.onAssistantChunk(sessionId, state, event);
|
|
293
342
|
} else if (event.type === 'assistant/message') {
|
|
294
343
|
const state = this.state(sessionId);
|
|
295
344
|
this.onAssistantMessage(sessionId, state, event);
|
|
@@ -307,6 +356,113 @@ export class AutoContinueRunner {
|
|
|
307
356
|
.join('');
|
|
308
357
|
}
|
|
309
358
|
|
|
359
|
+
private assistantChunkText(event: SessionEvent<'assistant/chunk'>): string {
|
|
360
|
+
return event.data.chunk.type === 'text-delta' ? event.data.chunk.text : '';
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
private normalizedSegment(text: string): string {
|
|
364
|
+
return text.replace(/\s+/g, ' ').trim();
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
private isNearDuplicateSegment(left: string, right: string): boolean {
|
|
368
|
+
if (left === right) return true;
|
|
369
|
+
const leftLen = left.length;
|
|
370
|
+
const rightLen = right.length;
|
|
371
|
+
const longer = Math.max(leftLen, rightLen);
|
|
372
|
+
const shorter = Math.min(leftLen, rightLen);
|
|
373
|
+
if (shorter === 0 || shorter / longer < 0.85) return false;
|
|
374
|
+
if (longer > STREAM_NEAR_DUPLICATE_MAX_CHARS) return false;
|
|
375
|
+
const maxDistance = Math.max(6, Math.floor(longer * 0.08));
|
|
376
|
+
if (Math.abs(leftLen - rightLen) > maxDistance) return false;
|
|
377
|
+
return this.withinEditDistance(left, right, maxDistance);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
private withinEditDistance(left: string, right: string, maxDistance: number): boolean {
|
|
381
|
+
if (left === right) return true;
|
|
382
|
+
if (maxDistance < 0) return false;
|
|
383
|
+
const leftLen = left.length;
|
|
384
|
+
const rightLen = right.length;
|
|
385
|
+
if (Math.abs(leftLen - rightLen) > maxDistance) return false;
|
|
386
|
+
if (leftLen === 0 || rightLen === 0) return Math.max(leftLen, rightLen) <= maxDistance;
|
|
387
|
+
const unreachable = maxDistance + 1;
|
|
388
|
+
let previous = new Int32Array(rightLen + 1);
|
|
389
|
+
let current = new Int32Array(rightLen + 1);
|
|
390
|
+
previous.fill(unreachable);
|
|
391
|
+
for (let col = 0; col <= Math.min(rightLen, maxDistance); col += 1) {
|
|
392
|
+
previous[col] = col;
|
|
393
|
+
}
|
|
394
|
+
for (let row = 1; row <= leftLen; row += 1) {
|
|
395
|
+
current.fill(unreachable);
|
|
396
|
+
if (row <= maxDistance) current[0] = row;
|
|
397
|
+
const firstCol = Math.max(1, row - maxDistance);
|
|
398
|
+
const lastCol = Math.min(rightLen, row + maxDistance);
|
|
399
|
+
let minInRow = unreachable;
|
|
400
|
+
for (let col = firstCol; col <= lastCol; col += 1) {
|
|
401
|
+
const insertion = (current[col - 1] ?? unreachable) + 1;
|
|
402
|
+
const deletion = (previous[col] ?? unreachable) + 1;
|
|
403
|
+
const substitution =
|
|
404
|
+
(previous[col - 1] ?? unreachable) +
|
|
405
|
+
(left.charCodeAt(row - 1) === right.charCodeAt(col - 1) ? 0 : 1);
|
|
406
|
+
const score = Math.min(insertion, deletion, substitution, unreachable);
|
|
407
|
+
current[col] = score;
|
|
408
|
+
if (score < minInRow) minInRow = score;
|
|
409
|
+
}
|
|
410
|
+
if (minInRow > maxDistance) return false;
|
|
411
|
+
[previous, current] = [current, previous];
|
|
412
|
+
}
|
|
413
|
+
return (previous[rightLen] ?? unreachable) <= maxDistance;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
private noteStreamSegment(sessionId: SessionId, state: SessionState, segment: string): void {
|
|
417
|
+
const normalized = this.normalizedSegment(segment);
|
|
418
|
+
const config = this.getConfig();
|
|
419
|
+
if (normalized === '') return;
|
|
420
|
+
if (normalized.length < config.loopShortChars) {
|
|
421
|
+
state.streamLastSegment = '';
|
|
422
|
+
state.streamRepeatRun = 0;
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
if (
|
|
426
|
+
state.streamLastSegment !== '' &&
|
|
427
|
+
this.isNearDuplicateSegment(normalized, state.streamLastSegment)
|
|
428
|
+
) {
|
|
429
|
+
state.streamRepeatRun += 1;
|
|
430
|
+
state.streamLastSegment = normalized;
|
|
431
|
+
} else {
|
|
432
|
+
state.streamLastSegment = normalized;
|
|
433
|
+
state.streamRepeatRun = 1;
|
|
434
|
+
}
|
|
435
|
+
if (state.streamRepeatRun >= config.loopRepeatText) {
|
|
436
|
+
this.log(
|
|
437
|
+
`检测到流式消息内复读 ${sessionId}: 连续 ${state.streamRepeatRun} 段近似重复文本`,
|
|
438
|
+
);
|
|
439
|
+
this.interruptLoop(sessionId, state);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
private onAssistantChunk(
|
|
444
|
+
sessionId: SessionId,
|
|
445
|
+
state: SessionState,
|
|
446
|
+
event: SessionEvent<'assistant/chunk'>,
|
|
447
|
+
): void {
|
|
448
|
+
if (!this.getConfig().loopGuard || !state.running || state.loopFired) return;
|
|
449
|
+
const chunk = this.assistantChunkText(event);
|
|
450
|
+
if (chunk === '') return;
|
|
451
|
+
const merged = `${state.streamTail}${chunk}`.replace(/\r/g, '');
|
|
452
|
+
const pieces = merged.split(/\n(?:[ \t]*\n)+/u);
|
|
453
|
+
const tail = pieces.pop() ?? '';
|
|
454
|
+
for (const piece of pieces) this.noteStreamSegment(sessionId, state, piece);
|
|
455
|
+
if (tail.length <= STREAM_TAIL_MAX_CHARS) {
|
|
456
|
+
state.streamTail = tail;
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
state.streamTail = tail.slice(-STREAM_TAIL_MAX_CHARS);
|
|
460
|
+
if (/\S/u.test(tail)) {
|
|
461
|
+
state.streamLastSegment = '';
|
|
462
|
+
state.streamRepeatRun = 0;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
310
466
|
private onAssistantMessage(
|
|
311
467
|
sessionId: SessionId,
|
|
312
468
|
state: SessionState,
|
|
@@ -335,34 +491,42 @@ export class AutoContinueRunner {
|
|
|
335
491
|
state.shortRun = 0; // 长句 = 有实际输出, 重置
|
|
336
492
|
state.lastShortAt = 0;
|
|
337
493
|
}
|
|
494
|
+
const streamTail = state.streamTail;
|
|
495
|
+
state.streamTail = '';
|
|
496
|
+
if (streamTail !== '') this.noteStreamSegment(sessionId, state, streamTail);
|
|
497
|
+
state.streamLastSegment = '';
|
|
498
|
+
state.streamRepeatRun = 0;
|
|
338
499
|
this.checkLoop(sessionId, state);
|
|
339
500
|
}
|
|
340
501
|
|
|
341
502
|
/** 两个循环信号的公共检查; 命中且本回合未打断过则打断。 */
|
|
342
|
-
private checkLoop(
|
|
503
|
+
private checkLoop(
|
|
504
|
+
sessionId: SessionId,
|
|
505
|
+
state: SessionState,
|
|
506
|
+
toolRepeat?: ToolRepeatSignal,
|
|
507
|
+
): void {
|
|
343
508
|
if (!this.getConfig().loopGuard) return;
|
|
344
509
|
if (state.loopFired) return;
|
|
345
510
|
if (!state.running) return; // 只干预运行中的回合
|
|
346
511
|
const config = this.getConfig();
|
|
347
512
|
if (state.sameTextRun >= config.loopRepeatText) {
|
|
348
513
|
this.log(`检测到空转循环 ${sessionId}: 连续 ${state.sameTextRun} 条相同消息`);
|
|
349
|
-
|
|
514
|
+
this.interruptLoop(sessionId, state);
|
|
350
515
|
} else if (state.shortRun >= config.loopShortCount) {
|
|
351
516
|
this.log(`检测到空转循环 ${sessionId}: 连续 ${state.shortRun} 条短句且无工具调用`);
|
|
352
|
-
|
|
353
|
-
} else if (
|
|
354
|
-
|
|
355
|
-
this.
|
|
356
|
-
void this.interruptLoop(sessionId, state);
|
|
517
|
+
this.interruptLoop(sessionId, state);
|
|
518
|
+
} else if (toolRepeat !== undefined && toolRepeat.count >= config.loopToolRepeat) {
|
|
519
|
+
this.log(`检测到工具死循环 ${sessionId}: 「${toolRepeat.tool}」连续 ${toolRepeat.count} 次(同参数同结果)`);
|
|
520
|
+
this.interruptLoop(sessionId, state);
|
|
357
521
|
}
|
|
358
522
|
}
|
|
359
523
|
|
|
360
524
|
/**
|
|
361
525
|
* 打断运行中的回合: cancel(带来源标记)+ 进冷却。
|
|
362
|
-
*
|
|
363
|
-
*
|
|
526
|
+
* 只有随后持久化的 turn/end 精确携带专属 hook cause 时,
|
|
527
|
+
* 才会用 loopText 重启回合——DSH 的 first-cause 语义保证用户 Stop 优先。
|
|
364
528
|
*/
|
|
365
|
-
private
|
|
529
|
+
private interruptLoop(sessionId: SessionId, state: SessionState): void {
|
|
366
530
|
if (state.loopFired) return;
|
|
367
531
|
// 打断本身受冷却约束: 距上次打断/发送太近时不再打断, 防止反复打断刷屏
|
|
368
532
|
if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) {
|
|
@@ -370,21 +534,19 @@ export class AutoContinueRunner {
|
|
|
370
534
|
return;
|
|
371
535
|
}
|
|
372
536
|
state.loopFired = true;
|
|
373
|
-
state.loopCancelled = true;
|
|
374
537
|
state.lastAttemptAt = Date.now(); // 打断计入冷却, 防反复打断
|
|
375
|
-
this.bumpStat({ looped: 1 });
|
|
376
538
|
try {
|
|
377
539
|
const agent = this.ctx.agents.get(sessionId);
|
|
378
540
|
if (agent === undefined) {
|
|
379
541
|
this.log(`打断循环失败 ${sessionId}: 无 live agent`);
|
|
380
|
-
state.
|
|
542
|
+
state.loopFired = false;
|
|
381
543
|
return;
|
|
382
544
|
}
|
|
383
|
-
agent.cancel(
|
|
545
|
+
agent.cancel(LOOP_GUARD_CANCEL_CAUSE, { keepInbox: true });
|
|
384
546
|
this.log(`已打断循环 ${sessionId}: cancel 已受理`);
|
|
385
547
|
} catch (error) {
|
|
386
548
|
this.log(`打断循环失败 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
387
|
-
state.
|
|
549
|
+
state.loopFired = false;
|
|
388
550
|
}
|
|
389
551
|
}
|
|
390
552
|
|
|
@@ -394,16 +556,16 @@ export class AutoContinueRunner {
|
|
|
394
556
|
case 'turn/start':
|
|
395
557
|
state.running = true;
|
|
396
558
|
// 新回合开始: 清空上一步工具调用状态, 避免跨回合误用护栏
|
|
397
|
-
state.
|
|
398
|
-
state.lastToolResult = undefined;
|
|
559
|
+
state.tools.startTurn(event.seq);
|
|
399
560
|
// loop guard 状态按回合重置
|
|
400
561
|
state.shortRun = 0;
|
|
401
562
|
state.lastShortAt = 0;
|
|
402
563
|
state.lastAssistantText = '';
|
|
403
564
|
state.sameTextRun = 0;
|
|
404
|
-
state.
|
|
565
|
+
state.streamTail = '';
|
|
566
|
+
state.streamLastSegment = '';
|
|
567
|
+
state.streamRepeatRun = 0;
|
|
405
568
|
state.loopFired = false;
|
|
406
|
-
state.loopCancelled = false;
|
|
407
569
|
if (state.loopRetryTimer !== undefined) {
|
|
408
570
|
clearTimeout(state.loopRetryTimer);
|
|
409
571
|
state.loopRetryTimer = undefined;
|
|
@@ -412,26 +574,35 @@ export class AutoContinueRunner {
|
|
|
412
574
|
break;
|
|
413
575
|
case 'turn/end': {
|
|
414
576
|
state.running = false;
|
|
577
|
+
const loopCancelPending = state.loopFired;
|
|
578
|
+
state.loopFired = false;
|
|
415
579
|
this.cancelPending(sessionId, '收到新的 turn/end');
|
|
416
580
|
const reason = event.data.reason;
|
|
417
|
-
|
|
581
|
+
const reasonKind = readReasonKind(reason);
|
|
582
|
+
if (reasonKind === undefined) {
|
|
583
|
+
console.error(`[auto-continue] 忽略畸形 turn/end ${sessionId}: reason 无法解释`);
|
|
584
|
+
break;
|
|
585
|
+
}
|
|
586
|
+
if (reasonKind === 'completed') {
|
|
418
587
|
// 成功回合: 恢复健康状态, 并确认上一次自动发送的效果
|
|
419
588
|
state.consecutive = 0;
|
|
420
589
|
state.lastFailure = undefined;
|
|
421
590
|
this.noteRecovery(sessionId, 'completed');
|
|
422
|
-
} else if (
|
|
423
|
-
if (
|
|
591
|
+
} else if (reasonKind === 'aborted') {
|
|
592
|
+
if (isLoopGuardCancelReason((reason as { reason?: unknown }).reason)) {
|
|
424
593
|
// 我们自己的 loop guard 打断: 视为可恢复中断, 用循环提示文本重启回合。
|
|
425
594
|
// 不清 consecutive / lastAttemptAt: 冷却与连续上限在 loop 路径同样生效,
|
|
426
595
|
// 防止无限打断重发(issue #13); 打断本身受冷却约束, 重启也要等冷却。
|
|
427
|
-
|
|
428
|
-
state.loopFired = false;
|
|
596
|
+
if (loopCancelPending) this.bumpStat({ looped: 1 });
|
|
429
597
|
state.pendingRecoveryAt = 0;
|
|
430
598
|
state.shortRun = 0;
|
|
431
599
|
state.lastShortAt = 0;
|
|
432
600
|
state.lastAssistantText = '';
|
|
433
601
|
state.sameTextRun = 0;
|
|
434
|
-
state.
|
|
602
|
+
state.streamTail = '';
|
|
603
|
+
state.streamLastSegment = '';
|
|
604
|
+
state.streamRepeatRun = 0;
|
|
605
|
+
state.tools.resetRepeat();
|
|
435
606
|
// 重启受冷却约束(防紧密打断循环): 等剩余冷却结束后再调度
|
|
436
607
|
const cooldown = this.cooldownFor(state);
|
|
437
608
|
const remaining = cooldown - (Date.now() - state.lastAttemptAt);
|
|
@@ -454,27 +625,27 @@ export class AutoContinueRunner {
|
|
|
454
625
|
state.consecutive = 0;
|
|
455
626
|
state.pendingRecoveryAt = 0;
|
|
456
627
|
}
|
|
457
|
-
} else if (
|
|
628
|
+
} else if (reasonKind === 'blocked') {
|
|
458
629
|
// 策略拒绝: 不自动继续
|
|
459
|
-
} else if (
|
|
630
|
+
} else if (reasonKind === 'interrupted') {
|
|
460
631
|
// 实时路径的 interrupted 仅来自崩溃修复重载(loop 从不实时发出);
|
|
461
632
|
// 用户手动停止在 DSH 中标记为 aborted, 不走到这里。实时流里出现
|
|
462
633
|
// interrupted 视为异常中断, 不自动继续——宿主崩溃孤儿回合由扫描恢复。
|
|
463
634
|
state.consecutive = 0;
|
|
464
635
|
state.pendingRecoveryAt = 0;
|
|
465
|
-
} else if (
|
|
636
|
+
} else if (reasonKind === 'error') {
|
|
466
637
|
// 记录失败事实(分类与模板填充用), 然后按类型处理
|
|
467
|
-
const
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
638
|
+
const failure = parseFailureFacts((reason as { error?: unknown }).error);
|
|
639
|
+
if (failure === undefined) {
|
|
640
|
+
console.error(`[auto-continue] 忽略畸形 turn/end ${sessionId}: error details 无法解释`);
|
|
641
|
+
break;
|
|
642
|
+
}
|
|
643
|
+
state.lastFailure = failure;
|
|
473
644
|
state.lastTurn = event.data.turn;
|
|
474
645
|
state.lastFailureAt = Date.now();
|
|
475
646
|
this.noteRecovery(sessionId, 'error');
|
|
476
647
|
this.onTurnFailure(sessionId, 'turn/end:error', state.lastFailure);
|
|
477
|
-
} else if (
|
|
648
|
+
} else if (reasonKind === 'max-tokens') {
|
|
478
649
|
state.lastFailureAt = Date.now();
|
|
479
650
|
this.noteRecovery(sessionId, 'error');
|
|
480
651
|
this.schedule(sessionId, 'turn/end:max-tokens');
|
|
@@ -711,16 +882,20 @@ export class AutoContinueRunner {
|
|
|
711
882
|
}
|
|
712
883
|
state.lastAttemptAt = Date.now(); // 先记账: 无论成败, 本次尝试都进入冷却
|
|
713
884
|
try {
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
);
|
|
885
|
+
const message = createUserMessage({
|
|
886
|
+
content: [{ type: 'text', text }],
|
|
887
|
+
source: { kind: 'user' },
|
|
888
|
+
});
|
|
889
|
+
// `followup` may publish the matching session event synchronously.
|
|
890
|
+
trackPendingEcho(state, message.id);
|
|
891
|
+
try {
|
|
892
|
+
agent.followup(message);
|
|
893
|
+
} catch (error) {
|
|
894
|
+
forgetPendingEcho(state, message.id);
|
|
895
|
+
throw error;
|
|
896
|
+
}
|
|
720
897
|
const now = Date.now();
|
|
721
898
|
state.consecutive += 1;
|
|
722
|
-
state.lastAutoAt = now;
|
|
723
|
-
state.lastSentText = text;
|
|
724
899
|
state.pendingRecoveryAt = now; // 等待窗口内的下一个回合结束来判定恢复结果
|
|
725
900
|
this.bumpStat({ sent: 1, ...(state.lastFailure !== undefined ? { code: state.lastFailure.code } : {}) });
|
|
726
901
|
this.log(`已自动发送「${text}」到 ${sessionId}(${reason}), 第 ${state.consecutive} 次连续`);
|
|
@@ -765,7 +940,7 @@ export class AutoContinueRunner {
|
|
|
765
940
|
): string {
|
|
766
941
|
let text = fillTemplate(template, {
|
|
767
942
|
facts: state.lastFailure,
|
|
768
|
-
tool: state.lastTool,
|
|
943
|
+
tool: state.tools.lastTool(),
|
|
769
944
|
turn: state.lastTurn,
|
|
770
945
|
errorCount: state.consecutive + 1,
|
|
771
946
|
elapsedMs: state.lastFailureAt > 0 ? Date.now() - state.lastFailureAt : undefined,
|
|
@@ -786,12 +961,7 @@ export class AutoContinueRunner {
|
|
|
786
961
|
tool?: string;
|
|
787
962
|
result?: string;
|
|
788
963
|
} {
|
|
789
|
-
|
|
790
|
-
if (state.lastToolResult === 'pending') return { kind: 'pending', tool: state.lastTool };
|
|
791
|
-
if (state.lastToolResult.ok) {
|
|
792
|
-
return { kind: 'done', tool: state.lastTool, result: state.lastToolResult.excerpt };
|
|
793
|
-
}
|
|
794
|
-
return { kind: 'failed', tool: state.lastTool };
|
|
964
|
+
return state.tools.guard();
|
|
795
965
|
}
|
|
796
966
|
|
|
797
967
|
private async bootScanLoop(): Promise<void> {
|
|
@@ -827,12 +997,31 @@ export class AutoContinueRunner {
|
|
|
827
997
|
if (config.paused) return true; // 全局暂停: 不做任何扫描
|
|
828
998
|
// 只扫 live agents(host 重启后 agent-loop 会 resume 崩溃会话, 冷会话无需处理)
|
|
829
999
|
const now = Date.now();
|
|
830
|
-
const candidates: {
|
|
1000
|
+
const candidates: {
|
|
1001
|
+
sessionId: SessionId;
|
|
1002
|
+
events: readonly SessionEvent[];
|
|
1003
|
+
lastActivityAt: number;
|
|
1004
|
+
listIndex: number;
|
|
1005
|
+
}[] = [];
|
|
831
1006
|
for (const agent of this.ctx.agents.list()) {
|
|
832
1007
|
const session = agent.session;
|
|
833
1008
|
if (session.header.origin === 'subagent') continue; // 子代理由父代理处理
|
|
834
|
-
|
|
1009
|
+
const events = snapshotSessionEvents(session);
|
|
1010
|
+
const lastActivityAt = events.reduce(
|
|
1011
|
+
(latest, event) => Math.max(latest, event.time),
|
|
1012
|
+
Number.isFinite(session.header.createdAt) ? session.header.createdAt : 0,
|
|
1013
|
+
);
|
|
1014
|
+
candidates.push({
|
|
1015
|
+
sessionId: session.id,
|
|
1016
|
+
events,
|
|
1017
|
+
lastActivityAt,
|
|
1018
|
+
listIndex: candidates.length,
|
|
1019
|
+
});
|
|
835
1020
|
}
|
|
1021
|
+
candidates.sort(
|
|
1022
|
+
(left, right) =>
|
|
1023
|
+
right.lastActivityAt - left.lastActivityAt || left.listIndex - right.listIndex,
|
|
1024
|
+
);
|
|
836
1025
|
for (const candidate of candidates.slice(0, config.scanLimit)) {
|
|
837
1026
|
if (this.disposed) return true;
|
|
838
1027
|
const state = this.state(candidate.sessionId);
|
|
@@ -852,7 +1041,8 @@ export class AutoContinueRunner {
|
|
|
852
1041
|
}
|
|
853
1042
|
if (lastEnd === undefined) continue;
|
|
854
1043
|
const reason = lastEnd.data.reason;
|
|
855
|
-
|
|
1044
|
+
const reasonKind = readReasonKind(reason);
|
|
1045
|
+
if (reasonKind === undefined || !isNonHumanReason(reasonKind)) continue;
|
|
856
1046
|
if (lastEnd.time < now - config.freshMs) continue; // 太久远, 不翻旧账
|
|
857
1047
|
// 该 turn/end 之后不能有新回合或用户消息(说明已被处理)
|
|
858
1048
|
let superseded = false;
|
|
@@ -865,8 +1055,21 @@ export class AutoContinueRunner {
|
|
|
865
1055
|
if (superseded) continue;
|
|
866
1056
|
// 幂等护栏: 从历史事件里重建上一步工具调用的执行状态
|
|
867
1057
|
this.applyGuardFromEvents(state, events, lastEnd.seq);
|
|
868
|
-
|
|
869
|
-
this.
|
|
1058
|
+
const scanReason = `scan:turn/end:${reasonKind}`;
|
|
1059
|
+
this.log(`扫描发现中断 ${candidate.sessionId}(turn/end:${reasonKind}), 交给恢复策略处理`);
|
|
1060
|
+
if (reasonKind === 'error') {
|
|
1061
|
+
const failure = parseFailureFacts((reason as { error?: unknown }).error);
|
|
1062
|
+
if (failure === undefined) {
|
|
1063
|
+
console.error(`[auto-continue] 忽略畸形扫描 turn/end ${candidate.sessionId}: error details 无法解释`);
|
|
1064
|
+
continue;
|
|
1065
|
+
}
|
|
1066
|
+
state.lastFailure = failure;
|
|
1067
|
+
state.lastTurn = lastEnd.data.turn;
|
|
1068
|
+
state.lastFailureAt = lastEnd.time;
|
|
1069
|
+
this.onTurnFailure(candidate.sessionId, scanReason, state.lastFailure);
|
|
1070
|
+
} else {
|
|
1071
|
+
this.schedule(candidate.sessionId, scanReason);
|
|
1072
|
+
}
|
|
870
1073
|
}
|
|
871
1074
|
return true;
|
|
872
1075
|
}
|
|
@@ -877,22 +1080,6 @@ export class AutoContinueRunner {
|
|
|
877
1080
|
events: readonly SessionEvent[],
|
|
878
1081
|
untilSeq: number,
|
|
879
1082
|
): void {
|
|
880
|
-
state.
|
|
881
|
-
state.lastToolResult = undefined;
|
|
882
|
-
let call: SessionEvent<'tool/call'> | undefined;
|
|
883
|
-
for (const event of events) {
|
|
884
|
-
if (event.seq >= untilSeq) continue;
|
|
885
|
-
if (event.type === 'tool/call') call = event;
|
|
886
|
-
}
|
|
887
|
-
if (call === undefined) return;
|
|
888
|
-
state.lastTool = call.data.name;
|
|
889
|
-
state.lastToolResult = 'pending';
|
|
890
|
-
for (const event of events) {
|
|
891
|
-
if (event.seq <= call.seq || event.seq >= untilSeq) continue;
|
|
892
|
-
if (event.type === 'tool/result') {
|
|
893
|
-
state.lastToolResult = toolResultFacts(event.data);
|
|
894
|
-
break;
|
|
895
|
-
}
|
|
896
|
-
}
|
|
1083
|
+
state.tools.restore(events, untilSeq);
|
|
897
1084
|
}
|
|
898
1085
|
}
|
package/src/index.ts
CHANGED
|
@@ -76,7 +76,7 @@ export const AutoContinueSchema = z.object({
|
|
|
76
76
|
loopWindowMs: z.natural().min(1000).default(30000),
|
|
77
77
|
/** Consecutive short sentences trip the loop guard. */
|
|
78
78
|
loopShortCount: z.natural().min(2).default(12),
|
|
79
|
-
/** Consecutive identical
|
|
79
|
+
/** Consecutive identical assistant messages trip the loop guard (strongest signal; also used for streamed intra-message repetition). */
|
|
80
80
|
loopRepeatText: z.natural().min(2).default(4),
|
|
81
81
|
/** Consecutive identical tool calls with identical arguments AND results trip the loop guard. */
|
|
82
82
|
loopToolRepeat: z.natural().min(2).default(5),
|