dsh-client-auto-continue 0.17.4 → 0.19.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 +47 -0
- package/README.md +230 -281
- package/README.ru.md +382 -0
- package/README.zh.md +229 -279
- package/docs/auto-continue-workflow.archify.json +3 -3
- package/docs/auto-continue-workflow.en.archify.json +3 -3
- package/docs/auto-continue-workflow.en.html +1 -1
- package/docs/auto-continue-workflow.html +1 -1
- package/docs/auto-continue-workflow.ru.svg +530 -0
- package/docs/banner-ru-dark.svg +38 -0
- package/docs/banner-ru.svg +38 -0
- package/docs/demo-ru-static.svg +115 -0
- package/docs/demo-ru.svg +147 -0
- package/docs/releases/v0.18.0.md +58 -0
- package/docs/releases/v0.19.0.md +62 -0
- package/docs/social-preview.png +0 -0
- package/docs/social-preview.svg +30 -1
- package/lib/client.js +347 -100
- package/lib/client.js.map +3 -3
- package/lib/index.js +790 -49
- package/lib/types/client/auto-continue-icon.d.ts +7 -0
- package/lib/types/client/bridge.d.ts +2 -0
- package/lib/types/client/composer-toggle.d.ts +2 -0
- package/lib/types/client/locales.d.ts +19 -0
- package/lib/types/client/settings-card.d.ts +8 -0
- package/lib/types/host/connectivity.d.ts +4 -0
- package/lib/types/host/engine.d.ts +97 -5
- package/lib/types/index.d.ts +64 -0
- package/lib/types/shared/core.d.ts +54 -1
- package/locale/ru.json +6 -0
- package/package.json +6 -4
- package/scripts/build-docs-assets.mjs +126 -0
- package/src/client/auto-continue-icon.tsx +6 -27
- package/src/client/bridge.ts +26 -6
- package/src/client/composer-toggle.tsx +22 -11
- package/src/client/index.ts +5 -1
- package/src/client/locales.ts +241 -38
- package/src/client/settings-card.tsx +31 -4
- package/src/client/settings-notifications.ts +3 -2
- package/src/client/styles.ts +17 -19
- package/src/host/connectivity.ts +54 -0
- package/src/host/engine.ts +852 -40
- package/src/host/settings-migration.ts +1 -1
- package/src/index.ts +26 -1
- package/src/shared/core.ts +94 -3
package/src/host/engine.ts
CHANGED
|
@@ -19,6 +19,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent';
|
|
|
19
19
|
import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types';
|
|
20
20
|
import { foldRequestHeader, type Session } from '@deepseek-ai/dsh-session';
|
|
21
21
|
import {
|
|
22
|
+
AUTO_CONTINUE_SOURCE_KIND,
|
|
22
23
|
DEFAULT_CONFIG,
|
|
23
24
|
RECOVERY_WINDOW_MS,
|
|
24
25
|
effectiveCooldown,
|
|
@@ -28,6 +29,8 @@ import {
|
|
|
28
29
|
freshState,
|
|
29
30
|
isNonHumanReason,
|
|
30
31
|
isOurEcho,
|
|
32
|
+
isNetworkFailure,
|
|
33
|
+
isSessionMode,
|
|
31
34
|
isTransientAgentError,
|
|
32
35
|
isTransientFailure,
|
|
33
36
|
resolveConfig,
|
|
@@ -40,39 +43,63 @@ import {
|
|
|
40
43
|
type DayStats,
|
|
41
44
|
type RecoveryAttempt,
|
|
42
45
|
type FailureFacts,
|
|
46
|
+
type SessionMode,
|
|
43
47
|
type SessionState,
|
|
44
48
|
type NotifyAction,
|
|
45
49
|
type NotifyOptions,
|
|
46
50
|
type TemplateContext,
|
|
47
51
|
type ToolRepeatSignal,
|
|
48
52
|
} from '../shared/core.ts';
|
|
53
|
+
import { probeConnectivity, type ConnectivityProbe } from './connectivity.ts';
|
|
49
54
|
|
|
50
55
|
const NOTICE_COPY = {
|
|
51
56
|
zh: {
|
|
52
|
-
notContinuedTitle: 'dsh-auto-continue:
|
|
57
|
+
notContinuedTitle: 'dsh-auto-continue: 请处理会话错误',
|
|
53
58
|
permanentErrorBody: (sessionId: SessionId, summary: string) =>
|
|
54
|
-
`${sessionId}:
|
|
59
|
+
`${sessionId}: ${summary}。请处理此错误后再继续。`,
|
|
55
60
|
resumeAction: '立即续跑',
|
|
56
61
|
pauseAction: '暂停该会话 1 小时',
|
|
57
|
-
continuedTitle: 'dsh-auto-continue:
|
|
62
|
+
continuedTitle: 'dsh-auto-continue: 已发送继续消息',
|
|
58
63
|
continuedBody: (sessionId: SessionId, text: string, count: number) =>
|
|
59
|
-
`${sessionId}: 已发送「${text}
|
|
60
|
-
stoppedTitle: 'dsh-auto-continue:
|
|
64
|
+
`${sessionId}: 已发送「${text}」(连续尝试 ${count} 次)`,
|
|
65
|
+
stoppedTitle: 'dsh-auto-continue: 已达到重试上限',
|
|
61
66
|
stoppedBody: (sessionId: SessionId, count: number) =>
|
|
62
|
-
`${sessionId}:
|
|
67
|
+
`${sessionId}: 已连续尝试恢复 ${count} 次。请检查会话后再继续。`,
|
|
68
|
+
loopCapTitle: 'dsh-auto-continue: 自主循环已到上限',
|
|
69
|
+
loopCapBody: (sessionId: SessionId, count: number) =>
|
|
70
|
+
`${sessionId}: 已自主续跑 ${count} 轮, 循环暂停; 发一条消息或重新开启循环即可继续`,
|
|
63
71
|
},
|
|
64
72
|
en: {
|
|
65
|
-
notContinuedTitle: 'dsh-auto-continue:
|
|
73
|
+
notContinuedTitle: 'dsh-auto-continue: Review session error',
|
|
66
74
|
permanentErrorBody: (sessionId: SessionId, summary: string) =>
|
|
67
|
-
`${sessionId}:
|
|
75
|
+
`${sessionId}: ${summary}. Resolve this error before continuing.`,
|
|
68
76
|
resumeAction: 'Resume now',
|
|
69
77
|
pauseAction: 'Pause this session for 1 hour',
|
|
70
|
-
continuedTitle: 'dsh-auto-continue:
|
|
78
|
+
continuedTitle: 'dsh-auto-continue: Continue message sent',
|
|
71
79
|
continuedBody: (sessionId: SessionId, text: string, count: number) =>
|
|
72
|
-
`${sessionId}: Sent "${text}" (consecutive
|
|
73
|
-
stoppedTitle: 'dsh-auto-continue:
|
|
80
|
+
`${sessionId}: Sent "${text}" (consecutive attempts: ${count})`,
|
|
81
|
+
stoppedTitle: 'dsh-auto-continue: Retry limit reached',
|
|
74
82
|
stoppedBody: (sessionId: SessionId, count: number) =>
|
|
75
|
-
`${sessionId}: ${count}
|
|
83
|
+
`${sessionId}: Consecutive recovery attempts: ${count}. Review the conversation before continuing.`,
|
|
84
|
+
loopCapTitle: 'dsh-auto-continue: Autonomous loop limit reached',
|
|
85
|
+
loopCapBody: (sessionId: SessionId, count: number) =>
|
|
86
|
+
`${sessionId}: Stopped after ${count} autonomous rounds; send a message or turn the loop back on to keep going`,
|
|
87
|
+
},
|
|
88
|
+
ru: {
|
|
89
|
+
notContinuedTitle: 'dsh-auto-continue: продолжение не выполнено',
|
|
90
|
+
permanentErrorBody: (sessionId: SessionId, summary: string) =>
|
|
91
|
+
`${sessionId}: постоянная ошибка ${summary}; нужно вмешательство вручную`,
|
|
92
|
+
resumeAction: 'Продолжить сейчас',
|
|
93
|
+
pauseAction: 'Приостановить сессию на 1 час',
|
|
94
|
+
continuedTitle: 'dsh-auto-continue: продолжено автоматически',
|
|
95
|
+
continuedBody: (sessionId: SessionId, text: string, count: number) =>
|
|
96
|
+
`${sessionId}: отправлено «${text}» (попытка подряд: ${count})`,
|
|
97
|
+
stoppedTitle: 'dsh-auto-continue: авто-продолжение остановлено',
|
|
98
|
+
stoppedBody: (sessionId: SessionId, count: number) =>
|
|
99
|
+
`${sessionId}: сбоев подряд: ${count}; нужно вмешательство вручную`,
|
|
100
|
+
loopCapTitle: 'dsh-auto-continue: достигнут лимит автономного цикла',
|
|
101
|
+
loopCapBody: (sessionId: SessionId, count: number) =>
|
|
102
|
+
`${sessionId}: остановлено после ${count} автономных раундов; отправьте сообщение или включите цикл снова, чтобы продолжить`,
|
|
76
103
|
},
|
|
77
104
|
} as const satisfies Record<AutoContinueLocale, Record<string, unknown>>;
|
|
78
105
|
|
|
@@ -102,6 +129,82 @@ const STORED_READ_TIMEOUT_MS = 5000;
|
|
|
102
129
|
/** 单个存储会话连续观察/物化失败达此数后放弃, 避免坏日志反复占满每轮观察配额。 */
|
|
103
130
|
const SWEEP_MAX_FAILURES = 3;
|
|
104
131
|
|
|
132
|
+
/** Why a child session needs its root session woken after a restart. */
|
|
133
|
+
type ChildInterruptCause = 'open-turn' | 'disposed' | 'interrupted' | 'max-tokens' | 'error';
|
|
134
|
+
|
|
135
|
+
/** One interrupted child session, grouped under the root session that owns it. */
|
|
136
|
+
interface ChildInterrupt {
|
|
137
|
+
readonly id: SessionId;
|
|
138
|
+
readonly title: string | undefined;
|
|
139
|
+
readonly preset: string | undefined;
|
|
140
|
+
readonly cause: ChildInterruptCause;
|
|
141
|
+
readonly at: number;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** A header-shaped record good enough to resolve a parent chain. */
|
|
145
|
+
interface SessionHeaderLike {
|
|
146
|
+
readonly id: SessionId;
|
|
147
|
+
readonly parentSession?: SessionId;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Cancel causes a host shutdown or a restart produces; only these justify a wake-up. */
|
|
151
|
+
const RESTART_CANCEL_CAUSES: ReadonlySet<string> = new Set(['disposed', 'legacy']);
|
|
152
|
+
/** Cancel causes that record an explicit human or parent decision; never recover these. */
|
|
153
|
+
const DECISION_CANCEL_CAUSES: ReadonlySet<string> = new Set(['user', 'parent', 'hook']);
|
|
154
|
+
/** Bound child observations per sweep round: child logs are as large as root logs. */
|
|
155
|
+
const CHILD_SWEEP_LIMIT = 8;
|
|
156
|
+
/** Bound how many ancestor hops a dirty parent chain may cost before giving up. */
|
|
157
|
+
const CHILD_ROOT_MAX_DEPTH = 8;
|
|
158
|
+
|
|
159
|
+
/** Host service key for goals (0.2.x); older hosts simply do not register it. */
|
|
160
|
+
const GOALS_SERVICE_KEY = 'goals';
|
|
161
|
+
|
|
162
|
+
/** Copy for each child interruption cause, keyed by UI locale. */
|
|
163
|
+
const CHILD_CAUSE_COPY = {
|
|
164
|
+
zh: {
|
|
165
|
+
'open-turn': '回合开始后中断',
|
|
166
|
+
disposed: '宿主销毁',
|
|
167
|
+
interrupted: '崩溃恢复标记',
|
|
168
|
+
'max-tokens': '输出长度耗尽',
|
|
169
|
+
error: '可重试错误',
|
|
170
|
+
},
|
|
171
|
+
en: {
|
|
172
|
+
'open-turn': 'turn cut off after start',
|
|
173
|
+
disposed: 'host disposed the agent',
|
|
174
|
+
interrupted: 'closed by crash recovery',
|
|
175
|
+
'max-tokens': 'output ceiling reached',
|
|
176
|
+
error: 'retryable error',
|
|
177
|
+
},
|
|
178
|
+
ru: {
|
|
179
|
+
'open-turn': 'ход прерван после начала',
|
|
180
|
+
disposed: 'хост уничтожил агента',
|
|
181
|
+
interrupted: 'закрыт восстановлением после сбоя',
|
|
182
|
+
'max-tokens': 'достигнут лимит вывода',
|
|
183
|
+
error: 'повторяемая ошибка',
|
|
184
|
+
},
|
|
185
|
+
} as const satisfies Record<AutoContinueLocale, Record<ChildInterruptCause, string>>;
|
|
186
|
+
|
|
187
|
+
/** Structural view of `ctx.goals`; declared locally because devDeps target an older host. */
|
|
188
|
+
interface GoalRefLike {
|
|
189
|
+
readonly id: string;
|
|
190
|
+
/** Mutations are CAS-checked against this revision; omitting it raises GOAL_STALE_REVISION. */
|
|
191
|
+
readonly revision: number;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
interface GoalViewLike {
|
|
195
|
+
readonly id: string;
|
|
196
|
+
/** The host's `view()` exposes no `ref`; callers build `{ id, revision }` from the view. */
|
|
197
|
+
readonly ref?: GoalRefLike;
|
|
198
|
+
readonly phase?: string;
|
|
199
|
+
readonly activation?: string;
|
|
200
|
+
readonly revision?: number;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
interface GoalServiceLike {
|
|
204
|
+
get(agent: Agent): GoalViewLike | undefined;
|
|
205
|
+
resume(agent: Agent, ref: GoalRefLike): unknown;
|
|
206
|
+
}
|
|
207
|
+
|
|
105
208
|
/**
|
|
106
209
|
* 存储扫描消费的宿主服务结构类型。这些服务(sessionQuery 等)随 dsh
|
|
107
210
|
* 版本整组演进, 直接引类型包会拖动 devDependency 时代; 按消费面声明,
|
|
@@ -214,6 +317,86 @@ function readReasonKind(value: unknown): string | undefined {
|
|
|
214
317
|
return typeof kind === 'string' && kind.trim() !== '' ? kind : undefined;
|
|
215
318
|
}
|
|
216
319
|
|
|
320
|
+
/** Read the nested cancel cause of an `aborted` turn/end (`reason.reason.kind`). */
|
|
321
|
+
function readCancelCause(value: unknown): string | undefined {
|
|
322
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;
|
|
323
|
+
const reason = value as { kind?: unknown; reason?: unknown };
|
|
324
|
+
if (reason.kind !== 'aborted') return undefined;
|
|
325
|
+
return readReasonKind(reason.reason);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** Whether the host closed an `aborted` turn (restart, reload, teardown) rather than the user. */
|
|
329
|
+
function isHostCancel(value: unknown): boolean {
|
|
330
|
+
const cause = readCancelCause(value);
|
|
331
|
+
return cause !== undefined && RESTART_CANCEL_CAUSES.has(cause);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Decide whether a child session's tail is a restart interruption worth waking
|
|
336
|
+
* its root session for. Returns `undefined` when the child finished normally,
|
|
337
|
+
* was stopped by a human or by its parent, or was superseded by a later user
|
|
338
|
+
* message — i.e. whenever a wake-up would be a ghost turn.
|
|
339
|
+
*/
|
|
340
|
+
function classifyChildInterruption(
|
|
341
|
+
events: readonly SessionEvent[],
|
|
342
|
+
config: AutoContinueConfig,
|
|
343
|
+
): ChildInterruptCause | undefined {
|
|
344
|
+
let lastEnd: SessionEvent<'turn/end'> | undefined;
|
|
345
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
346
|
+
const event = events[i];
|
|
347
|
+
if (event?.type === 'turn/end') { lastEnd = event; break; }
|
|
348
|
+
}
|
|
349
|
+
const lastStart = latestTurnStart(events);
|
|
350
|
+
if (lastStart !== undefined && (lastEnd === undefined || lastStart.seq > lastEnd.seq)) {
|
|
351
|
+
if (isMaintenanceTurnStart(lastStart)) return undefined;
|
|
352
|
+
// 与主扫描同口径: 过了 freshMs 的中断不是这次重启造成的, 唤醒只会复活陈年父会话。
|
|
353
|
+
if ((events[events.length - 1]?.time ?? 0) < Date.now() - config.freshMs) return undefined;
|
|
354
|
+
return 'open-turn';
|
|
355
|
+
}
|
|
356
|
+
const end = lastEnd;
|
|
357
|
+
if (end === undefined) return undefined;
|
|
358
|
+
if (end.time < Date.now() - config.freshMs) return undefined;
|
|
359
|
+
// A message written after the closing turn means someone already took over.
|
|
360
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
361
|
+
const event = events[i];
|
|
362
|
+
if (event === undefined || event.seq <= end.seq) break;
|
|
363
|
+
if (event.type === 'user/message') return undefined;
|
|
364
|
+
}
|
|
365
|
+
const reason = end.data.reason;
|
|
366
|
+
const kind = readReasonKind(reason);
|
|
367
|
+
if (kind === undefined) return undefined;
|
|
368
|
+
if (kind === 'aborted') {
|
|
369
|
+
const cause = readCancelCause(reason);
|
|
370
|
+
if (cause === undefined || DECISION_CANCEL_CAUSES.has(cause)) return undefined;
|
|
371
|
+
return RESTART_CANCEL_CAUSES.has(cause) ? 'disposed' : undefined;
|
|
372
|
+
}
|
|
373
|
+
if (kind === 'interrupted') return 'interrupted';
|
|
374
|
+
if (kind === 'max-tokens') return 'max-tokens';
|
|
375
|
+
if (kind === 'error') {
|
|
376
|
+
const failure = parseFailureFacts((reason as { error?: unknown }).error);
|
|
377
|
+
if (failure === undefined) return undefined;
|
|
378
|
+
if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) return undefined;
|
|
379
|
+
return 'error';
|
|
380
|
+
}
|
|
381
|
+
return undefined;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** Walk `parentSession` up to a root session; `undefined` when the chain is dirty. */
|
|
385
|
+
function resolveRootHeader(
|
|
386
|
+
header: SessionHeaderLike,
|
|
387
|
+
byId: ReadonlyMap<string, SessionHeaderLike>,
|
|
388
|
+
): SessionId | undefined {
|
|
389
|
+
let current: SessionHeaderLike = header;
|
|
390
|
+
for (let depth = 0; depth <= CHILD_ROOT_MAX_DEPTH; depth += 1) {
|
|
391
|
+
const parentId = current.parentSession;
|
|
392
|
+
if (parentId === undefined || parentId === '') return current.id;
|
|
393
|
+
const parent = byId.get(parentId);
|
|
394
|
+
if (parent === undefined) return undefined;
|
|
395
|
+
current = parent;
|
|
396
|
+
}
|
|
397
|
+
return undefined;
|
|
398
|
+
}
|
|
399
|
+
|
|
217
400
|
function isLoopGuardCancelReason(value: unknown): boolean {
|
|
218
401
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
|
|
219
402
|
const cause = value as { kind?: unknown; reason?: unknown };
|
|
@@ -260,8 +443,15 @@ async function pumpStream<T>(
|
|
|
260
443
|
}
|
|
261
444
|
|
|
262
445
|
/** 插件主体: 一条 mux 流 + 一条 host 流 + 启动/重连扫描。 */
|
|
446
|
+
/** Soft cap on cached subagent lineage entries before stale ones are pruned. */
|
|
447
|
+
const LINEAGE_CACHE_LIMIT = 2000;
|
|
448
|
+
|
|
263
449
|
export class AutoContinueRunner {
|
|
264
450
|
private readonly states = new Map<SessionId, SessionState>();
|
|
451
|
+
/** Cached subagent lineage: session id -> direct parent id (undefined when the header has none). */
|
|
452
|
+
private readonly parents = new Map<SessionId, SessionId | undefined>();
|
|
453
|
+
/** Sessions already identified as subagents, including event views without header metadata. */
|
|
454
|
+
private readonly subagentSessions = new Set<SessionId>();
|
|
265
455
|
private readonly pauseUntil = new Map<SessionId, number>();
|
|
266
456
|
private dayStats: DayStats = emptyDayStats();
|
|
267
457
|
private readonly recoveryAttempts: RecoveryAttempt[] = [];
|
|
@@ -277,6 +467,16 @@ export class AutoContinueRunner {
|
|
|
277
467
|
private readonly bootScanErrors = new WeakSet<object>();
|
|
278
468
|
/** 存储扫描已裁决的会话 id, 避免每轮重复冷读大日志。 */
|
|
279
469
|
private readonly storedSwept = new Set<SessionId>();
|
|
470
|
+
/** 子会话裁决独立记账: storedSwept 在 origin 判断之前就已标记, 不能复用。 */
|
|
471
|
+
private readonly childSwept = new Set<SessionId>();
|
|
472
|
+
/** 本轮已花掉的子会话观察配额(每轮重置, 子会话日志与主会话同等昂贵)。 */
|
|
473
|
+
private childScanned = 0;
|
|
474
|
+
/** 本轮收集到的子会话中断, 按 root 主会话 id 归组。 */
|
|
475
|
+
private readonly childInterrupts = new Map<SessionId, ChildInterrupt[]>();
|
|
476
|
+
/** 已唤醒过的 root 会话 → 上次唤醒覆盖的子会话签名, 防止每轮重复催同一批。 */
|
|
477
|
+
private readonly childWoken = new Map<SessionId, string>();
|
|
478
|
+
/** 已打印过「父链不可解析」的子会话, 避免 15 分钟扫描窗口内每轮重扫把日志刷爆。 */
|
|
479
|
+
private readonly childDirtyLogged = new Set<SessionId>();
|
|
280
480
|
/** 存储会话的连续观察/物化失败次数, 触达 SWEEP_MAX_FAILURES 后不再重试。 */
|
|
281
481
|
private readonly storedSweepFailures = new Map<SessionId, number>();
|
|
282
482
|
private storedSweepAnnounced = false;
|
|
@@ -284,6 +484,8 @@ export class AutoContinueRunner {
|
|
|
284
484
|
private wakeBootScan: (() => void) | undefined;
|
|
285
485
|
private storedSweep: Promise<void> | undefined;
|
|
286
486
|
private readonly stopStoredSweep = new AbortController();
|
|
487
|
+
/** 并发的断网挂起共用同一次连通性检测。 */
|
|
488
|
+
private connectivityCheck: Promise<boolean> | undefined;
|
|
287
489
|
|
|
288
490
|
/**
|
|
289
491
|
* @param ctx - host plugin context (agents registry, session events).
|
|
@@ -292,6 +494,7 @@ export class AutoContinueRunner {
|
|
|
292
494
|
constructor(
|
|
293
495
|
private readonly ctx: Context,
|
|
294
496
|
private readonly getConfig: () => AutoContinueConfig,
|
|
497
|
+
private readonly probe: ConnectivityProbe = probeConnectivity,
|
|
295
498
|
) {
|
|
296
499
|
// 单实例事件源: 宿主进程内的会话事件 firehose, 天然覆盖所有会话。
|
|
297
500
|
this.disposeSessionEvents = ctx.on('session/event', (session, event) => {
|
|
@@ -341,7 +544,7 @@ export class AutoContinueRunner {
|
|
|
341
544
|
void this.bootScanLoop();
|
|
342
545
|
}
|
|
343
546
|
this.log(
|
|
344
|
-
`已启动(
|
|
547
|
+
`已启动(文本="${config.continueText}", 宽限 ${config.graceMs}ms, ` +
|
|
345
548
|
`冷却 ${config.cooldownMs}ms, 最多连续 ${config.maxConsecutive} 次)`,
|
|
346
549
|
);
|
|
347
550
|
}
|
|
@@ -392,6 +595,29 @@ export class AutoContinueRunner {
|
|
|
392
595
|
}
|
|
393
596
|
|
|
394
597
|
private sessionConfig(sessionId: SessionId): AutoContinueConfig {
|
|
598
|
+
const config = this.getConfig();
|
|
599
|
+
if (this.isSubagentSession(sessionId)) {
|
|
600
|
+
// A subagent inherits only the enabled/off decision of its main
|
|
601
|
+
// conversation (an explicit mode stored for the child wins). It never runs
|
|
602
|
+
// the autonomous loop or the loop guard, and the startup scan keeps leaving
|
|
603
|
+
// it to its parent: those three stay parent-only.
|
|
604
|
+
const enabled = this.subagentRecoveryEnabled(sessionId);
|
|
605
|
+
return {
|
|
606
|
+
...config,
|
|
607
|
+
paused: config.paused || !enabled,
|
|
608
|
+
resumeCompletedTurns: false,
|
|
609
|
+
loopGuard: false,
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
return this.ownSessionConfig(sessionId);
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* The session's own mode, ignoring subagent inheritance. The stored-session
|
|
617
|
+
* sweep and the restart hand-off (`resumeInterruptedChildren`) use this, so
|
|
618
|
+
* turning live subagent recovery off never silently disables them.
|
|
619
|
+
*/
|
|
620
|
+
private ownSessionConfig(sessionId: SessionId): AutoContinueConfig {
|
|
395
621
|
const config = this.getConfig();
|
|
396
622
|
const mode = sessionMode(config.sessionModes, sessionId);
|
|
397
623
|
return {
|
|
@@ -406,6 +632,9 @@ export class AutoContinueRunner {
|
|
|
406
632
|
if (this.disposed) return;
|
|
407
633
|
for (const [sessionId, state] of this.states) {
|
|
408
634
|
const config = this.sessionConfig(sessionId);
|
|
635
|
+
// 循环由关到开视为一次新的授权: 轮数上限重新计数。
|
|
636
|
+
if (config.resumeCompletedTurns && state.loopEnabled === false) this.resetLoopIterations(state);
|
|
637
|
+
state.loopEnabled = config.resumeCompletedTurns;
|
|
409
638
|
if (config.paused || (isLoopReason(state.pendingReason ?? '') && !config.resumeCompletedTurns)) {
|
|
410
639
|
this.cancelPending(sessionId, '会话模式或全局设置已更改');
|
|
411
640
|
}
|
|
@@ -447,8 +676,12 @@ export class AutoContinueRunner {
|
|
|
447
676
|
if (state.pendingTimer !== undefined) clearTimeout(state.pendingTimer);
|
|
448
677
|
if (state.loopRetryTimer !== undefined) clearTimeout(state.loopRetryTimer);
|
|
449
678
|
if (state.cooldownRetryTimer !== undefined) clearTimeout(state.cooldownRetryTimer);
|
|
679
|
+
if (state.offlineTimer !== undefined) clearTimeout(state.offlineTimer);
|
|
680
|
+
state.offlineWait = undefined;
|
|
450
681
|
}
|
|
451
682
|
this.states.clear();
|
|
683
|
+
this.parents.clear();
|
|
684
|
+
this.subagentSessions.clear();
|
|
452
685
|
}
|
|
453
686
|
|
|
454
687
|
private state(sessionId: SessionId): SessionState {
|
|
@@ -460,21 +693,184 @@ export class AutoContinueRunner {
|
|
|
460
693
|
return state;
|
|
461
694
|
}
|
|
462
695
|
|
|
463
|
-
/**
|
|
464
|
-
private
|
|
465
|
-
|
|
466
|
-
|
|
696
|
+
/** Record a subagent session's lineage and its parent id when the header carries one. */
|
|
697
|
+
private noteSubagent(sessionId: SessionId, parentSession?: SessionId): void {
|
|
698
|
+
this.subagentSessions.add(sessionId);
|
|
699
|
+
if (parentSession !== undefined && parentSession !== '') {
|
|
700
|
+
this.parents.set(sessionId, parentSession);
|
|
701
|
+
} else if (!this.parents.has(sessionId)) {
|
|
702
|
+
this.parents.set(sessionId, undefined);
|
|
703
|
+
}
|
|
467
704
|
}
|
|
468
705
|
|
|
469
706
|
/** Read durable origin from the live agent for direct action paths as well. */
|
|
470
707
|
private isSubagent(sessionId: SessionId, state: SessionState): boolean {
|
|
471
708
|
if (state.subagent) return true;
|
|
472
|
-
const
|
|
473
|
-
if (
|
|
474
|
-
|
|
709
|
+
const header = this.ctx.agents.get(sessionId)?.session?.header;
|
|
710
|
+
if (header?.origin !== 'subagent') return false;
|
|
711
|
+
state.subagent = true;
|
|
712
|
+
this.noteSubagent(sessionId, header.parentSession);
|
|
475
713
|
return true;
|
|
476
714
|
}
|
|
477
715
|
|
|
716
|
+
/** Header origin, cached set or state flag; for paths that only have the session id. */
|
|
717
|
+
private isSubagentSession(sessionId: SessionId): boolean {
|
|
718
|
+
if (this.subagentSessions.has(sessionId)) return true;
|
|
719
|
+
const state = this.states.get(sessionId);
|
|
720
|
+
if (state?.subagent === true) return true;
|
|
721
|
+
const header = this.ctx.agents.get(sessionId)?.session?.header;
|
|
722
|
+
if (header?.origin !== 'subagent') return false;
|
|
723
|
+
this.noteSubagent(sessionId, header.parentSession);
|
|
724
|
+
return true;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/**
|
|
728
|
+
* Direct subagent parent id. DSH stores fork lineage in the same
|
|
729
|
+
* `header.parentSession` field, so only a session whose header origin is
|
|
730
|
+
* `subagent` may be followed upward: an ordinary ancestor (the visible main
|
|
731
|
+
* conversation, even a forked one) is the top of the recovery lineage.
|
|
732
|
+
*/
|
|
733
|
+
private parentOf(sessionId: SessionId): SessionId | undefined {
|
|
734
|
+
if (this.parents.has(sessionId)) return this.parents.get(sessionId);
|
|
735
|
+
const header = this.ctx.agents.get(sessionId)?.session?.header;
|
|
736
|
+
// No live header yet: leave the lineage unresolved so a later live agent
|
|
737
|
+
// with the same id can still provide it instead of caching "no parent".
|
|
738
|
+
if (header === undefined) return undefined;
|
|
739
|
+
if (header.origin !== 'subagent') {
|
|
740
|
+
this.parents.set(sessionId, undefined); // known ordinary: top of the lineage
|
|
741
|
+
return undefined;
|
|
742
|
+
}
|
|
743
|
+
const parent = header.parentSession;
|
|
744
|
+
this.noteSubagent(sessionId, parent);
|
|
745
|
+
return parent;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/** Explicit session mode stored for this exact id, if the user gave one. */
|
|
749
|
+
private explicitMode(sessionId: SessionId): SessionMode | undefined {
|
|
750
|
+
const modes = this.getConfig().sessionModes;
|
|
751
|
+
const mode = modes[sessionId];
|
|
752
|
+
return Object.prototype.hasOwnProperty.call(modes, sessionId) && isSessionMode(mode) ? mode : undefined;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
/**
|
|
756
|
+
* A subagent's effective mode, or `undefined` when the lineage cannot be
|
|
757
|
+
* verified. An intermediate parent that is no longer live (and was never seen
|
|
758
|
+
* here) used to stop the walk early, fall back to the profile default and
|
|
759
|
+
* resume a child whose main conversation is Off; refusing the send is safe.
|
|
760
|
+
*/
|
|
761
|
+
private resolveSubagentMode(sessionId: SessionId): SessionMode | undefined {
|
|
762
|
+
const own = this.explicitMode(sessionId);
|
|
763
|
+
if (own !== undefined) return own;
|
|
764
|
+
const seen = new Set<SessionId>([sessionId]);
|
|
765
|
+
let current: SessionId = sessionId;
|
|
766
|
+
for (let depth = 0; depth < 32; depth += 1) {
|
|
767
|
+
const known = this.parents.has(current);
|
|
768
|
+
const header = this.ctx.agents.get(current)?.session?.header;
|
|
769
|
+
// The chain is not visible yet (an intermediate parent never live here), so
|
|
770
|
+
// neither its mode nor its pause can be verified. Refuse the send and
|
|
771
|
+
// re-resolve on the next event once that ancestor appears.
|
|
772
|
+
if (!known && header === undefined) return undefined;
|
|
773
|
+
const parent = known
|
|
774
|
+
? this.parents.get(current)
|
|
775
|
+
: header?.origin === 'subagent' ? header.parentSession : undefined;
|
|
776
|
+
if (parent === undefined || parent === '') {
|
|
777
|
+
// A subagent without `parentSession` is unlinked: nothing to inherit. Check the
|
|
778
|
+
// cached flag too, so this still holds once the child's header is gone.
|
|
779
|
+
if (header?.origin === 'subagent' || this.subagentSessions.has(current)) return undefined;
|
|
780
|
+
return this.explicitMode(current) ?? 'default';
|
|
781
|
+
}
|
|
782
|
+
if (seen.has(parent)) return undefined;
|
|
783
|
+
seen.add(parent);
|
|
784
|
+
current = parent;
|
|
785
|
+
}
|
|
786
|
+
return undefined;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/** Whether the setting and the inherited main-chat mode allow live recovery for this child. */
|
|
790
|
+
private subagentRecoveryEnabled(sessionId: SessionId): boolean {
|
|
791
|
+
if (!this.getConfig().resumeSubagentSessions) return false;
|
|
792
|
+
const mode = this.resolveSubagentMode(sessionId);
|
|
793
|
+
return mode !== undefined && mode !== 'off';
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/** Modes children inherit from their main conversation, for the composer's display. */
|
|
797
|
+
inheritedSubagentModes(): Record<string, SessionMode> {
|
|
798
|
+
this.pruneLineage();
|
|
799
|
+
const inherited: Record<string, SessionMode> = {};
|
|
800
|
+
for (const sessionId of this.parents.keys()) {
|
|
801
|
+
// Only children that are still loaded can show a composer; skip the rest.
|
|
802
|
+
if (this.ctx.agents.get(sessionId) === undefined) continue;
|
|
803
|
+
if (!this.isSubagentSession(sessionId)) continue;
|
|
804
|
+
if (this.explicitMode(sessionId) !== undefined) continue;
|
|
805
|
+
const mode = this.resolveSubagentMode(sessionId);
|
|
806
|
+
// Children never run the autonomous loop, so a loop parent means recovery for them.
|
|
807
|
+
if (mode !== undefined) inherited[sessionId] = mode === 'loop' ? 'recover' : mode;
|
|
808
|
+
}
|
|
809
|
+
return inherited;
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/**
|
|
813
|
+
* Keep the lineage caches bounded on long-lived hosts. Once the cache grows,
|
|
814
|
+
* entries for sessions that are no longer loaded are dropped; they are re-read
|
|
815
|
+
* from the live header if the session comes back.
|
|
816
|
+
*/
|
|
817
|
+
private pruneLineage(): void {
|
|
818
|
+
if (this.parents.size + this.subagentSessions.size <= LINEAGE_CACHE_LIMIT) return;
|
|
819
|
+
// `states` keeps its own `subagent` flag, so dropping a non-loaded child here loses nothing.
|
|
820
|
+
const keep = (sessionId: SessionId) => this.ctx.agents.get(sessionId) !== undefined;
|
|
821
|
+
const needed = new Set<SessionId>();
|
|
822
|
+
for (const sessionId of this.parents.keys()) {
|
|
823
|
+
if (!keep(sessionId)) continue;
|
|
824
|
+
// Keep the chain above a loaded child so its inherited mode still resolves.
|
|
825
|
+
let current: SessionId | undefined = sessionId;
|
|
826
|
+
for (let depth = 0; depth < 32 && current !== undefined && !needed.has(current); depth += 1) {
|
|
827
|
+
needed.add(current);
|
|
828
|
+
current = this.parents.get(current);
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
for (const sessionId of [...this.parents.keys()]) if (!needed.has(sessionId)) this.parents.delete(sessionId);
|
|
832
|
+
for (const sessionId of [...this.subagentSessions]) if (!needed.has(sessionId) && !keep(sessionId)) this.subagentSessions.delete(sessionId);
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
/** Mark a child session; drop only queued sends that its effective policy no longer allows. */
|
|
836
|
+
private markSubagent(sessionId: SessionId, state: SessionState, parentSession?: SessionId): void {
|
|
837
|
+
const first = !state.subagent;
|
|
838
|
+
state.subagent = true;
|
|
839
|
+
this.noteSubagent(sessionId, parentSession);
|
|
840
|
+
if (first && !this.subagentRecoveryEnabled(sessionId)) this.cancelPending(sessionId, '子代理会话');
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/** Pause deadline, including the parents' "pause this session 1h" for subagents. */
|
|
844
|
+
private effectivePauseUntil(sessionId: SessionId): number {
|
|
845
|
+
let until = this.pauseUntil.get(sessionId) ?? 0;
|
|
846
|
+
if (!this.isSubagentSession(sessionId)) return until;
|
|
847
|
+
// parentOf() only follows subagent-origin sessions, so fork lineage of the
|
|
848
|
+
// main conversation is never treated as a parent for pause purposes.
|
|
849
|
+
const seen = new Set<SessionId>([sessionId]);
|
|
850
|
+
let current: SessionId | undefined = sessionId;
|
|
851
|
+
for (let depth = 0; depth < 32; depth += 1) {
|
|
852
|
+
current = this.parentOf(current);
|
|
853
|
+
if (current === undefined || current === '' || seen.has(current)) break;
|
|
854
|
+
seen.add(current);
|
|
855
|
+
until = Math.max(until, this.pauseUntil.get(current) ?? 0);
|
|
856
|
+
}
|
|
857
|
+
return until;
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/** Whether this session sits below `ancestorId` in the subagent lineage (never fork lineage). */
|
|
861
|
+
private isDescendantOf(sessionId: SessionId, ancestorId: SessionId): boolean {
|
|
862
|
+
const seen = new Set<SessionId>([sessionId]);
|
|
863
|
+
let current: SessionId | undefined = sessionId;
|
|
864
|
+
for (let depth = 0; depth < 32; depth += 1) {
|
|
865
|
+
current = this.parentOf(current);
|
|
866
|
+
if (current === undefined || current === '') return false;
|
|
867
|
+
if (current === ancestorId) return true;
|
|
868
|
+
if (seen.has(current)) return false;
|
|
869
|
+
seen.add(current);
|
|
870
|
+
}
|
|
871
|
+
return false;
|
|
872
|
+
}
|
|
873
|
+
|
|
478
874
|
/**
|
|
479
875
|
* 事件入口(host 单实例): 预处理工具调用/结果/模型消息(护栏与循环信号),
|
|
480
876
|
* 然后交给回合状态机。
|
|
@@ -483,10 +879,12 @@ export class AutoContinueRunner {
|
|
|
483
879
|
const sessionId = session.id;
|
|
484
880
|
const sessionState = this.states.get(sessionId);
|
|
485
881
|
if (session.header?.origin === 'subagent') {
|
|
486
|
-
this.markSubagent(sessionId, sessionState ?? this.state(sessionId));
|
|
487
|
-
|
|
882
|
+
this.markSubagent(sessionId, sessionState ?? this.state(sessionId), session.header.parentSession);
|
|
883
|
+
} else if (sessionState?.subagent) {
|
|
884
|
+
// Origin known from an earlier frame; keep the lineage fresh and process the
|
|
885
|
+
// event normally instead of ignoring a subagent's live turn.
|
|
886
|
+
this.noteSubagent(sessionId, session.header?.parentSession ?? this.parentOf(sessionId));
|
|
488
887
|
}
|
|
489
|
-
if (sessionState?.subagent) return;
|
|
490
888
|
if (sessionState?.maintenanceTurn !== undefined &&
|
|
491
889
|
sessionState.maintenanceTurn === (event.data as { turn?: number }).turn &&
|
|
492
890
|
event.type !== 'turn/start' && event.type !== 'turn/end') return;
|
|
@@ -913,6 +1311,7 @@ export class AutoContinueRunner {
|
|
|
913
1311
|
if (event.data.source.kind === 'user') {
|
|
914
1312
|
// 用户手动介入: 清零上限与跨标签页发送计数
|
|
915
1313
|
state.consecutive = 0;
|
|
1314
|
+
this.resetLoopIterations(state);
|
|
916
1315
|
this.cancelPending(sessionId, '用户手动发送消息');
|
|
917
1316
|
}
|
|
918
1317
|
break;
|
|
@@ -925,7 +1324,13 @@ export class AutoContinueRunner {
|
|
|
925
1324
|
|
|
926
1325
|
private onTurnFailure(sessionId: SessionId, reason: string, failure: FailureFacts): void {
|
|
927
1326
|
const config = this.getConfig();
|
|
928
|
-
if (
|
|
1327
|
+
if (this.isSubagentSession(sessionId)) {
|
|
1328
|
+
// Subagents inherit only the main conversation's enabled/off decision; an
|
|
1329
|
+
// Off parent or the disabled setting means no live recovery at all. The
|
|
1330
|
+
// global pause is not checked here, so diagnostics for permanent errors
|
|
1331
|
+
// match ordinary sessions while paused.
|
|
1332
|
+
if (!this.subagentRecoveryEnabled(sessionId)) return;
|
|
1333
|
+
} else if (sessionMode(config.sessionModes, sessionId) === 'off') return;
|
|
929
1334
|
if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
|
|
930
1335
|
const copy = NOTICE_COPY[config.locale];
|
|
931
1336
|
const summary = `${failure.code}${failure.status !== undefined ? ` (HTTP ${failure.status})` : ''}`;
|
|
@@ -965,6 +1370,12 @@ export class AutoContinueRunner {
|
|
|
965
1370
|
this.log(`通知按钮: 暂停 ${sessionId} 1 小时`);
|
|
966
1371
|
this.pauseUntil.set(sessionId, Date.now() + 60 * 60 * 1000);
|
|
967
1372
|
this.cancelPending(sessionId, '通知按钮暂停该会话');
|
|
1373
|
+
// A paused main conversation also suspends the subagents it owns.
|
|
1374
|
+
for (const candidate of this.states.keys()) {
|
|
1375
|
+
if (candidate !== sessionId && this.isDescendantOf(candidate, sessionId)) {
|
|
1376
|
+
this.cancelPending(candidate, '父会话已暂停');
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
968
1379
|
}
|
|
969
1380
|
}
|
|
970
1381
|
|
|
@@ -1034,12 +1445,13 @@ export class AutoContinueRunner {
|
|
|
1034
1445
|
/** 立即为该会话发送一次自动继续(无视冷却与连续上限; 由通知按钮触发)。 */
|
|
1035
1446
|
async resumeNow(sessionId: SessionId): Promise<void> {
|
|
1036
1447
|
if (this.disposed) return;
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1448
|
+
// Subagent recovery is opt-out and inherits the main conversation's mode: an
|
|
1449
|
+
// Off child must not receive a send through the explicit button either, even
|
|
1450
|
+
// though a manual send bypasses the paused flag.
|
|
1451
|
+
if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) return;
|
|
1452
|
+
// A manual send replaces every queued one: leave a pending cooldown or
|
|
1453
|
+
// offline retry armed and the reader receives the continuation twice.
|
|
1454
|
+
this.cancelPending(sessionId, '手动续跑');
|
|
1043
1455
|
try {
|
|
1044
1456
|
await this.fire(sessionId, MANUAL_NOTIFICATION_REASON, true);
|
|
1045
1457
|
} catch (error) {
|
|
@@ -1062,16 +1474,17 @@ export class AutoContinueRunner {
|
|
|
1062
1474
|
const state = this.state(sessionId);
|
|
1063
1475
|
const config = this.sessionConfig(sessionId);
|
|
1064
1476
|
if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
|
|
1065
|
-
if (this.isSubagent(sessionId, state)) return; // 子代理会话由父代理处理, 不抢跑
|
|
1066
1477
|
if (config.paused) {
|
|
1067
1478
|
this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
|
|
1068
1479
|
return;
|
|
1069
1480
|
}
|
|
1070
|
-
if (Date.now() <
|
|
1481
|
+
if (Date.now() < this.effectivePauseUntil(sessionId)) {
|
|
1071
1482
|
this.log(`跳过 ${sessionId}(${reason}): 会话暂停中`);
|
|
1072
1483
|
return;
|
|
1073
1484
|
}
|
|
1074
1485
|
if (state.pendingTimer !== undefined) return; // 已有待发送
|
|
1486
|
+
if (state.offlineWait !== undefined || state.offlineTimer !== undefined) return; // 断网挂起中, 恢复后自会续跑
|
|
1487
|
+
if (isLoopReason(reason) && this.loopCapReached(sessionId, state, config)) return;
|
|
1075
1488
|
// 连续上限优先于冷却: 已经放弃的会话不该再安排冷却后的重试。
|
|
1076
1489
|
// 自主循环的完成续跑(force)不受二者约束。
|
|
1077
1490
|
if (!force && state.consecutive >= config.maxConsecutive) {
|
|
@@ -1095,7 +1508,7 @@ export class AutoContinueRunner {
|
|
|
1095
1508
|
state.pendingReason = undefined;
|
|
1096
1509
|
// 保险丝: 定时器回调内任何异常(含 inactive context)都不得成为未捕获异常炸掉进程。
|
|
1097
1510
|
try {
|
|
1098
|
-
|
|
1511
|
+
this.fireWhenOnline(sessionId, reason, force);
|
|
1099
1512
|
} catch (error) {
|
|
1100
1513
|
console.error(`[auto-continue] 定时发送异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1101
1514
|
}
|
|
@@ -1159,6 +1572,13 @@ export class AutoContinueRunner {
|
|
|
1159
1572
|
state.loopRetryTimer = undefined;
|
|
1160
1573
|
cancelled = true;
|
|
1161
1574
|
}
|
|
1575
|
+
if (state.offlineWait !== undefined || state.offlineTimer !== undefined) {
|
|
1576
|
+
if (state.offlineTimer !== undefined) clearTimeout(state.offlineTimer);
|
|
1577
|
+
state.offlineTimer = undefined;
|
|
1578
|
+
state.offlineWait = undefined;
|
|
1579
|
+
state.offlineSince = 0;
|
|
1580
|
+
cancelled = true;
|
|
1581
|
+
}
|
|
1162
1582
|
if (cancelled) this.log(`取消 ${sessionId} 的自动继续(${why})`);
|
|
1163
1583
|
}
|
|
1164
1584
|
|
|
@@ -1171,12 +1591,14 @@ export class AutoContinueRunner {
|
|
|
1171
1591
|
// 宽限期内循环被关闭: 发送前必须重新检查开关, 与 :silent 恢复同样处理。
|
|
1172
1592
|
// 否则「关掉循环」后仍会多发出一次续跑。
|
|
1173
1593
|
if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
|
|
1174
|
-
|
|
1594
|
+
// Direct sends (notifications) must respect the setting and the inherited
|
|
1595
|
+
// mode even though they bypass the paused flag below.
|
|
1596
|
+
if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) return;
|
|
1175
1597
|
if (config.paused && !manualResume) {
|
|
1176
1598
|
this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
|
|
1177
1599
|
return;
|
|
1178
1600
|
}
|
|
1179
|
-
if (!manualResume && Date.now() <
|
|
1601
|
+
if (!manualResume && Date.now() < this.effectivePauseUntil(sessionId)) {
|
|
1180
1602
|
this.log(`跳过 ${sessionId}(${reason}): 会话暂停中`);
|
|
1181
1603
|
return;
|
|
1182
1604
|
}
|
|
@@ -1202,7 +1624,7 @@ export class AutoContinueRunner {
|
|
|
1202
1624
|
try {
|
|
1203
1625
|
const message = createUserMessage({
|
|
1204
1626
|
content: [{ type: 'text', text }],
|
|
1205
|
-
source: { kind: 'user' },
|
|
1627
|
+
source: { kind: config.usePluginSource ? AUTO_CONTINUE_SOURCE_KIND : 'user' },
|
|
1206
1628
|
});
|
|
1207
1629
|
// `followup` may publish the matching session event synchronously.
|
|
1208
1630
|
trackPendingEcho(state, message.id);
|
|
@@ -1216,8 +1638,12 @@ export class AutoContinueRunner {
|
|
|
1216
1638
|
this.prioritizedFollowups.delete(message.id);
|
|
1217
1639
|
}
|
|
1218
1640
|
const now = Date.now();
|
|
1641
|
+
// 续跑已发出: 被重启失活的 goal 需要在这里重新武装, 否则续跑消息会跑但
|
|
1642
|
+
// goal 的自动继续轮不会转起来(disarm 是宿主卸载驱动的正常动作)。
|
|
1643
|
+
this.rearmGoal(sessionId, config);
|
|
1219
1644
|
// 自主循环的成功续跑不计入连续上限: 上限只约束失败(网络中断等)。
|
|
1220
1645
|
if (reason !== LOOP_COMPLETED_REASON) state.consecutive += 1;
|
|
1646
|
+
if (isLoopReason(reason)) state.loopIterations += 1;
|
|
1221
1647
|
state.pendingRecoveryAt = now; // 等待窗口内的下一个回合结束来判定恢复结果
|
|
1222
1648
|
if (reason !== LOOP_COMPLETED_REASON) {
|
|
1223
1649
|
this.recoveryAttempts.unshift({
|
|
@@ -1259,6 +1685,93 @@ export class AutoContinueRunner {
|
|
|
1259
1685
|
}
|
|
1260
1686
|
}
|
|
1261
1687
|
|
|
1688
|
+
private resetLoopIterations(state: SessionState): void {
|
|
1689
|
+
state.loopIterations = 0;
|
|
1690
|
+
state.loopCapNotified = false;
|
|
1691
|
+
}
|
|
1692
|
+
|
|
1693
|
+
/** 自主循环轮数上限: 触顶后静默停下, 每次触顶只提示一次。 */
|
|
1694
|
+
private loopCapReached(sessionId: SessionId, state: SessionState, config: AutoContinueConfig): boolean {
|
|
1695
|
+
const cap = config.loopMaxIterations;
|
|
1696
|
+
if (cap <= 0 || state.loopIterations < cap) return false;
|
|
1697
|
+
if (!state.loopCapNotified) {
|
|
1698
|
+
state.loopCapNotified = true;
|
|
1699
|
+
this.log(`自主循环已续跑 ${state.loopIterations} 轮, 达到上限 ${cap}, 停止 ${sessionId}; 用户发消息或重新开启循环后重新计数`);
|
|
1700
|
+
if (config.notify) {
|
|
1701
|
+
const copy = NOTICE_COPY[config.locale];
|
|
1702
|
+
this.notify(
|
|
1703
|
+
sessionId,
|
|
1704
|
+
copy.loopCapTitle,
|
|
1705
|
+
copy.loopCapBody(sessionId, state.loopIterations),
|
|
1706
|
+
this.notifyOptions(sessionId, config.locale),
|
|
1707
|
+
);
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
return true;
|
|
1711
|
+
}
|
|
1712
|
+
|
|
1713
|
+
private checkConnectivity(): Promise<boolean> {
|
|
1714
|
+
if (this.connectivityCheck === undefined) {
|
|
1715
|
+
const check = this.probe()
|
|
1716
|
+
.catch(() => true) // 检测本身出错时放行, 不因探测失败卡住恢复
|
|
1717
|
+
.finally(() => {
|
|
1718
|
+
if (this.connectivityCheck === check) this.connectivityCheck = undefined;
|
|
1719
|
+
});
|
|
1720
|
+
this.connectivityCheck = check;
|
|
1721
|
+
}
|
|
1722
|
+
return this.connectivityCheck;
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
/**
|
|
1726
|
+
* 网络类失败的续跑先过连通性检测: 断网时发出去必然再失败一次, 白白吃掉连续上限,
|
|
1727
|
+
* 等网络恢复时预算已耗尽。挂起期间不计次数, 每 offlineCheckMs 复检一次, 恢复后
|
|
1728
|
+
* 重新走 schedule(宽限、冷却照常)。手动续跑和非网络原因不受影响。
|
|
1729
|
+
*/
|
|
1730
|
+
private fireWhenOnline(sessionId: SessionId, reason: string, force: boolean): void {
|
|
1731
|
+
const state = this.state(sessionId);
|
|
1732
|
+
const config = this.sessionConfig(sessionId);
|
|
1733
|
+
const gated = config.pauseWhenOffline &&
|
|
1734
|
+
reason !== MANUAL_NOTIFICATION_REASON &&
|
|
1735
|
+
!isLoopReason(reason) &&
|
|
1736
|
+
state.lastFailure !== undefined &&
|
|
1737
|
+
isNetworkFailure(state.lastFailure);
|
|
1738
|
+
if (!gated) {
|
|
1739
|
+
this.fire(sessionId, reason, force);
|
|
1740
|
+
return;
|
|
1741
|
+
}
|
|
1742
|
+
const token = {};
|
|
1743
|
+
state.offlineWait = token;
|
|
1744
|
+
state.pendingReason = reason;
|
|
1745
|
+
void this.checkConnectivity().then((online) => {
|
|
1746
|
+
if (this.disposed || state.offlineWait !== token) return; // 已被取消或被新的检测取代
|
|
1747
|
+
if (online) {
|
|
1748
|
+
state.offlineWait = undefined;
|
|
1749
|
+
state.pendingReason = undefined;
|
|
1750
|
+
if (state.offlineSince !== 0) {
|
|
1751
|
+
this.log(`网络已恢复 ${sessionId}, 断网挂起 ${Math.round((Date.now() - state.offlineSince) / 1000)}s 后继续(${reason})`);
|
|
1752
|
+
state.offlineSince = 0;
|
|
1753
|
+
this.schedule(sessionId, reason, force);
|
|
1754
|
+
return;
|
|
1755
|
+
}
|
|
1756
|
+
this.fire(sessionId, reason, force);
|
|
1757
|
+
return;
|
|
1758
|
+
}
|
|
1759
|
+
if (state.offlineSince === 0) {
|
|
1760
|
+
state.offlineSince = Date.now();
|
|
1761
|
+
this.log(`网络不可用, 挂起 ${sessionId} 的自动继续(${reason}), 每 ${config.offlineCheckMs}ms 复检, 不消耗重试次数`);
|
|
1762
|
+
}
|
|
1763
|
+
state.offlineTimer = setTimeout(() => {
|
|
1764
|
+
state.offlineTimer = undefined;
|
|
1765
|
+
if (state.offlineWait !== token) return;
|
|
1766
|
+
try {
|
|
1767
|
+
this.fireWhenOnline(sessionId, reason, force);
|
|
1768
|
+
} catch (error) {
|
|
1769
|
+
console.error(`[auto-continue] 断网复检异常 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1770
|
+
}
|
|
1771
|
+
}, config.offlineCheckMs);
|
|
1772
|
+
});
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1262
1775
|
/**
|
|
1263
1776
|
* 组装本次续跑消息: 模板填充 + 幂等护栏。
|
|
1264
1777
|
* 护栏依据上一步工具调用的执行状态附加指引, 防止重跑副作用操作:
|
|
@@ -1307,7 +1820,9 @@ export class AutoContinueRunner {
|
|
|
1307
1820
|
if (await this.scanInterrupted()) return;
|
|
1308
1821
|
const config = this.getConfig();
|
|
1309
1822
|
if (!config.paused && config.scanOnBoot && this.storedSweep === undefined) {
|
|
1823
|
+
this.childScanned = 0; // 每轮重置子会话观察配额
|
|
1310
1824
|
this.storedSweep = this.sweepStoredSessions(config, deadline)
|
|
1825
|
+
.then(() => this.wakeInterruptedChildren(config, deadline))
|
|
1311
1826
|
.catch(error => {
|
|
1312
1827
|
if (!this.disposed) this.ctx.logger.error(`Stored session scan failed: ${String(error)}`);
|
|
1313
1828
|
})
|
|
@@ -1375,7 +1890,9 @@ export class AutoContinueRunner {
|
|
|
1375
1890
|
const event = events[i];
|
|
1376
1891
|
if (event?.type === 'turn/end') { lastEnd = event; break; }
|
|
1377
1892
|
}
|
|
1378
|
-
|
|
1893
|
+
let reasonKind = readReasonKind(lastEnd?.data.reason);
|
|
1894
|
+
// A host-closed tail (`disposed`/`legacy`) is a restart signature, not a user stop.
|
|
1895
|
+
if (reasonKind === 'aborted' && isHostCancel(lastEnd?.data.reason)) reasonKind = 'interrupted';
|
|
1379
1896
|
const lastStart = latestTurnStart(events);
|
|
1380
1897
|
const maintenance = lastStart?.data.turn === lastEnd?.data.turn && isMaintenanceTurnStart(lastStart);
|
|
1381
1898
|
const silent = reasonKind === 'no-visible-output' && config.resumeSilentTurns;
|
|
@@ -1487,7 +2004,27 @@ export class AutoContinueRunner {
|
|
|
1487
2004
|
if (!Array.isArray(records)) throw new TypeError('stored session listing is not an array');
|
|
1488
2005
|
if (!this.storedSweepAnnounced) {
|
|
1489
2006
|
this.storedSweepAnnounced = true;
|
|
1490
|
-
|
|
2007
|
+
// 诊断口径: 宿主返回的 header 是否携带 origin, 决定子会话分支能否进入。
|
|
2008
|
+
let children = 0;
|
|
2009
|
+
let otherOrigins = 0;
|
|
2010
|
+
let originMissing = 0;
|
|
2011
|
+
for (const record of records) {
|
|
2012
|
+
const origin = (record?.header as { origin?: string } | undefined)?.origin;
|
|
2013
|
+
if (origin === 'subagent') children += 1;
|
|
2014
|
+
else if (origin === undefined) originMissing += 1;
|
|
2015
|
+
else otherOrigins += 1;
|
|
2016
|
+
}
|
|
2017
|
+
this.ctx.logger.info(
|
|
2018
|
+
`存储扫描就绪: ${records.length} 个会话记录 (subagent ${children} / 无 origin ${originMissing} / 其它 origin ${otherOrigins})`,
|
|
2019
|
+
);
|
|
2020
|
+
}
|
|
2021
|
+
// 父子链解析只依赖 header: 一次建成索引, 子会话不必各自再读父日志。
|
|
2022
|
+
const headersById = new Map<string, SessionHeaderLike>();
|
|
2023
|
+
for (const record of records) {
|
|
2024
|
+
const header = record?.header as SessionHeaderLike | undefined;
|
|
2025
|
+
if (header !== undefined && typeof header.id === 'string' && header.id !== '') {
|
|
2026
|
+
headersById.set(header.id, header);
|
|
2027
|
+
}
|
|
1491
2028
|
}
|
|
1492
2029
|
let observed = 0;
|
|
1493
2030
|
for (const record of records) {
|
|
@@ -1497,10 +2034,18 @@ export class AutoContinueRunner {
|
|
|
1497
2034
|
continue;
|
|
1498
2035
|
}
|
|
1499
2036
|
const sessionId = record.header.id;
|
|
1500
|
-
if (this.
|
|
2037
|
+
if (this.ownSessionConfig(sessionId).paused || Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) continue;
|
|
2038
|
+
if (record.header.origin === 'subagent') {
|
|
2039
|
+
// 子会话的记账完全交给 childSwept。若沿用 storedSwept(它在下面为 root 记账),
|
|
2040
|
+
// 配额用尽的那一批会被永久标成"已裁决": 之后每轮都在这里被挡掉, 775 个子会话
|
|
2041
|
+
// 只判 8 个, 而配额本意只是限制单轮的冷读成本。
|
|
2042
|
+
if (config.resumeInterruptedChildren) {
|
|
2043
|
+
await this.sweepChild(record, headersById, config, deadline);
|
|
2044
|
+
}
|
|
2045
|
+
continue;
|
|
2046
|
+
}
|
|
1501
2047
|
if (record.live || this.storedSwept.has(sessionId)) continue;
|
|
1502
2048
|
this.storedSwept.add(sessionId);
|
|
1503
|
-
if (record.header.origin === 'subagent') continue;
|
|
1504
2049
|
observed += 1;
|
|
1505
2050
|
let observation: StoredObservation | undefined;
|
|
1506
2051
|
try {
|
|
@@ -1535,6 +2080,7 @@ export class AutoContinueRunner {
|
|
|
1535
2080
|
freshAt = events[events.length - 1]?.time ?? 0;
|
|
1536
2081
|
} else {
|
|
1537
2082
|
reasonKind = readReasonKind(lastEnd?.data.reason);
|
|
2083
|
+
if (reasonKind === 'aborted' && isHostCancel(lastEnd?.data.reason)) reasonKind = 'interrupted';
|
|
1538
2084
|
freshAt = lastEnd?.time ?? 0;
|
|
1539
2085
|
}
|
|
1540
2086
|
// 过期或被取代的永久错误与 live 扫描一致地静默跳过, 不再单独上报。
|
|
@@ -1596,6 +2142,272 @@ export class AutoContinueRunner {
|
|
|
1596
2142
|
}
|
|
1597
2143
|
}
|
|
1598
2144
|
|
|
2145
|
+
/**
|
|
2146
|
+
* 子会话裁决。子会话本身永不直接续跑(父代理权威, 见 README), 但启动扫描要
|
|
2147
|
+
* 知道它是否在重启时被打断, 才能在自己的 root 会话上补一次带清单的唤醒。
|
|
2148
|
+
* 独立 `childSwept` 记账与独立配额: 主扫描的 `storedSwept` 在 origin 判断
|
|
2149
|
+
* 之前就已标记, 复用它会让子会话永远扫不到, 也会吃掉主扫描的观察预算。
|
|
2150
|
+
*/
|
|
2151
|
+
private async sweepChild(
|
|
2152
|
+
record: {
|
|
2153
|
+
readonly header: SessionHeaderLike & {
|
|
2154
|
+
readonly origin?: string;
|
|
2155
|
+
readonly agentPreset?: string;
|
|
2156
|
+
readonly title?: unknown;
|
|
2157
|
+
};
|
|
2158
|
+
readonly persisted?: boolean;
|
|
2159
|
+
},
|
|
2160
|
+
headersById: ReadonlyMap<string, SessionHeaderLike>,
|
|
2161
|
+
config: AutoContinueConfig,
|
|
2162
|
+
deadline: number,
|
|
2163
|
+
): Promise<void> {
|
|
2164
|
+
const header = record.header;
|
|
2165
|
+
const sessionId = header.id;
|
|
2166
|
+
const parentId = header.parentSession;
|
|
2167
|
+
if (parentId === undefined || parentId === '') return;
|
|
2168
|
+
// one-shot 子会话在结果落库后已被丢弃, 没有可续的日志。
|
|
2169
|
+
if (record.persisted !== true) return;
|
|
2170
|
+
if (this.childSwept.has(sessionId)) return;
|
|
2171
|
+
// live 会话由实时事件路径负责; 冷读它既费钱又会与写归属相撞。
|
|
2172
|
+
if (this.ctx.agents.get(sessionId) !== undefined) return;
|
|
2173
|
+
if (this.childScanned >= CHILD_SWEEP_LIMIT) return;
|
|
2174
|
+
if (this.ownSessionConfig(sessionId).paused) return;
|
|
2175
|
+
const rootId = resolveRootHeader(header, headersById);
|
|
2176
|
+
if (rootId === undefined || rootId === sessionId) {
|
|
2177
|
+
// 每轮扫描都会重走这里; 只记一次, 否则 15 分钟 freshMs 窗口内会刷出数万行噪声。
|
|
2178
|
+
if (!this.childDirtyLogged.has(sessionId)) {
|
|
2179
|
+
this.childDirtyLogged.add(sessionId);
|
|
2180
|
+
this.log(`子会话 ${sessionId} 父链不可解析(脏引用或自环), 跳过(每会话只记一次)`);
|
|
2181
|
+
}
|
|
2182
|
+
return; // 脏引用或自环: 不猜
|
|
2183
|
+
}
|
|
2184
|
+
const query = this.ctx.get('sessionQuery');
|
|
2185
|
+
if (query === undefined) return;
|
|
2186
|
+
this.childSwept.add(sessionId);
|
|
2187
|
+
this.childScanned += 1;
|
|
2188
|
+
let observation: StoredObservation | undefined;
|
|
2189
|
+
try {
|
|
2190
|
+
const stored: StoredObservation = await this.readStored(
|
|
2191
|
+
signal => query.observeSession(sessionId, { projectionMode: 'all', signal }),
|
|
2192
|
+
deadline,
|
|
2193
|
+
);
|
|
2194
|
+
observation = stored;
|
|
2195
|
+
if (this.disposed) return;
|
|
2196
|
+
const events = validateSessionEvents(stored.events);
|
|
2197
|
+
if (events.length === 0) return;
|
|
2198
|
+
const cause = classifyChildInterruption(events, config);
|
|
2199
|
+
if (cause === undefined) return;
|
|
2200
|
+
const tail = events[events.length - 1];
|
|
2201
|
+
const list = this.childInterrupts.get(rootId) ?? [];
|
|
2202
|
+
list.push({
|
|
2203
|
+
id: sessionId,
|
|
2204
|
+
title: typeof header.title === 'string' && header.title !== '' ? header.title : undefined,
|
|
2205
|
+
preset: header.agentPreset,
|
|
2206
|
+
cause,
|
|
2207
|
+
at: tail?.time ?? Date.now(),
|
|
2208
|
+
});
|
|
2209
|
+
this.childInterrupts.set(rootId, list);
|
|
2210
|
+
this.log(`子会话 ${sessionId} 重启时被打断(${cause}), 记入 root ${rootId}`);
|
|
2211
|
+
} catch (error) {
|
|
2212
|
+
this.childSwept.delete(sessionId); // 冷读失败允许下一轮重试
|
|
2213
|
+
if (!this.disposed) {
|
|
2214
|
+
this.ctx.logger.info(
|
|
2215
|
+
`子会话 ${sessionId} 冷读失败: ${error instanceof Error ? error.message : String(error)}`,
|
|
2216
|
+
);
|
|
2217
|
+
}
|
|
2218
|
+
} finally {
|
|
2219
|
+
observation?.[Symbol.dispose]?.();
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
2222
|
+
|
|
2223
|
+
/** 把本轮收集到的子会话中断转成 root 会话上的一次唤醒(同一批只催一次)。 */
|
|
2224
|
+
private async wakeInterruptedChildren(
|
|
2225
|
+
config: AutoContinueConfig,
|
|
2226
|
+
deadline: number,
|
|
2227
|
+
): Promise<void> {
|
|
2228
|
+
if (this.disposed || this.childInterrupts.size === 0) return;
|
|
2229
|
+
if (config.paused || !config.scanOnBoot || !config.resumeInterruptedChildren) return;
|
|
2230
|
+
// 不整体 clear: 只有"已裁决"的 root 才销账。若在循环前 clear, 任一 root 因冷却或
|
|
2231
|
+
// 主路径已排期而提前返回, 这批孩子就永久丢了 —— 它们已在 childSwept 里, 不会再被收集。
|
|
2232
|
+
for (const [rootId, children] of [...this.childInterrupts]) {
|
|
2233
|
+
if (this.disposed || Date.now() >= deadline) return; // 未处理的留到下一轮
|
|
2234
|
+
try {
|
|
2235
|
+
if (await this.wakeRoot(config, rootId, children, deadline)) {
|
|
2236
|
+
this.childInterrupts.delete(rootId);
|
|
2237
|
+
}
|
|
2238
|
+
} catch (error) {
|
|
2239
|
+
// 抛错也要销账, 否则每轮重试同一条坏数据。
|
|
2240
|
+
this.childInterrupts.delete(rootId);
|
|
2241
|
+
if (!this.disposed) {
|
|
2242
|
+
this.ctx.logger.info(
|
|
2243
|
+
`子会话唤醒 ${rootId} 失败: ${error instanceof Error ? error.message : String(error)}`,
|
|
2244
|
+
);
|
|
2245
|
+
}
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2250
|
+
/**
|
|
2251
|
+
* 在 root 会话上唤醒一次。只有在 root 自己是"干净终态"时才动手: 它若被打断,
|
|
2252
|
+
* 主扫描本来就会续跑它; 它若被用户手动停止, 唤醒就是幽灵回合。
|
|
2253
|
+
*/
|
|
2254
|
+
private async wakeRoot(
|
|
2255
|
+
config: AutoContinueConfig,
|
|
2256
|
+
rootId: SessionId,
|
|
2257
|
+
children: readonly ChildInterrupt[],
|
|
2258
|
+
deadline: number,
|
|
2259
|
+
): Promise<boolean> {
|
|
2260
|
+
// 返回值语义: true = 已裁决(可销账), false = 稍后重试(必须留住这一批)。
|
|
2261
|
+
if (this.sessionConfig(rootId).paused) return false;
|
|
2262
|
+
if (Date.now() < (this.pauseUntil.get(rootId) ?? 0)) return false;
|
|
2263
|
+
const state = this.state(rootId);
|
|
2264
|
+
if (state.pendingTimer !== undefined) return false; // 主路径已排好, 下一轮再看
|
|
2265
|
+
if (state.consecutive >= config.maxConsecutive) return true; // 预算耗尽: 不必每轮重试
|
|
2266
|
+
if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) return false;
|
|
2267
|
+
const batch = children.map(child => `${child.id}:${child.cause}`).sort().join(',');
|
|
2268
|
+
if (this.childWoken.get(rootId) === batch) return true;
|
|
2269
|
+
if (!(await this.rootAcceptsWake(rootId, deadline))) return true; // 明确裁决: 不该唤醒
|
|
2270
|
+
const agent = await this.ensureLiveAgent(rootId, deadline);
|
|
2271
|
+
if (agent === undefined || this.disposed) return false;
|
|
2272
|
+
const text = this.buildChildResumeText(config, children);
|
|
2273
|
+
const message = createUserMessage({
|
|
2274
|
+
content: [{ type: 'text', text }],
|
|
2275
|
+
source: { kind: 'user' },
|
|
2276
|
+
});
|
|
2277
|
+
state.lastAttemptAt = Date.now();
|
|
2278
|
+
agent.followup(message);
|
|
2279
|
+
this.childWoken.set(rootId, batch);
|
|
2280
|
+
this.log(
|
|
2281
|
+
`已唤醒 ${rootId}: ${children.length} 个子会话在重启时被打断, 清单已交给父会话处置`,
|
|
2282
|
+
);
|
|
2283
|
+
this.rearmGoal(rootId, config);
|
|
2284
|
+
return true;
|
|
2285
|
+
}
|
|
2286
|
+
|
|
2287
|
+
/** 父会话只在"干净结束"或"被宿主关闭"时接受唤醒; 用户手动停止的绝不复活。 */
|
|
2288
|
+
private async rootAcceptsWake(sessionId: SessionId, deadline: number): Promise<boolean> {
|
|
2289
|
+
const query = this.ctx.get('sessionQuery');
|
|
2290
|
+
if (query === undefined) return false;
|
|
2291
|
+
let events: readonly SessionEvent[];
|
|
2292
|
+
let stored: StoredObservation | undefined;
|
|
2293
|
+
try {
|
|
2294
|
+
const observation: StoredObservation = await this.readStored(
|
|
2295
|
+
signal => query.observeSession(sessionId, { projectionMode: 'all', signal }),
|
|
2296
|
+
deadline,
|
|
2297
|
+
);
|
|
2298
|
+
stored = observation;
|
|
2299
|
+
events = validateSessionEvents(observation.events);
|
|
2300
|
+
} catch {
|
|
2301
|
+
return false;
|
|
2302
|
+
} finally {
|
|
2303
|
+
// validateSessionEvents 可能抛在畸形日志上, 租约必须无条件释放。
|
|
2304
|
+
stored?.[Symbol.dispose]?.();
|
|
2305
|
+
}
|
|
2306
|
+
if (events.length === 0) return false;
|
|
2307
|
+
let lastEnd: SessionEvent<'turn/end'> | undefined;
|
|
2308
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
2309
|
+
const event = events[i];
|
|
2310
|
+
if (event?.type === 'turn/end') { lastEnd = event; break; }
|
|
2311
|
+
}
|
|
2312
|
+
const lastStart = latestTurnStart(events);
|
|
2313
|
+
const end = lastEnd;
|
|
2314
|
+
if (lastStart !== undefined && (end === undefined || lastStart.seq > end.seq)) return false;
|
|
2315
|
+
if (end === undefined) return false;
|
|
2316
|
+
const kind = readReasonKind(end.data.reason);
|
|
2317
|
+
if (kind === 'completed') return true;
|
|
2318
|
+
if (kind === 'aborted') return isHostCancel(end.data.reason);
|
|
2319
|
+
return false;
|
|
2320
|
+
}
|
|
2321
|
+
|
|
2322
|
+
/** 发送需要 live agent; 存储会话沿既有物化路径拉起, 复用 preset 与模型回装。 */
|
|
2323
|
+
private async ensureLiveAgent(sessionId: SessionId, deadline: number): Promise<Agent | undefined> {
|
|
2324
|
+
const live = this.ctx.agents.get(sessionId);
|
|
2325
|
+
if (live !== undefined) return live;
|
|
2326
|
+
const query = this.ctx.get('sessionQuery');
|
|
2327
|
+
if (query === undefined) return undefined;
|
|
2328
|
+
let presetId: string | undefined;
|
|
2329
|
+
let model: { provider: string; model: string } | undefined;
|
|
2330
|
+
let stored: StoredObservation | undefined;
|
|
2331
|
+
try {
|
|
2332
|
+
const observation: StoredObservation = await this.readStored(
|
|
2333
|
+
signal => query.observeSession(sessionId, { projectionMode: 'all', signal }),
|
|
2334
|
+
deadline,
|
|
2335
|
+
);
|
|
2336
|
+
stored = observation;
|
|
2337
|
+
presetId = observation.projections?.values.agentPreset ?? observation.header.agentPreset;
|
|
2338
|
+
// 与主扫描一致回装日志记录的模型选择, 否则父会话会以默认模型被拉起。
|
|
2339
|
+
const loggedConfig = foldRequestHeader(validateSessionEvents(observation.events))?.config;
|
|
2340
|
+
if (loggedConfig !== undefined) model = { provider: loggedConfig.provider, model: loggedConfig.model };
|
|
2341
|
+
} catch {
|
|
2342
|
+
return undefined;
|
|
2343
|
+
} finally {
|
|
2344
|
+
stored?.[Symbol.dispose]?.();
|
|
2345
|
+
}
|
|
2346
|
+
const ok = await this.materializeStored(sessionId, presetId, model);
|
|
2347
|
+
if (!ok || this.disposed) return undefined;
|
|
2348
|
+
return this.ctx.agents.get(sessionId);
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2351
|
+
/** 唤醒文本必须带会话级证据: 否则父会话看不到任何状态, 只会白跑一轮再回一句"都结束了"。 */
|
|
2352
|
+
private buildChildResumeText(
|
|
2353
|
+
config: AutoContinueConfig,
|
|
2354
|
+
children: readonly ChildInterrupt[],
|
|
2355
|
+
): string {
|
|
2356
|
+
const lines = children.map((child) => {
|
|
2357
|
+
const label = child.title !== undefined ? `「${child.title}」` : '';
|
|
2358
|
+
const preset = child.preset !== undefined ? ` (${child.preset})` : '';
|
|
2359
|
+
const cause = CHILD_CAUSE_COPY[config.locale][child.cause];
|
|
2360
|
+
return `- ${child.id} ${label}${preset} — ${cause}`;
|
|
2361
|
+
});
|
|
2362
|
+
const header = config.locale === 'zh'
|
|
2363
|
+
? '重启时你开的以下子代理 / 团队成员会话被打断, 没有跑完。请逐个检查, 按需要继续或收尾:'
|
|
2364
|
+
: 'These child sessions you started (subagent / team member) were interrupted by a restart and did not finish. Check each one and either continue it or wrap it up:';
|
|
2365
|
+
const tail = config.locale === 'zh'
|
|
2366
|
+
? '要继续的用 send_message / subagent 重新拉起对应会话(重启后它们并未加载); 已完成或不再需要的, 说明结论即可。'
|
|
2367
|
+
: 'Use send_message (or subagent) to bring back the ones that should continue — they are not loaded after the restart; for finished or abandoned ones, just state the conclusion.';
|
|
2368
|
+
return [header, ...lines, tail].join('\n');
|
|
2369
|
+
}
|
|
2370
|
+
|
|
2371
|
+
/**
|
|
2372
|
+
* 重启会把 active goal 置为 disarmed(宿主卸载驱动的正常动作), 只有人类授权的
|
|
2373
|
+
* resume 能重新 arm; paused 则是人类的显式决定。两者都默认关闭。
|
|
2374
|
+
*/
|
|
2375
|
+
private rearmGoal(sessionId: SessionId, config: AutoContinueConfig): void {
|
|
2376
|
+
if (!config.resumeGoals) return;
|
|
2377
|
+
const goals = (this.ctx as unknown as { get(key: string): unknown }).get(GOALS_SERVICE_KEY) as
|
|
2378
|
+
| GoalServiceLike
|
|
2379
|
+
| undefined;
|
|
2380
|
+
if (goals === undefined) return;
|
|
2381
|
+
const agent = this.ctx.agents.get(sessionId);
|
|
2382
|
+
if (agent === undefined) return;
|
|
2383
|
+
try {
|
|
2384
|
+
const view = goals.get(agent);
|
|
2385
|
+
if (view === undefined) return;
|
|
2386
|
+
// 宿主的 view() 不带 ref 字段, 而 resume() 用 revision 做 CAS 校验(expectCurrent):
|
|
2387
|
+
// 只带 id 必定抛 GOAL_STALE_REVISION 被这里 catch 成一行日志 —— 等于开关失效。
|
|
2388
|
+
// 缺 revision 时 fail closed, 不猜。
|
|
2389
|
+
const revision = view.revision;
|
|
2390
|
+
if (revision === undefined) {
|
|
2391
|
+
this.log(`会话 ${sessionId}: goal 视图缺 revision, 跳过重新武装(宿主会拒绝无 revision 的 resume)`);
|
|
2392
|
+
return;
|
|
2393
|
+
}
|
|
2394
|
+
const ref: GoalRefLike = view.ref ?? { id: view.id, revision };
|
|
2395
|
+
if (view.phase === 'active' && view.activation === 'disarmed') {
|
|
2396
|
+
goals.resume(agent, ref);
|
|
2397
|
+
this.log(`会话 ${sessionId}: goal 被重启失活, 已重新武装`);
|
|
2398
|
+
return;
|
|
2399
|
+
}
|
|
2400
|
+
if (view.phase === 'paused' && config.resumePausedGoals) {
|
|
2401
|
+
goals.resume(agent, ref);
|
|
2402
|
+
this.log(`会话 ${sessionId}: 已恢复被暂停的 goal`);
|
|
2403
|
+
}
|
|
2404
|
+
} catch (error) {
|
|
2405
|
+
this.ctx.logger.info(
|
|
2406
|
+
`goal 恢复失败 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`,
|
|
2407
|
+
);
|
|
2408
|
+
}
|
|
2409
|
+
}
|
|
2410
|
+
|
|
1599
2411
|
/**
|
|
1600
2412
|
* 按会话记录的 preset 组合把存储会话恢复为 live agent(镜像会话控制
|
|
1601
2413
|
* 器的 adopt 路径: preset 挂载 + 会话已记录的模型选择回装)。模型选择
|