dsh-client-auto-continue 0.11.4 → 0.11.6
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/README.md +3 -2
- package/README.zh.md +3 -2
- package/lib/client.js +13 -4
- package/lib/client.js.map +2 -2
- package/lib/index.js +112 -1
- package/lib/types/host/engine.d.ts +6 -0
- package/lib/types/index.d.ts +2 -2
- package/lib/types/shared/core.d.ts +7 -1
- package/package.json +2 -2
- package/src/client/index.ts +37 -0
- package/src/client/locales.ts +4 -4
- package/src/host/engine.ts +126 -0
- package/src/index.ts +1 -1
- package/src/shared/core.ts +10 -1
package/lib/index.js
CHANGED
|
@@ -551,6 +551,9 @@ var freshState = () => ({
|
|
|
551
551
|
lastShortAt: 0,
|
|
552
552
|
lastAssistantText: "",
|
|
553
553
|
sameTextRun: 0,
|
|
554
|
+
streamTail: "",
|
|
555
|
+
streamLastSegment: "",
|
|
556
|
+
streamRepeatRun: 0,
|
|
554
557
|
loopFired: false,
|
|
555
558
|
loopRetryTimer: void 0
|
|
556
559
|
});
|
|
@@ -612,6 +615,8 @@ var LOOP_GUARD_CANCEL_CAUSE = {
|
|
|
612
615
|
kind: "hook",
|
|
613
616
|
reason: "dsh-auto-continue:loop-guard"
|
|
614
617
|
};
|
|
618
|
+
var STREAM_NEAR_DUPLICATE_MAX_CHARS = 2048;
|
|
619
|
+
var STREAM_TAIL_MAX_CHARS = 4096;
|
|
615
620
|
function snapshotSessionEvents(session) {
|
|
616
621
|
const compatible = session;
|
|
617
622
|
if (typeof compatible.snapshotEvents === "function") return compatible.snapshotEvents();
|
|
@@ -763,6 +768,9 @@ var AutoContinueRunner = class {
|
|
|
763
768
|
const state = this.state(sessionId);
|
|
764
769
|
const repeat = state.tools.confirmRepeatAtStep(event.seq);
|
|
765
770
|
if (repeat !== void 0) this.checkLoop(sessionId, state, repeat);
|
|
771
|
+
} else if (event.type === "assistant/chunk") {
|
|
772
|
+
const state = this.state(sessionId);
|
|
773
|
+
this.onAssistantChunk(sessionId, state, event);
|
|
766
774
|
} else if (event.type === "assistant/message") {
|
|
767
775
|
const state = this.state(sessionId);
|
|
768
776
|
this.onAssistantMessage(sessionId, state, event);
|
|
@@ -775,6 +783,98 @@ var AutoContinueRunner = class {
|
|
|
775
783
|
if (!Array.isArray(content)) return "";
|
|
776
784
|
return content.filter((part) => part.type === "text").map((part) => part.text).join("");
|
|
777
785
|
}
|
|
786
|
+
assistantChunkText(event) {
|
|
787
|
+
return event.data.chunk.type === "text-delta" ? event.data.chunk.text : "";
|
|
788
|
+
}
|
|
789
|
+
normalizedSegment(text) {
|
|
790
|
+
return text.replace(/\s+/g, " ").trim();
|
|
791
|
+
}
|
|
792
|
+
isNearDuplicateSegment(left, right) {
|
|
793
|
+
if (left === right) return true;
|
|
794
|
+
const leftLen = left.length;
|
|
795
|
+
const rightLen = right.length;
|
|
796
|
+
const longer = Math.max(leftLen, rightLen);
|
|
797
|
+
const shorter = Math.min(leftLen, rightLen);
|
|
798
|
+
if (shorter === 0 || shorter / longer < 0.85) return false;
|
|
799
|
+
if (longer > STREAM_NEAR_DUPLICATE_MAX_CHARS) return false;
|
|
800
|
+
const maxDistance = Math.max(6, Math.floor(longer * 0.08));
|
|
801
|
+
if (Math.abs(leftLen - rightLen) > maxDistance) return false;
|
|
802
|
+
return this.withinEditDistance(left, right, maxDistance);
|
|
803
|
+
}
|
|
804
|
+
withinEditDistance(left, right, maxDistance) {
|
|
805
|
+
if (left === right) return true;
|
|
806
|
+
if (maxDistance < 0) return false;
|
|
807
|
+
const leftLen = left.length;
|
|
808
|
+
const rightLen = right.length;
|
|
809
|
+
if (Math.abs(leftLen - rightLen) > maxDistance) return false;
|
|
810
|
+
if (leftLen === 0 || rightLen === 0) return Math.max(leftLen, rightLen) <= maxDistance;
|
|
811
|
+
const unreachable = maxDistance + 1;
|
|
812
|
+
let previous = new Int32Array(rightLen + 1);
|
|
813
|
+
let current = new Int32Array(rightLen + 1);
|
|
814
|
+
previous.fill(unreachable);
|
|
815
|
+
for (let col = 0; col <= Math.min(rightLen, maxDistance); col += 1) {
|
|
816
|
+
previous[col] = col;
|
|
817
|
+
}
|
|
818
|
+
for (let row = 1; row <= leftLen; row += 1) {
|
|
819
|
+
current.fill(unreachable);
|
|
820
|
+
if (row <= maxDistance) current[0] = row;
|
|
821
|
+
const firstCol = Math.max(1, row - maxDistance);
|
|
822
|
+
const lastCol = Math.min(rightLen, row + maxDistance);
|
|
823
|
+
let minInRow = unreachable;
|
|
824
|
+
for (let col = firstCol; col <= lastCol; col += 1) {
|
|
825
|
+
const insertion = (current[col - 1] ?? unreachable) + 1;
|
|
826
|
+
const deletion = (previous[col] ?? unreachable) + 1;
|
|
827
|
+
const substitution = (previous[col - 1] ?? unreachable) + (left.charCodeAt(row - 1) === right.charCodeAt(col - 1) ? 0 : 1);
|
|
828
|
+
const score = Math.min(insertion, deletion, substitution, unreachable);
|
|
829
|
+
current[col] = score;
|
|
830
|
+
if (score < minInRow) minInRow = score;
|
|
831
|
+
}
|
|
832
|
+
if (minInRow > maxDistance) return false;
|
|
833
|
+
[previous, current] = [current, previous];
|
|
834
|
+
}
|
|
835
|
+
return (previous[rightLen] ?? unreachable) <= maxDistance;
|
|
836
|
+
}
|
|
837
|
+
noteStreamSegment(sessionId, state, segment) {
|
|
838
|
+
const normalized = this.normalizedSegment(segment);
|
|
839
|
+
const config = this.getConfig();
|
|
840
|
+
if (normalized === "") return;
|
|
841
|
+
if (normalized.length < config.loopShortChars) {
|
|
842
|
+
state.streamLastSegment = "";
|
|
843
|
+
state.streamRepeatRun = 0;
|
|
844
|
+
return;
|
|
845
|
+
}
|
|
846
|
+
if (state.streamLastSegment !== "" && this.isNearDuplicateSegment(normalized, state.streamLastSegment)) {
|
|
847
|
+
state.streamRepeatRun += 1;
|
|
848
|
+
state.streamLastSegment = normalized;
|
|
849
|
+
} else {
|
|
850
|
+
state.streamLastSegment = normalized;
|
|
851
|
+
state.streamRepeatRun = 1;
|
|
852
|
+
}
|
|
853
|
+
if (state.streamRepeatRun >= config.loopRepeatText) {
|
|
854
|
+
this.log(
|
|
855
|
+
`检测到流式消息内复读 ${sessionId}: 连续 ${state.streamRepeatRun} 段近似重复文本`
|
|
856
|
+
);
|
|
857
|
+
this.interruptLoop(sessionId, state);
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
onAssistantChunk(sessionId, state, event) {
|
|
861
|
+
if (!this.getConfig().loopGuard || !state.running || state.loopFired) return;
|
|
862
|
+
const chunk = this.assistantChunkText(event);
|
|
863
|
+
if (chunk === "") return;
|
|
864
|
+
const merged = `${state.streamTail}${chunk}`.replace(/\r/g, "");
|
|
865
|
+
const pieces = merged.split(/\n(?:[ \t]*\n)+/u);
|
|
866
|
+
const tail = pieces.pop() ?? "";
|
|
867
|
+
for (const piece of pieces) this.noteStreamSegment(sessionId, state, piece);
|
|
868
|
+
if (tail.length <= STREAM_TAIL_MAX_CHARS) {
|
|
869
|
+
state.streamTail = tail;
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
872
|
+
state.streamTail = tail.slice(-STREAM_TAIL_MAX_CHARS);
|
|
873
|
+
if (/\S/u.test(tail)) {
|
|
874
|
+
state.streamLastSegment = "";
|
|
875
|
+
state.streamRepeatRun = 0;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
778
878
|
onAssistantMessage(sessionId, state, event) {
|
|
779
879
|
if (!this.getConfig().loopGuard) return;
|
|
780
880
|
const text = this.assistantText(event);
|
|
@@ -796,6 +896,11 @@ var AutoContinueRunner = class {
|
|
|
796
896
|
state.shortRun = 0;
|
|
797
897
|
state.lastShortAt = 0;
|
|
798
898
|
}
|
|
899
|
+
const streamTail = state.streamTail;
|
|
900
|
+
state.streamTail = "";
|
|
901
|
+
if (streamTail !== "") this.noteStreamSegment(sessionId, state, streamTail);
|
|
902
|
+
state.streamLastSegment = "";
|
|
903
|
+
state.streamRepeatRun = 0;
|
|
799
904
|
this.checkLoop(sessionId, state);
|
|
800
905
|
}
|
|
801
906
|
/** 两个循环信号的公共检查; 命中且本回合未打断过则打断。 */
|
|
@@ -852,6 +957,9 @@ var AutoContinueRunner = class {
|
|
|
852
957
|
state.lastShortAt = 0;
|
|
853
958
|
state.lastAssistantText = "";
|
|
854
959
|
state.sameTextRun = 0;
|
|
960
|
+
state.streamTail = "";
|
|
961
|
+
state.streamLastSegment = "";
|
|
962
|
+
state.streamRepeatRun = 0;
|
|
855
963
|
state.loopFired = false;
|
|
856
964
|
if (state.loopRetryTimer !== void 0) {
|
|
857
965
|
clearTimeout(state.loopRetryTimer);
|
|
@@ -882,6 +990,9 @@ var AutoContinueRunner = class {
|
|
|
882
990
|
state.lastShortAt = 0;
|
|
883
991
|
state.lastAssistantText = "";
|
|
884
992
|
state.sameTextRun = 0;
|
|
993
|
+
state.streamTail = "";
|
|
994
|
+
state.streamLastSegment = "";
|
|
995
|
+
state.streamRepeatRun = 0;
|
|
885
996
|
state.tools.resetRepeat();
|
|
886
997
|
const cooldown = this.cooldownFor(state);
|
|
887
998
|
const remaining = cooldown - (Date.now() - state.lastAttemptAt);
|
|
@@ -1334,7 +1445,7 @@ var AutoContinueSchema = z2.object({
|
|
|
1334
1445
|
loopWindowMs: z2.natural().min(1e3).default(3e4),
|
|
1335
1446
|
/** Consecutive short sentences trip the loop guard. */
|
|
1336
1447
|
loopShortCount: z2.natural().min(2).default(12),
|
|
1337
|
-
/** Consecutive identical
|
|
1448
|
+
/** Consecutive identical assistant messages trip the loop guard (strongest signal; also used for streamed intra-message repetition). */
|
|
1338
1449
|
loopRepeatText: z2.natural().min(2).default(4),
|
|
1339
1450
|
/** Consecutive identical tool calls with identical arguments AND results trip the loop guard. */
|
|
1340
1451
|
loopToolRepeat: z2.natural().min(2).default(5),
|
|
@@ -69,6 +69,12 @@ export declare class AutoContinueRunner {
|
|
|
69
69
|
private onHostEvent;
|
|
70
70
|
/** 从 assistant/message 事件提取纯文本。 */
|
|
71
71
|
private assistantText;
|
|
72
|
+
private assistantChunkText;
|
|
73
|
+
private normalizedSegment;
|
|
74
|
+
private isNearDuplicateSegment;
|
|
75
|
+
private withinEditDistance;
|
|
76
|
+
private noteStreamSegment;
|
|
77
|
+
private onAssistantChunk;
|
|
72
78
|
private onAssistantMessage;
|
|
73
79
|
/** 两个循环信号的公共检查; 命中且本回合未打断过则打断。 */
|
|
74
80
|
private checkLoop;
|
package/lib/types/index.d.ts
CHANGED
|
@@ -61,7 +61,7 @@ export declare const AutoContinueSchema: z<Schemastery.ObjectS<{
|
|
|
61
61
|
loopWindowMs: z<number, number>;
|
|
62
62
|
/** Consecutive short sentences trip the loop guard. */
|
|
63
63
|
loopShortCount: z<number, number>;
|
|
64
|
-
/** Consecutive identical
|
|
64
|
+
/** Consecutive identical assistant messages trip the loop guard (strongest signal; also used for streamed intra-message repetition). */
|
|
65
65
|
loopRepeatText: z<number, number>;
|
|
66
66
|
/** Consecutive identical tool calls with identical arguments AND results trip the loop guard. */
|
|
67
67
|
loopToolRepeat: z<number, number>;
|
|
@@ -114,7 +114,7 @@ export declare const AutoContinueSchema: z<Schemastery.ObjectS<{
|
|
|
114
114
|
loopWindowMs: z<number, number>;
|
|
115
115
|
/** Consecutive short sentences trip the loop guard. */
|
|
116
116
|
loopShortCount: z<number, number>;
|
|
117
|
-
/** Consecutive identical
|
|
117
|
+
/** Consecutive identical assistant messages trip the loop guard (strongest signal; also used for streamed intra-message repetition). */
|
|
118
118
|
loopRepeatText: z<number, number>;
|
|
119
119
|
/** Consecutive identical tool calls with identical arguments AND results trip the loop guard. */
|
|
120
120
|
loopToolRepeat: z<number, number>;
|
|
@@ -74,7 +74,7 @@ export interface AutoContinueSettings {
|
|
|
74
74
|
loopShortCount?: number;
|
|
75
75
|
/** Consecutive identical tool calls with identical arguments AND identical results trip the loop guard. */
|
|
76
76
|
loopToolRepeat?: number;
|
|
77
|
-
/** Consecutive identical
|
|
77
|
+
/** Consecutive identical assistant messages trip the loop guard (strongest signal; also used for streamed intra-message repetition). */
|
|
78
78
|
loopRepeatText?: number;
|
|
79
79
|
/** Text sent after the loop guard cancels and restarts a turn (supports {tool}). */
|
|
80
80
|
loopText?: string;
|
|
@@ -297,6 +297,12 @@ export interface SessionState {
|
|
|
297
297
|
lastAssistantText: string;
|
|
298
298
|
/** 连续相同文本消息数(最强空转信号, 不限长度)。 */
|
|
299
299
|
sameTextRun: number;
|
|
300
|
+
/** 流式消息尚未闭合的有界尾段(assistant/chunk 增量分段检测用)。 */
|
|
301
|
+
streamTail: string;
|
|
302
|
+
/** 流式消息最近一个长段的归一化文本。 */
|
|
303
|
+
streamLastSegment: string;
|
|
304
|
+
/** 流式消息内连续近似重复长段计数。 */
|
|
305
|
+
streamRepeatRun: number;
|
|
300
306
|
/** 本回合已触发过 loop guard(防重复打断)。 */
|
|
301
307
|
loopFired: boolean;
|
|
302
308
|
/** loop 重启的延迟定时器(冷却结束后再 schedule)。 */
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-client-auto-continue",
|
|
3
3
|
"description": "DSH Web UI plugin: automatically sends a localized continue prompt when a request is interrupted by network errors or other non-human causes",
|
|
4
|
-
"version": "0.11.
|
|
4
|
+
"version": "0.11.6",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
7
7
|
"types": "lib/types/index.d.ts",
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"build": "node build.mjs && tsc -p tsconfig.build.json",
|
|
47
47
|
"watch": "node build.mjs --watch",
|
|
48
48
|
"typecheck": "tsc --noEmit",
|
|
49
|
-
"test": "node tests/simulate-host.mjs && node tests/settings-host-compat.mjs && node tests/simulate-client-loader.mjs && node tests/settings-card-ui.mjs && node tests/prepare-github-package.mjs",
|
|
49
|
+
"test": "node tests/simulate-host.mjs && node tests/settings-host-compat.mjs && node tests/simulate-client-loader.mjs && node tests/locale-mirror-bounded.mjs && node tests/settings-card-ui.mjs && node tests/prepare-github-package.mjs",
|
|
50
50
|
"prepack": "npm run build"
|
|
51
51
|
},
|
|
52
52
|
"keywords": [
|
package/src/client/index.ts
CHANGED
|
@@ -57,11 +57,48 @@ export function apply(ctx: ClientContext): void {
|
|
|
57
57
|
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'auto-continue: dictionaries');
|
|
58
58
|
|
|
59
59
|
const scope = ctx.settingsScope.bind<AutoContinueSettings>({ namespace: SETTINGS_NS });
|
|
60
|
+
/**
|
|
61
|
+
* Mirror the browser locale into the host config, with a hard per-page budget.
|
|
62
|
+
*
|
|
63
|
+
* The write is only needed while the stored value disagrees with the page, so
|
|
64
|
+
* every notification re-checks the snapshot — but two unbounded writers hid in
|
|
65
|
+
* that check, and both of them hammer `settings.yaml` until the host settings
|
|
66
|
+
* write queue backs up (observed: ~1 write / 400 ms when a completed write does
|
|
67
|
+
* not fold back before the next document tick, and a two-page ping-pong when
|
|
68
|
+
* two pages with different UI languages keep overwriting each other).
|
|
69
|
+
*
|
|
70
|
+
* So: keep the subscription and the `locale/change` hook (a scope that is not
|
|
71
|
+
* `ready` yet still mirrors once it is, and a real language switch still wins),
|
|
72
|
+
* but cap this page at {@link MAX_MIRROR_ATTEMPTS} writes per active locale.
|
|
73
|
+
*
|
|
74
|
+
* The budget must NOT be reset by a matching snapshot. In the real
|
|
75
|
+
* `SettingsScopeController`, a successful `set()` folds the mutation response
|
|
76
|
+
* into the WRITING page's own mirror (`mirror.acceptView` -> scope `derive()` ->
|
|
77
|
+
* subscriber), so under the two-page ping-pong each page first sees its own
|
|
78
|
+
* accepted value — matching its active locale — and would hand itself a fresh
|
|
79
|
+
* budget before the other page writes back. That is an unbounded loop again
|
|
80
|
+
* (probed: 400+ host writes). Reset only when the browser's active locale
|
|
81
|
+
* genuinely changes; a matching snapshot then simply needs no write.
|
|
82
|
+
*/
|
|
83
|
+
const MAX_MIRROR_ATTEMPTS = 3;
|
|
84
|
+
let mirroredLocale: string | undefined;
|
|
85
|
+
let mirrorAttempts = 0;
|
|
60
86
|
const syncLocale = (): void => {
|
|
61
87
|
const active = ctx.locale.getLocale().active;
|
|
62
88
|
const snapshot = scope.getSnapshot();
|
|
63
89
|
if (snapshot.status !== 'ready' || !snapshot.writable || snapshot.mode !== 'host') return;
|
|
90
|
+
// A genuine language switch is the only thing that earns a fresh budget: the
|
|
91
|
+
// attempt count must survive matching snapshots, because the writing page's
|
|
92
|
+
// own acknowledgement arrives as a match (see above). Tracking `mirroredLocale`
|
|
93
|
+
// on every pass is what lets a later real switch be recognised.
|
|
94
|
+
if (mirroredLocale !== active) {
|
|
95
|
+
mirroredLocale = active;
|
|
96
|
+
mirrorAttempts = 0;
|
|
97
|
+
}
|
|
98
|
+
// Converged: nothing to write.
|
|
64
99
|
if (snapshot.value?.locale === active) return;
|
|
100
|
+
if (mirrorAttempts >= MAX_MIRROR_ATTEMPTS) return;
|
|
101
|
+
mirrorAttempts += 1;
|
|
65
102
|
void scope.set('locale', active);
|
|
66
103
|
};
|
|
67
104
|
ctx.effect(() => scope.subscribe(syncLocale), 'auto-continue: locale settings sync');
|
package/src/client/locales.ts
CHANGED
|
@@ -73,7 +73,7 @@ export const zh = {
|
|
|
73
73
|
'stats.gaveUp': '停止(达上限)',
|
|
74
74
|
'stats.looped': '循环打断',
|
|
75
75
|
'field.loopGuard': '循环守卫',
|
|
76
|
-
'field.loopGuardHint': '检测运行中的回合空转:
|
|
76
|
+
'field.loopGuardHint': '检测运行中的回合空转: 连续短句且无工具调用、流式消息内连续复读, 或连续调用相同工具时, 自动取消并用循环提示文本重启回合。',
|
|
77
77
|
'field.loopShortChars': '短句长度上限 (字符)',
|
|
78
78
|
'field.loopShortCharsHint': '模型消息文本短于该值计为一条短句(空转信号)。',
|
|
79
79
|
'field.loopWindowMs': '短句时间窗 (ms)',
|
|
@@ -81,7 +81,7 @@ export const zh = {
|
|
|
81
81
|
'field.loopShortCount': '连续短句阈值',
|
|
82
82
|
'field.loopShortCountHint': '时间窗内连续多少条短句且期间无工具调用时判定空转循环。',
|
|
83
83
|
'field.loopRepeatText': '相同消息重复次数',
|
|
84
|
-
'field.loopRepeatTextHint': '连续输出多少条完全相同的消息时判定空转(最强信号, 不限长度,
|
|
84
|
+
'field.loopRepeatTextHint': '连续输出多少条完全相同的消息时判定空转(最强信号, 不限长度, 也用于流式消息内连续复读段落)。',
|
|
85
85
|
'field.loopToolRepeat': '同工具重复次数',
|
|
86
86
|
'field.loopToolRepeatHint': '同工具+同参数+同结果的连续调用多少次时判定死循环; 参数或结果有变化视为有进展。',
|
|
87
87
|
'field.loopText': '循环提示文本',
|
|
@@ -182,7 +182,7 @@ export const en: Record<SettingsCardKey, string> = {
|
|
|
182
182
|
'stats.gaveUp': 'Gave up (cap)',
|
|
183
183
|
'stats.looped': 'Loops broken',
|
|
184
184
|
'field.loopGuard': 'Loop guard',
|
|
185
|
-
'field.loopGuardHint': 'Detects a running turn spinning in place — many short sentences with no tool calls, or the same tool repeating — cancels
|
|
185
|
+
'field.loopGuardHint': 'Detects a running turn spinning in place — many short sentences with no tool calls, repeated paragraphs inside one streamed assistant message, or the same tool repeating — then cancels and restarts with the loop text.',
|
|
186
186
|
'field.loopShortChars': 'Short-sentence max (chars)',
|
|
187
187
|
'field.loopShortCharsHint': 'A model message shorter than this counts as a short sentence (spinning signal).',
|
|
188
188
|
'field.loopWindowMs': 'Short-sentence window (ms)',
|
|
@@ -190,7 +190,7 @@ export const en: Record<SettingsCardKey, string> = {
|
|
|
190
190
|
'field.loopShortCount': 'Short-sentence threshold',
|
|
191
191
|
'field.loopShortCountHint': 'How many consecutive short sentences inside the window, with no tool call, trip the loop guard.',
|
|
192
192
|
'field.loopRepeatText': 'Identical message count',
|
|
193
|
-
'field.loopRepeatTextHint': 'How many consecutive identical messages trip the guard (strongest signal, any length
|
|
193
|
+
'field.loopRepeatTextHint': 'How many consecutive identical messages trip the guard (strongest signal, any length; also used for repeated paragraphs inside one streamed assistant message).',
|
|
194
194
|
'field.loopToolRepeat': 'Same-tool repeat count',
|
|
195
195
|
'field.loopToolRepeatHint': 'How many consecutive calls of the same tool with identical arguments and results trip the loop guard; a changed argument or result counts as progress.',
|
|
196
196
|
'field.loopText': 'Loop text',
|
package/src/host/engine.ts
CHANGED
|
@@ -79,6 +79,11 @@ const LOOP_GUARD_CANCEL_CAUSE = {
|
|
|
79
79
|
reason: 'dsh-auto-continue:loop-guard',
|
|
80
80
|
} as const;
|
|
81
81
|
|
|
82
|
+
/** Keep fuzzy matching off the unbounded host event path; exact repeats remain unlimited. */
|
|
83
|
+
const STREAM_NEAR_DUPLICATE_MAX_CHARS = 2_048;
|
|
84
|
+
/** Bound unfinished text copied between token chunks when a provider emits no paragraph break. */
|
|
85
|
+
const STREAM_TAIL_MAX_CHARS = 4_096;
|
|
86
|
+
|
|
82
87
|
/** 通知桥事件: host 引擎产生, browser 侧订阅展示(Notification / 动作按钮)。 */
|
|
83
88
|
export interface HostNotice {
|
|
84
89
|
/** 稳定标识(供 browser 去重)。 */
|
|
@@ -331,6 +336,9 @@ export class AutoContinueRunner {
|
|
|
331
336
|
const state = this.state(sessionId);
|
|
332
337
|
const repeat = state.tools.confirmRepeatAtStep(event.seq);
|
|
333
338
|
if (repeat !== undefined) this.checkLoop(sessionId, state, repeat);
|
|
339
|
+
} else if (event.type === 'assistant/chunk') {
|
|
340
|
+
const state = this.state(sessionId);
|
|
341
|
+
this.onAssistantChunk(sessionId, state, event);
|
|
334
342
|
} else if (event.type === 'assistant/message') {
|
|
335
343
|
const state = this.state(sessionId);
|
|
336
344
|
this.onAssistantMessage(sessionId, state, event);
|
|
@@ -348,6 +356,113 @@ export class AutoContinueRunner {
|
|
|
348
356
|
.join('');
|
|
349
357
|
}
|
|
350
358
|
|
|
359
|
+
private assistantChunkText(event: SessionEvent<'assistant/chunk'>): string {
|
|
360
|
+
return event.data.chunk.type === 'text-delta' ? event.data.chunk.text : '';
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
private normalizedSegment(text: string): string {
|
|
364
|
+
return text.replace(/\s+/g, ' ').trim();
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
private isNearDuplicateSegment(left: string, right: string): boolean {
|
|
368
|
+
if (left === right) return true;
|
|
369
|
+
const leftLen = left.length;
|
|
370
|
+
const rightLen = right.length;
|
|
371
|
+
const longer = Math.max(leftLen, rightLen);
|
|
372
|
+
const shorter = Math.min(leftLen, rightLen);
|
|
373
|
+
if (shorter === 0 || shorter / longer < 0.85) return false;
|
|
374
|
+
if (longer > STREAM_NEAR_DUPLICATE_MAX_CHARS) return false;
|
|
375
|
+
const maxDistance = Math.max(6, Math.floor(longer * 0.08));
|
|
376
|
+
if (Math.abs(leftLen - rightLen) > maxDistance) return false;
|
|
377
|
+
return this.withinEditDistance(left, right, maxDistance);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
private withinEditDistance(left: string, right: string, maxDistance: number): boolean {
|
|
381
|
+
if (left === right) return true;
|
|
382
|
+
if (maxDistance < 0) return false;
|
|
383
|
+
const leftLen = left.length;
|
|
384
|
+
const rightLen = right.length;
|
|
385
|
+
if (Math.abs(leftLen - rightLen) > maxDistance) return false;
|
|
386
|
+
if (leftLen === 0 || rightLen === 0) return Math.max(leftLen, rightLen) <= maxDistance;
|
|
387
|
+
const unreachable = maxDistance + 1;
|
|
388
|
+
let previous = new Int32Array(rightLen + 1);
|
|
389
|
+
let current = new Int32Array(rightLen + 1);
|
|
390
|
+
previous.fill(unreachable);
|
|
391
|
+
for (let col = 0; col <= Math.min(rightLen, maxDistance); col += 1) {
|
|
392
|
+
previous[col] = col;
|
|
393
|
+
}
|
|
394
|
+
for (let row = 1; row <= leftLen; row += 1) {
|
|
395
|
+
current.fill(unreachable);
|
|
396
|
+
if (row <= maxDistance) current[0] = row;
|
|
397
|
+
const firstCol = Math.max(1, row - maxDistance);
|
|
398
|
+
const lastCol = Math.min(rightLen, row + maxDistance);
|
|
399
|
+
let minInRow = unreachable;
|
|
400
|
+
for (let col = firstCol; col <= lastCol; col += 1) {
|
|
401
|
+
const insertion = (current[col - 1] ?? unreachable) + 1;
|
|
402
|
+
const deletion = (previous[col] ?? unreachable) + 1;
|
|
403
|
+
const substitution =
|
|
404
|
+
(previous[col - 1] ?? unreachable) +
|
|
405
|
+
(left.charCodeAt(row - 1) === right.charCodeAt(col - 1) ? 0 : 1);
|
|
406
|
+
const score = Math.min(insertion, deletion, substitution, unreachable);
|
|
407
|
+
current[col] = score;
|
|
408
|
+
if (score < minInRow) minInRow = score;
|
|
409
|
+
}
|
|
410
|
+
if (minInRow > maxDistance) return false;
|
|
411
|
+
[previous, current] = [current, previous];
|
|
412
|
+
}
|
|
413
|
+
return (previous[rightLen] ?? unreachable) <= maxDistance;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
private noteStreamSegment(sessionId: SessionId, state: SessionState, segment: string): void {
|
|
417
|
+
const normalized = this.normalizedSegment(segment);
|
|
418
|
+
const config = this.getConfig();
|
|
419
|
+
if (normalized === '') return;
|
|
420
|
+
if (normalized.length < config.loopShortChars) {
|
|
421
|
+
state.streamLastSegment = '';
|
|
422
|
+
state.streamRepeatRun = 0;
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
if (
|
|
426
|
+
state.streamLastSegment !== '' &&
|
|
427
|
+
this.isNearDuplicateSegment(normalized, state.streamLastSegment)
|
|
428
|
+
) {
|
|
429
|
+
state.streamRepeatRun += 1;
|
|
430
|
+
state.streamLastSegment = normalized;
|
|
431
|
+
} else {
|
|
432
|
+
state.streamLastSegment = normalized;
|
|
433
|
+
state.streamRepeatRun = 1;
|
|
434
|
+
}
|
|
435
|
+
if (state.streamRepeatRun >= config.loopRepeatText) {
|
|
436
|
+
this.log(
|
|
437
|
+
`检测到流式消息内复读 ${sessionId}: 连续 ${state.streamRepeatRun} 段近似重复文本`,
|
|
438
|
+
);
|
|
439
|
+
this.interruptLoop(sessionId, state);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
private onAssistantChunk(
|
|
444
|
+
sessionId: SessionId,
|
|
445
|
+
state: SessionState,
|
|
446
|
+
event: SessionEvent<'assistant/chunk'>,
|
|
447
|
+
): void {
|
|
448
|
+
if (!this.getConfig().loopGuard || !state.running || state.loopFired) return;
|
|
449
|
+
const chunk = this.assistantChunkText(event);
|
|
450
|
+
if (chunk === '') return;
|
|
451
|
+
const merged = `${state.streamTail}${chunk}`.replace(/\r/g, '');
|
|
452
|
+
const pieces = merged.split(/\n(?:[ \t]*\n)+/u);
|
|
453
|
+
const tail = pieces.pop() ?? '';
|
|
454
|
+
for (const piece of pieces) this.noteStreamSegment(sessionId, state, piece);
|
|
455
|
+
if (tail.length <= STREAM_TAIL_MAX_CHARS) {
|
|
456
|
+
state.streamTail = tail;
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
state.streamTail = tail.slice(-STREAM_TAIL_MAX_CHARS);
|
|
460
|
+
if (/\S/u.test(tail)) {
|
|
461
|
+
state.streamLastSegment = '';
|
|
462
|
+
state.streamRepeatRun = 0;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
351
466
|
private onAssistantMessage(
|
|
352
467
|
sessionId: SessionId,
|
|
353
468
|
state: SessionState,
|
|
@@ -376,6 +491,11 @@ export class AutoContinueRunner {
|
|
|
376
491
|
state.shortRun = 0; // 长句 = 有实际输出, 重置
|
|
377
492
|
state.lastShortAt = 0;
|
|
378
493
|
}
|
|
494
|
+
const streamTail = state.streamTail;
|
|
495
|
+
state.streamTail = '';
|
|
496
|
+
if (streamTail !== '') this.noteStreamSegment(sessionId, state, streamTail);
|
|
497
|
+
state.streamLastSegment = '';
|
|
498
|
+
state.streamRepeatRun = 0;
|
|
379
499
|
this.checkLoop(sessionId, state);
|
|
380
500
|
}
|
|
381
501
|
|
|
@@ -442,6 +562,9 @@ export class AutoContinueRunner {
|
|
|
442
562
|
state.lastShortAt = 0;
|
|
443
563
|
state.lastAssistantText = '';
|
|
444
564
|
state.sameTextRun = 0;
|
|
565
|
+
state.streamTail = '';
|
|
566
|
+
state.streamLastSegment = '';
|
|
567
|
+
state.streamRepeatRun = 0;
|
|
445
568
|
state.loopFired = false;
|
|
446
569
|
if (state.loopRetryTimer !== undefined) {
|
|
447
570
|
clearTimeout(state.loopRetryTimer);
|
|
@@ -476,6 +599,9 @@ export class AutoContinueRunner {
|
|
|
476
599
|
state.lastShortAt = 0;
|
|
477
600
|
state.lastAssistantText = '';
|
|
478
601
|
state.sameTextRun = 0;
|
|
602
|
+
state.streamTail = '';
|
|
603
|
+
state.streamLastSegment = '';
|
|
604
|
+
state.streamRepeatRun = 0;
|
|
479
605
|
state.tools.resetRepeat();
|
|
480
606
|
// 重启受冷却约束(防紧密打断循环): 等剩余冷却结束后再调度
|
|
481
607
|
const cooldown = this.cooldownFor(state);
|
package/src/index.ts
CHANGED
|
@@ -76,7 +76,7 @@ export const AutoContinueSchema = z.object({
|
|
|
76
76
|
loopWindowMs: z.natural().min(1000).default(30000),
|
|
77
77
|
/** Consecutive short sentences trip the loop guard. */
|
|
78
78
|
loopShortCount: z.natural().min(2).default(12),
|
|
79
|
-
/** Consecutive identical
|
|
79
|
+
/** Consecutive identical assistant messages trip the loop guard (strongest signal; also used for streamed intra-message repetition). */
|
|
80
80
|
loopRepeatText: z.natural().min(2).default(4),
|
|
81
81
|
/** Consecutive identical tool calls with identical arguments AND results trip the loop guard. */
|
|
82
82
|
loopToolRepeat: z.natural().min(2).default(5),
|
package/src/shared/core.ts
CHANGED
|
@@ -80,7 +80,7 @@ export interface AutoContinueSettings {
|
|
|
80
80
|
loopShortCount?: number;
|
|
81
81
|
/** Consecutive identical tool calls with identical arguments AND identical results trip the loop guard. */
|
|
82
82
|
loopToolRepeat?: number;
|
|
83
|
-
/** Consecutive identical
|
|
83
|
+
/** Consecutive identical assistant messages trip the loop guard (strongest signal; also used for streamed intra-message repetition). */
|
|
84
84
|
loopRepeatText?: number;
|
|
85
85
|
/** Text sent after the loop guard cancels and restarts a turn (supports {tool}). */
|
|
86
86
|
loopText?: string;
|
|
@@ -821,6 +821,12 @@ export interface SessionState {
|
|
|
821
821
|
lastAssistantText: string;
|
|
822
822
|
/** 连续相同文本消息数(最强空转信号, 不限长度)。 */
|
|
823
823
|
sameTextRun: number;
|
|
824
|
+
/** 流式消息尚未闭合的有界尾段(assistant/chunk 增量分段检测用)。 */
|
|
825
|
+
streamTail: string;
|
|
826
|
+
/** 流式消息最近一个长段的归一化文本。 */
|
|
827
|
+
streamLastSegment: string;
|
|
828
|
+
/** 流式消息内连续近似重复长段计数。 */
|
|
829
|
+
streamRepeatRun: number;
|
|
824
830
|
/** 本回合已触发过 loop guard(防重复打断)。 */
|
|
825
831
|
loopFired: boolean;
|
|
826
832
|
/** loop 重启的延迟定时器(冷却结束后再 schedule)。 */
|
|
@@ -844,6 +850,9 @@ export const freshState = (): SessionState => ({
|
|
|
844
850
|
lastShortAt: 0,
|
|
845
851
|
lastAssistantText: '',
|
|
846
852
|
sameTextRun: 0,
|
|
853
|
+
streamTail: '',
|
|
854
|
+
streamLastSegment: '',
|
|
855
|
+
streamRepeatRun: 0,
|
|
847
856
|
loopFired: false,
|
|
848
857
|
loopRetryTimer: undefined,
|
|
849
858
|
});
|