dsh-client-auto-continue 0.20.2 → 0.21.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 +13 -0
- package/README.md +7 -5
- package/README.ru.md +7 -5
- package/README.zh.md +7 -5
- package/docs/releases/v0.21.0.md +56 -0
- package/lib/client.js +16 -1
- package/lib/client.js.map +2 -2
- package/lib/index.js +200 -13
- package/lib/types/client/locales.d.ts +3 -0
- package/lib/types/client/settings-card.d.ts +1 -0
- package/lib/types/host/engine.d.ts +20 -0
- package/lib/types/index.d.ts +8 -0
- package/lib/types/shared/core.d.ts +5 -0
- package/package.json +2 -2
- package/src/client/locales.ts +9 -0
- package/src/client/settings-card.tsx +5 -2
- package/src/host/engine.ts +238 -19
- package/src/index.ts +2 -0
- package/src/shared/core.ts +13 -0
package/src/host/engine.ts
CHANGED
|
@@ -123,6 +123,8 @@ const LOOP_GUARD_CANCEL_CAUSE = {
|
|
|
123
123
|
const LOOP_COMPLETED_REASON = 'turn/end:completed';
|
|
124
124
|
const LOOP_SILENT_REASON = 'turn/end:loop-silent';
|
|
125
125
|
const MANUAL_NOTIFICATION_REASON = 'manual:notification';
|
|
126
|
+
/** The host's question tool; a plain continue while it is unanswered reads as the user's reply. */
|
|
127
|
+
const ASK_USER_QUESTION_TOOL = 'ask_user_question';
|
|
126
128
|
|
|
127
129
|
/** Yield between storage batches without spending a live-scan polling interval. */
|
|
128
130
|
const SWEEP_OBSERVE_BATCH = 16;
|
|
@@ -245,7 +247,9 @@ interface GoalServiceLike {
|
|
|
245
247
|
interface StoredObservation {
|
|
246
248
|
readonly events: readonly SessionEvent[];
|
|
247
249
|
readonly header: { readonly id?: SessionId; readonly origin?: string; readonly agentPreset?: string };
|
|
248
|
-
readonly projections?: {
|
|
250
|
+
readonly projections?: {
|
|
251
|
+
readonly values: { readonly agentPreset?: string; readonly goal?: { readonly goal?: { readonly phase?: string } } | null };
|
|
252
|
+
};
|
|
249
253
|
[Symbol.dispose]?: () => void;
|
|
250
254
|
}
|
|
251
255
|
|
|
@@ -444,6 +448,68 @@ function isLoopGuardCancelReason(value: unknown): boolean {
|
|
|
444
448
|
return cause.kind === LOOP_GUARD_CANCEL_CAUSE.kind && cause.reason === LOOP_GUARD_CANCEL_CAUSE.reason;
|
|
445
449
|
}
|
|
446
450
|
|
|
451
|
+
const TEMPLATE_PLACEHOLDER = /\{(?:code|message|status|tool|turn|errorCount|sessionTitle|elapsed|result)\}/;
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* The literal pieces of what `fillTemplate` can make of a template; each placeholder is a gap
|
|
455
|
+
* that may hold anything. `undefined` when there is no literal text: it would match every message.
|
|
456
|
+
*/
|
|
457
|
+
function templateParts(template: string): string[] | undefined {
|
|
458
|
+
const parts = template.split(TEMPLATE_PLACEHOLDER);
|
|
459
|
+
return parts.join('').trim() === '' ? undefined : parts;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* Whole-message match of literal pieces with free gaps between them. Taking each middle piece
|
|
464
|
+
* at its leftmost position is enough for this shape, so it runs in linear time. A regex with
|
|
465
|
+
* one `[\s\S]*` per placeholder backtracks polynomially on a long near-miss: 4 KB took 1.6 s
|
|
466
|
+
* with four placeholders, and the boot scan tests every user message in the log.
|
|
467
|
+
*/
|
|
468
|
+
function matchesParts(text: string, parts: readonly string[]): boolean {
|
|
469
|
+
const first = parts[0] ?? '';
|
|
470
|
+
if (parts.length === 1) return text === first;
|
|
471
|
+
const last = parts[parts.length - 1] ?? '';
|
|
472
|
+
if (text.length < first.length + last.length || !text.startsWith(first) || !text.endsWith(last)) return false;
|
|
473
|
+
const end = text.length - last.length;
|
|
474
|
+
let at = first.length;
|
|
475
|
+
for (let i = 1; i < parts.length - 1; i += 1) {
|
|
476
|
+
const part = parts[i] ?? '';
|
|
477
|
+
const found = text.indexOf(part, at);
|
|
478
|
+
if (found < 0 || found + part.length > end) return false;
|
|
479
|
+
at = found + part.length;
|
|
480
|
+
}
|
|
481
|
+
return true;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** `left` followed by `separator` and `right`, as one sequence of pieces. */
|
|
485
|
+
function joinParts(left: readonly string[], separator: string, right: readonly string[]): string[] {
|
|
486
|
+
return [...left.slice(0, -1), `${left[left.length - 1] ?? ''}${separator}${right[0] ?? ''}`, ...right.slice(1)];
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
const definedParts = (templates: readonly string[]): string[][] =>
|
|
490
|
+
templates.map(templateParts).filter((parts): parts is string[] => parts !== undefined);
|
|
491
|
+
|
|
492
|
+
/** Child hand-offs in any locale; the child id and code are gaps. */
|
|
493
|
+
const HANDOFF_SHAPES = definedParts(Object.values(HANDOFF_COPY).map(copy => copy('{code}', '{code}')));
|
|
494
|
+
const isHandoffText = (text: string): boolean => HANDOFF_SHAPES.some(parts => matchesParts(text, parts));
|
|
495
|
+
|
|
496
|
+
/** Whole-message match for a continuation built from the current texts, guard note included. */
|
|
497
|
+
function continueTextMatcher(config: AutoContinueConfig): (text: string) => boolean {
|
|
498
|
+
const texts = definedParts([
|
|
499
|
+
config.continueText, config.continueTextMaxTokens, config.continueTextSilent, config.continueTextLoop,
|
|
500
|
+
config.continueTextInterrupted, config.continueTextQuestion, config.loopText,
|
|
501
|
+
]);
|
|
502
|
+
const guards = definedParts([config.guardPendingText, config.guardDoneText]);
|
|
503
|
+
const shapes = texts.flatMap(text => [text, ...guards.map(guard => joinParts(text, ' ', guard))]);
|
|
504
|
+
return text => shapes.some(parts => matchesParts(text, parts));
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function messageText(content: unknown): string {
|
|
508
|
+
if (!Array.isArray(content)) return '';
|
|
509
|
+
return content.map((block: { type?: unknown; text?: unknown } | null) =>
|
|
510
|
+
block?.type === 'text' && typeof block.text === 'string' ? block.text : '').join('');
|
|
511
|
+
}
|
|
512
|
+
|
|
447
513
|
/**
|
|
448
514
|
* 事件流泵: 带指数退避的 SSE 重连循环。
|
|
449
515
|
* - 从未收到任何帧(宿主未就绪): 退避重试, 不触发扫描
|
|
@@ -973,11 +1039,7 @@ export class AutoContinueRunner {
|
|
|
973
1039
|
const state = this.state(sessionId);
|
|
974
1040
|
if (this.tracksOutput(state, event)) {
|
|
975
1041
|
const chunk = event.data.chunk;
|
|
976
|
-
|
|
977
|
-
chunk.type === 'tool-call-delta' ||
|
|
978
|
-
(chunk.type === 'block-end' && this.hasVisibleContent([chunk.block])) ||
|
|
979
|
-
(chunk.type === 'block-start' && chunk.blockType !== 'reasoning' && chunk.blockType !== 'text');
|
|
980
|
-
if (visible) state.turnOutput = 'visible';
|
|
1042
|
+
if (this.chunkVisible(chunk)) state.turnOutput = 'visible';
|
|
981
1043
|
else if (state.turnOutput === 'empty' && chunk.type !== 'usage' && chunk.type !== 'finish') state.turnOutput = 'silent';
|
|
982
1044
|
}
|
|
983
1045
|
this.onAssistantChunk(sessionId, state, event);
|
|
@@ -997,6 +1059,13 @@ export class AutoContinueRunner {
|
|
|
997
1059
|
event.seq > state.outputStartSeq;
|
|
998
1060
|
}
|
|
999
1061
|
|
|
1062
|
+
private chunkVisible(chunk: SessionEvent<'assistant/chunk'>['data']['chunk']): boolean {
|
|
1063
|
+
return (chunk.type === 'text-delta' && visibleText(chunk.text) !== '') ||
|
|
1064
|
+
chunk.type === 'tool-call-delta' ||
|
|
1065
|
+
(chunk.type === 'block-end' && this.hasVisibleContent([chunk.block])) ||
|
|
1066
|
+
(chunk.type === 'block-start' && chunk.blockType !== 'reasoning' && chunk.blockType !== 'text');
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1000
1069
|
/** Treat unknown block kinds conservatively: only reasoning and blank text are silent. */
|
|
1001
1070
|
private hasVisibleContent(content: unknown): boolean {
|
|
1002
1071
|
if (!Array.isArray(content)) return false;
|
|
@@ -1728,7 +1797,9 @@ export class AutoContinueRunner {
|
|
|
1728
1797
|
* The child's own recovery mode decides; the parent only has to be alive to
|
|
1729
1798
|
* authorize the call.
|
|
1730
1799
|
*/
|
|
1731
|
-
private async reviveChild(
|
|
1800
|
+
private async reviveChild(
|
|
1801
|
+
sessionId: SessionId, reason: string, text: string, force: boolean, checkGoal: boolean,
|
|
1802
|
+
): Promise<void> {
|
|
1732
1803
|
if (this.disposed || this.getConfig().paused) return;
|
|
1733
1804
|
if (!this.subagentRecoveryEnabled(sessionId)) return;
|
|
1734
1805
|
const state = this.state(sessionId);
|
|
@@ -1750,6 +1821,22 @@ export class AutoContinueRunner {
|
|
|
1750
1821
|
return;
|
|
1751
1822
|
}
|
|
1752
1823
|
}
|
|
1824
|
+
if (checkGoal) {
|
|
1825
|
+
// The disposed child has no agent for `goals.get`; its stored goal projection holds the phase.
|
|
1826
|
+
state.reviveInFlight = true;
|
|
1827
|
+
let held: string | undefined;
|
|
1828
|
+
try {
|
|
1829
|
+
held = await this.storedGoalHold(sessionId, config);
|
|
1830
|
+
} finally {
|
|
1831
|
+
state.reviveInFlight = false;
|
|
1832
|
+
}
|
|
1833
|
+
if (this.disposed) return;
|
|
1834
|
+
if (held !== undefined) {
|
|
1835
|
+
state.recovering = false;
|
|
1836
|
+
this.log(`冷恢复跳过 ${sessionId}: goal 处于 ${held}, 不替用户续跑`);
|
|
1837
|
+
return;
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1753
1840
|
const parent = this.parentOf(sessionId);
|
|
1754
1841
|
if (parent === undefined || parent === '') return;
|
|
1755
1842
|
const handoff = this.handoffText(sessionId, reason);
|
|
@@ -1953,6 +2040,10 @@ export class AutoContinueRunner {
|
|
|
1953
2040
|
// 模板填充: continueText 可含 {code}/{message}/{status}/{tool}/{turn}/{errorCount}/{sessionTitle}/{elapsed} 占位符
|
|
1954
2041
|
const template = this.templateFor(config, reason);
|
|
1955
2042
|
const text = this.buildContinueText(config, state, template);
|
|
2043
|
+
// Resuming an interrupted turn (restart, retryable error) speaks for the user; finishing a
|
|
2044
|
+
// cut-off answer (max-tokens, silent), loop rounds and the manual button do not.
|
|
2045
|
+
const resumesInterruption = !manualResume && !isLoopReason(reason) && !reason.startsWith('loop:') &&
|
|
2046
|
+
!reason.endsWith(':silent') && !reason.includes('max-tokens');
|
|
1956
2047
|
// 发送: followup 负责唤醒; 同步 inbox 插入事件会在唤醒前把本消息移到已有队列之前。
|
|
1957
2048
|
const agent = this.ctx.agents.get(sessionId);
|
|
1958
2049
|
if (agent === undefined) {
|
|
@@ -1962,11 +2053,17 @@ export class AutoContinueRunner {
|
|
|
1962
2053
|
// failure to its main conversation instead. A manual "Resume now" must
|
|
1963
2054
|
// revive a disposed child too: its force flag only relaxes the cooldown.
|
|
1964
2055
|
if (this.isSubagentSession(sessionId) && this.subagentRecoveryEnabled(sessionId)) {
|
|
1965
|
-
void this.reviveChild(sessionId, reason, text, manualResume);
|
|
2056
|
+
void this.reviveChild(sessionId, reason, text, manualResume, resumesInterruption);
|
|
1966
2057
|
}
|
|
1967
2058
|
this.log(`跳过 ${sessionId}(${reason}): 无 live agent`);
|
|
1968
2059
|
return;
|
|
1969
2060
|
}
|
|
2061
|
+
const heldGoal = resumesInterruption ? this.heldGoalPhase(agent, config) : undefined;
|
|
2062
|
+
if (heldGoal !== undefined) {
|
|
2063
|
+
state.recovering = false;
|
|
2064
|
+
this.log(`跳过 ${sessionId}(${reason}): goal 处于 ${heldGoal}, 不替用户续跑`);
|
|
2065
|
+
return;
|
|
2066
|
+
}
|
|
1970
2067
|
state.lastAttemptAt = Date.now(); // 先记账: 无论成败, 本次尝试都进入冷却
|
|
1971
2068
|
try {
|
|
1972
2069
|
const message = createUserMessage({
|
|
@@ -2135,15 +2232,17 @@ export class AutoContinueRunner {
|
|
|
2135
2232
|
state: SessionState,
|
|
2136
2233
|
template: string,
|
|
2137
2234
|
): string {
|
|
2138
|
-
|
|
2235
|
+
const guard = this.currentGuard(state);
|
|
2236
|
+
// An unanswered question gets its own text, without the guard note: "continue" would answer it.
|
|
2237
|
+
const unanswered = (guard.kind === 'pending' || guard.kind === 'failed') && guard.tool === ASK_USER_QUESTION_TOOL;
|
|
2238
|
+
let text = fillTemplate(unanswered ? config.continueTextQuestion : template, {
|
|
2139
2239
|
facts: state.lastFailure,
|
|
2140
2240
|
tool: state.tools.lastTool(),
|
|
2141
2241
|
turn: state.lastTurn,
|
|
2142
2242
|
errorCount: state.consecutive + 1,
|
|
2143
2243
|
elapsedMs: state.lastFailureAt > 0 ? Date.now() - state.lastFailureAt : undefined,
|
|
2144
2244
|
});
|
|
2145
|
-
if (!config.guardTools) return text;
|
|
2146
|
-
const guard = this.currentGuard(state);
|
|
2245
|
+
if (unanswered || !config.guardTools) return text;
|
|
2147
2246
|
if (guard.kind === 'pending') {
|
|
2148
2247
|
text += ` ${fillTemplate(config.guardPendingText, { tool: guard.tool, result: guard.result })}`;
|
|
2149
2248
|
} else if (guard.kind === 'done') {
|
|
@@ -2270,6 +2369,14 @@ export class AutoContinueRunner {
|
|
|
2270
2369
|
continue;
|
|
2271
2370
|
}
|
|
2272
2371
|
}
|
|
2372
|
+
// The in-memory count died with the old host; a continue -> crash -> restart cycle must
|
|
2373
|
+
// still run into the cap.
|
|
2374
|
+
state.consecutive = Math.max(state.consecutive, this.continuationsInLog(events, config));
|
|
2375
|
+
if (state.consecutive >= config.maxConsecutive) {
|
|
2376
|
+
this.bootScannedSessions.add(session);
|
|
2377
|
+
this.log(`跳过 ${sessionId}(启动扫描): 重启前已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`);
|
|
2378
|
+
continue;
|
|
2379
|
+
}
|
|
2273
2380
|
candidates.push({
|
|
2274
2381
|
session, sessionId, events, lastEnd, reasonKind, failure,
|
|
2275
2382
|
lastActivityAt: events.reduce((latest, event) => Math.max(latest, event.time), 0),
|
|
@@ -2607,6 +2714,11 @@ export class AutoContinueRunner {
|
|
|
2607
2714
|
if (events.length === 0) return;
|
|
2608
2715
|
const cause = classifyChildInterruption(events, config);
|
|
2609
2716
|
if (cause === undefined) return;
|
|
2717
|
+
const held = this.goalHold(stored.projections?.values.goal?.goal?.phase, config);
|
|
2718
|
+
if (held !== undefined) {
|
|
2719
|
+
this.log(`子会话 ${sessionId} 的 goal 处于 ${held}, 不列入 root ${rootId} 的唤醒`);
|
|
2720
|
+
return;
|
|
2721
|
+
}
|
|
2610
2722
|
const tail = events[events.length - 1];
|
|
2611
2723
|
const list = this.childInterrupts.get(rootId) ?? [];
|
|
2612
2724
|
list.push({
|
|
@@ -2676,9 +2788,14 @@ export class AutoContinueRunner {
|
|
|
2676
2788
|
if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) return false;
|
|
2677
2789
|
const batch = children.map(child => `${child.id}:${child.cause}`).sort().join(',');
|
|
2678
2790
|
if (this.childWoken.get(rootId) === batch) return true;
|
|
2679
|
-
if (!(await this.rootAcceptsWake(rootId, deadline))) return true; // 明确裁决: 不该唤醒
|
|
2791
|
+
if (!(await this.rootAcceptsWake(rootId, config, deadline))) return true; // 明确裁决: 不该唤醒
|
|
2680
2792
|
const agent = await this.ensureLiveAgent(rootId, deadline);
|
|
2681
2793
|
if (agent === undefined || this.disposed) return false;
|
|
2794
|
+
const heldGoal = this.heldGoalPhase(agent, config);
|
|
2795
|
+
if (heldGoal !== undefined) {
|
|
2796
|
+
this.log(`跳过唤醒 ${rootId}: goal 处于 ${heldGoal}, 不替用户续跑`);
|
|
2797
|
+
return true;
|
|
2798
|
+
}
|
|
2682
2799
|
const text = this.buildChildResumeText(config, children);
|
|
2683
2800
|
const message = createUserMessage({
|
|
2684
2801
|
content: [{ type: 'text', text }],
|
|
@@ -2695,7 +2812,7 @@ export class AutoContinueRunner {
|
|
|
2695
2812
|
}
|
|
2696
2813
|
|
|
2697
2814
|
/** 父会话只在"干净结束"或"被宿主关闭"时接受唤醒; 用户手动停止的绝不复活。 */
|
|
2698
|
-
private async rootAcceptsWake(sessionId: SessionId, deadline: number): Promise<boolean> {
|
|
2815
|
+
private async rootAcceptsWake(sessionId: SessionId, config: AutoContinueConfig, deadline: number): Promise<boolean> {
|
|
2699
2816
|
const query = this.ctx.get('sessionQuery');
|
|
2700
2817
|
if (query === undefined) return false;
|
|
2701
2818
|
let events: readonly SessionEvent[];
|
|
@@ -2724,9 +2841,15 @@ export class AutoContinueRunner {
|
|
|
2724
2841
|
if (lastStart !== undefined && (end === undefined || lastStart.seq > end.seq)) return false;
|
|
2725
2842
|
if (end === undefined) return false;
|
|
2726
2843
|
const kind = readReasonKind(end.data.reason);
|
|
2727
|
-
if (kind
|
|
2728
|
-
|
|
2729
|
-
|
|
2844
|
+
if (kind !== 'completed' && !(kind === 'aborted' && isHostCancel(end.data.reason))) return false;
|
|
2845
|
+
// A clean root is no scan candidate, so its count is rebuilt here or the cap above reads 0.
|
|
2846
|
+
const state = this.state(sessionId);
|
|
2847
|
+
state.consecutive = Math.max(state.consecutive, this.continuationsInLog(events, config));
|
|
2848
|
+
if (state.consecutive >= config.maxConsecutive) {
|
|
2849
|
+
this.log(`跳过唤醒 ${sessionId}: 重启前已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`);
|
|
2850
|
+
return false;
|
|
2851
|
+
}
|
|
2852
|
+
return true;
|
|
2730
2853
|
}
|
|
2731
2854
|
|
|
2732
2855
|
/** 发送需要 live agent; 存储会话沿既有物化路径拉起, 复用 preset 与模型回装。 */
|
|
@@ -2784,9 +2907,7 @@ export class AutoContinueRunner {
|
|
|
2784
2907
|
*/
|
|
2785
2908
|
private rearmGoal(sessionId: SessionId, config: AutoContinueConfig): void {
|
|
2786
2909
|
if (!config.resumeGoals) return;
|
|
2787
|
-
const goals =
|
|
2788
|
-
| GoalServiceLike
|
|
2789
|
-
| undefined;
|
|
2910
|
+
const goals = this.goals();
|
|
2790
2911
|
if (goals === undefined) return;
|
|
2791
2912
|
const agent = this.ctx.agents.get(sessionId);
|
|
2792
2913
|
if (agent === undefined) return;
|
|
@@ -2818,6 +2939,104 @@ export class AutoContinueRunner {
|
|
|
2818
2939
|
}
|
|
2819
2940
|
}
|
|
2820
2941
|
|
|
2942
|
+
private goals(): GoalServiceLike | undefined {
|
|
2943
|
+
return (this.ctx as unknown as { get(key: string): unknown }).get(GOALS_SERVICE_KEY) as GoalServiceLike | undefined;
|
|
2944
|
+
}
|
|
2945
|
+
|
|
2946
|
+
/**
|
|
2947
|
+
* A paused or blocked goal is a decision to stop and wait; a continue sent anyway reads as the
|
|
2948
|
+
* user resuming it. `resumePausedGoals` is the user's standing permission to resume paused
|
|
2949
|
+
* goals, so it lets those through.
|
|
2950
|
+
*/
|
|
2951
|
+
private heldGoalPhase(agent: Agent, config: AutoContinueConfig): string | undefined {
|
|
2952
|
+
let phase: string | undefined;
|
|
2953
|
+
try {
|
|
2954
|
+
const goals = this.goals();
|
|
2955
|
+
if (goals === undefined) return undefined; // a host without goals
|
|
2956
|
+
phase = goals.get(agent)?.phase;
|
|
2957
|
+
} catch {
|
|
2958
|
+
return 'unreadable'; // the goal may be paused or blocked: do not speak for the user
|
|
2959
|
+
}
|
|
2960
|
+
return this.goalHold(phase, config);
|
|
2961
|
+
}
|
|
2962
|
+
|
|
2963
|
+
private goalHold(phase: string | undefined, config: AutoContinueConfig): string | undefined {
|
|
2964
|
+
if (phase === 'blocked') return phase;
|
|
2965
|
+
if (phase === 'paused' && !(config.resumeGoals && config.resumePausedGoals)) return phase;
|
|
2966
|
+
return undefined;
|
|
2967
|
+
}
|
|
2968
|
+
|
|
2969
|
+
/** `heldGoalPhase` for a session without a live agent, read from its stored goal projection. */
|
|
2970
|
+
private async storedGoalHold(sessionId: SessionId, config: AutoContinueConfig): Promise<string | undefined> {
|
|
2971
|
+
if (this.goals() === undefined) return undefined; // a host without goals
|
|
2972
|
+
const query = this.ctx.get('sessionQuery');
|
|
2973
|
+
if (query === undefined) return 'unreadable';
|
|
2974
|
+
let stored: StoredObservation | undefined;
|
|
2975
|
+
try {
|
|
2976
|
+
const observation: StoredObservation = await this.readStored(
|
|
2977
|
+
signal => query.observeSession(sessionId, { projectionMode: 'all', signal }),
|
|
2978
|
+
Date.now() + STORED_READ_TIMEOUT_MS,
|
|
2979
|
+
);
|
|
2980
|
+
stored = observation;
|
|
2981
|
+
return this.goalHold(observation.projections?.values.goal?.goal?.phase, config);
|
|
2982
|
+
} catch (error) {
|
|
2983
|
+
// Nothing stored (a discarded one-shot child, no persistence) holds no goal: keep the old fallback.
|
|
2984
|
+
if ((error as { code?: unknown } | null)?.code === 'SESSION_QUERY_SESSION_NOT_FOUND') return undefined;
|
|
2985
|
+
return 'unreadable';
|
|
2986
|
+
} finally {
|
|
2987
|
+
stored?.[Symbol.dispose]?.();
|
|
2988
|
+
}
|
|
2989
|
+
}
|
|
2990
|
+
|
|
2991
|
+
/**
|
|
2992
|
+
* Continuations this plugin sent since the last message from the user, manual stop or turn
|
|
2993
|
+
* with visible output, read from the log so the consecutive cap survives a host restart.
|
|
2994
|
+
* Mirrors the in-memory count: a continuation right after a visible completion is a loop
|
|
2995
|
+
* round and does not count. With `usePluginSource` off a continuation is a `user` message
|
|
2996
|
+
* matching one of the configured continue texts, so a user message identical to one of them
|
|
2997
|
+
* is counted too; that can only stop recovery earlier, never later.
|
|
2998
|
+
*/
|
|
2999
|
+
private continuationsInLog(events: readonly SessionEvent[], config: AutoContinueConfig): number {
|
|
3000
|
+
const ours = continueTextMatcher(config);
|
|
3001
|
+
let count = 0;
|
|
3002
|
+
let visible = false;
|
|
3003
|
+
let maintenance = false;
|
|
3004
|
+
let afterSuccess = false;
|
|
3005
|
+
for (const event of events) {
|
|
3006
|
+
if (event.type === 'turn/start') {
|
|
3007
|
+
visible = false;
|
|
3008
|
+
maintenance = isMaintenanceTurnStart(event);
|
|
3009
|
+
} else if (event.type === 'tool/call') {
|
|
3010
|
+
visible = true;
|
|
3011
|
+
} else if (event.type === 'assistant/chunk') {
|
|
3012
|
+
if (this.chunkVisible(event.data.chunk)) visible = true;
|
|
3013
|
+
} else if (event.type === 'assistant/message') {
|
|
3014
|
+
if (this.hasVisibleContent(event.data.message?.content)) visible = true;
|
|
3015
|
+
} else if (event.type === 'turn/end') {
|
|
3016
|
+
if (maintenance) continue;
|
|
3017
|
+
const reason = event.data.reason;
|
|
3018
|
+
const kind = readReasonKind(reason);
|
|
3019
|
+
afterSuccess = kind === 'completed' && visible;
|
|
3020
|
+
const userStop = kind === 'aborted' && !isHostCancel(reason) &&
|
|
3021
|
+
!isLoopGuardCancelReason((reason as { reason?: unknown }).reason);
|
|
3022
|
+
if (afterSuccess || userStop) count = 0;
|
|
3023
|
+
} else if (event.type === 'user/message') {
|
|
3024
|
+
const source = event.data.source?.kind;
|
|
3025
|
+
const text = messageText(event.data.content);
|
|
3026
|
+
// A child hand-off is a registered echo: in memory it neither counts nor resets.
|
|
3027
|
+
if (isHandoffText(text)) continue;
|
|
3028
|
+
if (source === AUTO_CONTINUE_SOURCE_KIND || (source === 'user' && ours(text))) {
|
|
3029
|
+
if (!afterSuccess) count += 1;
|
|
3030
|
+
} else if (source === 'user') {
|
|
3031
|
+
count = 0;
|
|
3032
|
+
}
|
|
3033
|
+
// Only the one continuation right after a visible completion is a loop round.
|
|
3034
|
+
if (source === AUTO_CONTINUE_SOURCE_KIND || source === 'user') afterSuccess = false;
|
|
3035
|
+
}
|
|
3036
|
+
}
|
|
3037
|
+
return count;
|
|
3038
|
+
}
|
|
3039
|
+
|
|
2821
3040
|
/**
|
|
2822
3041
|
* 按会话记录的 preset 组合把存储会话恢复为 live agent(镜像会话控制
|
|
2823
3042
|
* 器的 adopt 路径: preset 挂载 + 会话已记录的模型选择回装)。模型选择
|
package/src/index.ts
CHANGED
|
@@ -48,6 +48,8 @@ const settingsFields = {
|
|
|
48
48
|
continueTextLoop: z.string().default(''),
|
|
49
49
|
/** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
|
|
50
50
|
continueTextInterrupted: z.string().default(''),
|
|
51
|
+
/** Text sent instead of a continue text (and its guard note) while the user has not answered the last `ask_user_question`. */
|
|
52
|
+
continueTextQuestion: z.string().default(''),
|
|
51
53
|
/** Idempotency guard: inspect the last tool call before resuming and steer the model. */
|
|
52
54
|
guardTools: z.boolean().default(true),
|
|
53
55
|
/** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
|
package/src/shared/core.ts
CHANGED
|
@@ -52,6 +52,8 @@ export const LOCALIZED_TEXT_DEFAULTS = {
|
|
|
52
52
|
continueTextLoop: '继续',
|
|
53
53
|
continueTextInterrupted:
|
|
54
54
|
'继续。宿主在你上一轮运行期间重启了; 重启时未完成的工具调用已按「结果未知」收尾。从中断处继续, 重试可能有副作用的操作前先核实外部状态。',
|
|
55
|
+
continueTextQuestion:
|
|
56
|
+
'这是宿主重启后插件自动发送的消息, 不是用户的回复。你上一步向用户提出的问题因重启中断, 用户还没有回答。请重新提出同一个问题并等待回答, 不要替用户做决定。',
|
|
55
57
|
guardPendingText: '(上一步工具「{tool}」可能未完成, 先确认状态再继续, 不要重复执行)',
|
|
56
58
|
guardDoneText: '(上一步工具「{tool}」已完成, 结果: {result}; 不要重复执行, 直接继续)',
|
|
57
59
|
loopText: '(检测到你可能陷入循环, 请停止重复刚才的动作, 换一种方式继续)',
|
|
@@ -64,6 +66,8 @@ export const LOCALIZED_TEXT_DEFAULTS = {
|
|
|
64
66
|
continueTextLoop: 'Continue',
|
|
65
67
|
continueTextInterrupted:
|
|
66
68
|
'Continue. The harness was restarted while your previous turn was still running; tool calls pending at the restart are recorded with unknown outcomes. Resume where you left off, verifying external state before retrying anything that may have side effects.',
|
|
69
|
+
continueTextQuestion:
|
|
70
|
+
"This message was sent automatically by the plugin after a harness restart; it is not the user's reply. The question you asked the user was cut off by the restart and has not been answered. Ask the same question again and wait for the answer; do not decide for the user.",
|
|
67
71
|
guardPendingText:
|
|
68
72
|
'(The previous tool "{tool}" may not have completed. Check its state before continuing and do not run it again.)',
|
|
69
73
|
guardDoneText:
|
|
@@ -79,6 +83,8 @@ export const LOCALIZED_TEXT_DEFAULTS = {
|
|
|
79
83
|
continueTextLoop: 'Продолжай',
|
|
80
84
|
continueTextInterrupted:
|
|
81
85
|
'Продолжай. Хост перезапустился, пока предыдущий ход ещё выполнялся; вызовы инструментов, незавершённые на момент перезапуска, записаны с неизвестным результатом. Продолжай с места остановки, проверяя внешнее состояние перед повтором действий с возможными побочными эффектами.',
|
|
86
|
+
continueTextQuestion:
|
|
87
|
+
'Это сообщение плагин отправил автоматически после перезапуска хоста, это не ответ пользователя. Вопрос, который ты задал пользователю, прервался из-за перезапуска, и ответа на него ещё нет. Задай тот же вопрос снова и дождись ответа, не принимай решение за пользователя.',
|
|
82
88
|
guardPendingText:
|
|
83
89
|
'(Предыдущий инструмент «{tool}», возможно, не завершился. Проверь его состояние перед продолжением и не запускай его повторно.)',
|
|
84
90
|
guardDoneText:
|
|
@@ -110,6 +116,8 @@ export interface AutoContinueSettings {
|
|
|
110
116
|
continueTextLoop?: string;
|
|
111
117
|
/** Text sent when a turn is recovered after a harness restart closed it as interrupted. */
|
|
112
118
|
continueTextInterrupted?: string;
|
|
119
|
+
/** Text sent instead of a continue text (and its guard note) while the user has not answered the last `ask_user_question`. */
|
|
120
|
+
continueTextQuestion?: string;
|
|
113
121
|
/** Idempotency guard: inspect the last tool call before resuming and steer the model. */
|
|
114
122
|
guardTools?: boolean;
|
|
115
123
|
/** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
|
|
@@ -249,6 +257,10 @@ export function resolveConfig(section: AutoContinueSettings | undefined): AutoCo
|
|
|
249
257
|
typeof value.continueTextInterrupted === 'string' && value.continueTextInterrupted.trim() !== ''
|
|
250
258
|
? value.continueTextInterrupted
|
|
251
259
|
: localized.continueTextInterrupted;
|
|
260
|
+
const questionText =
|
|
261
|
+
typeof value.continueTextQuestion === 'string' && value.continueTextQuestion.trim() !== ''
|
|
262
|
+
? value.continueTextQuestion
|
|
263
|
+
: localized.continueTextQuestion;
|
|
252
264
|
const guardPendingText =
|
|
253
265
|
typeof value.guardPendingText === 'string' && value.guardPendingText.trim() !== ''
|
|
254
266
|
? value.guardPendingText
|
|
@@ -268,6 +280,7 @@ export function resolveConfig(section: AutoContinueSettings | undefined): AutoCo
|
|
|
268
280
|
continueTextSilent: silentText,
|
|
269
281
|
continueTextLoop: loopText,
|
|
270
282
|
continueTextInterrupted: interruptedText,
|
|
283
|
+
continueTextQuestion: questionText,
|
|
271
284
|
guardTools: booleanOr(value.guardTools, DEFAULT_CONFIG.guardTools),
|
|
272
285
|
guardPendingText,
|
|
273
286
|
guardDoneText,
|