dsh-client-auto-continue 0.14.2 → 0.15.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 +18 -4
- package/README.zh.md +18 -4
- package/lib/client.js +84 -12
- package/lib/client.js.map +2 -2
- package/lib/index.js +253 -21
- package/lib/types/client/bridge.d.ts +2 -0
- package/lib/types/client/dsh-store-compat.d.ts +1 -1
- package/lib/types/client/index.d.ts +1 -1
- package/lib/types/client/locales.d.ts +15 -0
- package/lib/types/client/settings-card.d.ts +1 -0
- package/lib/types/client/settings-form.d.ts +3 -1
- package/lib/types/host/engine.d.ts +27 -1
- package/lib/types/index.d.ts +8 -0
- package/lib/types/shared/core.d.ts +11 -0
- package/package.json +3 -3
- package/src/client/bridge.ts +10 -2
- package/src/client/dsh-store-compat.ts +1 -1
- package/src/client/index.ts +3 -1
- package/src/client/locales.ts +34 -4
- package/src/client/settings-card.tsx +35 -3
- package/src/client/settings-form.ts +8 -3
- package/src/client/styles.ts +1 -0
- package/src/host/engine.ts +265 -19
- package/src/index.ts +3 -0
- package/src/shared/core.ts +19 -0
package/src/host/engine.ts
CHANGED
|
@@ -17,7 +17,7 @@ import type { Context } from '@deepseek-ai/cordis';
|
|
|
17
17
|
import { createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
18
18
|
import type { Agent } from '@deepseek-ai/dsh-agent';
|
|
19
19
|
import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types';
|
|
20
|
-
import type
|
|
20
|
+
import { foldRequestHeader, type Session } from '@deepseek-ai/dsh-session';
|
|
21
21
|
import {
|
|
22
22
|
DEFAULT_CONFIG,
|
|
23
23
|
RECOVERY_WINDOW_MS,
|
|
@@ -37,6 +37,7 @@ import {
|
|
|
37
37
|
type AutoContinueConfig,
|
|
38
38
|
type AutoContinueLocale,
|
|
39
39
|
type DayStats,
|
|
40
|
+
type RecoveryAttempt,
|
|
40
41
|
type FailureFacts,
|
|
41
42
|
type SessionState,
|
|
42
43
|
type NotifyAction,
|
|
@@ -93,6 +94,25 @@ const LOOP_GUARD_CANCEL_CAUSE = {
|
|
|
93
94
|
const LOOP_COMPLETED_REASON = 'turn/end:completed';
|
|
94
95
|
const LOOP_SILENT_REASON = 'turn/end:loop-silent';
|
|
95
96
|
const MANUAL_NOTIFICATION_REASON = 'manual:notification';
|
|
97
|
+
|
|
98
|
+
/** Yield between storage batches without spending a live-scan polling interval. */
|
|
99
|
+
const SWEEP_OBSERVE_BATCH = 16;
|
|
100
|
+
const STORED_READ_TIMEOUT_MS = 5000;
|
|
101
|
+
/** 单个存储会话连续观察/物化失败达此数后放弃, 避免坏日志反复占满每轮观察配额。 */
|
|
102
|
+
const SWEEP_MAX_FAILURES = 3;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 存储扫描消费的宿主服务结构类型。这些服务(sessionQuery 等)随 dsh
|
|
106
|
+
* 版本整组演进, 直接引类型包会拖动 devDependency 时代; 按消费面声明,
|
|
107
|
+
* 缺服务的宿主在运行时禁用存储扫描即可。
|
|
108
|
+
*/
|
|
109
|
+
interface StoredObservation {
|
|
110
|
+
readonly events: readonly SessionEvent[];
|
|
111
|
+
readonly header: { readonly id?: SessionId; readonly origin?: string; readonly agentPreset?: string };
|
|
112
|
+
readonly projections?: { readonly values: { readonly agentPreset?: string } };
|
|
113
|
+
[Symbol.dispose]?: () => void;
|
|
114
|
+
}
|
|
115
|
+
|
|
96
116
|
const isLoopReason = (reason: string): boolean =>
|
|
97
117
|
reason === LOOP_COMPLETED_REASON || reason === LOOP_SILENT_REASON;
|
|
98
118
|
|
|
@@ -101,6 +121,9 @@ const STREAM_NEAR_DUPLICATE_MAX_CHARS = 2_048;
|
|
|
101
121
|
/** Bound unfinished text copied between token chunks when a provider emits no paragraph break. */
|
|
102
122
|
const STREAM_TAIL_MAX_CHARS = 4_096;
|
|
103
123
|
|
|
124
|
+
/** Ignore invisible formatting only for detection, never rewrite the stored message. */
|
|
125
|
+
const visibleText = (text: string): string => text.replace(/\p{Cf}/gu, '').trim();
|
|
126
|
+
|
|
104
127
|
/** 通知桥事件: host 引擎产生, browser 侧订阅展示(Notification / 动作按钮)。 */
|
|
105
128
|
export interface HostNotice {
|
|
106
129
|
/** 稳定标识(供 browser 去重)。 */
|
|
@@ -130,6 +153,10 @@ function snapshotSessionEvents(session: Session): readonly SessionEvent[] {
|
|
|
130
153
|
const compatible = session as CompatibleSession;
|
|
131
154
|
const snapshot = compatible.snapshotEvents;
|
|
132
155
|
const events = typeof snapshot === 'function' ? snapshot.call(session) : compatible.events;
|
|
156
|
+
return validateSessionEvents(events);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function validateSessionEvents(events: unknown): readonly SessionEvent[] {
|
|
133
160
|
if (!Array.isArray(events)) throw new TypeError('session history is not an event array');
|
|
134
161
|
// Do not filter damaged entries: one could have been a manual stop, newer turn,
|
|
135
162
|
// or tool result. An incomplete history is not safe evidence for a continuation.
|
|
@@ -223,6 +250,7 @@ export class AutoContinueRunner {
|
|
|
223
250
|
private readonly states = new Map<SessionId, SessionState>();
|
|
224
251
|
private readonly pauseUntil = new Map<SessionId, number>();
|
|
225
252
|
private dayStats: DayStats = emptyDayStats();
|
|
253
|
+
private readonly recoveryAttempts: RecoveryAttempt[] = [];
|
|
226
254
|
private readonly notices: HostNotice[] = [];
|
|
227
255
|
private readonly noticeListeners = new Set<() => void>();
|
|
228
256
|
private readonly stateListeners = new Set<() => void>();
|
|
@@ -233,8 +261,15 @@ export class AutoContinueRunner {
|
|
|
233
261
|
private readonly bootScannedSessions = new WeakSet<Session>();
|
|
234
262
|
/** Also bound diagnostics when even an agent's session getter is unavailable. */
|
|
235
263
|
private readonly bootScanErrors = new WeakSet<object>();
|
|
264
|
+
/** 存储扫描已裁决的会话 id, 避免每轮重复冷读大日志。 */
|
|
265
|
+
private readonly storedSwept = new Set<SessionId>();
|
|
266
|
+
/** 存储会话的连续观察/物化失败次数, 触达 SWEEP_MAX_FAILURES 后不再重试。 */
|
|
267
|
+
private readonly storedSweepFailures = new Map<SessionId, number>();
|
|
268
|
+
private storedSweepAnnounced = false;
|
|
236
269
|
private bootScanTimer: ReturnType<typeof setTimeout> | undefined;
|
|
237
270
|
private wakeBootScan: (() => void) | undefined;
|
|
271
|
+
private storedSweep: Promise<void> | undefined;
|
|
272
|
+
private readonly stopStoredSweep = new AbortController();
|
|
238
273
|
|
|
239
274
|
/**
|
|
240
275
|
* @param ctx - host plugin context (agents registry, session events).
|
|
@@ -308,6 +343,10 @@ export class AutoContinueRunner {
|
|
|
308
343
|
return { ...this.dayStats, byCode: { ...this.dayStats.byCode } };
|
|
309
344
|
}
|
|
310
345
|
|
|
346
|
+
recentRecoveryAttempts(): RecoveryAttempt[] {
|
|
347
|
+
return this.recoveryAttempts.map(attempt => ({ ...attempt }));
|
|
348
|
+
}
|
|
349
|
+
|
|
311
350
|
/** 对外(状态桥): 当前生效的会话级暂停列表。 */
|
|
312
351
|
activePauses(): { sessionId: SessionId; until: number }[] {
|
|
313
352
|
const now = Date.now();
|
|
@@ -360,6 +399,7 @@ export class AutoContinueRunner {
|
|
|
360
399
|
dispose(): void {
|
|
361
400
|
if (this.disposed) return;
|
|
362
401
|
this.disposed = true;
|
|
402
|
+
this.stopStoredSweep.abort();
|
|
363
403
|
if (this.bootScanTimer !== undefined) clearTimeout(this.bootScanTimer);
|
|
364
404
|
this.bootScanTimer = undefined;
|
|
365
405
|
this.wakeBootScan?.();
|
|
@@ -425,6 +465,8 @@ export class AutoContinueRunner {
|
|
|
425
465
|
// 任何新鲜调用都代表进展(即使缺关联 id);旧帧重放不能清短句 streak。
|
|
426
466
|
if (state.tools.recordCall(event)) {
|
|
427
467
|
state.shortRun = 0;
|
|
468
|
+
state.sameTextRun = 0;
|
|
469
|
+
state.lastAssistantText = '';
|
|
428
470
|
if (this.tracksOutput(state, event)) state.turnOutput = 'visible';
|
|
429
471
|
}
|
|
430
472
|
} else if (event.type === 'tool/result') {
|
|
@@ -439,7 +481,7 @@ export class AutoContinueRunner {
|
|
|
439
481
|
const state = this.state(sessionId);
|
|
440
482
|
if (this.tracksOutput(state, event)) {
|
|
441
483
|
const chunk = event.data.chunk;
|
|
442
|
-
const visible = (chunk.type === 'text-delta' && chunk.text
|
|
484
|
+
const visible = (chunk.type === 'text-delta' && visibleText(chunk.text) !== '') ||
|
|
443
485
|
chunk.type === 'tool-call-delta' ||
|
|
444
486
|
(chunk.type === 'block-end' && this.hasVisibleContent([chunk.block])) ||
|
|
445
487
|
(chunk.type === 'block-start' && chunk.blockType !== 'reasoning' && chunk.blockType !== 'text');
|
|
@@ -470,7 +512,7 @@ export class AutoContinueRunner {
|
|
|
470
512
|
if (part === null || typeof part !== 'object') return true;
|
|
471
513
|
const block = part as { type?: unknown; text?: unknown };
|
|
472
514
|
if (block.type === 'reasoning') return false;
|
|
473
|
-
if (block.type === 'text') return typeof block.text !== 'string' || block.text
|
|
515
|
+
if (block.type === 'text') return typeof block.text !== 'string' || visibleText(block.text) !== '';
|
|
474
516
|
return true;
|
|
475
517
|
});
|
|
476
518
|
}
|
|
@@ -490,7 +532,7 @@ export class AutoContinueRunner {
|
|
|
490
532
|
}
|
|
491
533
|
|
|
492
534
|
private normalizedSegment(text: string): string {
|
|
493
|
-
return text.replace(/\s+/g, ' ')
|
|
535
|
+
return visibleText(text).replace(/\s+/g, ' ');
|
|
494
536
|
}
|
|
495
537
|
|
|
496
538
|
private isNearDuplicateSegment(left: string, right: string): boolean {
|
|
@@ -599,14 +641,14 @@ export class AutoContinueRunner {
|
|
|
599
641
|
): void {
|
|
600
642
|
if (!this.getConfig().loopGuard) return;
|
|
601
643
|
const text = this.assistantText(event);
|
|
602
|
-
const trimmed = text
|
|
644
|
+
const trimmed = visibleText(text);
|
|
603
645
|
// 相同文本重复(不限长度): 模型反复输出完全相同的消息是最强的循环信号,
|
|
604
646
|
// 例如 "Let me test variants of the regex..." 连续 7 遍
|
|
605
647
|
if (trimmed !== '' && trimmed === state.lastAssistantText) {
|
|
606
648
|
state.sameTextRun += 1;
|
|
607
649
|
} else {
|
|
608
650
|
state.lastAssistantText = trimmed;
|
|
609
|
-
state.sameTextRun = 1;
|
|
651
|
+
state.sameTextRun = trimmed === '' ? 0 : 1;
|
|
610
652
|
}
|
|
611
653
|
// 短句计数(长度 < loopShortChars 且落在时间窗内): 空转信号
|
|
612
654
|
if (trimmed.length < this.getConfig().loopShortChars) {
|
|
@@ -856,13 +898,14 @@ export class AutoContinueRunner {
|
|
|
856
898
|
/** 通知操作按钮与回调(「立即续跑」/「暂停该会话 1 小时」)。 */
|
|
857
899
|
private notifyOptions(sessionId: SessionId, locale: AutoContinueLocale): NotifyOptions {
|
|
858
900
|
const copy = NOTICE_COPY[locale];
|
|
859
|
-
|
|
860
|
-
|
|
901
|
+
// 未物化的存储会话没有 live agent, 「立即续跑」只会空转; 只保留暂停。
|
|
902
|
+
const actions: NotifyAction[] = this.ctx.agents.get(sessionId) === undefined
|
|
903
|
+
? [{ action: 'pause1h', title: copy.pauseAction }]
|
|
904
|
+
: [
|
|
861
905
|
{ action: 'resume', title: copy.resumeAction },
|
|
862
906
|
{ action: 'pause1h', title: copy.pauseAction },
|
|
863
|
-
]
|
|
864
|
-
|
|
865
|
-
};
|
|
907
|
+
];
|
|
908
|
+
return { actions, onAction: (action) => this.onNotifyAction(sessionId, action) };
|
|
866
909
|
}
|
|
867
910
|
|
|
868
911
|
private onNotifyAction(sessionId: SessionId, action: string): void {
|
|
@@ -1038,6 +1081,7 @@ export class AutoContinueRunner {
|
|
|
1038
1081
|
if (isLoopReason(reason)) return config.continueTextLoop;
|
|
1039
1082
|
if (reason.endsWith(':silent')) return config.continueTextSilent;
|
|
1040
1083
|
if (reason.includes('max-tokens')) return config.continueTextMaxTokens;
|
|
1084
|
+
if (reason.includes('interrupted')) return config.continueTextInterrupted;
|
|
1041
1085
|
return config.continueText;
|
|
1042
1086
|
}
|
|
1043
1087
|
|
|
@@ -1115,6 +1159,17 @@ export class AutoContinueRunner {
|
|
|
1115
1159
|
// 自主循环的成功续跑不计入连续上限: 上限只约束失败(网络中断等)。
|
|
1116
1160
|
if (reason !== LOOP_COMPLETED_REASON) state.consecutive += 1;
|
|
1117
1161
|
state.pendingRecoveryAt = now; // 等待窗口内的下一个回合结束来判定恢复结果
|
|
1162
|
+
if (reason !== LOOP_COMPLETED_REASON) {
|
|
1163
|
+
this.recoveryAttempts.unshift({
|
|
1164
|
+
sessionId, at: now, consecutive: state.consecutive,
|
|
1165
|
+
reason: manualResume ? 'manual'
|
|
1166
|
+
: reason === 'loop:aborted' ? 'loop-guard'
|
|
1167
|
+
: reason.endsWith(':silent') || reason === LOOP_SILENT_REASON ? 'silent'
|
|
1168
|
+
: reason.endsWith(':interrupted') ? 'interrupted'
|
|
1169
|
+
: reason.endsWith(':max-tokens') ? 'max-tokens' : 'error',
|
|
1170
|
+
});
|
|
1171
|
+
this.recoveryAttempts.length = Math.min(this.recoveryAttempts.length, 20);
|
|
1172
|
+
}
|
|
1118
1173
|
this.bumpStat({ sent: 1, ...(state.lastFailure !== undefined ? { code: state.lastFailure.code } : {}) });
|
|
1119
1174
|
this.log(`已自动发送「${text}」到 ${sessionId}(${reason}), 第 ${state.consecutive} 次连续`);
|
|
1120
1175
|
if (config.notify) {
|
|
@@ -1190,6 +1245,14 @@ export class AutoContinueRunner {
|
|
|
1190
1245
|
if (attempt > 0 && Date.now() >= deadline) return;
|
|
1191
1246
|
try {
|
|
1192
1247
|
if (await this.scanInterrupted()) return;
|
|
1248
|
+
const config = this.getConfig();
|
|
1249
|
+
if (!config.paused && config.scanOnBoot && this.storedSweep === undefined) {
|
|
1250
|
+
this.storedSweep = this.sweepStoredSessions(config, deadline)
|
|
1251
|
+
.catch(error => {
|
|
1252
|
+
if (!this.disposed) this.ctx.logger.error(`Stored session scan failed: ${String(error)}`);
|
|
1253
|
+
})
|
|
1254
|
+
.finally(() => { this.storedSweep = undefined; });
|
|
1255
|
+
}
|
|
1193
1256
|
} catch (error) {
|
|
1194
1257
|
if (this.disposed) return;
|
|
1195
1258
|
// 宿主未就绪时每 3s 重试; 只节流记录日志, 避免刷屏。
|
|
@@ -1204,12 +1267,13 @@ export class AutoContinueRunner {
|
|
|
1204
1267
|
const remaining = deadline - Date.now();
|
|
1205
1268
|
if (this.disposed || remaining <= 0) return;
|
|
1206
1269
|
await new Promise<void>((resolve) => {
|
|
1207
|
-
this.wakeBootScan =
|
|
1208
|
-
|
|
1270
|
+
this.wakeBootScan = () => {
|
|
1271
|
+
if (this.bootScanTimer !== undefined) clearTimeout(this.bootScanTimer);
|
|
1209
1272
|
this.bootScanTimer = undefined;
|
|
1210
1273
|
this.wakeBootScan = undefined;
|
|
1211
1274
|
resolve();
|
|
1212
|
-
}
|
|
1275
|
+
};
|
|
1276
|
+
this.bootScanTimer = setTimeout(this.wakeBootScan, Math.min(3000, remaining));
|
|
1213
1277
|
});
|
|
1214
1278
|
}
|
|
1215
1279
|
}
|
|
@@ -1309,11 +1373,10 @@ export class AutoContinueRunner {
|
|
|
1309
1373
|
state.lastFailureAt = lastEnd.time;
|
|
1310
1374
|
this.onTurnFailure(sessionId, scanReason, failure);
|
|
1311
1375
|
} else {
|
|
1312
|
-
if (reasonKind === 'no-visible-output')
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
}
|
|
1376
|
+
if (reasonKind === 'no-visible-output') state.lastFailure = undefined;
|
|
1377
|
+
// 没有失败事实的恢复(如 interrupted)也要填 {turn}/{elapsed}, README 对所有继续文本承诺这些占位符。
|
|
1378
|
+
state.lastTurn = lastEnd.data.turn;
|
|
1379
|
+
state.lastFailureAt = lastEnd.time;
|
|
1317
1380
|
this.schedule(sessionId, scanReason);
|
|
1318
1381
|
}
|
|
1319
1382
|
recoveries += 1;
|
|
@@ -1326,6 +1389,189 @@ export class AutoContinueRunner {
|
|
|
1326
1389
|
return false;
|
|
1327
1390
|
}
|
|
1328
1391
|
|
|
1392
|
+
/** Bound cold reads even if a backend ignores cancellation; release late leases. */
|
|
1393
|
+
private async readStored<T extends object>(read: (signal: AbortSignal) => Promise<T>, deadline: number): Promise<T> {
|
|
1394
|
+
const timeout = new AbortController();
|
|
1395
|
+
const signal = AbortSignal.any([this.stopStoredSweep.signal, timeout.signal]);
|
|
1396
|
+
const timer = setTimeout(() => timeout.abort(new Error('Stored session read timed out')), Math.max(0, Math.min(STORED_READ_TIMEOUT_MS, deadline - Date.now())));
|
|
1397
|
+
let onAbort: () => void;
|
|
1398
|
+
const cancelled = new Promise<never>((_resolve, reject) => {
|
|
1399
|
+
onAbort = () => reject(signal.reason);
|
|
1400
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
1401
|
+
if (signal.aborted) onAbort();
|
|
1402
|
+
});
|
|
1403
|
+
const pending = Promise.resolve().then(() => { signal.throwIfAborted(); return read(signal); });
|
|
1404
|
+
void pending.then(value => {
|
|
1405
|
+
if (signal.aborted) (value as { [Symbol.dispose]?: () => void })[Symbol.dispose]?.();
|
|
1406
|
+
}).catch(() => {});
|
|
1407
|
+
try {
|
|
1408
|
+
return await Promise.race([pending, cancelled]);
|
|
1409
|
+
} finally {
|
|
1410
|
+
clearTimeout(timer);
|
|
1411
|
+
signal.removeEventListener('abort', onAbort!);
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
/**
|
|
1416
|
+
* 存储扫描: 枚举持久化会话, 把尾部命中恢复谓词的未加载会话物化为
|
|
1417
|
+
* live agent。宿主重启后 agent 仅在客户端打开会话时才懒加载, 不物化
|
|
1418
|
+
* 则启动扫描永远看不到它们; 谓词与上方扫描一致, 仅失败类原因。
|
|
1419
|
+
*/
|
|
1420
|
+
private async sweepStoredSessions(config: AutoContinueConfig, deadline: number): Promise<void> {
|
|
1421
|
+
const query = this.ctx.get('sessionQuery');
|
|
1422
|
+
if (query === undefined) return;
|
|
1423
|
+
const records = await this.readStored(signal => query.listSessions(signal), deadline);
|
|
1424
|
+
if (!Array.isArray(records)) throw new TypeError('stored session listing is not an array');
|
|
1425
|
+
if (!this.storedSweepAnnounced) {
|
|
1426
|
+
this.storedSweepAnnounced = true;
|
|
1427
|
+
this.ctx.logger.info(`存储扫描就绪: ${records.length} 个会话记录`);
|
|
1428
|
+
}
|
|
1429
|
+
let observed = 0;
|
|
1430
|
+
for (const record of records) {
|
|
1431
|
+
if (this.disposed || Date.now() >= deadline || this.getConfig().paused || !this.getConfig().scanOnBoot) return;
|
|
1432
|
+
if (typeof record?.header?.id !== 'string' || record.header.id === '') {
|
|
1433
|
+
this.logBootScanFailure(undefined, new TypeError('stored session record has no id'));
|
|
1434
|
+
continue;
|
|
1435
|
+
}
|
|
1436
|
+
const sessionId = record.header.id;
|
|
1437
|
+
if (record.live || this.storedSwept.has(sessionId)) continue;
|
|
1438
|
+
this.storedSwept.add(sessionId);
|
|
1439
|
+
if (record.header.origin === 'subagent') continue;
|
|
1440
|
+
observed += 1;
|
|
1441
|
+
let observation: StoredObservation | undefined;
|
|
1442
|
+
try {
|
|
1443
|
+
const stored: StoredObservation = await this.readStored(signal => query.observeSession(sessionId, { projectionMode: 'all', signal }), deadline);
|
|
1444
|
+
observation = stored;
|
|
1445
|
+
if (this.disposed) return;
|
|
1446
|
+
const events = validateSessionEvents(stored.events);
|
|
1447
|
+
if (events.length === 0) continue;
|
|
1448
|
+
// 快照之后客户端可能已打开该会话: 归还 live 扫描, 避免与 live 路径
|
|
1449
|
+
// 重复上报, 也避免物化撞上写归属。
|
|
1450
|
+
if (this.ctx.agents.get(sessionId) !== undefined) continue;
|
|
1451
|
+
let lastEnd: SessionEvent<'turn/end'> | undefined;
|
|
1452
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
1453
|
+
const event = events[i];
|
|
1454
|
+
if (event?.type === 'turn/end') { lastEnd = event; break; }
|
|
1455
|
+
}
|
|
1456
|
+
let lastStart: SessionEvent<'turn/start'> | undefined;
|
|
1457
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
1458
|
+
const event = events[i];
|
|
1459
|
+
if (event?.type === 'turn/start') { lastStart = event; break; }
|
|
1460
|
+
}
|
|
1461
|
+
// 兜底分支: 真实 sessionQuery 冷读会把内存中的 interruptedTurnClosers
|
|
1462
|
+
// 折叠进返回日志(尾部即合成 turn/end), 上方 closed-tail 才是生产主路
|
|
1463
|
+
// 径。这里覆盖两种例外——不折叠的宿主实现, 以及 listSessions 快照与
|
|
1464
|
+
// observeSession 之间客户端刚打开、切在轮次中间的 live 视图。
|
|
1465
|
+
const openTurn = lastStart !== undefined && (lastEnd === undefined || lastStart.seq > lastEnd.seq);
|
|
1466
|
+
let reasonKind: string | undefined;
|
|
1467
|
+
let freshAt: number;
|
|
1468
|
+
if (openTurn) {
|
|
1469
|
+
reasonKind = 'interrupted';
|
|
1470
|
+
freshAt = events[events.length - 1]?.time ?? 0;
|
|
1471
|
+
} else {
|
|
1472
|
+
reasonKind = readReasonKind(lastEnd?.data.reason);
|
|
1473
|
+
freshAt = lastEnd?.time ?? 0;
|
|
1474
|
+
}
|
|
1475
|
+
// 过期或被取代的永久错误与 live 扫描一致地静默跳过, 不再单独上报。
|
|
1476
|
+
if (reasonKind === undefined || freshAt < Date.now() - config.freshMs) continue;
|
|
1477
|
+
if (reasonKind !== undefined && !openTurn) {
|
|
1478
|
+
const silent = reasonKind === 'no-visible-output' && config.resumeSilentTurns;
|
|
1479
|
+
// 尾随 turn/start 已按 openTurn 处理, 这里只剩用户接管一种取代形态。
|
|
1480
|
+
const superseded = events.some((event) =>
|
|
1481
|
+
lastEnd !== undefined && event.seq > lastEnd.seq && event.type === 'user/message' && event.data.source.kind === 'user',
|
|
1482
|
+
);
|
|
1483
|
+
if ((!isNonHumanReason(reasonKind) && !silent) || superseded) continue;
|
|
1484
|
+
// 镜像 live 扫描的裁决: 畸形/永久错误不值得物化——物化后同样会被拦下。
|
|
1485
|
+
if (reasonKind === 'error') {
|
|
1486
|
+
const failure = parseFailureFacts((lastEnd!.data.reason as { error?: unknown }).error);
|
|
1487
|
+
if (failure === undefined) {
|
|
1488
|
+
console.error(`[auto-continue] 忽略畸形存储 turn/end ${sessionId}: error details 无法解释`);
|
|
1489
|
+
continue;
|
|
1490
|
+
}
|
|
1491
|
+
// 永久错误同样走 onTurnFailure, 镜像 live 路径的统计与通知旁效。
|
|
1492
|
+
if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
|
|
1493
|
+
this.onTurnFailure(sessionId, 'sweep:turn/end:error', failure);
|
|
1494
|
+
continue;
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
const presetId = stored.projections?.values.agentPreset ?? stored.header.agentPreset;
|
|
1499
|
+
const loggedConfig = foldRequestHeader(events)?.config;
|
|
1500
|
+
if (!await this.materializeStored(
|
|
1501
|
+
sessionId,
|
|
1502
|
+
presetId,
|
|
1503
|
+
loggedConfig === undefined ? undefined : { provider: loggedConfig.provider, model: loggedConfig.model },
|
|
1504
|
+
)) {
|
|
1505
|
+
this.storedSwept.delete(sessionId);
|
|
1506
|
+
return;
|
|
1507
|
+
}
|
|
1508
|
+
this.storedSweepFailures.delete(sessionId);
|
|
1509
|
+
this.wakeBootScan?.();
|
|
1510
|
+
this.ctx.logger.info(openTurn
|
|
1511
|
+
? `扫描物化存储会话 ${sessionId}(日志止于 turn/start, 视作 interrupted), 交给启动扫描接管`
|
|
1512
|
+
: `扫描物化存储会话 ${sessionId}(turn/end:${reasonKind}), 交给启动扫描接管`);
|
|
1513
|
+
} catch (error) {
|
|
1514
|
+
if (this.disposed) return;
|
|
1515
|
+
// 观察或物化失败允许下一轮重试; 连续触达上限后放弃, 并清掉计数——
|
|
1516
|
+
// 已永久跳过的会话不再进入该映射, 不给长存活宿主留死重。
|
|
1517
|
+
const failures = (this.storedSweepFailures.get(sessionId) ?? 0) + 1;
|
|
1518
|
+
if (failures < SWEEP_MAX_FAILURES) {
|
|
1519
|
+
this.storedSweepFailures.set(sessionId, failures);
|
|
1520
|
+
this.storedSwept.delete(sessionId);
|
|
1521
|
+
} else {
|
|
1522
|
+
this.storedSweepFailures.delete(sessionId);
|
|
1523
|
+
}
|
|
1524
|
+
this.ctx.logger.error(`存储会话 ${sessionId} 物化失败: ${error instanceof Error ? error.message : String(error)}`);
|
|
1525
|
+
} finally {
|
|
1526
|
+
observation?.[Symbol.dispose]?.();
|
|
1527
|
+
if (observed % SWEEP_OBSERVE_BATCH === 0 && !this.disposed) {
|
|
1528
|
+
await new Promise<void>(resolve => setTimeout(resolve, 0));
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
/**
|
|
1535
|
+
* 按会话记录的 preset 组合把存储会话恢复为 live agent(镜像会话控制
|
|
1536
|
+
* 器的 adopt 路径: preset 挂载 + 会话已记录的模型选择回装)。模型选择
|
|
1537
|
+
* 以日志记录的 request-header 播种 agentOptions——{{model}}/{{provider}}
|
|
1538
|
+
* 提示变量与首次请求路由都读它, 驱动器还会因路由吻合而自行回装日志
|
|
1539
|
+
* 记录的 effort; 无落点(从未发过请求的会话)回落宿主默认。恢复时追
|
|
1540
|
+
* 加的合成 turn/end(`interrupted`)随后由常规扫描按既有关卡恢复。
|
|
1541
|
+
*/
|
|
1542
|
+
private async materializeStored(
|
|
1543
|
+
sessionId: SessionId,
|
|
1544
|
+
presetId: string | undefined,
|
|
1545
|
+
logged: { provider: string; model: string } | undefined,
|
|
1546
|
+
): Promise<boolean> {
|
|
1547
|
+
if (this.disposed || this.getConfig().paused || !this.getConfig().scanOnBoot) return false;
|
|
1548
|
+
const presets = this.ctx.get('agentPresets');
|
|
1549
|
+
// Mirrors session-controller's adopt: without agent options the agent has no
|
|
1550
|
+
// provider/model, so prompt variables like {{model}} have no value and the
|
|
1551
|
+
// request carries no route.
|
|
1552
|
+
const defaultModel = this.ctx.get('agentDefaultModel');
|
|
1553
|
+
const selection = defaultModel?.currentSelection();
|
|
1554
|
+
const agentOptions = logged !== undefined
|
|
1555
|
+
? { provider: logged.provider, model: logged.model }
|
|
1556
|
+
: selection === undefined ? undefined : { provider: selection.provider, model: selection.model };
|
|
1557
|
+
if (presets === undefined) {
|
|
1558
|
+
await this.ctx.agents.resume({ resumeSessionId: sessionId, agentOptions, signal: this.stopStoredSweep.signal });
|
|
1559
|
+
return true;
|
|
1560
|
+
}
|
|
1561
|
+
const resolvedId = (await presets.resolve(presetId)).id;
|
|
1562
|
+
if (this.disposed || this.getConfig().paused || !this.getConfig().scanOnBoot) return false;
|
|
1563
|
+
if (this.ctx.agents.get(sessionId) !== undefined) return true;
|
|
1564
|
+
await this.ctx.agents.resume({
|
|
1565
|
+
resumeSessionId: sessionId,
|
|
1566
|
+
agentOptions,
|
|
1567
|
+
signal: this.stopStoredSweep.signal,
|
|
1568
|
+
setup: async (agentCtx) => {
|
|
1569
|
+
await presets.mount(agentCtx, resolvedId);
|
|
1570
|
+
},
|
|
1571
|
+
});
|
|
1572
|
+
return true;
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1329
1575
|
/** Captured identity only: even session.id can throw when the header is damaged. */
|
|
1330
1576
|
private logBootScanFailure(sessionId: SessionId | undefined, error: unknown): void {
|
|
1331
1577
|
console.error(`[auto-continue] 启动扫描跳过会话 ${sessionId ?? '(id unavailable)'}: ${
|
package/src/index.ts
CHANGED
|
@@ -38,6 +38,8 @@ export const AutoContinueSchema = z.object({
|
|
|
38
38
|
continueTextSilent: z.string().default(''),
|
|
39
39
|
/** Text sent for each autonomous-loop continuation (same placeholders as `continueText`). */
|
|
40
40
|
continueTextLoop: z.string().default(''),
|
|
41
|
+
/** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
|
|
42
|
+
continueTextInterrupted: z.string().default(''),
|
|
41
43
|
/** Idempotency guard: inspect the last tool call before resuming and steer the model. */
|
|
42
44
|
guardTools: z.boolean().default(true),
|
|
43
45
|
/** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
|
|
@@ -163,6 +165,7 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
|
|
|
163
165
|
type: 'state',
|
|
164
166
|
stats: runner.todayStats(),
|
|
165
167
|
paused: runner.activePauses(),
|
|
168
|
+
recoveryAttempts: runner.recentRecoveryAttempts(),
|
|
166
169
|
});
|
|
167
170
|
|
|
168
171
|
runner.subscribeNotices(() => {
|
package/src/shared/core.ts
CHANGED
|
@@ -17,6 +17,8 @@ export const LOCALIZED_TEXT_DEFAULTS = {
|
|
|
17
17
|
continueTextSilent:
|
|
18
18
|
'继续。你上一轮只输出了内部推理, 既没有回复也没有调用工具, 用户什么都没看到。每一轮都要以工具调用或可见回复结束。',
|
|
19
19
|
continueTextLoop: '继续',
|
|
20
|
+
continueTextInterrupted:
|
|
21
|
+
'继续。宿主在你上一轮运行期间重启了; 重启时未完成的工具调用已按「结果未知」收尾。从中断处继续, 重试可能有副作用的操作前先核实外部状态。',
|
|
20
22
|
guardPendingText: '(上一步工具「{tool}」可能未完成, 先确认状态再继续, 不要重复执行)',
|
|
21
23
|
guardDoneText: '(上一步工具「{tool}」已完成, 结果: {result}; 不要重复执行, 直接继续)',
|
|
22
24
|
loopText: '(检测到你可能陷入循环, 请停止重复刚才的动作, 换一种方式继续)',
|
|
@@ -27,6 +29,8 @@ export const LOCALIZED_TEXT_DEFAULTS = {
|
|
|
27
29
|
continueTextSilent:
|
|
28
30
|
'Continue. Your previous turn ended with internal reasoning only, with no message and no tool call, so nothing reached the user. Always finish a turn with a tool call or a visible answer.',
|
|
29
31
|
continueTextLoop: 'Continue',
|
|
32
|
+
continueTextInterrupted:
|
|
33
|
+
'Continue. The harness was restarted while your previous turn was still running; tool calls pending at the restart are recorded with unknown outcomes. Resume where you left off, verifying external state before retrying anything that may have side effects.',
|
|
30
34
|
guardPendingText:
|
|
31
35
|
'(The previous tool "{tool}" may not have completed. Check its state before continuing and do not run it again.)',
|
|
32
36
|
guardDoneText:
|
|
@@ -52,6 +56,8 @@ export interface AutoContinueSettings {
|
|
|
52
56
|
continueTextSilent?: string;
|
|
53
57
|
/** Text sent for each autonomous-loop continuation (same placeholders as `continueText`). */
|
|
54
58
|
continueTextLoop?: string;
|
|
59
|
+
/** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
|
|
60
|
+
continueTextInterrupted?: string;
|
|
55
61
|
/** Idempotency guard: inspect the last tool call before resuming and steer the model. */
|
|
56
62
|
guardTools?: boolean;
|
|
57
63
|
/** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
|
|
@@ -164,6 +170,10 @@ export function resolveConfig(section: AutoContinueSettings | undefined): AutoCo
|
|
|
164
170
|
typeof value.continueTextLoop === 'string' && value.continueTextLoop.trim() !== ''
|
|
165
171
|
? value.continueTextLoop
|
|
166
172
|
: localized.continueTextLoop;
|
|
173
|
+
const interruptedText =
|
|
174
|
+
typeof value.continueTextInterrupted === 'string' && value.continueTextInterrupted.trim() !== ''
|
|
175
|
+
? value.continueTextInterrupted
|
|
176
|
+
: localized.continueTextInterrupted;
|
|
167
177
|
const guardPendingText =
|
|
168
178
|
typeof value.guardPendingText === 'string' && value.guardPendingText.trim() !== ''
|
|
169
179
|
? value.guardPendingText
|
|
@@ -180,6 +190,7 @@ export function resolveConfig(section: AutoContinueSettings | undefined): AutoCo
|
|
|
180
190
|
resumeCompletedTurns: booleanOr(value.resumeCompletedTurns, DEFAULT_CONFIG.resumeCompletedTurns),
|
|
181
191
|
continueTextSilent: silentText,
|
|
182
192
|
continueTextLoop: loopText,
|
|
193
|
+
continueTextInterrupted: interruptedText,
|
|
183
194
|
guardTools: booleanOr(value.guardTools, DEFAULT_CONFIG.guardTools),
|
|
184
195
|
guardPendingText,
|
|
185
196
|
guardDoneText,
|
|
@@ -788,6 +799,14 @@ function clientTimeZone(): string | undefined {
|
|
|
788
799
|
}
|
|
789
800
|
}
|
|
790
801
|
|
|
802
|
+
/** A sent recovery prompt, not proof that the following turn succeeded. */
|
|
803
|
+
export interface RecoveryAttempt {
|
|
804
|
+
sessionId: string;
|
|
805
|
+
at: number;
|
|
806
|
+
reason: 'error' | 'max-tokens' | 'silent' | 'interrupted' | 'loop-guard' | 'manual';
|
|
807
|
+
consecutive: number;
|
|
808
|
+
}
|
|
809
|
+
|
|
791
810
|
/** 一天的自动继续统计(host 单实例内存态)。 */
|
|
792
811
|
export interface DayStats {
|
|
793
812
|
/** 本地日期 YYYY-MM-DD。 */
|