dsh-client-auto-continue 0.18.0 → 0.20.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 +38 -0
- package/README.md +230 -310
- package/README.ru.md +382 -0
- package/README.zh.md +229 -308
- 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.19.0.md +62 -0
- package/docs/releases/v0.20.0.md +46 -0
- package/docs/social-preview.png +0 -0
- package/docs/social-preview.svg +30 -1
- package/lib/client.js +297 -99
- package/lib/client.js.map +3 -3
- package/lib/index.js +496 -43
- 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 +5 -0
- package/lib/types/client/settings-card.d.ts +1 -0
- package/lib/types/host/engine.d.ts +88 -4
- package/lib/types/index.d.ts +8 -0
- package/lib/types/shared/core.d.ts +21 -1
- package/locale/ru.json +6 -0
- package/package.json +5 -3
- 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 +215 -40
- package/src/client/settings-card.tsx +8 -2
- package/src/client/settings-notifications.ts +3 -2
- package/src/client/styles.ts +17 -19
- package/src/host/engine.ts +571 -41
- package/src/host/settings-migration.ts +1 -1
- package/src/index.ts +23 -1
- package/src/shared/core.ts +32 -2
package/src/host/engine.ts
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
16
|
import type { Context } from '@deepseek-ai/cordis';
|
|
17
|
+
import { randomUUID } from 'node:crypto';
|
|
17
18
|
import { createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
18
19
|
import type { Agent } from '@deepseek-ai/dsh-agent';
|
|
19
20
|
import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types';
|
|
@@ -30,6 +31,7 @@ import {
|
|
|
30
31
|
isNonHumanReason,
|
|
31
32
|
isOurEcho,
|
|
32
33
|
isNetworkFailure,
|
|
34
|
+
isSessionMode,
|
|
33
35
|
isTransientAgentError,
|
|
34
36
|
isTransientFailure,
|
|
35
37
|
resolveConfig,
|
|
@@ -42,6 +44,7 @@ import {
|
|
|
42
44
|
type DayStats,
|
|
43
45
|
type RecoveryAttempt,
|
|
44
46
|
type FailureFacts,
|
|
47
|
+
type SessionMode,
|
|
45
48
|
type SessionState,
|
|
46
49
|
type NotifyAction,
|
|
47
50
|
type NotifyOptions,
|
|
@@ -52,37 +55,53 @@ import { probeConnectivity, type ConnectivityProbe } from './connectivity.ts';
|
|
|
52
55
|
|
|
53
56
|
const NOTICE_COPY = {
|
|
54
57
|
zh: {
|
|
55
|
-
notContinuedTitle: 'dsh-auto-continue:
|
|
58
|
+
notContinuedTitle: 'dsh-auto-continue: 请处理会话错误',
|
|
56
59
|
permanentErrorBody: (sessionId: SessionId, summary: string) =>
|
|
57
|
-
`${sessionId}:
|
|
60
|
+
`${sessionId}: ${summary}。请处理此错误后再继续。`,
|
|
58
61
|
resumeAction: '立即续跑',
|
|
59
62
|
pauseAction: '暂停该会话 1 小时',
|
|
60
|
-
continuedTitle: 'dsh-auto-continue:
|
|
63
|
+
continuedTitle: 'dsh-auto-continue: 已发送继续消息',
|
|
61
64
|
continuedBody: (sessionId: SessionId, text: string, count: number) =>
|
|
62
|
-
`${sessionId}: 已发送「${text}
|
|
63
|
-
stoppedTitle: 'dsh-auto-continue:
|
|
65
|
+
`${sessionId}: 已发送「${text}」(连续尝试 ${count} 次)`,
|
|
66
|
+
stoppedTitle: 'dsh-auto-continue: 已达到重试上限',
|
|
64
67
|
stoppedBody: (sessionId: SessionId, count: number) =>
|
|
65
|
-
`${sessionId}:
|
|
68
|
+
`${sessionId}: 已连续尝试恢复 ${count} 次。请检查会话后再继续。`,
|
|
66
69
|
loopCapTitle: 'dsh-auto-continue: 自主循环已到上限',
|
|
67
70
|
loopCapBody: (sessionId: SessionId, count: number) =>
|
|
68
71
|
`${sessionId}: 已自主续跑 ${count} 轮, 循环暂停; 发一条消息或重新开启循环即可继续`,
|
|
69
72
|
},
|
|
70
73
|
en: {
|
|
71
|
-
notContinuedTitle: 'dsh-auto-continue:
|
|
74
|
+
notContinuedTitle: 'dsh-auto-continue: Review session error',
|
|
72
75
|
permanentErrorBody: (sessionId: SessionId, summary: string) =>
|
|
73
|
-
`${sessionId}:
|
|
76
|
+
`${sessionId}: ${summary}. Resolve this error before continuing.`,
|
|
74
77
|
resumeAction: 'Resume now',
|
|
75
78
|
pauseAction: 'Pause this session for 1 hour',
|
|
76
|
-
continuedTitle: 'dsh-auto-continue:
|
|
79
|
+
continuedTitle: 'dsh-auto-continue: Continue message sent',
|
|
77
80
|
continuedBody: (sessionId: SessionId, text: string, count: number) =>
|
|
78
|
-
`${sessionId}: Sent "${text}" (consecutive
|
|
79
|
-
stoppedTitle: 'dsh-auto-continue:
|
|
81
|
+
`${sessionId}: Sent "${text}" (consecutive attempts: ${count})`,
|
|
82
|
+
stoppedTitle: 'dsh-auto-continue: Retry limit reached',
|
|
80
83
|
stoppedBody: (sessionId: SessionId, count: number) =>
|
|
81
|
-
`${sessionId}: ${count}
|
|
84
|
+
`${sessionId}: Consecutive recovery attempts: ${count}. Review the conversation before continuing.`,
|
|
82
85
|
loopCapTitle: 'dsh-auto-continue: Autonomous loop limit reached',
|
|
83
86
|
loopCapBody: (sessionId: SessionId, count: number) =>
|
|
84
87
|
`${sessionId}: Stopped after ${count} autonomous rounds; send a message or turn the loop back on to keep going`,
|
|
85
88
|
},
|
|
89
|
+
ru: {
|
|
90
|
+
notContinuedTitle: 'dsh-auto-continue: продолжение не выполнено',
|
|
91
|
+
permanentErrorBody: (sessionId: SessionId, summary: string) =>
|
|
92
|
+
`${sessionId}: постоянная ошибка ${summary}; нужно вмешательство вручную`,
|
|
93
|
+
resumeAction: 'Продолжить сейчас',
|
|
94
|
+
pauseAction: 'Приостановить сессию на 1 час',
|
|
95
|
+
continuedTitle: 'dsh-auto-continue: продолжено автоматически',
|
|
96
|
+
continuedBody: (sessionId: SessionId, text: string, count: number) =>
|
|
97
|
+
`${sessionId}: отправлено «${text}» (попытка подряд: ${count})`,
|
|
98
|
+
stoppedTitle: 'dsh-auto-continue: авто-продолжение остановлено',
|
|
99
|
+
stoppedBody: (sessionId: SessionId, count: number) =>
|
|
100
|
+
`${sessionId}: сбоев подряд: ${count}; нужно вмешательство вручную`,
|
|
101
|
+
loopCapTitle: 'dsh-auto-continue: достигнут лимит автономного цикла',
|
|
102
|
+
loopCapBody: (sessionId: SessionId, count: number) =>
|
|
103
|
+
`${sessionId}: остановлено после ${count} автономных раундов; отправьте сообщение или включите цикл снова, чтобы продолжить`,
|
|
104
|
+
},
|
|
86
105
|
} as const satisfies Record<AutoContinueLocale, Record<string, unknown>>;
|
|
87
106
|
|
|
88
107
|
/** Durable cancel identity reserved for this plugin's loop guard. */
|
|
@@ -137,6 +156,20 @@ const DECISION_CANCEL_CAUSES: ReadonlySet<string> = new Set(['user', 'parent', '
|
|
|
137
156
|
const CHILD_SWEEP_LIMIT = 8;
|
|
138
157
|
/** Bound how many ancestor hops a dirty parent chain may cost before giving up. */
|
|
139
158
|
const CHILD_ROOT_MAX_DEPTH = 8;
|
|
159
|
+
/** Do not hand the same child failure to its main conversation more often than this. */
|
|
160
|
+
const HANDOFF_COOLDOWN_MS = 5 * 60 * 1000;
|
|
161
|
+
/** Bound the host cold-resume call: a stalled service must not block recovery forever. */
|
|
162
|
+
const REVIVE_TIMEOUT_MS = 15_000;
|
|
163
|
+
|
|
164
|
+
/** Copy for the live hand-off that replaces an impossible child resume, keyed by UI locale. */
|
|
165
|
+
const HANDOFF_COPY = {
|
|
166
|
+
zh: (child: string, code: string) =>
|
|
167
|
+
`子代理会话 ${child} 因 ${code} 中断, 已无法直接续跑。请检查它的状态, 然后继续或收尾。`,
|
|
168
|
+
en: (child: string, code: string) =>
|
|
169
|
+
`Child session ${child} was interrupted by ${code} and can no longer be resumed directly. Check its state, then continue it or wrap it up.`,
|
|
170
|
+
ru: (child: string, code: string) =>
|
|
171
|
+
`Дочерняя сессия ${child} прервалась из-за ${code} и больше не может быть продолжена напрямую. Проверь её состояние и продолжи или заверши.`,
|
|
172
|
+
} as const satisfies Record<AutoContinueLocale, (child: string, code: string) => string>;
|
|
140
173
|
|
|
141
174
|
/** Host service key for goals (0.2.x); older hosts simply do not register it. */
|
|
142
175
|
const GOALS_SERVICE_KEY = 'goals';
|
|
@@ -157,6 +190,13 @@ const CHILD_CAUSE_COPY = {
|
|
|
157
190
|
'max-tokens': 'output ceiling reached',
|
|
158
191
|
error: 'retryable error',
|
|
159
192
|
},
|
|
193
|
+
ru: {
|
|
194
|
+
'open-turn': 'ход прерван после начала',
|
|
195
|
+
disposed: 'хост уничтожил агента',
|
|
196
|
+
interrupted: 'закрыт восстановлением после сбоя',
|
|
197
|
+
'max-tokens': 'достигнут лимит вывода',
|
|
198
|
+
error: 'повторяемая ошибка',
|
|
199
|
+
},
|
|
160
200
|
} as const satisfies Record<AutoContinueLocale, Record<ChildInterruptCause, string>>;
|
|
161
201
|
|
|
162
202
|
/** Structural view of `ctx.goals`; declared locally because devDeps target an older host. */
|
|
@@ -300,6 +340,12 @@ function readCancelCause(value: unknown): string | undefined {
|
|
|
300
340
|
return readReasonKind(reason.reason);
|
|
301
341
|
}
|
|
302
342
|
|
|
343
|
+
/** Whether the host closed an `aborted` turn (restart, reload, teardown) rather than the user. */
|
|
344
|
+
function isHostCancel(value: unknown): boolean {
|
|
345
|
+
const cause = readCancelCause(value);
|
|
346
|
+
return cause !== undefined && RESTART_CANCEL_CAUSES.has(cause);
|
|
347
|
+
}
|
|
348
|
+
|
|
303
349
|
/**
|
|
304
350
|
* Decide whether a child session's tail is a restart interruption worth waking
|
|
305
351
|
* its root session for. Returns `undefined` when the child finished normally,
|
|
@@ -412,8 +458,15 @@ async function pumpStream<T>(
|
|
|
412
458
|
}
|
|
413
459
|
|
|
414
460
|
/** 插件主体: 一条 mux 流 + 一条 host 流 + 启动/重连扫描。 */
|
|
461
|
+
/** Soft cap on cached subagent lineage entries before stale ones are pruned. */
|
|
462
|
+
const LINEAGE_CACHE_LIMIT = 2000;
|
|
463
|
+
|
|
415
464
|
export class AutoContinueRunner {
|
|
416
465
|
private readonly states = new Map<SessionId, SessionState>();
|
|
466
|
+
/** Cached subagent lineage: session id -> direct parent id (undefined when the header has none). */
|
|
467
|
+
private readonly parents = new Map<SessionId, SessionId | undefined>();
|
|
468
|
+
/** Sessions already identified as subagents, including event views without header metadata. */
|
|
469
|
+
private readonly subagentSessions = new Set<SessionId>();
|
|
417
470
|
private readonly pauseUntil = new Map<SessionId, number>();
|
|
418
471
|
private dayStats: DayStats = emptyDayStats();
|
|
419
472
|
private readonly recoveryAttempts: RecoveryAttempt[] = [];
|
|
@@ -421,6 +474,10 @@ export class AutoContinueRunner {
|
|
|
421
474
|
private readonly noticeListeners = new Set<() => void>();
|
|
422
475
|
private readonly stateListeners = new Set<() => void>();
|
|
423
476
|
private readonly prioritizedFollowups = new Set<string>();
|
|
477
|
+
/** In-flight cold-resume calls, aborted when the plugin unloads. */
|
|
478
|
+
private readonly reviveControllers = new Set<AbortController>();
|
|
479
|
+
/** Hand-offs waiting for a live main conversation: parent -> child -> text. */
|
|
480
|
+
private readonly deferredHandoffs = new Map<SessionId, Map<SessionId, string>>();
|
|
424
481
|
private readonly disposeSessionEvents: () => void;
|
|
425
482
|
private readonly disposeInboxEvents: () => void;
|
|
426
483
|
private disposed = false;
|
|
@@ -506,7 +563,7 @@ export class AutoContinueRunner {
|
|
|
506
563
|
void this.bootScanLoop();
|
|
507
564
|
}
|
|
508
565
|
this.log(
|
|
509
|
-
`已启动(
|
|
566
|
+
`已启动(文本="${config.continueText}", 宽限 ${config.graceMs}ms, ` +
|
|
510
567
|
`冷却 ${config.cooldownMs}ms, 最多连续 ${config.maxConsecutive} 次)`,
|
|
511
568
|
);
|
|
512
569
|
}
|
|
@@ -557,6 +614,29 @@ export class AutoContinueRunner {
|
|
|
557
614
|
}
|
|
558
615
|
|
|
559
616
|
private sessionConfig(sessionId: SessionId): AutoContinueConfig {
|
|
617
|
+
const config = this.getConfig();
|
|
618
|
+
if (this.isSubagentSession(sessionId)) {
|
|
619
|
+
// A subagent inherits only the enabled/off decision of its main
|
|
620
|
+
// conversation (an explicit mode stored for the child wins). It never runs
|
|
621
|
+
// the autonomous loop or the loop guard, and the startup scan keeps leaving
|
|
622
|
+
// it to its parent: those three stay parent-only.
|
|
623
|
+
const enabled = this.subagentRecoveryEnabled(sessionId);
|
|
624
|
+
return {
|
|
625
|
+
...config,
|
|
626
|
+
paused: config.paused || !enabled,
|
|
627
|
+
resumeCompletedTurns: false,
|
|
628
|
+
loopGuard: false,
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
return this.ownSessionConfig(sessionId);
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* The session's own mode, ignoring subagent inheritance. The stored-session
|
|
636
|
+
* sweep and the restart hand-off (`resumeInterruptedChildren`) use this, so
|
|
637
|
+
* turning live subagent recovery off never silently disables them.
|
|
638
|
+
*/
|
|
639
|
+
private ownSessionConfig(sessionId: SessionId): AutoContinueConfig {
|
|
560
640
|
const config = this.getConfig();
|
|
561
641
|
const mode = sessionMode(config.sessionModes, sessionId);
|
|
562
642
|
return {
|
|
@@ -610,6 +690,10 @@ export class AutoContinueRunner {
|
|
|
610
690
|
this.wakeBootScan = undefined;
|
|
611
691
|
this.disposeSessionEvents();
|
|
612
692
|
this.disposeInboxEvents();
|
|
693
|
+
// Unload is an opt-out: never deliver a continuation after disposal.
|
|
694
|
+
for (const controller of this.reviveControllers) controller.abort();
|
|
695
|
+
this.reviveControllers.clear();
|
|
696
|
+
this.deferredHandoffs.clear();
|
|
613
697
|
this.prioritizedFollowups.clear();
|
|
614
698
|
for (const state of this.states.values()) {
|
|
615
699
|
if (state.pendingTimer !== undefined) clearTimeout(state.pendingTimer);
|
|
@@ -619,6 +703,8 @@ export class AutoContinueRunner {
|
|
|
619
703
|
state.offlineWait = undefined;
|
|
620
704
|
}
|
|
621
705
|
this.states.clear();
|
|
706
|
+
this.parents.clear();
|
|
707
|
+
this.subagentSessions.clear();
|
|
622
708
|
}
|
|
623
709
|
|
|
624
710
|
private state(sessionId: SessionId): SessionState {
|
|
@@ -630,33 +716,201 @@ export class AutoContinueRunner {
|
|
|
630
716
|
return state;
|
|
631
717
|
}
|
|
632
718
|
|
|
633
|
-
/**
|
|
634
|
-
private
|
|
635
|
-
|
|
636
|
-
|
|
719
|
+
/** Record a subagent session's lineage and its parent id when the header carries one. */
|
|
720
|
+
private noteSubagent(sessionId: SessionId, parentSession?: SessionId): void {
|
|
721
|
+
this.subagentSessions.add(sessionId);
|
|
722
|
+
if (parentSession !== undefined && parentSession !== '') {
|
|
723
|
+
this.parents.set(sessionId, parentSession);
|
|
724
|
+
} else if (!this.parents.has(sessionId)) {
|
|
725
|
+
this.parents.set(sessionId, undefined);
|
|
726
|
+
}
|
|
637
727
|
}
|
|
638
728
|
|
|
639
729
|
/** Read durable origin from the live agent for direct action paths as well. */
|
|
640
730
|
private isSubagent(sessionId: SessionId, state: SessionState): boolean {
|
|
641
731
|
if (state.subagent) return true;
|
|
642
|
-
const
|
|
643
|
-
if (
|
|
644
|
-
|
|
732
|
+
const header = this.ctx.agents.get(sessionId)?.session?.header;
|
|
733
|
+
if (header?.origin !== 'subagent') return false;
|
|
734
|
+
state.subagent = true;
|
|
735
|
+
this.noteSubagent(sessionId, header.parentSession);
|
|
645
736
|
return true;
|
|
646
737
|
}
|
|
647
738
|
|
|
739
|
+
/** Header origin, cached set or state flag; for paths that only have the session id. */
|
|
740
|
+
private isSubagentSession(sessionId: SessionId): boolean {
|
|
741
|
+
if (this.subagentSessions.has(sessionId)) return true;
|
|
742
|
+
const state = this.states.get(sessionId);
|
|
743
|
+
if (state?.subagent === true) return true;
|
|
744
|
+
const header = this.ctx.agents.get(sessionId)?.session?.header;
|
|
745
|
+
if (header?.origin !== 'subagent') return false;
|
|
746
|
+
this.noteSubagent(sessionId, header.parentSession);
|
|
747
|
+
return true;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* Direct subagent parent id. DSH stores fork lineage in the same
|
|
752
|
+
* `header.parentSession` field, so only a session whose header origin is
|
|
753
|
+
* `subagent` may be followed upward: an ordinary ancestor (the visible main
|
|
754
|
+
* conversation, even a forked one) is the top of the recovery lineage.
|
|
755
|
+
*/
|
|
756
|
+
private parentOf(sessionId: SessionId): SessionId | undefined {
|
|
757
|
+
if (this.parents.has(sessionId)) return this.parents.get(sessionId);
|
|
758
|
+
const header = this.ctx.agents.get(sessionId)?.session?.header;
|
|
759
|
+
// No live header yet: leave the lineage unresolved so a later live agent
|
|
760
|
+
// with the same id can still provide it instead of caching "no parent".
|
|
761
|
+
if (header === undefined) return undefined;
|
|
762
|
+
if (header.origin !== 'subagent') {
|
|
763
|
+
this.parents.set(sessionId, undefined); // known ordinary: top of the lineage
|
|
764
|
+
return undefined;
|
|
765
|
+
}
|
|
766
|
+
const parent = header.parentSession;
|
|
767
|
+
this.noteSubagent(sessionId, parent);
|
|
768
|
+
return parent;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/** Explicit session mode stored for this exact id, if the user gave one. */
|
|
772
|
+
private explicitMode(sessionId: SessionId): SessionMode | undefined {
|
|
773
|
+
const modes = this.getConfig().sessionModes;
|
|
774
|
+
const mode = modes[sessionId];
|
|
775
|
+
return Object.prototype.hasOwnProperty.call(modes, sessionId) && isSessionMode(mode) ? mode : undefined;
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
/**
|
|
779
|
+
* A subagent's effective mode, or `undefined` when the lineage cannot be
|
|
780
|
+
* verified. An intermediate parent that is no longer live (and was never seen
|
|
781
|
+
* here) used to stop the walk early, fall back to the profile default and
|
|
782
|
+
* resume a child whose main conversation is Off; refusing the send is safe.
|
|
783
|
+
*/
|
|
784
|
+
private resolveSubagentMode(sessionId: SessionId): SessionMode | undefined {
|
|
785
|
+
const own = this.explicitMode(sessionId);
|
|
786
|
+
if (own !== undefined) return own;
|
|
787
|
+
const seen = new Set<SessionId>([sessionId]);
|
|
788
|
+
let current: SessionId = sessionId;
|
|
789
|
+
for (let depth = 0; depth < 32; depth += 1) {
|
|
790
|
+
const known = this.parents.has(current);
|
|
791
|
+
const header = this.ctx.agents.get(current)?.session?.header;
|
|
792
|
+
// The chain is not visible yet (an intermediate parent never live here), so
|
|
793
|
+
// neither its mode nor its pause can be verified. Refuse the send and
|
|
794
|
+
// re-resolve on the next event once that ancestor appears.
|
|
795
|
+
if (!known && header === undefined) return undefined;
|
|
796
|
+
const parent = known
|
|
797
|
+
? this.parents.get(current)
|
|
798
|
+
: header?.origin === 'subagent' ? header.parentSession : undefined;
|
|
799
|
+
if (parent === undefined || parent === '') {
|
|
800
|
+
// A subagent without `parentSession` is unlinked: nothing to inherit. Check the
|
|
801
|
+
// cached flag too, so this still holds once the child's header is gone.
|
|
802
|
+
if (header?.origin === 'subagent' || this.subagentSessions.has(current)) return undefined;
|
|
803
|
+
return this.explicitMode(current) ?? 'default';
|
|
804
|
+
}
|
|
805
|
+
if (seen.has(parent)) return undefined;
|
|
806
|
+
seen.add(parent);
|
|
807
|
+
current = parent;
|
|
808
|
+
}
|
|
809
|
+
return undefined;
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/** Whether the setting and the inherited main-chat mode allow live recovery for this child. */
|
|
813
|
+
private subagentRecoveryEnabled(sessionId: SessionId): boolean {
|
|
814
|
+
if (!this.getConfig().resumeSubagentSessions) return false;
|
|
815
|
+
const mode = this.resolveSubagentMode(sessionId);
|
|
816
|
+
return mode !== undefined && mode !== 'off';
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/** Modes children inherit from their main conversation, for the composer's display. */
|
|
820
|
+
inheritedSubagentModes(): Record<string, SessionMode> {
|
|
821
|
+
this.pruneLineage();
|
|
822
|
+
const inherited: Record<string, SessionMode> = {};
|
|
823
|
+
for (const sessionId of this.parents.keys()) {
|
|
824
|
+
// Only children that are still loaded can show a composer; skip the rest.
|
|
825
|
+
if (this.ctx.agents.get(sessionId) === undefined) continue;
|
|
826
|
+
if (!this.isSubagentSession(sessionId)) continue;
|
|
827
|
+
if (this.explicitMode(sessionId) !== undefined) continue;
|
|
828
|
+
const mode = this.resolveSubagentMode(sessionId);
|
|
829
|
+
// Children never run the autonomous loop, so a loop parent means recovery for them.
|
|
830
|
+
if (mode !== undefined) inherited[sessionId] = mode === 'loop' ? 'recover' : mode;
|
|
831
|
+
}
|
|
832
|
+
return inherited;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
/**
|
|
836
|
+
* Keep the lineage caches bounded on long-lived hosts. Once the cache grows,
|
|
837
|
+
* entries for sessions that are no longer loaded are dropped; they are re-read
|
|
838
|
+
* from the live header if the session comes back.
|
|
839
|
+
*/
|
|
840
|
+
private pruneLineage(): void {
|
|
841
|
+
if (this.parents.size + this.subagentSessions.size <= LINEAGE_CACHE_LIMIT) return;
|
|
842
|
+
// `states` keeps its own `subagent` flag, so dropping a non-loaded child here loses nothing.
|
|
843
|
+
const keep = (sessionId: SessionId) => this.ctx.agents.get(sessionId) !== undefined;
|
|
844
|
+
const needed = new Set<SessionId>();
|
|
845
|
+
for (const sessionId of this.parents.keys()) {
|
|
846
|
+
if (!keep(sessionId)) continue;
|
|
847
|
+
// Keep the chain above a loaded child so its inherited mode still resolves.
|
|
848
|
+
let current: SessionId | undefined = sessionId;
|
|
849
|
+
for (let depth = 0; depth < 32 && current !== undefined && !needed.has(current); depth += 1) {
|
|
850
|
+
needed.add(current);
|
|
851
|
+
current = this.parents.get(current);
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
for (const sessionId of [...this.parents.keys()]) if (!needed.has(sessionId)) this.parents.delete(sessionId);
|
|
855
|
+
for (const sessionId of [...this.subagentSessions]) if (!needed.has(sessionId) && !keep(sessionId)) this.subagentSessions.delete(sessionId);
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
/** Mark a child session; drop only queued sends that its effective policy no longer allows. */
|
|
859
|
+
private markSubagent(sessionId: SessionId, state: SessionState, parentSession?: SessionId): void {
|
|
860
|
+
const first = !state.subagent;
|
|
861
|
+
state.subagent = true;
|
|
862
|
+
this.noteSubagent(sessionId, parentSession);
|
|
863
|
+
if (first && !this.subagentRecoveryEnabled(sessionId)) this.cancelPending(sessionId, '子代理会话');
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
/** Pause deadline, including the parents' "pause this session 1h" for subagents. */
|
|
867
|
+
private effectivePauseUntil(sessionId: SessionId): number {
|
|
868
|
+
let until = this.pauseUntil.get(sessionId) ?? 0;
|
|
869
|
+
if (!this.isSubagentSession(sessionId)) return until;
|
|
870
|
+
// parentOf() only follows subagent-origin sessions, so fork lineage of the
|
|
871
|
+
// main conversation is never treated as a parent for pause purposes.
|
|
872
|
+
const seen = new Set<SessionId>([sessionId]);
|
|
873
|
+
let current: SessionId | undefined = sessionId;
|
|
874
|
+
for (let depth = 0; depth < 32; depth += 1) {
|
|
875
|
+
current = this.parentOf(current);
|
|
876
|
+
if (current === undefined || current === '' || seen.has(current)) break;
|
|
877
|
+
seen.add(current);
|
|
878
|
+
until = Math.max(until, this.pauseUntil.get(current) ?? 0);
|
|
879
|
+
}
|
|
880
|
+
return until;
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
/** Whether this session sits below `ancestorId` in the subagent lineage (never fork lineage). */
|
|
884
|
+
private isDescendantOf(sessionId: SessionId, ancestorId: SessionId): boolean {
|
|
885
|
+
const seen = new Set<SessionId>([sessionId]);
|
|
886
|
+
let current: SessionId | undefined = sessionId;
|
|
887
|
+
for (let depth = 0; depth < 32; depth += 1) {
|
|
888
|
+
current = this.parentOf(current);
|
|
889
|
+
if (current === undefined || current === '') return false;
|
|
890
|
+
if (current === ancestorId) return true;
|
|
891
|
+
if (seen.has(current)) return false;
|
|
892
|
+
seen.add(current);
|
|
893
|
+
}
|
|
894
|
+
return false;
|
|
895
|
+
}
|
|
896
|
+
|
|
648
897
|
/**
|
|
649
898
|
* 事件入口(host 单实例): 预处理工具调用/结果/模型消息(护栏与循环信号),
|
|
650
899
|
* 然后交给回合状态机。
|
|
651
900
|
*/
|
|
652
901
|
private onHostEvent(session: Session, event: SessionEvent): void {
|
|
653
902
|
const sessionId = session.id;
|
|
903
|
+
// A main conversation that just came live again receives the hand-offs that
|
|
904
|
+
// were deferred while it had no agent.
|
|
905
|
+
this.flushDeferredHandoffs(sessionId);
|
|
654
906
|
const sessionState = this.states.get(sessionId);
|
|
655
907
|
if (session.header?.origin === 'subagent') {
|
|
656
|
-
this.markSubagent(sessionId, sessionState ?? this.state(sessionId));
|
|
657
|
-
|
|
908
|
+
this.markSubagent(sessionId, sessionState ?? this.state(sessionId), session.header.parentSession);
|
|
909
|
+
} else if (sessionState?.subagent) {
|
|
910
|
+
// Origin known from an earlier frame; keep the lineage fresh and process the
|
|
911
|
+
// event normally instead of ignoring a subagent's live turn.
|
|
912
|
+
this.noteSubagent(sessionId, session.header?.parentSession ?? this.parentOf(sessionId));
|
|
658
913
|
}
|
|
659
|
-
if (sessionState?.subagent) return;
|
|
660
914
|
if (sessionState?.maintenanceTurn !== undefined &&
|
|
661
915
|
sessionState.maintenanceTurn === (event.data as { turn?: number }).turn &&
|
|
662
916
|
event.type !== 'turn/start' && event.type !== 'turn/end') return;
|
|
@@ -1004,12 +1258,14 @@ export class AutoContinueRunner {
|
|
|
1004
1258
|
if (this.sessionConfig(sessionId).resumeCompletedTurns) {
|
|
1005
1259
|
if (turnOutput === 'visible') {
|
|
1006
1260
|
state.consecutive = 0;
|
|
1261
|
+
state.recovering = false;
|
|
1007
1262
|
state.lastFailure = undefined;
|
|
1008
1263
|
this.noteRecovery(sessionId, 'completed');
|
|
1009
1264
|
}
|
|
1010
1265
|
this.schedule(sessionId, LOOP_COMPLETED_REASON, true);
|
|
1011
1266
|
} else if (turnOutput === 'visible') {
|
|
1012
1267
|
state.consecutive = 0;
|
|
1268
|
+
state.recovering = false;
|
|
1013
1269
|
state.lastFailure = undefined;
|
|
1014
1270
|
this.noteRecovery(sessionId, 'completed');
|
|
1015
1271
|
}
|
|
@@ -1049,6 +1305,7 @@ export class AutoContinueRunner {
|
|
|
1049
1305
|
} else {
|
|
1050
1306
|
// 用户主动停止: 不自动继续, 视为用户介入
|
|
1051
1307
|
state.consecutive = 0;
|
|
1308
|
+
state.recovering = false;
|
|
1052
1309
|
state.pendingRecoveryAt = 0;
|
|
1053
1310
|
}
|
|
1054
1311
|
} else if (reasonKind === 'blocked') {
|
|
@@ -1083,6 +1340,7 @@ export class AutoContinueRunner {
|
|
|
1083
1340
|
if (event.data.source.kind === 'user') {
|
|
1084
1341
|
// 用户手动介入: 清零上限与跨标签页发送计数
|
|
1085
1342
|
state.consecutive = 0;
|
|
1343
|
+
state.recovering = false;
|
|
1086
1344
|
this.resetLoopIterations(state);
|
|
1087
1345
|
this.cancelPending(sessionId, '用户手动发送消息');
|
|
1088
1346
|
}
|
|
@@ -1096,7 +1354,21 @@ export class AutoContinueRunner {
|
|
|
1096
1354
|
|
|
1097
1355
|
private onTurnFailure(sessionId: SessionId, reason: string, failure: FailureFacts): void {
|
|
1098
1356
|
const config = this.getConfig();
|
|
1099
|
-
if (
|
|
1357
|
+
if (this.isSubagentSession(sessionId)) {
|
|
1358
|
+
// Subagents inherit only the main conversation's enabled/off decision; an
|
|
1359
|
+
// Off parent or the disabled setting means no live recovery at all. The
|
|
1360
|
+
// global pause is not checked here, so diagnostics for permanent errors
|
|
1361
|
+
// match ordinary sessions while paused.
|
|
1362
|
+
if (!this.subagentRecoveryEnabled(sessionId)) {
|
|
1363
|
+
const parent = this.parentOf(sessionId);
|
|
1364
|
+
if (parent !== undefined && parent !== '' && this.ctx.agents.get(parent) === undefined) {
|
|
1365
|
+
// Lineage is known but the parent is offline: keep the failure so the
|
|
1366
|
+
// hand-off is delivered once the main conversation is live again.
|
|
1367
|
+
this.deferHandoff(parent, sessionId, this.handoffText(sessionId, reason));
|
|
1368
|
+
}
|
|
1369
|
+
return;
|
|
1370
|
+
}
|
|
1371
|
+
} else if (sessionMode(config.sessionModes, sessionId) === 'off') return;
|
|
1100
1372
|
if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
|
|
1101
1373
|
const copy = NOTICE_COPY[config.locale];
|
|
1102
1374
|
const summary = `${failure.code}${failure.status !== undefined ? ` (HTTP ${failure.status})` : ''}`;
|
|
@@ -1136,6 +1408,12 @@ export class AutoContinueRunner {
|
|
|
1136
1408
|
this.log(`通知按钮: 暂停 ${sessionId} 1 小时`);
|
|
1137
1409
|
this.pauseUntil.set(sessionId, Date.now() + 60 * 60 * 1000);
|
|
1138
1410
|
this.cancelPending(sessionId, '通知按钮暂停该会话');
|
|
1411
|
+
// A paused main conversation also suspends the subagents it owns.
|
|
1412
|
+
for (const candidate of this.states.keys()) {
|
|
1413
|
+
if (candidate !== sessionId && this.isDescendantOf(candidate, sessionId)) {
|
|
1414
|
+
this.cancelPending(candidate, '父会话已暂停');
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1139
1417
|
}
|
|
1140
1418
|
}
|
|
1141
1419
|
|
|
@@ -1205,12 +1483,13 @@ export class AutoContinueRunner {
|
|
|
1205
1483
|
/** 立即为该会话发送一次自动继续(无视冷却与连续上限; 由通知按钮触发)。 */
|
|
1206
1484
|
async resumeNow(sessionId: SessionId): Promise<void> {
|
|
1207
1485
|
if (this.disposed) return;
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1486
|
+
// Subagent recovery is opt-out and inherits the main conversation's mode: an
|
|
1487
|
+
// Off child must not receive a send through the explicit button either, even
|
|
1488
|
+
// though a manual send bypasses the paused flag.
|
|
1489
|
+
if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) return;
|
|
1490
|
+
// A manual send replaces every queued one: leave a pending cooldown or
|
|
1491
|
+
// offline retry armed and the reader receives the continuation twice.
|
|
1492
|
+
this.cancelPending(sessionId, '手动续跑');
|
|
1214
1493
|
try {
|
|
1215
1494
|
await this.fire(sessionId, MANUAL_NOTIFICATION_REASON, true);
|
|
1216
1495
|
} catch (error) {
|
|
@@ -1233,12 +1512,11 @@ export class AutoContinueRunner {
|
|
|
1233
1512
|
const state = this.state(sessionId);
|
|
1234
1513
|
const config = this.sessionConfig(sessionId);
|
|
1235
1514
|
if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
|
|
1236
|
-
if (this.isSubagent(sessionId, state)) return; // 子代理会话由父代理处理, 不抢跑
|
|
1237
1515
|
if (config.paused) {
|
|
1238
1516
|
this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
|
|
1239
1517
|
return;
|
|
1240
1518
|
}
|
|
1241
|
-
if (Date.now() <
|
|
1519
|
+
if (Date.now() < this.effectivePauseUntil(sessionId)) {
|
|
1242
1520
|
this.log(`跳过 ${sessionId}(${reason}): 会话暂停中`);
|
|
1243
1521
|
return;
|
|
1244
1522
|
}
|
|
@@ -1275,6 +1553,7 @@ export class AutoContinueRunner {
|
|
|
1275
1553
|
}, config.graceMs);
|
|
1276
1554
|
state.pendingTimer = timer;
|
|
1277
1555
|
state.pendingReason = reason;
|
|
1556
|
+
state.recovering = true;
|
|
1278
1557
|
const template = this.templateFor(config, reason);
|
|
1279
1558
|
this.log(
|
|
1280
1559
|
`检测到非人为中断 ${sessionId}(${reason}), ${config.graceMs}ms 后自动发送「${template}」`,
|
|
@@ -1289,6 +1568,7 @@ export class AutoContinueRunner {
|
|
|
1289
1568
|
const state = this.state(sessionId);
|
|
1290
1569
|
if (state.cooldownRetryTimer !== undefined) clearTimeout(state.cooldownRetryTimer);
|
|
1291
1570
|
state.pendingReason = reason;
|
|
1571
|
+
state.recovering = true;
|
|
1292
1572
|
state.cooldownRetryTimer = setTimeout(() => {
|
|
1293
1573
|
state.cooldownRetryTimer = undefined;
|
|
1294
1574
|
state.pendingReason = undefined;
|
|
@@ -1342,6 +1622,234 @@ export class AutoContinueRunner {
|
|
|
1342
1622
|
if (cancelled) this.log(`取消 ${sessionId} 的自动继续(${why})`);
|
|
1343
1623
|
}
|
|
1344
1624
|
|
|
1625
|
+
/** Host-service facade used to cold-resume a disposed direct child. */
|
|
1626
|
+
private subagentPromptProvider: (() => unknown) | undefined;
|
|
1627
|
+
|
|
1628
|
+
/** Attach the loader-provided subagent service; it may load after this plugin. */
|
|
1629
|
+
setSubagentPromptProvider(provider: (() => unknown) | undefined): void {
|
|
1630
|
+
this.subagentPromptProvider = provider;
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
private subagentPrompts(): {
|
|
1634
|
+
prompt?: (
|
|
1635
|
+
request: {
|
|
1636
|
+
parentSessionId: string;
|
|
1637
|
+
childSessionId: string;
|
|
1638
|
+
mode: 'continuable';
|
|
1639
|
+
requestId: string;
|
|
1640
|
+
content: readonly { type: 'text'; text: string }[];
|
|
1641
|
+
delivery: 'queue' | 'steer';
|
|
1642
|
+
},
|
|
1643
|
+
signal: AbortSignal,
|
|
1644
|
+
) => Promise<{ messageId?: string }>
|
|
1645
|
+
} | undefined {
|
|
1646
|
+
const provided = this.subagentPromptProvider?.();
|
|
1647
|
+
if (provided !== undefined && provided !== null) return provided as ReturnType<typeof this.subagentPrompts>;
|
|
1648
|
+
try {
|
|
1649
|
+
return this.ctx.get('subagents') as ReturnType<typeof this.subagentPrompts>;
|
|
1650
|
+
} catch {
|
|
1651
|
+
return undefined;
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
/** Copy for one child hand-off, built once so a deferred delivery matches. */
|
|
1656
|
+
private handoffText(sessionId: SessionId, reason: string): string {
|
|
1657
|
+
const code = this.state(sessionId).lastFailure?.code ?? reason;
|
|
1658
|
+
return HANDOFF_COPY[this.sessionConfig(sessionId).locale](sessionId, code);
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
/**
|
|
1662
|
+
* Revive a disposed child through the host's cold resume and deliver the
|
|
1663
|
+
* continuation to it. Falls back to the main-conversation hand-off when the
|
|
1664
|
+
* host cannot resume (no persistence, no live parent, not a direct child).
|
|
1665
|
+
* The child's own recovery mode decides; the parent only has to be alive to
|
|
1666
|
+
* authorize the call.
|
|
1667
|
+
*/
|
|
1668
|
+
private async reviveChild(sessionId: SessionId, reason: string, text: string, force: boolean): Promise<void> {
|
|
1669
|
+
if (this.disposed || this.getConfig().paused) return;
|
|
1670
|
+
if (!this.subagentRecoveryEnabled(sessionId)) return;
|
|
1671
|
+
const state = this.state(sessionId);
|
|
1672
|
+
if (state.reviveInFlight === true) {
|
|
1673
|
+
this.log(`冷恢复跳过 ${sessionId}: 已有请求在途中`);
|
|
1674
|
+
return;
|
|
1675
|
+
}
|
|
1676
|
+
const config = this.sessionConfig(sessionId);
|
|
1677
|
+
if (!force) {
|
|
1678
|
+
// Cold resume spends the same retry budget as a live send: record the
|
|
1679
|
+
// attempt before awaiting, otherwise repeated failures bypass cooldown and
|
|
1680
|
+
// the consecutive cap.
|
|
1681
|
+
if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) {
|
|
1682
|
+
this.log(`冷恢复跳过 ${sessionId}: 处于冷却期`);
|
|
1683
|
+
return;
|
|
1684
|
+
}
|
|
1685
|
+
if (state.consecutive >= config.maxConsecutive) {
|
|
1686
|
+
this.log(`冷恢复跳过 ${sessionId}: 已连续自动继续 ${state.consecutive} 次`);
|
|
1687
|
+
return;
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
const parent = this.parentOf(sessionId);
|
|
1691
|
+
if (parent === undefined || parent === '') return;
|
|
1692
|
+
const handoff = this.handoffText(sessionId, reason);
|
|
1693
|
+
const parentAgent = this.ctx.agents.get(parent);
|
|
1694
|
+
if (parentAgent === undefined) {
|
|
1695
|
+
this.deferHandoff(parent, sessionId, handoff);
|
|
1696
|
+
return;
|
|
1697
|
+
}
|
|
1698
|
+
const prompts = this.subagentPrompts();
|
|
1699
|
+
if (typeof prompts?.prompt !== 'function') {
|
|
1700
|
+
this.handOffToParent(sessionId, reason, handoff);
|
|
1701
|
+
return;
|
|
1702
|
+
}
|
|
1703
|
+
state.lastAttemptAt = Date.now();
|
|
1704
|
+
state.consecutive += 1;
|
|
1705
|
+
state.reviveInFlight = true;
|
|
1706
|
+
const controller = new AbortController();
|
|
1707
|
+
this.reviveControllers.add(controller);
|
|
1708
|
+
let timedOut = false;
|
|
1709
|
+
const timeout = setTimeout(() => {
|
|
1710
|
+
timedOut = true;
|
|
1711
|
+
controller.abort();
|
|
1712
|
+
}, REVIVE_TIMEOUT_MS);
|
|
1713
|
+
try {
|
|
1714
|
+
await prompts.prompt(
|
|
1715
|
+
{
|
|
1716
|
+
parentSessionId: parent,
|
|
1717
|
+
childSessionId: sessionId,
|
|
1718
|
+
mode: 'continuable',
|
|
1719
|
+
requestId: randomUUID(),
|
|
1720
|
+
content: [{ type: 'text', text }],
|
|
1721
|
+
delivery: 'queue',
|
|
1722
|
+
},
|
|
1723
|
+
controller.signal,
|
|
1724
|
+
);
|
|
1725
|
+
this.log(`已冷恢复子代理 ${sessionId}`);
|
|
1726
|
+
} catch (error) {
|
|
1727
|
+
// An unload aborts the call on purpose; deliver nothing after opting out.
|
|
1728
|
+
if (this.disposed) return;
|
|
1729
|
+
this.log(`冷恢复 ${sessionId} 失败${timedOut ? '(超时)' : ''}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1730
|
+
this.handOffToParent(sessionId, reason, handoff);
|
|
1731
|
+
} finally {
|
|
1732
|
+
clearTimeout(timeout);
|
|
1733
|
+
this.reviveControllers.delete(controller);
|
|
1734
|
+
state.reviveInFlight = false;
|
|
1735
|
+
}
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
/** Existing state of a session, without materializing one just to read it. */
|
|
1739
|
+
private parentState(sessionId: SessionId): SessionState | undefined {
|
|
1740
|
+
return this.states.get(sessionId);
|
|
1741
|
+
}
|
|
1742
|
+
|
|
1743
|
+
/** Whether this session already has a continuation on the way. */
|
|
1744
|
+
private hasPendingSend(state: SessionState): boolean {
|
|
1745
|
+
return state.pendingTimer !== undefined
|
|
1746
|
+
|| state.cooldownRetryTimer !== undefined
|
|
1747
|
+
|| state.loopRetryTimer !== undefined
|
|
1748
|
+
|| state.offlineWait !== undefined
|
|
1749
|
+
|| state.offlineTimer !== undefined;
|
|
1750
|
+
}
|
|
1751
|
+
|
|
1752
|
+
/**
|
|
1753
|
+
* Ask the child's main conversation to take over a failure the plugin cannot
|
|
1754
|
+
* repair itself: the child handle is gone, so only the root can continue it.
|
|
1755
|
+
* The main conversation's Off is respected because this writes a user message
|
|
1756
|
+
* into it; a child's own mode is never overridden by that Off for cold resume.
|
|
1757
|
+
*/
|
|
1758
|
+
private handOffToParent(sessionId: SessionId, reason: string, text?: string): void {
|
|
1759
|
+
if (this.disposed || this.getConfig().paused) return;
|
|
1760
|
+
if (!this.subagentRecoveryEnabled(sessionId)) return;
|
|
1761
|
+
const parent = this.parentOf(sessionId);
|
|
1762
|
+
if (parent === undefined || parent === '') return;
|
|
1763
|
+
if (this.explicitMode(parent) === 'off') return;
|
|
1764
|
+
const state = this.state(sessionId);
|
|
1765
|
+
const now = Date.now();
|
|
1766
|
+
if (state.handedOffAt !== undefined && now - state.handedOffAt < HANDOFF_COOLDOWN_MS) return;
|
|
1767
|
+
const handoff = text ?? this.handoffText(sessionId, reason);
|
|
1768
|
+
const parentAgent = this.ctx.agents.get(parent);
|
|
1769
|
+
if (parentAgent === undefined) {
|
|
1770
|
+
this.deferHandoff(parent, sessionId, handoff);
|
|
1771
|
+
return;
|
|
1772
|
+
}
|
|
1773
|
+
// Any user message into the main conversation cancels its queued continuation,
|
|
1774
|
+
// and DSH already tells it which child failed. Stay silent while it recovers.
|
|
1775
|
+
const parentState = this.parentState(parent);
|
|
1776
|
+
if (parentState !== undefined && (parentState.recovering === true || this.hasPendingSend(parentState))) {
|
|
1777
|
+
this.log(`移交跳过 ${sessionId}: 主会话 ${parent} 正在自行恢复`);
|
|
1778
|
+
return;
|
|
1779
|
+
}
|
|
1780
|
+
try {
|
|
1781
|
+
this.sendHandoff(parent, parentAgent, handoff);
|
|
1782
|
+
state.handedOffAt = now;
|
|
1783
|
+
this.log(`已将子代理 ${sessionId} 的失败移交主会话 ${parent}`);
|
|
1784
|
+
} catch (error) {
|
|
1785
|
+
this.log(`移交 ${sessionId} 失败: ${error instanceof Error ? error.message : String(error)}`);
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
/**
|
|
1790
|
+
* Post a hand-off into the main conversation the same way a continuation is
|
|
1791
|
+
* sent: with the configured message source, and registered as our own echo so
|
|
1792
|
+
* the parent does not read it as the user stepping in (which would reset its
|
|
1793
|
+
* retry and loop counters and cancel whatever it had queued).
|
|
1794
|
+
*/
|
|
1795
|
+
private sendHandoff(parent: SessionId, parentAgent: Agent, text: string): void {
|
|
1796
|
+
const parentState = this.state(parent);
|
|
1797
|
+
const message = createUserMessage({
|
|
1798
|
+
content: [{ type: 'text', text }],
|
|
1799
|
+
source: { kind: this.getConfig().usePluginSource ? AUTO_CONTINUE_SOURCE_KIND : 'user' },
|
|
1800
|
+
});
|
|
1801
|
+
trackPendingEcho(parentState, message.id);
|
|
1802
|
+
try {
|
|
1803
|
+
parentAgent.followup(message);
|
|
1804
|
+
} catch (error) {
|
|
1805
|
+
forgetPendingEcho(parentState, message.id);
|
|
1806
|
+
throw error;
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
/** Keep one hand-off until its main conversation has a live agent again. */
|
|
1811
|
+
private deferHandoff(parent: SessionId, sessionId: SessionId, text: string): void {
|
|
1812
|
+
// Only live subagent recovery hands failures off; with it off nothing is kept.
|
|
1813
|
+
if (!this.getConfig().resumeSubagentSessions) return;
|
|
1814
|
+
const state = this.state(sessionId);
|
|
1815
|
+
const now = Date.now();
|
|
1816
|
+
if (state.handedOffAt !== undefined && now - state.handedOffAt < HANDOFF_COOLDOWN_MS) return;
|
|
1817
|
+
let pending = this.deferredHandoffs.get(parent);
|
|
1818
|
+
if (pending === undefined) {
|
|
1819
|
+
pending = new Map();
|
|
1820
|
+
this.deferredHandoffs.set(parent, pending);
|
|
1821
|
+
}
|
|
1822
|
+
pending.set(sessionId, text);
|
|
1823
|
+
this.log(`移交暂存 ${sessionId}: 主会话 ${parent} 无 live agent`);
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
/** Deliver queued hand-offs once their main conversation is live again. */
|
|
1827
|
+
private flushDeferredHandoffs(parent: SessionId): void {
|
|
1828
|
+
const pending = this.deferredHandoffs.get(parent);
|
|
1829
|
+
if (pending === undefined || pending.size === 0) return;
|
|
1830
|
+
if (this.explicitMode(parent) === 'off') {
|
|
1831
|
+
this.deferredHandoffs.delete(parent);
|
|
1832
|
+
return;
|
|
1833
|
+
}
|
|
1834
|
+
const parentAgent = this.ctx.agents.get(parent);
|
|
1835
|
+
if (parentAgent === undefined) return;
|
|
1836
|
+
this.deferredHandoffs.delete(parent);
|
|
1837
|
+
const now = Date.now();
|
|
1838
|
+
for (const [child, text] of pending) {
|
|
1839
|
+
// The parent may have turned the child's recovery off meanwhile.
|
|
1840
|
+
if (!this.subagentRecoveryEnabled(child)) continue;
|
|
1841
|
+
const state = this.state(child);
|
|
1842
|
+
if (state.handedOffAt !== undefined && now - state.handedOffAt < HANDOFF_COOLDOWN_MS) continue;
|
|
1843
|
+
try {
|
|
1844
|
+
this.sendHandoff(parent, parentAgent, text);
|
|
1845
|
+
state.handedOffAt = now;
|
|
1846
|
+
this.log(`已移交暂存子代理 ${child} 给主会话 ${parent}`);
|
|
1847
|
+
} catch (error) {
|
|
1848
|
+
this.log(`暂存移交 ${child} 失败: ${error instanceof Error ? error.message : String(error)}`);
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
|
|
1345
1853
|
private fire(sessionId: SessionId, reason: string, force = false): void {
|
|
1346
1854
|
if (this.disposed) return;
|
|
1347
1855
|
const state = this.state(sessionId);
|
|
@@ -1351,12 +1859,22 @@ export class AutoContinueRunner {
|
|
|
1351
1859
|
// 宽限期内循环被关闭: 发送前必须重新检查开关, 与 :silent 恢复同样处理。
|
|
1352
1860
|
// 否则「关掉循环」后仍会多发出一次续跑。
|
|
1353
1861
|
if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
|
|
1354
|
-
|
|
1862
|
+
// Direct sends (notifications) must respect the setting and the inherited
|
|
1863
|
+
// mode even though they bypass the paused flag below.
|
|
1864
|
+
if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) {
|
|
1865
|
+
const parent = this.parentOf(sessionId);
|
|
1866
|
+
if (parent !== undefined && parent !== '' && this.ctx.agents.get(parent) === undefined) {
|
|
1867
|
+
// Lineage is known but the parent is offline: keep the failure so the
|
|
1868
|
+
// hand-off can be delivered once the main conversation is live again.
|
|
1869
|
+
this.deferHandoff(parent, sessionId, this.handoffText(sessionId, reason));
|
|
1870
|
+
}
|
|
1871
|
+
return;
|
|
1872
|
+
}
|
|
1355
1873
|
if (config.paused && !manualResume) {
|
|
1356
1874
|
this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
|
|
1357
1875
|
return;
|
|
1358
1876
|
}
|
|
1359
|
-
if (!manualResume && Date.now() <
|
|
1877
|
+
if (!manualResume && Date.now() < this.effectivePauseUntil(sessionId)) {
|
|
1360
1878
|
this.log(`跳过 ${sessionId}(${reason}): 会话暂停中`);
|
|
1361
1879
|
return;
|
|
1362
1880
|
}
|
|
@@ -1375,6 +1893,14 @@ export class AutoContinueRunner {
|
|
|
1375
1893
|
// 发送: followup 负责唤醒; 同步 inbox 插入事件会在唤醒前把本消息移到已有队列之前。
|
|
1376
1894
|
const agent = this.ctx.agents.get(sessionId);
|
|
1377
1895
|
if (agent === undefined) {
|
|
1896
|
+
// A failed child is settled and disposed by the subagent runtime before the
|
|
1897
|
+
// send window opens, so a direct resume cannot reach it. Ask the host to
|
|
1898
|
+
// cold-resume it from persistence; when that is unavailable, hand the
|
|
1899
|
+
// failure to its main conversation instead. A manual "Resume now" must
|
|
1900
|
+
// revive a disposed child too: its force flag only relaxes the cooldown.
|
|
1901
|
+
if (this.isSubagentSession(sessionId) && this.subagentRecoveryEnabled(sessionId)) {
|
|
1902
|
+
void this.reviveChild(sessionId, reason, text, manualResume);
|
|
1903
|
+
}
|
|
1378
1904
|
this.log(`跳过 ${sessionId}(${reason}): 无 live agent`);
|
|
1379
1905
|
return;
|
|
1380
1906
|
}
|
|
@@ -1396,6 +1922,9 @@ export class AutoContinueRunner {
|
|
|
1396
1922
|
this.prioritizedFollowups.delete(message.id);
|
|
1397
1923
|
}
|
|
1398
1924
|
const now = Date.now();
|
|
1925
|
+
// The continuation is on the wire: the session is recovering itself until a
|
|
1926
|
+
// successful turn ends or the user intervenes. Child hand-offs read this.
|
|
1927
|
+
state.recovering = true;
|
|
1399
1928
|
// 续跑已发出: 被重启失活的 goal 需要在这里重新武装, 否则续跑消息会跑但
|
|
1400
1929
|
// goal 的自动继续轮不会转起来(disarm 是宿主卸载驱动的正常动作)。
|
|
1401
1930
|
this.rearmGoal(sessionId, config);
|
|
@@ -1500,6 +2029,7 @@ export class AutoContinueRunner {
|
|
|
1500
2029
|
const token = {};
|
|
1501
2030
|
state.offlineWait = token;
|
|
1502
2031
|
state.pendingReason = reason;
|
|
2032
|
+
state.recovering = true;
|
|
1503
2033
|
void this.checkConnectivity().then((online) => {
|
|
1504
2034
|
if (this.disposed || state.offlineWait !== token) return; // 已被取消或被新的检测取代
|
|
1505
2035
|
if (online) {
|
|
@@ -1648,7 +2178,9 @@ export class AutoContinueRunner {
|
|
|
1648
2178
|
const event = events[i];
|
|
1649
2179
|
if (event?.type === 'turn/end') { lastEnd = event; break; }
|
|
1650
2180
|
}
|
|
1651
|
-
|
|
2181
|
+
let reasonKind = readReasonKind(lastEnd?.data.reason);
|
|
2182
|
+
// A host-closed tail (`disposed`/`legacy`) is a restart signature, not a user stop.
|
|
2183
|
+
if (reasonKind === 'aborted' && isHostCancel(lastEnd?.data.reason)) reasonKind = 'interrupted';
|
|
1652
2184
|
const lastStart = latestTurnStart(events);
|
|
1653
2185
|
const maintenance = lastStart?.data.turn === lastEnd?.data.turn && isMaintenanceTurnStart(lastStart);
|
|
1654
2186
|
const silent = reasonKind === 'no-visible-output' && config.resumeSilentTurns;
|
|
@@ -1790,7 +2322,7 @@ export class AutoContinueRunner {
|
|
|
1790
2322
|
continue;
|
|
1791
2323
|
}
|
|
1792
2324
|
const sessionId = record.header.id;
|
|
1793
|
-
if (this.
|
|
2325
|
+
if (this.ownSessionConfig(sessionId).paused || Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) continue;
|
|
1794
2326
|
if (record.header.origin === 'subagent') {
|
|
1795
2327
|
// 子会话的记账完全交给 childSwept。若沿用 storedSwept(它在下面为 root 记账),
|
|
1796
2328
|
// 配额用尽的那一批会被永久标成"已裁决": 之后每轮都在这里被挡掉, 775 个子会话
|
|
@@ -1836,6 +2368,7 @@ export class AutoContinueRunner {
|
|
|
1836
2368
|
freshAt = events[events.length - 1]?.time ?? 0;
|
|
1837
2369
|
} else {
|
|
1838
2370
|
reasonKind = readReasonKind(lastEnd?.data.reason);
|
|
2371
|
+
if (reasonKind === 'aborted' && isHostCancel(lastEnd?.data.reason)) reasonKind = 'interrupted';
|
|
1839
2372
|
freshAt = lastEnd?.time ?? 0;
|
|
1840
2373
|
}
|
|
1841
2374
|
// 过期或被取代的永久错误与 live 扫描一致地静默跳过, 不再单独上报。
|
|
@@ -1926,7 +2459,7 @@ export class AutoContinueRunner {
|
|
|
1926
2459
|
// live 会话由实时事件路径负责; 冷读它既费钱又会与写归属相撞。
|
|
1927
2460
|
if (this.ctx.agents.get(sessionId) !== undefined) return;
|
|
1928
2461
|
if (this.childScanned >= CHILD_SWEEP_LIMIT) return;
|
|
1929
|
-
if (this.
|
|
2462
|
+
if (this.ownSessionConfig(sessionId).paused) return;
|
|
1930
2463
|
const rootId = resolveRootHeader(header, headersById);
|
|
1931
2464
|
if (rootId === undefined || rootId === sessionId) {
|
|
1932
2465
|
// 每轮扫描都会重走这里; 只记一次, 否则 15 分钟 freshMs 窗口内会刷出数万行噪声。
|
|
@@ -2070,10 +2603,7 @@ export class AutoContinueRunner {
|
|
|
2070
2603
|
if (end === undefined) return false;
|
|
2071
2604
|
const kind = readReasonKind(end.data.reason);
|
|
2072
2605
|
if (kind === 'completed') return true;
|
|
2073
|
-
if (kind === 'aborted')
|
|
2074
|
-
const cause = readCancelCause(end.data.reason);
|
|
2075
|
-
return cause !== undefined && RESTART_CANCEL_CAUSES.has(cause);
|
|
2076
|
-
}
|
|
2606
|
+
if (kind === 'aborted') return isHostCancel(end.data.reason);
|
|
2077
2607
|
return false;
|
|
2078
2608
|
}
|
|
2079
2609
|
|