dsh-client-auto-continue 0.14.3 → 0.16.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/CHANGELOG.md +35 -0
- package/README.md +44 -22
- package/README.zh.md +44 -22
- package/docs/releases/v0.16.0.md +75 -0
- package/docs/third-party-notices.md +19 -0
- package/lib/client.js +196 -49
- package/lib/client.js.map +2 -2
- package/lib/index.js +7776 -104
- package/lib/types/client/bridge.d.ts +4 -0
- package/lib/types/client/composer-toggle.d.ts +6 -4
- package/lib/types/client/index.d.ts +2 -2
- package/lib/types/client/locales.d.ts +21 -0
- package/lib/types/client/settings-card.d.ts +6 -4
- package/lib/types/host/engine.d.ts +29 -1
- package/lib/types/host/settings-migration.d.ts +14 -0
- package/lib/types/index.d.ts +22 -8
- package/lib/types/shared/core.d.ts +24 -1
- package/package.json +21 -13
- package/src/client/bridge.ts +43 -4
- package/src/client/composer-toggle.tsx +20 -12
- package/src/client/index.ts +5 -2
- package/src/client/locales.ts +56 -14
- package/src/client/settings-card.tsx +58 -18
- package/src/client/styles.ts +5 -1
- package/src/host/engine.ts +307 -24
- package/src/host/settings-migration.ts +117 -0
- package/src/index.ts +66 -12
- package/src/shared/core.ts +42 -1
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,
|
|
@@ -31,12 +31,14 @@ import {
|
|
|
31
31
|
isTransientAgentError,
|
|
32
32
|
isTransientFailure,
|
|
33
33
|
resolveConfig,
|
|
34
|
+
sessionMode,
|
|
34
35
|
sleep,
|
|
35
36
|
todayKey,
|
|
36
37
|
trackPendingEcho,
|
|
37
38
|
type AutoContinueConfig,
|
|
38
39
|
type AutoContinueLocale,
|
|
39
40
|
type DayStats,
|
|
41
|
+
type RecoveryAttempt,
|
|
40
42
|
type FailureFacts,
|
|
41
43
|
type SessionState,
|
|
42
44
|
type NotifyAction,
|
|
@@ -93,6 +95,25 @@ const LOOP_GUARD_CANCEL_CAUSE = {
|
|
|
93
95
|
const LOOP_COMPLETED_REASON = 'turn/end:completed';
|
|
94
96
|
const LOOP_SILENT_REASON = 'turn/end:loop-silent';
|
|
95
97
|
const MANUAL_NOTIFICATION_REASON = 'manual:notification';
|
|
98
|
+
|
|
99
|
+
/** Yield between storage batches without spending a live-scan polling interval. */
|
|
100
|
+
const SWEEP_OBSERVE_BATCH = 16;
|
|
101
|
+
const STORED_READ_TIMEOUT_MS = 5000;
|
|
102
|
+
/** 单个存储会话连续观察/物化失败达此数后放弃, 避免坏日志反复占满每轮观察配额。 */
|
|
103
|
+
const SWEEP_MAX_FAILURES = 3;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 存储扫描消费的宿主服务结构类型。这些服务(sessionQuery 等)随 dsh
|
|
107
|
+
* 版本整组演进, 直接引类型包会拖动 devDependency 时代; 按消费面声明,
|
|
108
|
+
* 缺服务的宿主在运行时禁用存储扫描即可。
|
|
109
|
+
*/
|
|
110
|
+
interface StoredObservation {
|
|
111
|
+
readonly events: readonly SessionEvent[];
|
|
112
|
+
readonly header: { readonly id?: SessionId; readonly origin?: string; readonly agentPreset?: string };
|
|
113
|
+
readonly projections?: { readonly values: { readonly agentPreset?: string } };
|
|
114
|
+
[Symbol.dispose]?: () => void;
|
|
115
|
+
}
|
|
116
|
+
|
|
96
117
|
const isLoopReason = (reason: string): boolean =>
|
|
97
118
|
reason === LOOP_COMPLETED_REASON || reason === LOOP_SILENT_REASON;
|
|
98
119
|
|
|
@@ -133,6 +154,10 @@ function snapshotSessionEvents(session: Session): readonly SessionEvent[] {
|
|
|
133
154
|
const compatible = session as CompatibleSession;
|
|
134
155
|
const snapshot = compatible.snapshotEvents;
|
|
135
156
|
const events = typeof snapshot === 'function' ? snapshot.call(session) : compatible.events;
|
|
157
|
+
return validateSessionEvents(events);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function validateSessionEvents(events: unknown): readonly SessionEvent[] {
|
|
136
161
|
if (!Array.isArray(events)) throw new TypeError('session history is not an event array');
|
|
137
162
|
// Do not filter damaged entries: one could have been a manual stop, newer turn,
|
|
138
163
|
// or tool result. An incomplete history is not safe evidence for a continuation.
|
|
@@ -226,6 +251,7 @@ export class AutoContinueRunner {
|
|
|
226
251
|
private readonly states = new Map<SessionId, SessionState>();
|
|
227
252
|
private readonly pauseUntil = new Map<SessionId, number>();
|
|
228
253
|
private dayStats: DayStats = emptyDayStats();
|
|
254
|
+
private readonly recoveryAttempts: RecoveryAttempt[] = [];
|
|
229
255
|
private readonly notices: HostNotice[] = [];
|
|
230
256
|
private readonly noticeListeners = new Set<() => void>();
|
|
231
257
|
private readonly stateListeners = new Set<() => void>();
|
|
@@ -236,8 +262,15 @@ export class AutoContinueRunner {
|
|
|
236
262
|
private readonly bootScannedSessions = new WeakSet<Session>();
|
|
237
263
|
/** Also bound diagnostics when even an agent's session getter is unavailable. */
|
|
238
264
|
private readonly bootScanErrors = new WeakSet<object>();
|
|
265
|
+
/** 存储扫描已裁决的会话 id, 避免每轮重复冷读大日志。 */
|
|
266
|
+
private readonly storedSwept = new Set<SessionId>();
|
|
267
|
+
/** 存储会话的连续观察/物化失败次数, 触达 SWEEP_MAX_FAILURES 后不再重试。 */
|
|
268
|
+
private readonly storedSweepFailures = new Map<SessionId, number>();
|
|
269
|
+
private storedSweepAnnounced = false;
|
|
239
270
|
private bootScanTimer: ReturnType<typeof setTimeout> | undefined;
|
|
240
271
|
private wakeBootScan: (() => void) | undefined;
|
|
272
|
+
private storedSweep: Promise<void> | undefined;
|
|
273
|
+
private readonly stopStoredSweep = new AbortController();
|
|
241
274
|
|
|
242
275
|
/**
|
|
243
276
|
* @param ctx - host plugin context (agents registry, session events).
|
|
@@ -311,6 +344,10 @@ export class AutoContinueRunner {
|
|
|
311
344
|
return { ...this.dayStats, byCode: { ...this.dayStats.byCode } };
|
|
312
345
|
}
|
|
313
346
|
|
|
347
|
+
recentRecoveryAttempts(): RecoveryAttempt[] {
|
|
348
|
+
return this.recoveryAttempts.map(attempt => ({ ...attempt }));
|
|
349
|
+
}
|
|
350
|
+
|
|
314
351
|
/** 对外(状态桥): 当前生效的会话级暂停列表。 */
|
|
315
352
|
activePauses(): { sessionId: SessionId; until: number }[] {
|
|
316
353
|
const now = Date.now();
|
|
@@ -341,6 +378,28 @@ export class AutoContinueRunner {
|
|
|
341
378
|
for (const listener of this.stateListeners) listener();
|
|
342
379
|
}
|
|
343
380
|
|
|
381
|
+
private sessionConfig(sessionId: SessionId): AutoContinueConfig {
|
|
382
|
+
const config = this.getConfig();
|
|
383
|
+
const mode = sessionMode(config.sessionModes, sessionId);
|
|
384
|
+
return {
|
|
385
|
+
...config,
|
|
386
|
+
paused: config.paused || mode === 'off',
|
|
387
|
+
resumeCompletedTurns: mode === 'default' ? config.resumeCompletedTurns : mode === 'loop',
|
|
388
|
+
loopGuard: config.loopGuard && mode !== 'off',
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
configurationChanged(): void {
|
|
393
|
+
if (this.disposed) return;
|
|
394
|
+
for (const [sessionId, state] of this.states) {
|
|
395
|
+
const config = this.sessionConfig(sessionId);
|
|
396
|
+
if (config.paused || (isLoopReason(state.pendingReason ?? '') && !config.resumeCompletedTurns)) {
|
|
397
|
+
this.cancelPending(sessionId, '会话模式或全局设置已更改');
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
this.emitState();
|
|
401
|
+
}
|
|
402
|
+
|
|
344
403
|
/** 对外(状态桥): 消费待展示的通知。 */
|
|
345
404
|
drainNotices(): HostNotice[] {
|
|
346
405
|
return this.notices.splice(0, this.notices.length);
|
|
@@ -363,6 +422,7 @@ export class AutoContinueRunner {
|
|
|
363
422
|
dispose(): void {
|
|
364
423
|
if (this.disposed) return;
|
|
365
424
|
this.disposed = true;
|
|
425
|
+
this.stopStoredSweep.abort();
|
|
366
426
|
if (this.bootScanTimer !== undefined) clearTimeout(this.bootScanTimer);
|
|
367
427
|
this.bootScanTimer = undefined;
|
|
368
428
|
this.wakeBootScan?.();
|
|
@@ -579,7 +639,7 @@ export class AutoContinueRunner {
|
|
|
579
639
|
state: SessionState,
|
|
580
640
|
event: SessionEvent<'assistant/chunk'>,
|
|
581
641
|
): void {
|
|
582
|
-
if (!this.
|
|
642
|
+
if (!this.sessionConfig(sessionId).loopGuard || !state.running || state.loopFired) return;
|
|
583
643
|
const chunk = this.assistantChunkText(event);
|
|
584
644
|
if (chunk === '') return;
|
|
585
645
|
const merged = `${state.streamTail}${chunk}`.replace(/\r/g, '');
|
|
@@ -602,7 +662,7 @@ export class AutoContinueRunner {
|
|
|
602
662
|
state: SessionState,
|
|
603
663
|
event: SessionEvent<'assistant/message'>,
|
|
604
664
|
): void {
|
|
605
|
-
if (!this.
|
|
665
|
+
if (!this.sessionConfig(sessionId).loopGuard) return;
|
|
606
666
|
const text = this.assistantText(event);
|
|
607
667
|
const trimmed = visibleText(text);
|
|
608
668
|
// 相同文本重复(不限长度): 模型反复输出完全相同的消息是最强的循环信号,
|
|
@@ -639,7 +699,7 @@ export class AutoContinueRunner {
|
|
|
639
699
|
state: SessionState,
|
|
640
700
|
toolRepeat?: ToolRepeatSignal,
|
|
641
701
|
): void {
|
|
642
|
-
if (!this.
|
|
702
|
+
if (!this.sessionConfig(sessionId).loopGuard) return;
|
|
643
703
|
if (state.loopFired) return;
|
|
644
704
|
if (!state.running) return; // 只干预运行中的回合
|
|
645
705
|
const config = this.getConfig();
|
|
@@ -732,11 +792,11 @@ export class AutoContinueRunner {
|
|
|
732
792
|
state.lastTurn = event.data.turn;
|
|
733
793
|
state.lastFailureAt = Date.now();
|
|
734
794
|
this.noteRecovery(sessionId, 'error');
|
|
735
|
-
if (this.
|
|
795
|
+
if (this.sessionConfig(sessionId).resumeCompletedTurns) {
|
|
736
796
|
// 自主循环覆盖无可见输出的回合, 但这类回合是「失败」而非成功:
|
|
737
797
|
// 不 force, 否则会绕过连续上限与冷却, 让卡住的模型无限重试。
|
|
738
798
|
this.schedule(sessionId, LOOP_SILENT_REASON);
|
|
739
|
-
} else if (this.
|
|
799
|
+
} else if (this.sessionConfig(sessionId).resumeSilentTurns) {
|
|
740
800
|
this.schedule(sessionId, `turn/end:${reasonKind}:silent`);
|
|
741
801
|
}
|
|
742
802
|
break;
|
|
@@ -747,7 +807,7 @@ export class AutoContinueRunner {
|
|
|
747
807
|
// 自主循环的例外只在于「是否续跑」, 不在于「是否清零预算」: 循环对每个
|
|
748
808
|
// completed 回合都强制续跑, 但失败预算依旧只在可见输出时清零, 否则
|
|
749
809
|
// 空回合/未观察到的回合会不断抹掉连续计数, 令连续上限永远无法生效。
|
|
750
|
-
if (this.
|
|
810
|
+
if (this.sessionConfig(sessionId).resumeCompletedTurns) {
|
|
751
811
|
if (turnOutput === 'visible') {
|
|
752
812
|
state.consecutive = 0;
|
|
753
813
|
state.lastFailure = undefined;
|
|
@@ -761,6 +821,7 @@ export class AutoContinueRunner {
|
|
|
761
821
|
}
|
|
762
822
|
} else if (reasonKind === 'aborted') {
|
|
763
823
|
if (isLoopGuardCancelReason((reason as { reason?: unknown }).reason)) {
|
|
824
|
+
if (this.sessionConfig(sessionId).paused) break;
|
|
764
825
|
// 我们自己的 loop guard 打断: 视为可恢复中断, 用循环提示文本重启回合。
|
|
765
826
|
// 不清 consecutive / lastAttemptAt: 冷却与连续上限在 loop 路径同样生效,
|
|
766
827
|
// 防止无限打断重发(issue #13); 打断本身受冷却约束, 重启也要等冷却。
|
|
@@ -840,6 +901,7 @@ export class AutoContinueRunner {
|
|
|
840
901
|
|
|
841
902
|
private onTurnFailure(sessionId: SessionId, reason: string, failure: FailureFacts): void {
|
|
842
903
|
const config = this.getConfig();
|
|
904
|
+
if (sessionMode(config.sessionModes, sessionId) === 'off') return;
|
|
843
905
|
if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
|
|
844
906
|
const copy = NOTICE_COPY[config.locale];
|
|
845
907
|
const summary = `${failure.code}${failure.status !== undefined ? ` (HTTP ${failure.status})` : ''}`;
|
|
@@ -861,13 +923,14 @@ export class AutoContinueRunner {
|
|
|
861
923
|
/** 通知操作按钮与回调(「立即续跑」/「暂停该会话 1 小时」)。 */
|
|
862
924
|
private notifyOptions(sessionId: SessionId, locale: AutoContinueLocale): NotifyOptions {
|
|
863
925
|
const copy = NOTICE_COPY[locale];
|
|
864
|
-
|
|
865
|
-
|
|
926
|
+
// 未物化的存储会话没有 live agent, 「立即续跑」只会空转; 只保留暂停。
|
|
927
|
+
const actions: NotifyAction[] = this.ctx.agents.get(sessionId) === undefined
|
|
928
|
+
? [{ action: 'pause1h', title: copy.pauseAction }]
|
|
929
|
+
: [
|
|
866
930
|
{ action: 'resume', title: copy.resumeAction },
|
|
867
931
|
{ action: 'pause1h', title: copy.pauseAction },
|
|
868
|
-
]
|
|
869
|
-
|
|
870
|
-
};
|
|
932
|
+
];
|
|
933
|
+
return { actions, onAction: (action) => this.onNotifyAction(sessionId, action) };
|
|
871
934
|
}
|
|
872
935
|
|
|
873
936
|
private onNotifyAction(sessionId: SessionId, action: string): void {
|
|
@@ -973,10 +1036,11 @@ export class AutoContinueRunner {
|
|
|
973
1036
|
|
|
974
1037
|
private schedule(sessionId: SessionId, reason: string, force = false): void {
|
|
975
1038
|
const state = this.state(sessionId);
|
|
976
|
-
const config = this.
|
|
1039
|
+
const config = this.sessionConfig(sessionId);
|
|
1040
|
+
if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
|
|
977
1041
|
if (this.isSubagent(sessionId, state)) return; // 子代理会话由父代理处理, 不抢跑
|
|
978
1042
|
if (config.paused) {
|
|
979
|
-
this.log(`跳过 ${sessionId}(${reason}):
|
|
1043
|
+
this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
|
|
980
1044
|
return;
|
|
981
1045
|
}
|
|
982
1046
|
if (Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) {
|
|
@@ -1004,6 +1068,7 @@ export class AutoContinueRunner {
|
|
|
1004
1068
|
const timer = setTimeout(() => {
|
|
1005
1069
|
if (state.pendingTimer !== timer) return;
|
|
1006
1070
|
state.pendingTimer = undefined;
|
|
1071
|
+
state.pendingReason = undefined;
|
|
1007
1072
|
// 保险丝: 定时器回调内任何异常(含 inactive context)都不得成为未捕获异常炸掉进程。
|
|
1008
1073
|
try {
|
|
1009
1074
|
void this.fire(sessionId, reason, force);
|
|
@@ -1012,6 +1077,7 @@ export class AutoContinueRunner {
|
|
|
1012
1077
|
}
|
|
1013
1078
|
}, config.graceMs);
|
|
1014
1079
|
state.pendingTimer = timer;
|
|
1080
|
+
state.pendingReason = reason;
|
|
1015
1081
|
const template = this.templateFor(config, reason);
|
|
1016
1082
|
this.log(
|
|
1017
1083
|
`检测到非人为中断 ${sessionId}(${reason}), ${config.graceMs}ms 后自动发送「${template}」`,
|
|
@@ -1025,8 +1091,10 @@ export class AutoContinueRunner {
|
|
|
1025
1091
|
private deferCooldownRetry(sessionId: SessionId, reason: string, remaining: number): void {
|
|
1026
1092
|
const state = this.state(sessionId);
|
|
1027
1093
|
if (state.cooldownRetryTimer !== undefined) clearTimeout(state.cooldownRetryTimer);
|
|
1094
|
+
state.pendingReason = reason;
|
|
1028
1095
|
state.cooldownRetryTimer = setTimeout(() => {
|
|
1029
1096
|
state.cooldownRetryTimer = undefined;
|
|
1097
|
+
state.pendingReason = undefined;
|
|
1030
1098
|
try {
|
|
1031
1099
|
this.schedule(sessionId, reason);
|
|
1032
1100
|
} catch (error) {
|
|
@@ -1043,11 +1111,13 @@ export class AutoContinueRunner {
|
|
|
1043
1111
|
if (isLoopReason(reason)) return config.continueTextLoop;
|
|
1044
1112
|
if (reason.endsWith(':silent')) return config.continueTextSilent;
|
|
1045
1113
|
if (reason.includes('max-tokens')) return config.continueTextMaxTokens;
|
|
1114
|
+
if (reason.includes('interrupted')) return config.continueTextInterrupted;
|
|
1046
1115
|
return config.continueText;
|
|
1047
1116
|
}
|
|
1048
1117
|
|
|
1049
1118
|
private cancelPending(sessionId: SessionId, why: string): void {
|
|
1050
1119
|
const state = this.state(sessionId);
|
|
1120
|
+
state.pendingReason = undefined;
|
|
1051
1121
|
let cancelled = false;
|
|
1052
1122
|
if (state.pendingTimer !== undefined) {
|
|
1053
1123
|
clearTimeout(state.pendingTimer);
|
|
@@ -1060,13 +1130,18 @@ export class AutoContinueRunner {
|
|
|
1060
1130
|
state.cooldownRetryTimer = undefined;
|
|
1061
1131
|
cancelled = true;
|
|
1062
1132
|
}
|
|
1133
|
+
if (state.loopRetryTimer !== undefined) {
|
|
1134
|
+
clearTimeout(state.loopRetryTimer);
|
|
1135
|
+
state.loopRetryTimer = undefined;
|
|
1136
|
+
cancelled = true;
|
|
1137
|
+
}
|
|
1063
1138
|
if (cancelled) this.log(`取消 ${sessionId} 的自动继续(${why})`);
|
|
1064
1139
|
}
|
|
1065
1140
|
|
|
1066
1141
|
private fire(sessionId: SessionId, reason: string, force = false): void {
|
|
1067
1142
|
if (this.disposed) return;
|
|
1068
1143
|
const state = this.state(sessionId);
|
|
1069
|
-
const config = this.
|
|
1144
|
+
const config = this.sessionConfig(sessionId);
|
|
1070
1145
|
const manualResume = force && reason === MANUAL_NOTIFICATION_REASON;
|
|
1071
1146
|
if (reason.endsWith(':silent') && !config.resumeSilentTurns) return;
|
|
1072
1147
|
// 宽限期内循环被关闭: 发送前必须重新检查开关, 与 :silent 恢复同样处理。
|
|
@@ -1074,7 +1149,7 @@ export class AutoContinueRunner {
|
|
|
1074
1149
|
if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
|
|
1075
1150
|
if (this.isSubagent(sessionId, state)) return; // 子代理会话由父代理处理, 不抢跑
|
|
1076
1151
|
if (config.paused && !manualResume) {
|
|
1077
|
-
this.log(`跳过 ${sessionId}(${reason}):
|
|
1152
|
+
this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
|
|
1078
1153
|
return;
|
|
1079
1154
|
}
|
|
1080
1155
|
if (!manualResume && Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) {
|
|
@@ -1120,6 +1195,17 @@ export class AutoContinueRunner {
|
|
|
1120
1195
|
// 自主循环的成功续跑不计入连续上限: 上限只约束失败(网络中断等)。
|
|
1121
1196
|
if (reason !== LOOP_COMPLETED_REASON) state.consecutive += 1;
|
|
1122
1197
|
state.pendingRecoveryAt = now; // 等待窗口内的下一个回合结束来判定恢复结果
|
|
1198
|
+
if (reason !== LOOP_COMPLETED_REASON) {
|
|
1199
|
+
this.recoveryAttempts.unshift({
|
|
1200
|
+
sessionId, at: now, consecutive: state.consecutive,
|
|
1201
|
+
reason: manualResume ? 'manual'
|
|
1202
|
+
: reason === 'loop:aborted' ? 'loop-guard'
|
|
1203
|
+
: reason.endsWith(':silent') || reason === LOOP_SILENT_REASON ? 'silent'
|
|
1204
|
+
: reason.endsWith(':interrupted') ? 'interrupted'
|
|
1205
|
+
: reason.endsWith(':max-tokens') ? 'max-tokens' : 'error',
|
|
1206
|
+
});
|
|
1207
|
+
this.recoveryAttempts.length = Math.min(this.recoveryAttempts.length, 20);
|
|
1208
|
+
}
|
|
1123
1209
|
this.bumpStat({ sent: 1, ...(state.lastFailure !== undefined ? { code: state.lastFailure.code } : {}) });
|
|
1124
1210
|
this.log(`已自动发送「${text}」到 ${sessionId}(${reason}), 第 ${state.consecutive} 次连续`);
|
|
1125
1211
|
if (config.notify) {
|
|
@@ -1195,6 +1281,14 @@ export class AutoContinueRunner {
|
|
|
1195
1281
|
if (attempt > 0 && Date.now() >= deadline) return;
|
|
1196
1282
|
try {
|
|
1197
1283
|
if (await this.scanInterrupted()) return;
|
|
1284
|
+
const config = this.getConfig();
|
|
1285
|
+
if (!config.paused && config.scanOnBoot && this.storedSweep === undefined) {
|
|
1286
|
+
this.storedSweep = this.sweepStoredSessions(config, deadline)
|
|
1287
|
+
.catch(error => {
|
|
1288
|
+
if (!this.disposed) this.ctx.logger.error(`Stored session scan failed: ${String(error)}`);
|
|
1289
|
+
})
|
|
1290
|
+
.finally(() => { this.storedSweep = undefined; });
|
|
1291
|
+
}
|
|
1198
1292
|
} catch (error) {
|
|
1199
1293
|
if (this.disposed) return;
|
|
1200
1294
|
// 宿主未就绪时每 3s 重试; 只节流记录日志, 避免刷屏。
|
|
@@ -1209,12 +1303,13 @@ export class AutoContinueRunner {
|
|
|
1209
1303
|
const remaining = deadline - Date.now();
|
|
1210
1304
|
if (this.disposed || remaining <= 0) return;
|
|
1211
1305
|
await new Promise<void>((resolve) => {
|
|
1212
|
-
this.wakeBootScan =
|
|
1213
|
-
|
|
1306
|
+
this.wakeBootScan = () => {
|
|
1307
|
+
if (this.bootScanTimer !== undefined) clearTimeout(this.bootScanTimer);
|
|
1214
1308
|
this.bootScanTimer = undefined;
|
|
1215
1309
|
this.wakeBootScan = undefined;
|
|
1216
1310
|
resolve();
|
|
1217
|
-
}
|
|
1311
|
+
};
|
|
1312
|
+
this.bootScanTimer = setTimeout(this.wakeBootScan, Math.min(3000, remaining));
|
|
1218
1313
|
});
|
|
1219
1314
|
}
|
|
1220
1315
|
}
|
|
@@ -1243,6 +1338,7 @@ export class AutoContinueRunner {
|
|
|
1243
1338
|
if (this.bootScannedSessions.has(session) || session.header?.origin === 'subagent') continue;
|
|
1244
1339
|
sessionId = session.id;
|
|
1245
1340
|
if (typeof sessionId !== 'string' || sessionId === '') throw new TypeError('session id is unavailable');
|
|
1341
|
+
if (this.sessionConfig(sessionId).paused) continue;
|
|
1246
1342
|
const state = this.state(sessionId);
|
|
1247
1343
|
if (state.pendingTimer !== undefined || state.consecutive >= config.maxConsecutive) continue;
|
|
1248
1344
|
if (now - state.lastAttemptAt < this.cooldownFor(state)) continue;
|
|
@@ -1314,11 +1410,10 @@ export class AutoContinueRunner {
|
|
|
1314
1410
|
state.lastFailureAt = lastEnd.time;
|
|
1315
1411
|
this.onTurnFailure(sessionId, scanReason, failure);
|
|
1316
1412
|
} else {
|
|
1317
|
-
if (reasonKind === 'no-visible-output')
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
}
|
|
1413
|
+
if (reasonKind === 'no-visible-output') state.lastFailure = undefined;
|
|
1414
|
+
// 没有失败事实的恢复(如 interrupted)也要填 {turn}/{elapsed}, README 对所有继续文本承诺这些占位符。
|
|
1415
|
+
state.lastTurn = lastEnd.data.turn;
|
|
1416
|
+
state.lastFailureAt = lastEnd.time;
|
|
1322
1417
|
this.schedule(sessionId, scanReason);
|
|
1323
1418
|
}
|
|
1324
1419
|
recoveries += 1;
|
|
@@ -1331,6 +1426,194 @@ export class AutoContinueRunner {
|
|
|
1331
1426
|
return false;
|
|
1332
1427
|
}
|
|
1333
1428
|
|
|
1429
|
+
/** Bound cold reads even if a backend ignores cancellation; release late leases. */
|
|
1430
|
+
private async readStored<T extends object>(read: (signal: AbortSignal) => Promise<T>, deadline: number): Promise<T> {
|
|
1431
|
+
const timeout = new AbortController();
|
|
1432
|
+
const signal = AbortSignal.any([this.stopStoredSweep.signal, timeout.signal]);
|
|
1433
|
+
const timer = setTimeout(() => timeout.abort(new Error('Stored session read timed out')), Math.max(0, Math.min(STORED_READ_TIMEOUT_MS, deadline - Date.now())));
|
|
1434
|
+
let onAbort: () => void;
|
|
1435
|
+
const cancelled = new Promise<never>((_resolve, reject) => {
|
|
1436
|
+
onAbort = () => reject(signal.reason);
|
|
1437
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
1438
|
+
if (signal.aborted) onAbort();
|
|
1439
|
+
});
|
|
1440
|
+
const pending = Promise.resolve().then(() => { signal.throwIfAborted(); return read(signal); });
|
|
1441
|
+
void pending.then(value => {
|
|
1442
|
+
if (signal.aborted) (value as { [Symbol.dispose]?: () => void })[Symbol.dispose]?.();
|
|
1443
|
+
}).catch(() => {});
|
|
1444
|
+
try {
|
|
1445
|
+
return await Promise.race([pending, cancelled]);
|
|
1446
|
+
} finally {
|
|
1447
|
+
clearTimeout(timer);
|
|
1448
|
+
signal.removeEventListener('abort', onAbort!);
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
/**
|
|
1453
|
+
* 存储扫描: 枚举持久化会话, 把尾部命中恢复谓词的未加载会话物化为
|
|
1454
|
+
* live agent。宿主重启后 agent 仅在客户端打开会话时才懒加载, 不物化
|
|
1455
|
+
* 则启动扫描永远看不到它们; 谓词与上方扫描一致, 仅失败类原因。
|
|
1456
|
+
*/
|
|
1457
|
+
private async sweepStoredSessions(config: AutoContinueConfig, deadline: number): Promise<void> {
|
|
1458
|
+
const query = this.ctx.get('sessionQuery');
|
|
1459
|
+
if (query === undefined) return;
|
|
1460
|
+
const records = await this.readStored(signal => query.listSessions(signal), deadline);
|
|
1461
|
+
if (!Array.isArray(records)) throw new TypeError('stored session listing is not an array');
|
|
1462
|
+
if (!this.storedSweepAnnounced) {
|
|
1463
|
+
this.storedSweepAnnounced = true;
|
|
1464
|
+
this.ctx.logger.info(`存储扫描就绪: ${records.length} 个会话记录`);
|
|
1465
|
+
}
|
|
1466
|
+
let observed = 0;
|
|
1467
|
+
for (const record of records) {
|
|
1468
|
+
if (this.disposed || Date.now() >= deadline || this.getConfig().paused || !this.getConfig().scanOnBoot) return;
|
|
1469
|
+
if (typeof record?.header?.id !== 'string' || record.header.id === '') {
|
|
1470
|
+
this.logBootScanFailure(undefined, new TypeError('stored session record has no id'));
|
|
1471
|
+
continue;
|
|
1472
|
+
}
|
|
1473
|
+
const sessionId = record.header.id;
|
|
1474
|
+
if (this.sessionConfig(sessionId).paused || Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) continue;
|
|
1475
|
+
if (record.live || this.storedSwept.has(sessionId)) continue;
|
|
1476
|
+
this.storedSwept.add(sessionId);
|
|
1477
|
+
if (record.header.origin === 'subagent') continue;
|
|
1478
|
+
observed += 1;
|
|
1479
|
+
let observation: StoredObservation | undefined;
|
|
1480
|
+
try {
|
|
1481
|
+
const stored: StoredObservation = await this.readStored(signal => query.observeSession(sessionId, { projectionMode: 'all', signal }), deadline);
|
|
1482
|
+
observation = stored;
|
|
1483
|
+
if (this.disposed) return;
|
|
1484
|
+
if (this.sessionConfig(sessionId).paused) {
|
|
1485
|
+
this.storedSwept.delete(sessionId);
|
|
1486
|
+
continue;
|
|
1487
|
+
}
|
|
1488
|
+
const events = validateSessionEvents(stored.events);
|
|
1489
|
+
if (events.length === 0) continue;
|
|
1490
|
+
// 快照之后客户端可能已打开该会话: 归还 live 扫描, 避免与 live 路径
|
|
1491
|
+
// 重复上报, 也避免物化撞上写归属。
|
|
1492
|
+
if (this.ctx.agents.get(sessionId) !== undefined) continue;
|
|
1493
|
+
let lastEnd: SessionEvent<'turn/end'> | undefined;
|
|
1494
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
1495
|
+
const event = events[i];
|
|
1496
|
+
if (event?.type === 'turn/end') { lastEnd = event; break; }
|
|
1497
|
+
}
|
|
1498
|
+
let lastStart: SessionEvent<'turn/start'> | undefined;
|
|
1499
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
1500
|
+
const event = events[i];
|
|
1501
|
+
if (event?.type === 'turn/start') { lastStart = event; break; }
|
|
1502
|
+
}
|
|
1503
|
+
// 兜底分支: 真实 sessionQuery 冷读会把内存中的 interruptedTurnClosers
|
|
1504
|
+
// 折叠进返回日志(尾部即合成 turn/end), 上方 closed-tail 才是生产主路
|
|
1505
|
+
// 径。这里覆盖两种例外——不折叠的宿主实现, 以及 listSessions 快照与
|
|
1506
|
+
// observeSession 之间客户端刚打开、切在轮次中间的 live 视图。
|
|
1507
|
+
const openTurn = lastStart !== undefined && (lastEnd === undefined || lastStart.seq > lastEnd.seq);
|
|
1508
|
+
let reasonKind: string | undefined;
|
|
1509
|
+
let freshAt: number;
|
|
1510
|
+
if (openTurn) {
|
|
1511
|
+
reasonKind = 'interrupted';
|
|
1512
|
+
freshAt = events[events.length - 1]?.time ?? 0;
|
|
1513
|
+
} else {
|
|
1514
|
+
reasonKind = readReasonKind(lastEnd?.data.reason);
|
|
1515
|
+
freshAt = lastEnd?.time ?? 0;
|
|
1516
|
+
}
|
|
1517
|
+
// 过期或被取代的永久错误与 live 扫描一致地静默跳过, 不再单独上报。
|
|
1518
|
+
if (reasonKind === undefined || freshAt < Date.now() - config.freshMs) continue;
|
|
1519
|
+
if (reasonKind !== undefined && !openTurn) {
|
|
1520
|
+
const silent = reasonKind === 'no-visible-output' && config.resumeSilentTurns;
|
|
1521
|
+
// 尾随 turn/start 已按 openTurn 处理, 这里只剩用户接管一种取代形态。
|
|
1522
|
+
const superseded = events.some((event) =>
|
|
1523
|
+
lastEnd !== undefined && event.seq > lastEnd.seq && event.type === 'user/message' && event.data.source.kind === 'user',
|
|
1524
|
+
);
|
|
1525
|
+
if ((!isNonHumanReason(reasonKind) && !silent) || superseded) continue;
|
|
1526
|
+
// 镜像 live 扫描的裁决: 畸形/永久错误不值得物化——物化后同样会被拦下。
|
|
1527
|
+
if (reasonKind === 'error') {
|
|
1528
|
+
const failure = parseFailureFacts((lastEnd!.data.reason as { error?: unknown }).error);
|
|
1529
|
+
if (failure === undefined) {
|
|
1530
|
+
console.error(`[auto-continue] 忽略畸形存储 turn/end ${sessionId}: error details 无法解释`);
|
|
1531
|
+
continue;
|
|
1532
|
+
}
|
|
1533
|
+
// 永久错误同样走 onTurnFailure, 镜像 live 路径的统计与通知旁效。
|
|
1534
|
+
if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
|
|
1535
|
+
this.onTurnFailure(sessionId, 'sweep:turn/end:error', failure);
|
|
1536
|
+
continue;
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
const presetId = stored.projections?.values.agentPreset ?? stored.header.agentPreset;
|
|
1541
|
+
const loggedConfig = foldRequestHeader(events)?.config;
|
|
1542
|
+
if (!await this.materializeStored(
|
|
1543
|
+
sessionId,
|
|
1544
|
+
presetId,
|
|
1545
|
+
loggedConfig === undefined ? undefined : { provider: loggedConfig.provider, model: loggedConfig.model },
|
|
1546
|
+
)) {
|
|
1547
|
+
this.storedSwept.delete(sessionId);
|
|
1548
|
+
return;
|
|
1549
|
+
}
|
|
1550
|
+
this.storedSweepFailures.delete(sessionId);
|
|
1551
|
+
this.wakeBootScan?.();
|
|
1552
|
+
this.ctx.logger.info(openTurn
|
|
1553
|
+
? `扫描物化存储会话 ${sessionId}(日志止于 turn/start, 视作 interrupted), 交给启动扫描接管`
|
|
1554
|
+
: `扫描物化存储会话 ${sessionId}(turn/end:${reasonKind}), 交给启动扫描接管`);
|
|
1555
|
+
} catch (error) {
|
|
1556
|
+
if (this.disposed) return;
|
|
1557
|
+
// 观察或物化失败允许下一轮重试; 连续触达上限后放弃, 并清掉计数——
|
|
1558
|
+
// 已永久跳过的会话不再进入该映射, 不给长存活宿主留死重。
|
|
1559
|
+
const failures = (this.storedSweepFailures.get(sessionId) ?? 0) + 1;
|
|
1560
|
+
if (failures < SWEEP_MAX_FAILURES) {
|
|
1561
|
+
this.storedSweepFailures.set(sessionId, failures);
|
|
1562
|
+
this.storedSwept.delete(sessionId);
|
|
1563
|
+
} else {
|
|
1564
|
+
this.storedSweepFailures.delete(sessionId);
|
|
1565
|
+
}
|
|
1566
|
+
this.ctx.logger.error(`存储会话 ${sessionId} 物化失败: ${error instanceof Error ? error.message : String(error)}`);
|
|
1567
|
+
} finally {
|
|
1568
|
+
observation?.[Symbol.dispose]?.();
|
|
1569
|
+
if (observed % SWEEP_OBSERVE_BATCH === 0 && !this.disposed) {
|
|
1570
|
+
await new Promise<void>(resolve => setTimeout(resolve, 0));
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
/**
|
|
1577
|
+
* 按会话记录的 preset 组合把存储会话恢复为 live agent(镜像会话控制
|
|
1578
|
+
* 器的 adopt 路径: preset 挂载 + 会话已记录的模型选择回装)。模型选择
|
|
1579
|
+
* 以日志记录的 request-header 播种 agentOptions——{{model}}/{{provider}}
|
|
1580
|
+
* 提示变量与首次请求路由都读它, 驱动器还会因路由吻合而自行回装日志
|
|
1581
|
+
* 记录的 effort; 无落点(从未发过请求的会话)回落宿主默认。恢复时追
|
|
1582
|
+
* 加的合成 turn/end(`interrupted`)随后由常规扫描按既有关卡恢复。
|
|
1583
|
+
*/
|
|
1584
|
+
private async materializeStored(
|
|
1585
|
+
sessionId: SessionId,
|
|
1586
|
+
presetId: string | undefined,
|
|
1587
|
+
logged: { provider: string; model: string } | undefined,
|
|
1588
|
+
): Promise<boolean> {
|
|
1589
|
+
if (this.disposed || this.sessionConfig(sessionId).paused || !this.getConfig().scanOnBoot) return false;
|
|
1590
|
+
const presets = this.ctx.get('agentPresets');
|
|
1591
|
+
// Mirrors session-controller's adopt: without agent options the agent has no
|
|
1592
|
+
// provider/model, so prompt variables like {{model}} have no value and the
|
|
1593
|
+
// request carries no route.
|
|
1594
|
+
const defaultModel = this.ctx.get('agentDefaultModel');
|
|
1595
|
+
const selection = defaultModel?.currentSelection();
|
|
1596
|
+
const agentOptions = logged !== undefined
|
|
1597
|
+
? { provider: logged.provider, model: logged.model }
|
|
1598
|
+
: selection === undefined ? undefined : { provider: selection.provider, model: selection.model };
|
|
1599
|
+
if (presets === undefined) {
|
|
1600
|
+
await this.ctx.agents.resume({ resumeSessionId: sessionId, agentOptions, signal: this.stopStoredSweep.signal });
|
|
1601
|
+
return true;
|
|
1602
|
+
}
|
|
1603
|
+
const resolvedId = (await presets.resolve(presetId)).id;
|
|
1604
|
+
if (this.disposed || this.sessionConfig(sessionId).paused || !this.getConfig().scanOnBoot) return false;
|
|
1605
|
+
if (this.ctx.agents.get(sessionId) !== undefined) return true;
|
|
1606
|
+
await this.ctx.agents.resume({
|
|
1607
|
+
resumeSessionId: sessionId,
|
|
1608
|
+
agentOptions,
|
|
1609
|
+
signal: this.stopStoredSweep.signal,
|
|
1610
|
+
setup: async (agentCtx) => {
|
|
1611
|
+
await presets.mount(agentCtx, resolvedId);
|
|
1612
|
+
},
|
|
1613
|
+
});
|
|
1614
|
+
return true;
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1334
1617
|
/** Captured identity only: even session.id can throw when the header is damaged. */
|
|
1335
1618
|
private logBootScanFailure(sessionId: SessionId | undefined, error: unknown): void {
|
|
1336
1619
|
console.error(`[auto-continue] 启动扫描跳过会话 ${sessionId ?? '(id unavailable)'}: ${
|