Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (`<`, `<a`, `</ac`, bare tag name without space) keep the small hold cap and are emitted at flush, so real prose is never delayed or lost; non-streaming JSON rewriters get the same fragment handling.
- **Identity plugin binding survives model switches (one conversation, many sessions)**: an identity registration (`POST /__bili/plugin/register` with `identity: true` — the omp/claude-code path) was consumed one-shot: the first request that carried the conversation id ate the registration and bound ITS session into plugin mode. Switching models or upstreams mid-conversation resolves a NEW session (session key = protocol|upstream|apiKey|conversation) — the registration was already gone, so the omp TUI flow "chat model → responses model" silently dropped back to wire injection (native tools gone, model roleplaying `acp_status` output). Identity registrations are now sticky for the conversation: every request carrying the id binds, LRU-refreshed and bounded by the same 64-entry cap. Wild-caught as "原生模式消失了" after a GLM-chat → qwen-responses model switch.
- **Responses: stamp `type:"message"` on type-less input items at ingress.** omp (pi-ai) sends user items without the spec-required `type` field; the kernel wire projection switches on `item.type` and silently dropped them, so user prompts never entered the compression state (no refs, never tagged, never compressible, invisible to nudge/preflight — #247 testing caught this).

Expand Down
71 changes: 50 additions & 21 deletions src/loop/tag-echo-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,24 @@
// underscore-namespaced text-protocol triggers (`\x3cacp_compress>` 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`, `</ac`, …
const PARTIAL_TAIL = /(\x3cacp\s[^<>]*|<\/?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: `<acp ` plus
// attrs, no `>` — a truncated imitation, never prose (triggers use `<acp_`).
const TRUNC_OPEN = /\x3cacp\s[^<>]*$/;
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 {
Expand All @@ -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
Expand Down Expand Up @@ -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;
}
Expand All @@ -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 = "";
}
Expand All @@ -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;
},
Expand Down
13 changes: 11 additions & 2 deletions tests/plugin-passthrough-tag-strip.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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 () => {
Expand Down
61 changes: 61 additions & 0 deletions tests/tag-echo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Loading