dsh-client-auto-continue 0.20.2 → 0.21.1
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 +21 -0
- package/README.md +8 -6
- package/README.ru.md +8 -6
- package/README.zh.md +8 -6
- package/docs/releases/v0.21.0.md +56 -0
- package/docs/releases/v0.21.1.md +39 -0
- package/lib/client.js +16 -1
- package/lib/client.js.map +2 -2
- package/lib/index.js +215 -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 +260 -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
|
|
|
@@ -372,6 +376,24 @@ function isHostCancel(value: unknown): boolean {
|
|
|
372
376
|
return cause !== undefined && RESTART_CANCEL_CAUSES.has(cause);
|
|
373
377
|
}
|
|
374
378
|
|
|
379
|
+
/**
|
|
380
|
+
* Whether the user switched the goal off. A restart and a user stop of a turn that was not a goal
|
|
381
|
+
* round both leave an active goal disarmed; only the stop is a decision to wait. The newer of the
|
|
382
|
+
* last user stop and the last goal resume/create decides, so the user's own resume lifts the hold.
|
|
383
|
+
*/
|
|
384
|
+
function goalStoppedByUser(events: readonly SessionEvent[]): boolean {
|
|
385
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
386
|
+
const event = events[index] as { type: string; data?: { operation?: unknown; reason?: unknown } };
|
|
387
|
+
if (event.type === 'goal/change') {
|
|
388
|
+
if (event.data?.operation === 'resume' || event.data?.operation === 'create') return false;
|
|
389
|
+
} else if (event.type === 'turn/end' && readCancelCause(event.data?.reason) === 'user') {
|
|
390
|
+
// Only the user's stop: a restart, parent, hook (loop guard) or unknown cause is not a decision to wait.
|
|
391
|
+
return true;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
return false;
|
|
395
|
+
}
|
|
396
|
+
|
|
375
397
|
/**
|
|
376
398
|
* Decide whether a child session's tail is a restart interruption worth waking
|
|
377
399
|
* its root session for. Returns `undefined` when the child finished normally,
|
|
@@ -444,6 +466,68 @@ function isLoopGuardCancelReason(value: unknown): boolean {
|
|
|
444
466
|
return cause.kind === LOOP_GUARD_CANCEL_CAUSE.kind && cause.reason === LOOP_GUARD_CANCEL_CAUSE.reason;
|
|
445
467
|
}
|
|
446
468
|
|
|
469
|
+
const TEMPLATE_PLACEHOLDER = /\{(?:code|message|status|tool|turn|errorCount|sessionTitle|elapsed|result)\}/;
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* The literal pieces of what `fillTemplate` can make of a template; each placeholder is a gap
|
|
473
|
+
* that may hold anything. `undefined` when there is no literal text: it would match every message.
|
|
474
|
+
*/
|
|
475
|
+
function templateParts(template: string): string[] | undefined {
|
|
476
|
+
const parts = template.split(TEMPLATE_PLACEHOLDER);
|
|
477
|
+
return parts.join('').trim() === '' ? undefined : parts;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Whole-message match of literal pieces with free gaps between them. Taking each middle piece
|
|
482
|
+
* at its leftmost position is enough for this shape, so it runs in linear time. A regex with
|
|
483
|
+
* one `[\s\S]*` per placeholder backtracks polynomially on a long near-miss: 4 KB took 1.6 s
|
|
484
|
+
* with four placeholders, and the boot scan tests every user message in the log.
|
|
485
|
+
*/
|
|
486
|
+
function matchesParts(text: string, parts: readonly string[]): boolean {
|
|
487
|
+
const first = parts[0] ?? '';
|
|
488
|
+
if (parts.length === 1) return text === first;
|
|
489
|
+
const last = parts[parts.length - 1] ?? '';
|
|
490
|
+
if (text.length < first.length + last.length || !text.startsWith(first) || !text.endsWith(last)) return false;
|
|
491
|
+
const end = text.length - last.length;
|
|
492
|
+
let at = first.length;
|
|
493
|
+
for (let i = 1; i < parts.length - 1; i += 1) {
|
|
494
|
+
const part = parts[i] ?? '';
|
|
495
|
+
const found = text.indexOf(part, at);
|
|
496
|
+
if (found < 0 || found + part.length > end) return false;
|
|
497
|
+
at = found + part.length;
|
|
498
|
+
}
|
|
499
|
+
return true;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** `left` followed by `separator` and `right`, as one sequence of pieces. */
|
|
503
|
+
function joinParts(left: readonly string[], separator: string, right: readonly string[]): string[] {
|
|
504
|
+
return [...left.slice(0, -1), `${left[left.length - 1] ?? ''}${separator}${right[0] ?? ''}`, ...right.slice(1)];
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
const definedParts = (templates: readonly string[]): string[][] =>
|
|
508
|
+
templates.map(templateParts).filter((parts): parts is string[] => parts !== undefined);
|
|
509
|
+
|
|
510
|
+
/** Child hand-offs in any locale; the child id and code are gaps. */
|
|
511
|
+
const HANDOFF_SHAPES = definedParts(Object.values(HANDOFF_COPY).map(copy => copy('{code}', '{code}')));
|
|
512
|
+
const isHandoffText = (text: string): boolean => HANDOFF_SHAPES.some(parts => matchesParts(text, parts));
|
|
513
|
+
|
|
514
|
+
/** Whole-message match for a continuation built from the current texts, guard note included. */
|
|
515
|
+
function continueTextMatcher(config: AutoContinueConfig): (text: string) => boolean {
|
|
516
|
+
const texts = definedParts([
|
|
517
|
+
config.continueText, config.continueTextMaxTokens, config.continueTextSilent, config.continueTextLoop,
|
|
518
|
+
config.continueTextInterrupted, config.continueTextQuestion, config.loopText,
|
|
519
|
+
]);
|
|
520
|
+
const guards = definedParts([config.guardPendingText, config.guardDoneText]);
|
|
521
|
+
const shapes = texts.flatMap(text => [text, ...guards.map(guard => joinParts(text, ' ', guard))]);
|
|
522
|
+
return text => shapes.some(parts => matchesParts(text, parts));
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function messageText(content: unknown): string {
|
|
526
|
+
if (!Array.isArray(content)) return '';
|
|
527
|
+
return content.map((block: { type?: unknown; text?: unknown } | null) =>
|
|
528
|
+
block?.type === 'text' && typeof block.text === 'string' ? block.text : '').join('');
|
|
529
|
+
}
|
|
530
|
+
|
|
447
531
|
/**
|
|
448
532
|
* 事件流泵: 带指数退避的 SSE 重连循环。
|
|
449
533
|
* - 从未收到任何帧(宿主未就绪): 退避重试, 不触发扫描
|
|
@@ -973,11 +1057,7 @@ export class AutoContinueRunner {
|
|
|
973
1057
|
const state = this.state(sessionId);
|
|
974
1058
|
if (this.tracksOutput(state, event)) {
|
|
975
1059
|
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';
|
|
1060
|
+
if (this.chunkVisible(chunk)) state.turnOutput = 'visible';
|
|
981
1061
|
else if (state.turnOutput === 'empty' && chunk.type !== 'usage' && chunk.type !== 'finish') state.turnOutput = 'silent';
|
|
982
1062
|
}
|
|
983
1063
|
this.onAssistantChunk(sessionId, state, event);
|
|
@@ -997,6 +1077,13 @@ export class AutoContinueRunner {
|
|
|
997
1077
|
event.seq > state.outputStartSeq;
|
|
998
1078
|
}
|
|
999
1079
|
|
|
1080
|
+
private chunkVisible(chunk: SessionEvent<'assistant/chunk'>['data']['chunk']): boolean {
|
|
1081
|
+
return (chunk.type === 'text-delta' && visibleText(chunk.text) !== '') ||
|
|
1082
|
+
chunk.type === 'tool-call-delta' ||
|
|
1083
|
+
(chunk.type === 'block-end' && this.hasVisibleContent([chunk.block])) ||
|
|
1084
|
+
(chunk.type === 'block-start' && chunk.blockType !== 'reasoning' && chunk.blockType !== 'text');
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1000
1087
|
/** Treat unknown block kinds conservatively: only reasoning and blank text are silent. */
|
|
1001
1088
|
private hasVisibleContent(content: unknown): boolean {
|
|
1002
1089
|
if (!Array.isArray(content)) return false;
|
|
@@ -1728,7 +1815,9 @@ export class AutoContinueRunner {
|
|
|
1728
1815
|
* The child's own recovery mode decides; the parent only has to be alive to
|
|
1729
1816
|
* authorize the call.
|
|
1730
1817
|
*/
|
|
1731
|
-
private async reviveChild(
|
|
1818
|
+
private async reviveChild(
|
|
1819
|
+
sessionId: SessionId, reason: string, text: string, force: boolean, checkGoal: boolean,
|
|
1820
|
+
): Promise<void> {
|
|
1732
1821
|
if (this.disposed || this.getConfig().paused) return;
|
|
1733
1822
|
if (!this.subagentRecoveryEnabled(sessionId)) return;
|
|
1734
1823
|
const state = this.state(sessionId);
|
|
@@ -1750,6 +1839,22 @@ export class AutoContinueRunner {
|
|
|
1750
1839
|
return;
|
|
1751
1840
|
}
|
|
1752
1841
|
}
|
|
1842
|
+
if (checkGoal) {
|
|
1843
|
+
// The disposed child has no agent for `goals.get`; its stored goal projection holds the phase.
|
|
1844
|
+
state.reviveInFlight = true;
|
|
1845
|
+
let held: string | undefined;
|
|
1846
|
+
try {
|
|
1847
|
+
held = await this.storedGoalHold(sessionId, config);
|
|
1848
|
+
} finally {
|
|
1849
|
+
state.reviveInFlight = false;
|
|
1850
|
+
}
|
|
1851
|
+
if (this.disposed) return;
|
|
1852
|
+
if (held !== undefined) {
|
|
1853
|
+
state.recovering = false;
|
|
1854
|
+
this.log(`冷恢复跳过 ${sessionId}: goal 处于 ${held}, 不替用户续跑`);
|
|
1855
|
+
return;
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1753
1858
|
const parent = this.parentOf(sessionId);
|
|
1754
1859
|
if (parent === undefined || parent === '') return;
|
|
1755
1860
|
const handoff = this.handoffText(sessionId, reason);
|
|
@@ -1953,6 +2058,10 @@ export class AutoContinueRunner {
|
|
|
1953
2058
|
// 模板填充: continueText 可含 {code}/{message}/{status}/{tool}/{turn}/{errorCount}/{sessionTitle}/{elapsed} 占位符
|
|
1954
2059
|
const template = this.templateFor(config, reason);
|
|
1955
2060
|
const text = this.buildContinueText(config, state, template);
|
|
2061
|
+
// Resuming an interrupted turn (restart, retryable error) speaks for the user; finishing a
|
|
2062
|
+
// cut-off answer (max-tokens, silent), loop rounds and the manual button do not.
|
|
2063
|
+
const resumesInterruption = !manualResume && !isLoopReason(reason) && !reason.startsWith('loop:') &&
|
|
2064
|
+
!reason.endsWith(':silent') && !reason.includes('max-tokens');
|
|
1956
2065
|
// 发送: followup 负责唤醒; 同步 inbox 插入事件会在唤醒前把本消息移到已有队列之前。
|
|
1957
2066
|
const agent = this.ctx.agents.get(sessionId);
|
|
1958
2067
|
if (agent === undefined) {
|
|
@@ -1962,11 +2071,17 @@ export class AutoContinueRunner {
|
|
|
1962
2071
|
// failure to its main conversation instead. A manual "Resume now" must
|
|
1963
2072
|
// revive a disposed child too: its force flag only relaxes the cooldown.
|
|
1964
2073
|
if (this.isSubagentSession(sessionId) && this.subagentRecoveryEnabled(sessionId)) {
|
|
1965
|
-
void this.reviveChild(sessionId, reason, text, manualResume);
|
|
2074
|
+
void this.reviveChild(sessionId, reason, text, manualResume, resumesInterruption);
|
|
1966
2075
|
}
|
|
1967
2076
|
this.log(`跳过 ${sessionId}(${reason}): 无 live agent`);
|
|
1968
2077
|
return;
|
|
1969
2078
|
}
|
|
2079
|
+
const heldGoal = resumesInterruption ? this.heldGoalPhase(agent, config) : undefined;
|
|
2080
|
+
if (heldGoal !== undefined) {
|
|
2081
|
+
state.recovering = false;
|
|
2082
|
+
this.log(`跳过 ${sessionId}(${reason}): goal 处于 ${heldGoal}, 不替用户续跑`);
|
|
2083
|
+
return;
|
|
2084
|
+
}
|
|
1970
2085
|
state.lastAttemptAt = Date.now(); // 先记账: 无论成败, 本次尝试都进入冷却
|
|
1971
2086
|
try {
|
|
1972
2087
|
const message = createUserMessage({
|
|
@@ -2135,15 +2250,17 @@ export class AutoContinueRunner {
|
|
|
2135
2250
|
state: SessionState,
|
|
2136
2251
|
template: string,
|
|
2137
2252
|
): string {
|
|
2138
|
-
|
|
2253
|
+
const guard = this.currentGuard(state);
|
|
2254
|
+
// An unanswered question gets its own text, without the guard note: "continue" would answer it.
|
|
2255
|
+
const unanswered = (guard.kind === 'pending' || guard.kind === 'failed') && guard.tool === ASK_USER_QUESTION_TOOL;
|
|
2256
|
+
let text = fillTemplate(unanswered ? config.continueTextQuestion : template, {
|
|
2139
2257
|
facts: state.lastFailure,
|
|
2140
2258
|
tool: state.tools.lastTool(),
|
|
2141
2259
|
turn: state.lastTurn,
|
|
2142
2260
|
errorCount: state.consecutive + 1,
|
|
2143
2261
|
elapsedMs: state.lastFailureAt > 0 ? Date.now() - state.lastFailureAt : undefined,
|
|
2144
2262
|
});
|
|
2145
|
-
if (!config.guardTools) return text;
|
|
2146
|
-
const guard = this.currentGuard(state);
|
|
2263
|
+
if (unanswered || !config.guardTools) return text;
|
|
2147
2264
|
if (guard.kind === 'pending') {
|
|
2148
2265
|
text += ` ${fillTemplate(config.guardPendingText, { tool: guard.tool, result: guard.result })}`;
|
|
2149
2266
|
} else if (guard.kind === 'done') {
|
|
@@ -2270,6 +2387,14 @@ export class AutoContinueRunner {
|
|
|
2270
2387
|
continue;
|
|
2271
2388
|
}
|
|
2272
2389
|
}
|
|
2390
|
+
// The in-memory count died with the old host; a continue -> crash -> restart cycle must
|
|
2391
|
+
// still run into the cap.
|
|
2392
|
+
state.consecutive = Math.max(state.consecutive, this.continuationsInLog(events, config));
|
|
2393
|
+
if (state.consecutive >= config.maxConsecutive) {
|
|
2394
|
+
this.bootScannedSessions.add(session);
|
|
2395
|
+
this.log(`跳过 ${sessionId}(启动扫描): 重启前已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`);
|
|
2396
|
+
continue;
|
|
2397
|
+
}
|
|
2273
2398
|
candidates.push({
|
|
2274
2399
|
session, sessionId, events, lastEnd, reasonKind, failure,
|
|
2275
2400
|
lastActivityAt: events.reduce((latest, event) => Math.max(latest, event.time), 0),
|
|
@@ -2607,6 +2732,11 @@ export class AutoContinueRunner {
|
|
|
2607
2732
|
if (events.length === 0) return;
|
|
2608
2733
|
const cause = classifyChildInterruption(events, config);
|
|
2609
2734
|
if (cause === undefined) return;
|
|
2735
|
+
const held = this.goalHold(stored.projections?.values.goal?.goal?.phase, config);
|
|
2736
|
+
if (held !== undefined) {
|
|
2737
|
+
this.log(`子会话 ${sessionId} 的 goal 处于 ${held}, 不列入 root ${rootId} 的唤醒`);
|
|
2738
|
+
return;
|
|
2739
|
+
}
|
|
2610
2740
|
const tail = events[events.length - 1];
|
|
2611
2741
|
const list = this.childInterrupts.get(rootId) ?? [];
|
|
2612
2742
|
list.push({
|
|
@@ -2676,9 +2806,14 @@ export class AutoContinueRunner {
|
|
|
2676
2806
|
if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) return false;
|
|
2677
2807
|
const batch = children.map(child => `${child.id}:${child.cause}`).sort().join(',');
|
|
2678
2808
|
if (this.childWoken.get(rootId) === batch) return true;
|
|
2679
|
-
if (!(await this.rootAcceptsWake(rootId, deadline))) return true; // 明确裁决: 不该唤醒
|
|
2809
|
+
if (!(await this.rootAcceptsWake(rootId, config, deadline))) return true; // 明确裁决: 不该唤醒
|
|
2680
2810
|
const agent = await this.ensureLiveAgent(rootId, deadline);
|
|
2681
2811
|
if (agent === undefined || this.disposed) return false;
|
|
2812
|
+
const heldGoal = this.heldGoalPhase(agent, config);
|
|
2813
|
+
if (heldGoal !== undefined) {
|
|
2814
|
+
this.log(`跳过唤醒 ${rootId}: goal 处于 ${heldGoal}, 不替用户续跑`);
|
|
2815
|
+
return true;
|
|
2816
|
+
}
|
|
2682
2817
|
const text = this.buildChildResumeText(config, children);
|
|
2683
2818
|
const message = createUserMessage({
|
|
2684
2819
|
content: [{ type: 'text', text }],
|
|
@@ -2695,7 +2830,7 @@ export class AutoContinueRunner {
|
|
|
2695
2830
|
}
|
|
2696
2831
|
|
|
2697
2832
|
/** 父会话只在"干净结束"或"被宿主关闭"时接受唤醒; 用户手动停止的绝不复活。 */
|
|
2698
|
-
private async rootAcceptsWake(sessionId: SessionId, deadline: number): Promise<boolean> {
|
|
2833
|
+
private async rootAcceptsWake(sessionId: SessionId, config: AutoContinueConfig, deadline: number): Promise<boolean> {
|
|
2699
2834
|
const query = this.ctx.get('sessionQuery');
|
|
2700
2835
|
if (query === undefined) return false;
|
|
2701
2836
|
let events: readonly SessionEvent[];
|
|
@@ -2724,9 +2859,15 @@ export class AutoContinueRunner {
|
|
|
2724
2859
|
if (lastStart !== undefined && (end === undefined || lastStart.seq > end.seq)) return false;
|
|
2725
2860
|
if (end === undefined) return false;
|
|
2726
2861
|
const kind = readReasonKind(end.data.reason);
|
|
2727
|
-
if (kind
|
|
2728
|
-
|
|
2729
|
-
|
|
2862
|
+
if (kind !== 'completed' && !(kind === 'aborted' && isHostCancel(end.data.reason))) return false;
|
|
2863
|
+
// A clean root is no scan candidate, so its count is rebuilt here or the cap above reads 0.
|
|
2864
|
+
const state = this.state(sessionId);
|
|
2865
|
+
state.consecutive = Math.max(state.consecutive, this.continuationsInLog(events, config));
|
|
2866
|
+
if (state.consecutive >= config.maxConsecutive) {
|
|
2867
|
+
this.log(`跳过唤醒 ${sessionId}: 重启前已连续自动继续 ${state.consecutive} 次, 等待用户介入或成功回合`);
|
|
2868
|
+
return false;
|
|
2869
|
+
}
|
|
2870
|
+
return true;
|
|
2730
2871
|
}
|
|
2731
2872
|
|
|
2732
2873
|
/** 发送需要 live agent; 存储会话沿既有物化路径拉起, 复用 preset 与模型回装。 */
|
|
@@ -2784,9 +2925,7 @@ export class AutoContinueRunner {
|
|
|
2784
2925
|
*/
|
|
2785
2926
|
private rearmGoal(sessionId: SessionId, config: AutoContinueConfig): void {
|
|
2786
2927
|
if (!config.resumeGoals) return;
|
|
2787
|
-
const goals =
|
|
2788
|
-
| GoalServiceLike
|
|
2789
|
-
| undefined;
|
|
2928
|
+
const goals = this.goals();
|
|
2790
2929
|
if (goals === undefined) return;
|
|
2791
2930
|
const agent = this.ctx.agents.get(sessionId);
|
|
2792
2931
|
if (agent === undefined) return;
|
|
@@ -2803,6 +2942,10 @@ export class AutoContinueRunner {
|
|
|
2803
2942
|
}
|
|
2804
2943
|
const ref: GoalRefLike = view.ref ?? { id: view.id, revision };
|
|
2805
2944
|
if (view.phase === 'active' && view.activation === 'disarmed') {
|
|
2945
|
+
if (goalStoppedByUser(snapshotSessionEvents(agent.session))) {
|
|
2946
|
+
this.log(`会话 ${sessionId}: goal 是用户停下的, 不重新武装(等用户自己恢复)`);
|
|
2947
|
+
return;
|
|
2948
|
+
}
|
|
2806
2949
|
goals.resume(agent, ref);
|
|
2807
2950
|
this.log(`会话 ${sessionId}: goal 被重启失活, 已重新武装`);
|
|
2808
2951
|
return;
|
|
@@ -2818,6 +2961,104 @@ export class AutoContinueRunner {
|
|
|
2818
2961
|
}
|
|
2819
2962
|
}
|
|
2820
2963
|
|
|
2964
|
+
private goals(): GoalServiceLike | undefined {
|
|
2965
|
+
return (this.ctx as unknown as { get(key: string): unknown }).get(GOALS_SERVICE_KEY) as GoalServiceLike | undefined;
|
|
2966
|
+
}
|
|
2967
|
+
|
|
2968
|
+
/**
|
|
2969
|
+
* A paused or blocked goal is a decision to stop and wait; a continue sent anyway reads as the
|
|
2970
|
+
* user resuming it. `resumePausedGoals` is the user's standing permission to resume paused
|
|
2971
|
+
* goals, so it lets those through.
|
|
2972
|
+
*/
|
|
2973
|
+
private heldGoalPhase(agent: Agent, config: AutoContinueConfig): string | undefined {
|
|
2974
|
+
let phase: string | undefined;
|
|
2975
|
+
try {
|
|
2976
|
+
const goals = this.goals();
|
|
2977
|
+
if (goals === undefined) return undefined; // a host without goals
|
|
2978
|
+
phase = goals.get(agent)?.phase;
|
|
2979
|
+
} catch {
|
|
2980
|
+
return 'unreadable'; // the goal may be paused or blocked: do not speak for the user
|
|
2981
|
+
}
|
|
2982
|
+
return this.goalHold(phase, config);
|
|
2983
|
+
}
|
|
2984
|
+
|
|
2985
|
+
private goalHold(phase: string | undefined, config: AutoContinueConfig): string | undefined {
|
|
2986
|
+
if (phase === 'blocked') return phase;
|
|
2987
|
+
if (phase === 'paused' && !(config.resumeGoals && config.resumePausedGoals)) return phase;
|
|
2988
|
+
return undefined;
|
|
2989
|
+
}
|
|
2990
|
+
|
|
2991
|
+
/** `heldGoalPhase` for a session without a live agent, read from its stored goal projection. */
|
|
2992
|
+
private async storedGoalHold(sessionId: SessionId, config: AutoContinueConfig): Promise<string | undefined> {
|
|
2993
|
+
if (this.goals() === undefined) return undefined; // a host without goals
|
|
2994
|
+
const query = this.ctx.get('sessionQuery');
|
|
2995
|
+
if (query === undefined) return 'unreadable';
|
|
2996
|
+
let stored: StoredObservation | undefined;
|
|
2997
|
+
try {
|
|
2998
|
+
const observation: StoredObservation = await this.readStored(
|
|
2999
|
+
signal => query.observeSession(sessionId, { projectionMode: 'all', signal }),
|
|
3000
|
+
Date.now() + STORED_READ_TIMEOUT_MS,
|
|
3001
|
+
);
|
|
3002
|
+
stored = observation;
|
|
3003
|
+
return this.goalHold(observation.projections?.values.goal?.goal?.phase, config);
|
|
3004
|
+
} catch (error) {
|
|
3005
|
+
// Nothing stored (a discarded one-shot child, no persistence) holds no goal: keep the old fallback.
|
|
3006
|
+
if ((error as { code?: unknown } | null)?.code === 'SESSION_QUERY_SESSION_NOT_FOUND') return undefined;
|
|
3007
|
+
return 'unreadable';
|
|
3008
|
+
} finally {
|
|
3009
|
+
stored?.[Symbol.dispose]?.();
|
|
3010
|
+
}
|
|
3011
|
+
}
|
|
3012
|
+
|
|
3013
|
+
/**
|
|
3014
|
+
* Continuations this plugin sent since the last message from the user, manual stop or turn
|
|
3015
|
+
* with visible output, read from the log so the consecutive cap survives a host restart.
|
|
3016
|
+
* Mirrors the in-memory count: a continuation right after a visible completion is a loop
|
|
3017
|
+
* round and does not count. With `usePluginSource` off a continuation is a `user` message
|
|
3018
|
+
* matching one of the configured continue texts, so a user message identical to one of them
|
|
3019
|
+
* is counted too; that can only stop recovery earlier, never later.
|
|
3020
|
+
*/
|
|
3021
|
+
private continuationsInLog(events: readonly SessionEvent[], config: AutoContinueConfig): number {
|
|
3022
|
+
const ours = continueTextMatcher(config);
|
|
3023
|
+
let count = 0;
|
|
3024
|
+
let visible = false;
|
|
3025
|
+
let maintenance = false;
|
|
3026
|
+
let afterSuccess = false;
|
|
3027
|
+
for (const event of events) {
|
|
3028
|
+
if (event.type === 'turn/start') {
|
|
3029
|
+
visible = false;
|
|
3030
|
+
maintenance = isMaintenanceTurnStart(event);
|
|
3031
|
+
} else if (event.type === 'tool/call') {
|
|
3032
|
+
visible = true;
|
|
3033
|
+
} else if (event.type === 'assistant/chunk') {
|
|
3034
|
+
if (this.chunkVisible(event.data.chunk)) visible = true;
|
|
3035
|
+
} else if (event.type === 'assistant/message') {
|
|
3036
|
+
if (this.hasVisibleContent(event.data.message?.content)) visible = true;
|
|
3037
|
+
} else if (event.type === 'turn/end') {
|
|
3038
|
+
if (maintenance) continue;
|
|
3039
|
+
const reason = event.data.reason;
|
|
3040
|
+
const kind = readReasonKind(reason);
|
|
3041
|
+
afterSuccess = kind === 'completed' && visible;
|
|
3042
|
+
const userStop = kind === 'aborted' && !isHostCancel(reason) &&
|
|
3043
|
+
!isLoopGuardCancelReason((reason as { reason?: unknown }).reason);
|
|
3044
|
+
if (afterSuccess || userStop) count = 0;
|
|
3045
|
+
} else if (event.type === 'user/message') {
|
|
3046
|
+
const source = event.data.source?.kind;
|
|
3047
|
+
const text = messageText(event.data.content);
|
|
3048
|
+
// A child hand-off is a registered echo: in memory it neither counts nor resets.
|
|
3049
|
+
if (isHandoffText(text)) continue;
|
|
3050
|
+
if (source === AUTO_CONTINUE_SOURCE_KIND || (source === 'user' && ours(text))) {
|
|
3051
|
+
if (!afterSuccess) count += 1;
|
|
3052
|
+
} else if (source === 'user') {
|
|
3053
|
+
count = 0;
|
|
3054
|
+
}
|
|
3055
|
+
// Only the one continuation right after a visible completion is a loop round.
|
|
3056
|
+
if (source === AUTO_CONTINUE_SOURCE_KIND || source === 'user') afterSuccess = false;
|
|
3057
|
+
}
|
|
3058
|
+
}
|
|
3059
|
+
return count;
|
|
3060
|
+
}
|
|
3061
|
+
|
|
2821
3062
|
/**
|
|
2822
3063
|
* 按会话记录的 preset 组合把存储会话恢复为 live agent(镜像会话控制
|
|
2823
3064
|
* 器的 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,
|