From 419fe1e5e789fb15fd0a19e15f9ed6407251590a Mon Sep 17 00:00:00 2001 From: ework-agent Date: Thu, 27 Aug 2026 23:07:23 +0800 Subject: [PATCH] fix: tag-echo filter strips truncated tag fragments (#294) --- CHANGELOG.md | 1 + src/loop/tag-echo-filter.ts | 71 +++++++++++++++------- tests/plugin-passthrough-tag-strip.test.ts | 13 +++- tests/tag-echo.test.ts | 61 +++++++++++++++++++ 4 files changed, 123 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 136fe88503..ace313c8c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag ### Fixes +- **Tag-echo filter strips truncated tag fragments (#294)**: the streaming tag-echo filter only stripped complete render tags, so a model echo cut off mid-stream (tag split across SSE chunks) left junk fragments in the output — and the unbounded lone-opening match could swallow an entire message that merely started tag-like, stripping it to empty. Now: (1) a definite unterminated opening (tag name + space, no closing `>` yet) is held across chunks up to 4096 chars instead of being passed through once it grew past the old 128-char hold cap, and dropped (with a warn) beyond that; (2) `flush()` at stream end drops arbitrary truncated openings (including an unclosed `tokens=` quote) and drops content swallowed after an unclosed attrs-bearing opening — a dangling ref fragment is tag content, not prose; (3) the lone-opening match is bounded to 256 chars of attrs, so prose that merely starts with a tag-like opening and contains a `>` later is no longer swallowed up to that `>` (the whole-message-stripped-to-empty case). Ambiguous short prefixes (`<`, `` etc.) and // ordinary prose containing `<` pass through untouched. -const PAIRED = /\x3cacp\s[^<>]*>([^<>]{0,64})<\/acp>/; -const LONE = /<\/?acp(?=[\s>])[^<>]*>/; +// Opening-tag attrs are bounded: a render tag opening is short (tokens + type, +// < 50 chars). An unbounded \x3cacp …\x3e match would swallow a long prose span +// that merely starts with \x3cacp and contains a \x3e somewhere later. +const PAIRED = /\x3cacp\s[^<>]{0,256}>([^<>]{0,64})<\/acp>/; +const LONE_OPEN = /\x3cacp(?:\s[^<>]{0,256})?>/; +const LONE_CLOSE = /<\/acp(?=[\s>])[^<>]{0,32}>/; // A suffix of the buffer that could still grow into a render tag: either an // unterminated `\x3cacp …` opening (attrs so far, no `>` yet) or a short // ambiguous prefix like `<`, `]*|<\/?a?c?p?)$/; -// An unterminated render-tag opening that already shows a quoted tokens= -// attribute — always an imitation truncated mid-tag, never prose. -const TRUNCATED_TAG = /\x3cacp\s[^<>]*tokens\s*=\s*"[^<>"]*"[^<>]*$/; +// An unterminated render-tag opening at the end of a string: `` — a truncated imitation, never prose (triggers use `]*$/; const CLOSE_TAG = "\x3c/acp"; const HOLD_LIMIT = 128; +// Hold cap for a definite unterminated opening tail — far beyond any real tag +// opening; beyond this the tail is dropped instead of held or passed through. +const TAG_OPEN_CAP = 4096; const SWALLOW_CAP = 80; export interface TagEchoFilter { @@ -31,8 +38,9 @@ export interface TagEchoFilter { export function stripAcpTags(text: string): string { return text .replace(new RegExp(PAIRED.source, "g"), "") - .replace(new RegExp(LONE.source, "g"), "") - .replace(new RegExp(TRUNCATED_TAG.source), ""); + .replace(new RegExp(LONE_OPEN.source, "g"), "") + .replace(new RegExp(LONE_CLOSE.source, "g"), "") + .replace(new RegExp(TRUNC_OPEN.source), ""); } // Cheap pre-check on a raw wire string (SSE event or JSON body): does it @@ -81,15 +89,30 @@ export function createTagEchoFilter(onDrop?: (snippet: string) => void): TagEcho return out; } const p = PAIRED.exec(buf); - const l = LONE.exec(buf); - let m: RegExpExecArray | null; - if (p && l) m = p.index <= l.index ? p : l; - else m = p ?? l; + const o = LONE_OPEN.exec(buf); + const c = LONE_CLOSE.exec(buf); + let m: RegExpExecArray | null = null; + for (const cand of [p, o, c]) { + if (cand && (m === null || cand.index < m.index)) m = cand; + } if (!m) { const t = PARTIAL_TAIL.exec(buf); - if (t && t[0].length <= HOLD_LIMIT) { - held = t[0]; - out += buf.slice(0, buf.length - t[0].length); + if (t) { + // A definite \x3cacp opening is never prose — hold it far + // past HOLD_LIMIT (drop it past TAG_OPEN_CAP); a short + // ambiguous prefix stays on the small hold cap so prose + // is never delayed or lost. + const definite = /^\x3cacp\s/.test(t[0]); + const cap = definite ? TAG_OPEN_CAP : HOLD_LIMIT; + if (t[0].length <= cap) { + held = t[0]; + out += buf.slice(0, buf.length - t[0].length); + } else if (definite) { + drop(t[0]); + out += buf.slice(0, buf.length - t[0].length); + } else { + out += buf; + } } else { out += buf; } @@ -99,10 +122,9 @@ export function createTagEchoFilter(onDrop?: (snippet: string) => void): TagEcho out += buf.slice(0, m.index); buf = buf.slice(m.index + m[0].length); // A PAIRED match is by definition a complete open+content+close - // span — only a LONE opening tag leaves the stream mid-tag and - // needs to swallow until its close arrives. - const wasPaired = m === p; - if (!wasPaired && /^\x3cacp\s/.test(m[0])) { + // span — only an attrs-bearing LONE_OPEN leaves the stream + // mid-tag and needs to swallow until its close arrives. + if (m === o && /^\x3cacp\s/.test(m[0])) { swallowUntilClose = true; swallowed = ""; } @@ -116,14 +138,21 @@ export function createTagEchoFilter(onDrop?: (snippet: string) => void): TagEcho return process(chunk); }, flush(): string { - let rest = swallowed + held; + const rest = swallowed + held; + const wasSwallowing = swallowUntilClose; swallowed = ""; held = ""; swallowUntilClose = false; - const t = new RegExp(TRUNCATED_TAG.source).exec(rest); + if (wasSwallowing) { + // Stream ended inside an unclosed render tag: the held content + // is tag content (a ref), not prose. + if (rest.length > 0) drop(rest); + return ""; + } + const t = new RegExp(TRUNC_OPEN.source).exec(rest); if (t) { drop(t[0]); - rest = rest.slice(0, t.index); + return rest.slice(0, t.index); } return rest; }, diff --git a/tests/plugin-passthrough-tag-strip.test.ts b/tests/plugin-passthrough-tag-strip.test.ts index 519edacfa1..e4e1350305 100644 --- a/tests/plugin-passthrough-tag-strip.test.ts +++ b/tests/plugin-passthrough-tag-strip.test.ts @@ -148,7 +148,7 @@ test("plugin passthrough preserves SSE framing for tag-free done-family events ( assert.ok(text.endsWith("\n\n"), "stream keeps event framing to the end"); }); -test("plugin passthrough flushes held tail when stream ends without a done-family event", async () => { +test("plugin passthrough resolves held tail at stream end without a done-family event", async () => { const out: string[] = []; const res = makeRes(out); const session = makeSession(); @@ -158,7 +158,16 @@ test("plugin passthrough flushes held tail when stream ends without a done-famil await pipePluginResponsesWithStrip(streamOf(events), res, session); const text = out.join(""); assert.ok(text.includes("prose "), "clean prefix passes"); - assert.ok(text.includes("m0"), "held unterminated fragment is flushed at stream end, not lost"); + assert.ok(!text.includes("m0"), "content of an unclosed tag is dropped at stream end, not flushed as junk"); + + const out2: string[] = []; + const res2 = makeRes(out2); + const events2 = [ + sse({ type: "response.output_text.delta", item_id: "msg_9", output_index: 0, delta: `prose \x3cac` }), + ]; + await pipePluginResponsesWithStrip(streamOf(events2), res2, session); + const text2 = out2.join(""); + assert.ok(text2.includes(`"delta":"prose \x3cac"`), "ambiguous prefix passes through untouched at stream end"); }); test("plugin passthrough rebuildEvent collapses multi-line data payloads into one line", async () => { diff --git a/tests/tag-echo.test.ts b/tests/tag-echo.test.ts index 5677fb5470..f6ad00f54d 100644 --- a/tests/tag-echo.test.ts +++ b/tests/tag-echo.test.ts @@ -304,3 +304,64 @@ test("non-stream rewriters leave tag-free text untouched", async () => { const rewrittenOpenai = rewriteOpenaiJsonResponse(structuredClone(openaiBody), { core: createCore(), config: { modelContextLimit: 200000 } as Config, messages: [], session: makeCtx("ns-openai-clean").session, log: () => {} }); assert.equal((rewrittenOpenai as { choices: Array<{ message: { content: string } }> }).choices[0].message.content, "clean 5 < 6 text"); }); + +test("streaming filter holds a definite open tail beyond the small hold cap instead of leaking it", () => { + const f = createTagEchoFilter(); + const attrs = "x".repeat(200); + assert.equal(f.push(`text ${OPEN}${attrs}`), "text "); + assert.ok(f.pending()); + assert.equal(f.push(`>m00001${CLOSE}`), ""); + assert.equal(f.flush(), ""); +}); + +test("streaming filter drops a definite open tail beyond the tag-open cap instead of passing it through", () => { + let dropped = ""; + const f = createTagEchoFilter((s) => { dropped = s; }); + assert.equal(f.push(`text ${OPEN}` + "x".repeat(5000)), "text "); + assert.equal(dropped.length, 5005); + assert.equal(f.push(`>m00001${CLOSE}`), ">m00001"); + assert.equal(f.flush(), ""); + assert.ok(f.dropped()); +}); + +test("stripAcpTags drops arbitrary truncated open fragments, keeps ambiguous prefixes", () => { + assert.equal(stripAcpTags(`text ${OPEN}type="text" tokens=`), "text "); + assert.equal(stripAcpTags(`text ${OPEN}tok`), "text "); + assert.equal(stripAcpTags(`text ${LT}acp`), `text ${LT}acp`); + assert.equal(stripAcpTags(`text ${LT}/acp`), `text ${LT}/acp`); +}); + +test("streaming flush drops arbitrary truncated open fragments", () => { + const f = createTagEchoFilter(); + assert.equal(f.push(`text ${OPEN}type="text" tokens=`), "text "); + assert.equal(f.flush(), ""); + const g = createTagEchoFilter(); + assert.equal(g.push(`text ${LT}acp`), "text "); + assert.equal(g.flush(), `${LT}acp`); +}); + +test("streaming flush drops content of a tag left unclosed at end of stream", () => { + const f = createTagEchoFilter(); + assert.equal(f.push(`text ${OPEN}tokens="1" type="text">m00001`), "text "); + assert.equal(f.flush(), ""); + assert.ok(f.dropped()); +}); + +test("long tag-like spans are prose, not tags (bounded open match)", () => { + const span = `${OPEN}${"x".repeat(300)}>`; + assert.equal(stripAcpTags(`before ${span} after`), `before ${span} after`); + const f = createTagEchoFilter(); + assert.equal(f.push(`before ${span} after`) + f.flush(), `before ${span} after`); + const g = createTagEchoFilter(); + assert.equal(g.push(`before ${OPEN}${"x".repeat(300)}`), "before "); + assert.ok(g.pending()); + assert.equal(g.push(`> after`), `${span} after`); + assert.equal(g.flush(), ""); +}); + +test("prose with a tag-like opening beyond the attr bound survives intact", () => { + const prose = `${OPEN}${"word ".repeat(60)}end > kept`; + assert.equal(stripAcpTags(prose), prose); + const f = createTagEchoFilter(); + assert.equal(f.push(prose) + f.flush(), prose); +});