dsh-client-auto-continue 0.20.1 → 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 +21 -0
- package/README.md +8 -6
- package/README.ru.md +8 -6
- package/README.zh.md +8 -6
- package/docs/releases/v0.20.2.md +49 -0
- 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 +236 -14
- 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 +26 -0
- package/lib/types/index.d.ts +8 -0
- package/lib/types/shared/core.d.ts +7 -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 +282 -20
- package/src/index.ts +2 -0
- package/src/shared/core.ts +16 -0
package/src/client/locales.ts
CHANGED
|
@@ -82,6 +82,9 @@ export const zh = {
|
|
|
82
82
|
'field.continueTextInterrupted': '宿主重启后恢复的继续文本',
|
|
83
83
|
'field.continueTextInterruptedHint': 'DSH 重启后恢复中断会话时发送的文本。',
|
|
84
84
|
'default.continueTextInterrupted': LOCALIZED_TEXT_DEFAULTS.zh.continueTextInterrupted,
|
|
85
|
+
'field.continueTextQuestion': '提问未获回答时的继续文本',
|
|
86
|
+
'field.continueTextQuestionHint': '被打断的上一步是向用户提问(ask_user_question)且用户还没回答时, 改发这段文本, 不附护栏提示, 让模型重新提问并等待回答。',
|
|
87
|
+
'default.continueTextQuestion': LOCALIZED_TEXT_DEFAULTS.zh.continueTextQuestion,
|
|
85
88
|
'field.guardTools': '幂等护栏',
|
|
86
89
|
'field.guardToolsHint': '继续前,工具结果未确认时提醒模型核实状态,已成功时提醒跳过该操作。',
|
|
87
90
|
'field.guardPendingText': '结果未确认时的护栏文本',
|
|
@@ -254,6 +257,9 @@ export const en: Record<SettingsCardKey, string> = {
|
|
|
254
257
|
'field.continueTextInterrupted': 'Continue text (after harness restart)',
|
|
255
258
|
'field.continueTextInterruptedHint': 'Text sent when resuming an interrupted session after DSH restarts.',
|
|
256
259
|
'default.continueTextInterrupted': LOCALIZED_TEXT_DEFAULTS.en.continueTextInterrupted,
|
|
260
|
+
'field.continueTextQuestion': 'Continue text (unanswered question)',
|
|
261
|
+
'field.continueTextQuestionHint': 'Sent instead, without a guard note, when the interrupted step was a question to the user (ask_user_question) that has not been answered, so the model asks again and waits.',
|
|
262
|
+
'default.continueTextQuestion': LOCALIZED_TEXT_DEFAULTS.en.continueTextQuestion,
|
|
257
263
|
'field.guardTools': 'Idempotency guard',
|
|
258
264
|
'field.guardToolsHint': 'Before resuming, remind the model to check unconfirmed tool results or skip an action that already succeeded.',
|
|
259
265
|
'field.guardPendingText': 'Guard text (unconfirmed result)',
|
|
@@ -409,6 +415,9 @@ export const ru: Record<SettingsCardKey, string> = {
|
|
|
409
415
|
'field.continueTextInterrupted': 'Текст продолжения (после перезапуска хоста)',
|
|
410
416
|
'field.continueTextInterruptedHint': 'Текст, отправляемый, когда сканирование при запуске продолжает сессию, прерванную перезапуском; по умолчанию объясняет перезапуск и просит сверять состояние перед повтором.',
|
|
411
417
|
'default.continueTextInterrupted': LOCALIZED_TEXT_DEFAULTS.ru.continueTextInterrupted,
|
|
418
|
+
'field.continueTextQuestion': 'Текст продолжения (вопрос без ответа)',
|
|
419
|
+
'field.continueTextQuestionHint': 'Отправляется вместо обычного текста и без заметки защиты, если прерванным шагом был вопрос пользователю (ask_user_question), на который ещё нет ответа: модель задаёт вопрос снова и ждёт ответа.',
|
|
420
|
+
'default.continueTextQuestion': LOCALIZED_TEXT_DEFAULTS.ru.continueTextQuestion,
|
|
412
421
|
'field.guardTools': 'Защита от повторного выполнения',
|
|
413
422
|
'field.guardToolsHint': 'Перед продолжением проверяет последний вызов инструмента: если результат не подтверждён, просит сначала проверить состояние; если вызов успешен — не повторять его. Помогает не дублировать коммиты и вызовы API.',
|
|
414
423
|
'field.guardPendingText': 'Текст защиты (результат не подтверждён)',
|
|
@@ -100,6 +100,7 @@ export interface AutoContinueSettingsCardState extends CardShell {
|
|
|
100
100
|
continueTextLoop: CardFieldState;
|
|
101
101
|
continueTextSilent: CardFieldState;
|
|
102
102
|
continueTextInterrupted: CardFieldState;
|
|
103
|
+
continueTextQuestion: CardFieldState;
|
|
103
104
|
guardTools: CardFieldState;
|
|
104
105
|
guardPendingText: CardFieldState;
|
|
105
106
|
guardDoneText: CardFieldState;
|
|
@@ -169,6 +170,7 @@ export class AutoContinueSettingsCardController {
|
|
|
169
170
|
textField('continueTextLoop'),
|
|
170
171
|
textField('continueTextSilent'),
|
|
171
172
|
textField('continueTextInterrupted'),
|
|
173
|
+
textField('continueTextQuestion'),
|
|
172
174
|
booleanField('guardTools'),
|
|
173
175
|
textField('guardPendingText'),
|
|
174
176
|
textField('guardDoneText'),
|
|
@@ -219,6 +221,7 @@ export class AutoContinueSettingsCardController {
|
|
|
219
221
|
continueTextLoop: this.form.field('continueTextLoop'),
|
|
220
222
|
continueTextSilent: this.form.field('continueTextSilent'),
|
|
221
223
|
continueTextInterrupted: this.form.field('continueTextInterrupted'),
|
|
224
|
+
continueTextQuestion: this.form.field('continueTextQuestion'),
|
|
222
225
|
guardTools: this.form.field('guardTools'),
|
|
223
226
|
guardPendingText: this.form.field('guardPendingText'),
|
|
224
227
|
guardDoneText: this.form.field('guardDoneText'),
|
|
@@ -331,7 +334,7 @@ const groups = [
|
|
|
331
334
|
{ id: 'general', fields: ['paused', 'showComposerToggle', 'usePluginSource', 'resumeSilentTurns', 'resumeSubagentSessions', 'resumeCompletedTurns', 'loopMaxIterations', 'notify'] },
|
|
332
335
|
{ id: 'recovery', fields: ['graceMs', 'cooldownMs', 'maxConsecutive', 'classify', 'retryableErrorPatterns', 'backoffFactor', 'backoffMaxMs', 'pauseWhenOffline', 'offlineCheckMs', 'resumeGoals', 'resumePausedGoals'] },
|
|
333
336
|
{ id: 'startup', fields: ['scanOnBoot', 'resumeInterruptedChildren', 'scanLimit', 'freshMs'] },
|
|
334
|
-
{ id: 'prompts', fields: ['continueText', 'continueTextMaxTokens', 'continueTextSilent', 'continueTextInterrupted', 'continueTextLoop', 'guardPendingText', 'guardDoneText', 'loopText'] },
|
|
337
|
+
{ id: 'prompts', fields: ['continueText', 'continueTextMaxTokens', 'continueTextSilent', 'continueTextInterrupted', 'continueTextQuestion', 'continueTextLoop', 'guardPendingText', 'guardDoneText', 'loopText'] },
|
|
335
338
|
{ id: 'safety', fields: ['guardTools', 'loopGuard', 'loopShortChars', 'loopWindowMs', 'loopShortCount', 'loopRepeatText', 'loopToolRepeat'] },
|
|
336
339
|
{ id: 'status', fields: ['verbose'] },
|
|
337
340
|
] as const satisfies ReadonlyArray<{ id: string; fields: readonly FieldName[] }>;
|
|
@@ -339,7 +342,7 @@ type Category = typeof groups[number]['id'];
|
|
|
339
342
|
const textDefaults: Partial<Record<FieldName, SettingsCardKey>> = {
|
|
340
343
|
continueText: 'default.continueText', continueTextMaxTokens: 'default.continueTextMaxTokens',
|
|
341
344
|
continueTextSilent: 'default.continueTextSilent', continueTextLoop: 'default.continueTextLoop',
|
|
342
|
-
continueTextInterrupted: 'default.continueTextInterrupted',
|
|
345
|
+
continueTextInterrupted: 'default.continueTextInterrupted', continueTextQuestion: 'default.continueTextQuestion',
|
|
343
346
|
guardPendingText: 'default.guardPendingText', guardDoneText: 'default.guardDoneText', loopText: 'default.loopText',
|
|
344
347
|
};
|
|
345
348
|
|
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
|
|
|
@@ -256,6 +260,15 @@ const isLoopReason = (reason: string): boolean =>
|
|
|
256
260
|
const STREAM_NEAR_DUPLICATE_MAX_CHARS = 2_048;
|
|
257
261
|
/** Bound unfinished text copied between token chunks when a provider emits no paragraph break. */
|
|
258
262
|
const STREAM_TAIL_MAX_CHARS = 4_096;
|
|
263
|
+
/**
|
|
264
|
+
* Rolling window of recent stream segments (paragraphs, or lines of an overlong
|
|
265
|
+
* paragraph). A degenerate stream cycles through a handful of short lines
|
|
266
|
+
* (`Writing.` / `Then: fill domain, go.`), which neither the long-segment gate nor
|
|
267
|
+
* the adjacent near-duplicate check sees; a nearly unique-free window does.
|
|
268
|
+
*/
|
|
269
|
+
const STREAM_WINDOW_SEGMENTS = 40;
|
|
270
|
+
/** At most this many distinct segments in a full window counts as a loop (20%). */
|
|
271
|
+
const STREAM_WINDOW_MAX_UNIQUE = 8;
|
|
259
272
|
|
|
260
273
|
/** Ignore invisible formatting only for detection, never rewrite the stored message. */
|
|
261
274
|
const visibleText = (text: string): string => text.replace(/\p{Cf}/gu, '').trim();
|
|
@@ -435,6 +448,68 @@ function isLoopGuardCancelReason(value: unknown): boolean {
|
|
|
435
448
|
return cause.kind === LOOP_GUARD_CANCEL_CAUSE.kind && cause.reason === LOOP_GUARD_CANCEL_CAUSE.reason;
|
|
436
449
|
}
|
|
437
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
|
+
|
|
438
513
|
/**
|
|
439
514
|
* 事件流泵: 带指数退避的 SSE 重连循环。
|
|
440
515
|
* - 从未收到任何帧(宿主未就绪): 退避重试, 不触发扫描
|
|
@@ -964,11 +1039,7 @@ export class AutoContinueRunner {
|
|
|
964
1039
|
const state = this.state(sessionId);
|
|
965
1040
|
if (this.tracksOutput(state, event)) {
|
|
966
1041
|
const chunk = event.data.chunk;
|
|
967
|
-
|
|
968
|
-
chunk.type === 'tool-call-delta' ||
|
|
969
|
-
(chunk.type === 'block-end' && this.hasVisibleContent([chunk.block])) ||
|
|
970
|
-
(chunk.type === 'block-start' && chunk.blockType !== 'reasoning' && chunk.blockType !== 'text');
|
|
971
|
-
if (visible) state.turnOutput = 'visible';
|
|
1042
|
+
if (this.chunkVisible(chunk)) state.turnOutput = 'visible';
|
|
972
1043
|
else if (state.turnOutput === 'empty' && chunk.type !== 'usage' && chunk.type !== 'finish') state.turnOutput = 'silent';
|
|
973
1044
|
}
|
|
974
1045
|
this.onAssistantChunk(sessionId, state, event);
|
|
@@ -988,6 +1059,13 @@ export class AutoContinueRunner {
|
|
|
988
1059
|
event.seq > state.outputStartSeq;
|
|
989
1060
|
}
|
|
990
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
|
+
|
|
991
1069
|
/** Treat unknown block kinds conservatively: only reasoning and blank text are silent. */
|
|
992
1070
|
private hasVisibleContent(content: unknown): boolean {
|
|
993
1071
|
if (!Array.isArray(content)) return false;
|
|
@@ -1071,6 +1149,7 @@ export class AutoContinueRunner {
|
|
|
1071
1149
|
const normalized = this.normalizedSegment(segment);
|
|
1072
1150
|
const config = this.getConfig();
|
|
1073
1151
|
if (normalized === '') return;
|
|
1152
|
+
if (this.noteStreamWindow(sessionId, state, normalized)) return;
|
|
1074
1153
|
if (normalized.length < config.loopShortChars) {
|
|
1075
1154
|
state.streamLastSegment = '';
|
|
1076
1155
|
state.streamRepeatRun = 0;
|
|
@@ -1094,6 +1173,26 @@ export class AutoContinueRunner {
|
|
|
1094
1173
|
}
|
|
1095
1174
|
}
|
|
1096
1175
|
|
|
1176
|
+
/**
|
|
1177
|
+
* 滚动窗口唯一率: 不看段长, 也不要求相邻, 所以短行交替复读(A/B/A/B)和短行
|
|
1178
|
+
* 连续复读都能命中。没有字母数字的段(分隔线、代码围栏、括号)不进窗口。
|
|
1179
|
+
* 返回 true 表示已打断。
|
|
1180
|
+
*/
|
|
1181
|
+
private noteStreamWindow(sessionId: SessionId, state: SessionState, normalized: string): boolean {
|
|
1182
|
+
if (!/[\p{L}\p{N}]/u.test(normalized)) return false;
|
|
1183
|
+
const window = state.streamWindow;
|
|
1184
|
+
window.push(normalized);
|
|
1185
|
+
if (window.length > STREAM_WINDOW_SEGMENTS) window.shift();
|
|
1186
|
+
if (window.length < STREAM_WINDOW_SEGMENTS) return false;
|
|
1187
|
+
const unique = new Set(window).size;
|
|
1188
|
+
if (unique > STREAM_WINDOW_MAX_UNIQUE) return false;
|
|
1189
|
+
this.log(
|
|
1190
|
+
`检测到流式消息内复读 ${sessionId}: 最近 ${STREAM_WINDOW_SEGMENTS} 段只有 ${unique} 种不同文本`,
|
|
1191
|
+
);
|
|
1192
|
+
this.interruptLoop(sessionId, state);
|
|
1193
|
+
return state.loopFired;
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1097
1196
|
private onAssistantChunk(
|
|
1098
1197
|
sessionId: SessionId,
|
|
1099
1198
|
state: SessionState,
|
|
@@ -1110,7 +1209,17 @@ export class AutoContinueRunner {
|
|
|
1110
1209
|
state.streamTail = tail;
|
|
1111
1210
|
return;
|
|
1112
1211
|
}
|
|
1113
|
-
|
|
1212
|
+
// 超长且一直没有空行: 把完整的行送进滚动窗口, 单换行分隔的刷屏也能被看到。
|
|
1213
|
+
const lines = tail.split('\n');
|
|
1214
|
+
const rest = lines.pop() ?? '';
|
|
1215
|
+
for (const line of lines) {
|
|
1216
|
+
const normalized = this.normalizedSegment(line);
|
|
1217
|
+
if (normalized !== '' && this.noteStreamWindow(sessionId, state, normalized)) {
|
|
1218
|
+
state.streamTail = '';
|
|
1219
|
+
return;
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
state.streamTail = rest.slice(-STREAM_TAIL_MAX_CHARS);
|
|
1114
1223
|
if (/\S/u.test(tail)) {
|
|
1115
1224
|
state.streamLastSegment = '';
|
|
1116
1225
|
state.streamRepeatRun = 0;
|
|
@@ -1150,6 +1259,7 @@ export class AutoContinueRunner {
|
|
|
1150
1259
|
if (streamTail !== '') this.noteStreamSegment(sessionId, state, streamTail);
|
|
1151
1260
|
state.streamLastSegment = '';
|
|
1152
1261
|
state.streamRepeatRun = 0;
|
|
1262
|
+
state.streamWindow = [];
|
|
1153
1263
|
this.checkLoop(sessionId, state);
|
|
1154
1264
|
}
|
|
1155
1265
|
|
|
@@ -1222,6 +1332,7 @@ export class AutoContinueRunner {
|
|
|
1222
1332
|
state.streamTail = '';
|
|
1223
1333
|
state.streamLastSegment = '';
|
|
1224
1334
|
state.streamRepeatRun = 0;
|
|
1335
|
+
state.streamWindow = [];
|
|
1225
1336
|
state.loopFired = false;
|
|
1226
1337
|
state.turnOutput = 'empty';
|
|
1227
1338
|
state.outputTurn = event.data.turn;
|
|
@@ -1304,6 +1415,7 @@ export class AutoContinueRunner {
|
|
|
1304
1415
|
state.streamTail = '';
|
|
1305
1416
|
state.streamLastSegment = '';
|
|
1306
1417
|
state.streamRepeatRun = 0;
|
|
1418
|
+
state.streamWindow = [];
|
|
1307
1419
|
state.tools.resetRepeat();
|
|
1308
1420
|
// 重启受冷却约束(防紧密打断循环): 等剩余冷却结束后再调度
|
|
1309
1421
|
const cooldown = this.cooldownFor(state);
|
|
@@ -1685,7 +1797,9 @@ export class AutoContinueRunner {
|
|
|
1685
1797
|
* The child's own recovery mode decides; the parent only has to be alive to
|
|
1686
1798
|
* authorize the call.
|
|
1687
1799
|
*/
|
|
1688
|
-
private async reviveChild(
|
|
1800
|
+
private async reviveChild(
|
|
1801
|
+
sessionId: SessionId, reason: string, text: string, force: boolean, checkGoal: boolean,
|
|
1802
|
+
): Promise<void> {
|
|
1689
1803
|
if (this.disposed || this.getConfig().paused) return;
|
|
1690
1804
|
if (!this.subagentRecoveryEnabled(sessionId)) return;
|
|
1691
1805
|
const state = this.state(sessionId);
|
|
@@ -1707,6 +1821,22 @@ export class AutoContinueRunner {
|
|
|
1707
1821
|
return;
|
|
1708
1822
|
}
|
|
1709
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
|
+
}
|
|
1710
1840
|
const parent = this.parentOf(sessionId);
|
|
1711
1841
|
if (parent === undefined || parent === '') return;
|
|
1712
1842
|
const handoff = this.handoffText(sessionId, reason);
|
|
@@ -1910,6 +2040,10 @@ export class AutoContinueRunner {
|
|
|
1910
2040
|
// 模板填充: continueText 可含 {code}/{message}/{status}/{tool}/{turn}/{errorCount}/{sessionTitle}/{elapsed} 占位符
|
|
1911
2041
|
const template = this.templateFor(config, reason);
|
|
1912
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');
|
|
1913
2047
|
// 发送: followup 负责唤醒; 同步 inbox 插入事件会在唤醒前把本消息移到已有队列之前。
|
|
1914
2048
|
const agent = this.ctx.agents.get(sessionId);
|
|
1915
2049
|
if (agent === undefined) {
|
|
@@ -1919,11 +2053,17 @@ export class AutoContinueRunner {
|
|
|
1919
2053
|
// failure to its main conversation instead. A manual "Resume now" must
|
|
1920
2054
|
// revive a disposed child too: its force flag only relaxes the cooldown.
|
|
1921
2055
|
if (this.isSubagentSession(sessionId) && this.subagentRecoveryEnabled(sessionId)) {
|
|
1922
|
-
void this.reviveChild(sessionId, reason, text, manualResume);
|
|
2056
|
+
void this.reviveChild(sessionId, reason, text, manualResume, resumesInterruption);
|
|
1923
2057
|
}
|
|
1924
2058
|
this.log(`跳过 ${sessionId}(${reason}): 无 live agent`);
|
|
1925
2059
|
return;
|
|
1926
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
|
+
}
|
|
1927
2067
|
state.lastAttemptAt = Date.now(); // 先记账: 无论成败, 本次尝试都进入冷却
|
|
1928
2068
|
try {
|
|
1929
2069
|
const message = createUserMessage({
|
|
@@ -2092,15 +2232,17 @@ export class AutoContinueRunner {
|
|
|
2092
2232
|
state: SessionState,
|
|
2093
2233
|
template: string,
|
|
2094
2234
|
): string {
|
|
2095
|
-
|
|
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, {
|
|
2096
2239
|
facts: state.lastFailure,
|
|
2097
2240
|
tool: state.tools.lastTool(),
|
|
2098
2241
|
turn: state.lastTurn,
|
|
2099
2242
|
errorCount: state.consecutive + 1,
|
|
2100
2243
|
elapsedMs: state.lastFailureAt > 0 ? Date.now() - state.lastFailureAt : undefined,
|
|
2101
2244
|
});
|
|
2102
|
-
if (!config.guardTools) return text;
|
|
2103
|
-
const guard = this.currentGuard(state);
|
|
2245
|
+
if (unanswered || !config.guardTools) return text;
|
|
2104
2246
|
if (guard.kind === 'pending') {
|
|
2105
2247
|
text += ` ${fillTemplate(config.guardPendingText, { tool: guard.tool, result: guard.result })}`;
|
|
2106
2248
|
} else if (guard.kind === 'done') {
|
|
@@ -2227,6 +2369,14 @@ export class AutoContinueRunner {
|
|
|
2227
2369
|
continue;
|
|
2228
2370
|
}
|
|
2229
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
|
+
}
|
|
2230
2380
|
candidates.push({
|
|
2231
2381
|
session, sessionId, events, lastEnd, reasonKind, failure,
|
|
2232
2382
|
lastActivityAt: events.reduce((latest, event) => Math.max(latest, event.time), 0),
|
|
@@ -2564,6 +2714,11 @@ export class AutoContinueRunner {
|
|
|
2564
2714
|
if (events.length === 0) return;
|
|
2565
2715
|
const cause = classifyChildInterruption(events, config);
|
|
2566
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
|
+
}
|
|
2567
2722
|
const tail = events[events.length - 1];
|
|
2568
2723
|
const list = this.childInterrupts.get(rootId) ?? [];
|
|
2569
2724
|
list.push({
|
|
@@ -2633,9 +2788,14 @@ export class AutoContinueRunner {
|
|
|
2633
2788
|
if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) return false;
|
|
2634
2789
|
const batch = children.map(child => `${child.id}:${child.cause}`).sort().join(',');
|
|
2635
2790
|
if (this.childWoken.get(rootId) === batch) return true;
|
|
2636
|
-
if (!(await this.rootAcceptsWake(rootId, deadline))) return true; // 明确裁决: 不该唤醒
|
|
2791
|
+
if (!(await this.rootAcceptsWake(rootId, config, deadline))) return true; // 明确裁决: 不该唤醒
|
|
2637
2792
|
const agent = await this.ensureLiveAgent(rootId, deadline);
|
|
2638
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
|
+
}
|
|
2639
2799
|
const text = this.buildChildResumeText(config, children);
|
|
2640
2800
|
const message = createUserMessage({
|
|
2641
2801
|
content: [{ type: 'text', text }],
|
|
@@ -2652,7 +2812,7 @@ export class AutoContinueRunner {
|
|
|
2652
2812
|
}
|
|
2653
2813
|
|
|
2654
2814
|
/** 父会话只在"干净结束"或"被宿主关闭"时接受唤醒; 用户手动停止的绝不复活。 */
|
|
2655
|
-
private async rootAcceptsWake(sessionId: SessionId, deadline: number): Promise<boolean> {
|
|
2815
|
+
private async rootAcceptsWake(sessionId: SessionId, config: AutoContinueConfig, deadline: number): Promise<boolean> {
|
|
2656
2816
|
const query = this.ctx.get('sessionQuery');
|
|
2657
2817
|
if (query === undefined) return false;
|
|
2658
2818
|
let events: readonly SessionEvent[];
|
|
@@ -2681,9 +2841,15 @@ export class AutoContinueRunner {
|
|
|
2681
2841
|
if (lastStart !== undefined && (end === undefined || lastStart.seq > end.seq)) return false;
|
|
2682
2842
|
if (end === undefined) return false;
|
|
2683
2843
|
const kind = readReasonKind(end.data.reason);
|
|
2684
|
-
if (kind
|
|
2685
|
-
|
|
2686
|
-
|
|
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;
|
|
2687
2853
|
}
|
|
2688
2854
|
|
|
2689
2855
|
/** 发送需要 live agent; 存储会话沿既有物化路径拉起, 复用 preset 与模型回装。 */
|
|
@@ -2741,9 +2907,7 @@ export class AutoContinueRunner {
|
|
|
2741
2907
|
*/
|
|
2742
2908
|
private rearmGoal(sessionId: SessionId, config: AutoContinueConfig): void {
|
|
2743
2909
|
if (!config.resumeGoals) return;
|
|
2744
|
-
const goals =
|
|
2745
|
-
| GoalServiceLike
|
|
2746
|
-
| undefined;
|
|
2910
|
+
const goals = this.goals();
|
|
2747
2911
|
if (goals === undefined) return;
|
|
2748
2912
|
const agent = this.ctx.agents.get(sessionId);
|
|
2749
2913
|
if (agent === undefined) return;
|
|
@@ -2775,6 +2939,104 @@ export class AutoContinueRunner {
|
|
|
2775
2939
|
}
|
|
2776
2940
|
}
|
|
2777
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
|
+
|
|
2778
3040
|
/**
|
|
2779
3041
|
* 按会话记录的 preset 组合把存储会话恢复为 live agent(镜像会话控制
|
|
2780
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,
|
|
@@ -993,6 +1006,8 @@ export interface SessionState {
|
|
|
993
1006
|
streamLastSegment: string;
|
|
994
1007
|
/** 流式消息内连续近似重复长段计数。 */
|
|
995
1008
|
streamRepeatRun: number;
|
|
1009
|
+
/** 流式消息最近若干段(或超长段的行)的归一化文本, 用于唯一率检测。 */
|
|
1010
|
+
streamWindow: string[];
|
|
996
1011
|
/** 本回合已触发过 loop guard(防重复打断)。 */
|
|
997
1012
|
loopFired: boolean;
|
|
998
1013
|
/** loop 重启的延迟定时器(冷却结束后再 schedule)。 */
|
|
@@ -1036,6 +1051,7 @@ export const freshState = (): SessionState => ({
|
|
|
1036
1051
|
streamTail: '',
|
|
1037
1052
|
streamLastSegment: '',
|
|
1038
1053
|
streamRepeatRun: 0,
|
|
1054
|
+
streamWindow: [],
|
|
1039
1055
|
loopFired: false,
|
|
1040
1056
|
loopRetryTimer: undefined,
|
|
1041
1057
|
cooldownRetryTimer: undefined,
|