diff --git a/src/loop/adapter-anthropic.ts b/src/loop/adapter-anthropic.ts index 468f08e675..41f60bb05f 100644 --- a/src/loop/adapter-anthropic.ts +++ b/src/loop/adapter-anthropic.ts @@ -4,7 +4,7 @@ import { dedupeAdjacentOutputConfig } from "../dedupe-adjacent-output-config.js" import { appendSystemText, declaredInclusiveFromUsage } from "../util.js"; import { stampAnthropicSystemCacheControl } from "./cache-control.js"; import { buildVisibilityMarker } from "./core.js"; -import { composeStreamFilters, createBiliArtifactFilter, createMarkerLineFilter, createTagEchoFilter } from "./tag-echo-filter.js"; +import { composeStreamFilters, createBareRefHeadFilter, createBiliArtifactFilter, createMarkerLineFilter, createTagEchoFilter } from "./tag-echo-filter.js"; import { degenerateTurnWarning } from "../degenerate-turn.js"; import { log as loggerLog } from "../logger.js"; import { createSseFramer, sseEventData, replaceSseEventData } from "../sse-util.js"; @@ -320,6 +320,7 @@ export function createAnthropicAdapter(requestBody: Record, ori // m00885: the shipped request text lets the filter keep an // emission-shaped span the user asked to be output verbatim. const requestText = JSON.stringify(requestBody); + // #5259: outermost — the bare-ref head guard acts on final outgoing bytes. const makeFilter = () => composeStreamFilters( composeStreamFilters( createTagEchoFilter((snippet, duringDrain) => { @@ -333,9 +334,14 @@ export function createAnthropicAdapter(requestBody: Record, ori loggerLog("warn", `[marker-echo] stripped model-emitted ACP confirmation marker: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); }), ), - createBiliArtifactFilter((snippet) => { - loggerLog("warn", `[bili-artifact] stripped model-emitted internal artifact: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); - }), + composeStreamFilters( + createBiliArtifactFilter((snippet) => { + loggerLog("warn", `[bili-artifact] stripped model-emitted internal artifact: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + }), + createBareRefHeadFilter((snippet) => { + loggerLog("warn", `[bare-ref-head] stripped model-emitted bare ref head (#5259): ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + }), + ), ); const tagFilter = makeFilter(); let lastTextIndex: number | null = null; diff --git a/src/loop/adapter-google.ts b/src/loop/adapter-google.ts index 9e9fe8c6dc..d8d4db5716 100644 --- a/src/loop/adapter-google.ts +++ b/src/loop/adapter-google.ts @@ -2,7 +2,7 @@ import type { CoreMessage } from "acp-kernel"; import { coreToGoogle } from "acp-kernel/wire"; import type { GooglePart } from "acp-kernel/wire"; import { buildVisibilityMarker } from "./core.js"; -import { composeStreamFilters, createBiliArtifactFilter, createMarkerLineFilter, createTagEchoFilter } from "./tag-echo-filter.js"; +import { composeStreamFilters, createBareRefHeadFilter, createBiliArtifactFilter, createMarkerLineFilter, createTagEchoFilter } from "./tag-echo-filter.js"; import { degenerateTurnWarning } from "../degenerate-turn.js"; import { log as loggerLog } from "../logger.js"; import { createSseFramer, sseEventData } from "../sse-util.js"; @@ -322,6 +322,7 @@ export function createGoogleAdapter( // m00885: the shipped request text lets the filter keep an // emission-shaped span the user asked to be output verbatim. const requestText = JSON.stringify(requestBody); + // #5259: outermost — the bare-ref head guard acts on final outgoing bytes. const makeFilter = () => composeStreamFilters( composeStreamFilters( createTagEchoFilter((snippet, duringDrain) => { @@ -335,9 +336,14 @@ export function createGoogleAdapter( loggerLog("warn", `[marker-echo] stripped model-emitted ACP confirmation marker: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); }), ), - createBiliArtifactFilter((snippet) => { - loggerLog("warn", `[bili-artifact] stripped model-emitted internal artifact: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); - }), + composeStreamFilters( + createBiliArtifactFilter((snippet) => { + loggerLog("warn", `[bili-artifact] stripped model-emitted internal artifact: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + }), + createBareRefHeadFilter((snippet) => { + loggerLog("warn", `[bare-ref-head] stripped model-emitted bare ref head (#5259): ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + }), + ), ); const tagFilter = makeFilter(); const flushFilter = function* (): Generator { diff --git a/src/loop/adapter-openai.ts b/src/loop/adapter-openai.ts index a195352343..df3d5d46dc 100644 --- a/src/loop/adapter-openai.ts +++ b/src/loop/adapter-openai.ts @@ -2,7 +2,7 @@ import type { CoreMessage } from "acp-kernel"; import { isRenderedSummaryMessage } from "acp-kernel"; import { coreToOpenai, injectOpenaiSystem } from "acp-kernel/wire"; import { buildVisibilityMarker } from "./core.js"; -import { composeStreamFilters, createBiliArtifactFilter, createIdentityStreamFilter, createMarkerLineFilter, createTagEchoFilter } from "./tag-echo-filter.js"; +import { composeStreamFilters, createBareRefHeadFilter, createBiliArtifactFilter, createIdentityStreamFilter, createMarkerLineFilter, createTagEchoFilter } from "./tag-echo-filter.js"; import { degenerateTurnWarning } from "../degenerate-turn.js"; import { log as loggerLog } from "../logger.js"; import { createSseFramer, sseEventData, replaceSseEventData } from "../sse-util.js"; @@ -270,6 +270,7 @@ export function createOpenaiAdapter(requestBody: Record, client // m00885: the shipped request text lets the filter keep an // emission-shaped span the user asked to be output verbatim. const requestText = JSON.stringify(requestBody); + // #5259: outermost — the bare-ref head guard acts on final outgoing bytes. const makeFieldFilter = () => composeStreamFilters( composeStreamFilters( createTagEchoFilter((snippet, duringDrain) => { @@ -283,9 +284,14 @@ export function createOpenaiAdapter(requestBody: Record, client loggerLog("warn", `[marker-echo] stripped model-emitted ACP confirmation marker: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); }), ), - createBiliArtifactFilter((snippet) => { - loggerLog("warn", `[bili-artifact] stripped model-emitted internal artifact: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); - }), + composeStreamFilters( + createBiliArtifactFilter((snippet) => { + loggerLog("warn", `[bili-artifact] stripped model-emitted internal artifact: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + }), + createBareRefHeadFilter((snippet) => { + loggerLog("warn", `[bare-ref-head] stripped model-emitted bare ref head (#5259): ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + }), + ), ); // Both instances exist up front: the degenerate gate below reads // the CONTENT filter's stats only (visible prose), and a reasoning- diff --git a/src/loop/adapter-responses.ts b/src/loop/adapter-responses.ts index 24f9d14605..981ffab0e2 100644 --- a/src/loop/adapter-responses.ts +++ b/src/loop/adapter-responses.ts @@ -6,7 +6,7 @@ import { coreToResponsesWithToolImages as coreToResponses, patchResponsesInputWi import { buildVisibilityMarker } from "./core.js"; import { hoistTrappedToolItems } from "../tool-pair-order.js"; import { hashId, strippedResponseIdWarning } from "../util.js"; -import { composeStreamFilters, createBiliArtifactFilter, createIdentityStreamFilter, createMarkerLineFilter, createTagEchoFilter, stripResponsesText, containsBiliInternalText, containsMarkerLineText, containsRenderTagText, containsToolCallEmissionText, ACP_NAME_ALT, type TagEchoFilter } from "./tag-echo-filter.js"; +import { composeStreamFilters, createBareRefHeadFilter, createBiliArtifactFilter, createIdentityStreamFilter, createMarkerLineFilter, createTagEchoFilter, stripResponsesText, containsBareRefHeadWire, containsBiliInternalText, containsEchoResidue, containsMarkerLineText, containsRenderTagText, containsToolCallEmissionText, ACP_NAME_ALT, type TagEchoFilter } from "./tag-echo-filter.js"; import { degenerateTurnWarning } from "../degenerate-turn.js"; import { log as loggerLog } from "../logger.js"; import { createSseFramer } from "../sse-util.js"; @@ -391,6 +391,7 @@ export function createResponsesAdapter(textProtocol?: boolean, projection?: Resp // — the absorb section exists on this request's wire iff absorbName // was resolved for it). const absorbArmedLocal = absorbName !== undefined; + // #5259: outermost — the bare-ref head guard acts on final outgoing bytes. const makeFilter = () => composeStreamFilters( composeStreamFilters( createTagEchoFilter((snippet, duringDrain) => { @@ -404,9 +405,14 @@ export function createResponsesAdapter(textProtocol?: boolean, projection?: Resp loggerLog("warn", `[marker-echo] stripped model-emitted ACP confirmation marker: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); }), ), - createBiliArtifactFilter((snippet) => { - loggerLog("warn", `[bili-artifact] stripped model-emitted internal artifact: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); - }), + composeStreamFilters( + createBiliArtifactFilter((snippet) => { + loggerLog("warn", `[bili-artifact] stripped model-emitted internal artifact: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + }), + createBareRefHeadFilter((snippet) => { + loggerLog("warn", `[bare-ref-head] stripped model-emitted bare ref head (#5259): ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + }), + ), ); const tagFilter = makeFilter(); // Unified ACP invariant: reasoning summaries are the thinking channel — @@ -524,7 +530,7 @@ export function createResponsesAdapter(textProtocol?: boolean, projection?: Resp // this fallthrough — strip on detection like the message // branches above (stripResponsesText never touches tool // argument fields). - const chunk = (containsRenderTagText(eventStr) || containsMarkerLineText(eventStr) || containsBiliInternalText(eventStr) || (absorbArmedLocal && containsToolCallEmissionText(eventStr))) ? rebuildResponsesEvent(type, stripResponsesText(obj, absorbArmedLocal, shippedRequestText)) : rawBuf; + const chunk = (containsRenderTagText(eventStr) || containsMarkerLineText(eventStr) || containsBiliInternalText(eventStr) || containsBareRefHeadWire(eventStr) || containsEchoResidue(eventStr) || (absorbArmedLocal && containsToolCallEmissionText(eventStr))) ? rebuildResponsesEvent(type, stripResponsesText(obj, absorbArmedLocal, shippedRequestText)) : rawBuf; yield { kind: "meta", chunk, firstRoundOnly: true } as ParsedStreamEvent; } } else if ( @@ -536,7 +542,7 @@ export function createResponsesAdapter(textProtocol?: boolean, projection?: Resp if (mapped) { yield { kind: "meta", chunk: rewriteRefEvent(type, stripResponsesText(obj), mapped), firstRoundOnly: false } as ParsedStreamEvent; } else if (!suppressTextLifecycle) { - const chunk = (containsRenderTagText(eventStr) || containsMarkerLineText(eventStr) || containsBiliInternalText(eventStr) || (absorbArmedLocal && containsToolCallEmissionText(eventStr))) ? rebuildResponsesEvent(type, stripResponsesText(obj, absorbArmedLocal, shippedRequestText)) : rawBuf; + const chunk = (containsRenderTagText(eventStr) || containsMarkerLineText(eventStr) || containsBiliInternalText(eventStr) || containsBareRefHeadWire(eventStr) || containsEchoResidue(eventStr) || (absorbArmedLocal && containsToolCallEmissionText(eventStr))) ? rebuildResponsesEvent(type, stripResponsesText(obj, absorbArmedLocal, shippedRequestText)) : rawBuf; yield { kind: "meta", chunk, firstRoundOnly: true } as ParsedStreamEvent; } } else if (type === "response.output_text.delta") { @@ -662,7 +668,7 @@ export function createResponsesAdapter(textProtocol?: boolean, projection?: Resp remapped.delete(origId); yield { kind: "meta", chunk: rewriteItemEvent(type, stripResponsesText(obj), mapped), firstRoundOnly: false } as ParsedStreamEvent; } else if (!suppressTextLifecycle) { - const chunk = (containsRenderTagText(eventStr) || containsMarkerLineText(eventStr) || containsBiliInternalText(eventStr) || (absorbArmedLocal && containsToolCallEmissionText(eventStr))) ? rebuildResponsesEvent(type, stripResponsesText(obj, absorbArmedLocal, shippedRequestText)) : rawBuf; + const chunk = (containsRenderTagText(eventStr) || containsMarkerLineText(eventStr) || containsBiliInternalText(eventStr) || containsBareRefHeadWire(eventStr) || containsEchoResidue(eventStr) || (absorbArmedLocal && containsToolCallEmissionText(eventStr))) ? rebuildResponsesEvent(type, stripResponsesText(obj, absorbArmedLocal, shippedRequestText)) : rawBuf; yield { kind: "meta", chunk, firstRoundOnly: true } as ParsedStreamEvent; } } else if (item?.type !== "message" || !suppressTextLifecycle) { @@ -670,7 +676,7 @@ export function createResponsesAdapter(textProtocol?: boolean, projection?: Resp // this fallthrough — strip on detection like the message // branches above (stripResponsesText never touches tool // argument fields). - const chunk = (containsRenderTagText(eventStr) || containsMarkerLineText(eventStr) || containsBiliInternalText(eventStr) || (absorbArmedLocal && containsToolCallEmissionText(eventStr))) ? rebuildResponsesEvent(type, stripResponsesText(obj, absorbArmedLocal, shippedRequestText)) : rawBuf; + const chunk = (containsRenderTagText(eventStr) || containsMarkerLineText(eventStr) || containsBiliInternalText(eventStr) || containsBareRefHeadWire(eventStr) || containsEchoResidue(eventStr) || (absorbArmedLocal && containsToolCallEmissionText(eventStr))) ? rebuildResponsesEvent(type, stripResponsesText(obj, absorbArmedLocal, shippedRequestText)) : rawBuf; yield { kind: "meta", chunk, firstRoundOnly: true } as ParsedStreamEvent; } } else if (type === "response.completed") { diff --git a/src/loop/tag-echo-filter.ts b/src/loop/tag-echo-filter.ts index ffeccfc48d..520df9e0b0 100644 --- a/src/loop/tag-echo-filter.ts +++ b/src/loop/tag-echo-filter.ts @@ -227,6 +227,25 @@ const TRUNC_REF_CLOSE = new RegExp("m\\d{4,}\\s*\\x3c\\/([a-zA-Z]{0,32})$"); // [\w>] lookbehind mirrors ORPHAN_REF_CLOSE: word-adjacent runs (xm01233) and // runs right after a tag terminator (\x3e, #644) are not this unit. const DEAD_REF_CLOSE = new RegExp("(?])m\\d{4,}\\s*\\x3c\\/[a-zA-Z]{0,32}(?![a-zA-Z])(?![^\\x3c\\x3e]{0,32}\\x3e)", "g"); +// #5195: opener-less render-tag residue — the model echoes a render tag but +// drops the ` (optionally + a close, +// which LONE_CLOSE peels separately). Every observed leak carries +// type="text">mNNNNN; the anchor attr (type="text" / tokens=N) plus a ref +// glued to the terminator is never prose (the ref-adjacency gate). Attr runs +// are bounded to 3 pre/post tokens — a real render tag carries ~2 — which keeps +// backtracking flat and rejects prose that merely mentions an attr. Whole-text: +// applied AFTER lone-open/mangled-open so an INTACT opener is already +// gone and this fires only on genuinely opener-less residue (protects #644, +// whose opener LONE_OPEN removes first, leaving no attrs>ref span behind). +const ATTR_TOKEN = "[A-Za-z_][A-Za-z0-9._-]*=\"[^\"]*\""; +const OPENERLESS_ANCHOR = "(?:type=\"text\"|tokens=\"\\d+\")"; +const OPENERLESS_ATTRS = "(?:" + ATTR_TOKEN + "[ \\t]*){0,3}"; +// Whitespace-preserving by design (#644 doctrine): the drop never consumes the +// space around it, so a chunk boundary landing on that space cannot flip the +// verdict — whole-text and streaming agree on the residual whitespace. +const OPENERLESS_REF_SRC = + "(?[ \\t]*" + REFS_RUN; +const OPENERLESS_REF = new RegExp(OPENERLESS_REF_SRC, "g"); // The wrapped-turn imitation: the model opens a render tag and writes its // payload where the attributes are still open, so the attribute list runs into // a `<` instead of ending at its `>`. The recorded shape (architect session @@ -537,6 +556,13 @@ function stripPass(text: string, dropToolCallEmission: boolean, requestText: str .replace(new RegExp(LONE_OPEN.source, "g"), "") .replace(new RegExp(MANGLED_OPEN.source, "g"), "") .replace(new RegExp(LONE_CLOSE.source, "g"), "") + // #5195: opener-less render-tag residue ([attrs incl type="text"/tokens=N] + // > ref-run). Runs AFTER lone-open/mangled-open above so an INTACT + // opener is already gone — this fires only on genuinely opener-less residue + // and cannot disturb #644 (whose opener LONE_OPEN removes first, leaving no + // attrs>ref span). A trailing close, when present, was already peeled by + // LONE_CLOSE above, so this drops just the attrs>ref half. + out = out.replace(OPENERLESS_REF, ""); // #2862: dead ref-close units (ref + unterminated close head, mid-text or // at EOF). Position matters twice: BEFORE the truncate passes — TRUNC_CLOSE // eats the \x3c/name tail first and would leave the bare ref behind (the @@ -607,6 +633,17 @@ export function normalizeEchoArtifacts(text: string): string { return stripAcpTags(text); } +/** Assistant-PROSE normalization for outbound model text fields: the ACP + * artifact set (stripAcpTags) plus the #5259 first-line bare-ref-head guard. + * Use ONLY on assistant-output fields (response bodies / deltas / done + * events) — never on inbound history: a user message may legitimately open + * with a quoted ref, and no inbound-stripping path exists today. Keeping the + * positional rule OUT of stripAcpTags itself keeps that boundary enforced by + * construction (stripAcpTags stays position-independent). */ +export function stripAssistantProse(text: string, dropToolCallEmission = false, requestText?: string): string { + return stripBareRefHead(stripAcpTags(text, dropToolCallEmission, requestText)); +} + // Raw-wire pre-check for forged confirmation markers (#717): the literal // "[ACP]" survives JSON escaping unscathed (brackets are not escaped), so a // plain includes() on the raw SSE/JSON string is sound and cheap. The @@ -631,13 +668,75 @@ export function containsRenderTagText(s: string): boolean { // #2190: post-audit shape check — a bare ref immediately followed by ANY close // tag is echo residue by construction (genuine prose never puts mNNNNN right // before ; the kernel wraps refs in tags, so a naked ref IS the leak). -// Used where bytes bypassed or escaped the filter and must be logged, not -// dropped: fast-path gate sites and filter release points. -const ECHO_RESIDUE = /m\d{4,}\s*\x3c\/[a-zA-Z]/; +// #5195: opener-less variant joins — anchor attr (type="text" / tokens=N) plus +// a ref glued to the terminator. Quotes tolerate JSON escaping (\") because +// fast-path gate sites test RAW wire strings where " inside values arrives +// escaped; decoded-text sites match the plain form. Gate sites use it to +// ENGAGE the strip pass (both shapes are stripped there); release points log +// what still escapes. +const ECHO_RESIDUE = /m\d{4,}\s*\x3c\/[a-zA-Z]|(?:type=\\?"text\\?"|tokens=\\?"\d+\\?")\s*>\s*m\d{4,}/; export function containsEchoResidue(s: string): boolean { return ECHO_RESIDUE.test(s); } +// ─── #5259: bare kernel-ref head (no tag at all) ───────────────────────────── +// Shape census (dsh desktop, OpenAI lane, v0.1.209): an assistant reply whose +// first text block is a bare ledger ref plus one stray letter — `m01464b\n` — +// no tag opener, no attribute text, nothing for a shape match to key on. The +// model imitated a copyable ref literal from its context at generation time; +// the reasoning channel shows no decision to emit it. Every existing channel +// misses this shape: the tag-echo family keys on \x3c-headed names or anchor +// attributes (#206/#5195), the marker line on "[ACP]" (#717). What IS +// available is position + shape: the WHOLE first line of an assistant text +// channel equals m + 4..6 digits + at most one letter. Width bound: kernel +// refs start four-digit (m0001), six digits means ~1M messages — far past any +// real session — so the candidate prefix stays ≤8 chars and every hold is +// bounded. Strict byte-0 (no leading whitespace) and strict \n (no CRLF): +// observed residue is byte-0, \n-terminated; widening either axis buys only +// false-positive surface. First LINE of the channel only — later lines are +// out of scope by design (the reported shape; residue elsewhere stays +// observable, not silently rewritten). +const BARE_REF_LINE = /^m\d{4,6}[a-zA-Z]?$/; + +/** Whole-text counterpart: drop a FIRST line consisting solely of the + * residue shape (its \n included); anything else passes through. */ +export function stripBareRefHead(text: string): string { + const nl = text.indexOf("\n"); + // #2023: reaching EOF with NO newline means the ref is the whole answer — + // a bare citation the model legitimately produced. The client must see it. + // The residue shape always resumes with a \n because real content follows. + if (nl < 0) return text; + const line = text.slice(0, nl); + if (!BARE_REF_LINE.test(line)) return text; + return text.slice(nl + 1); +} + +/** Field-level engage predicate for the whole-text strips (stream*.ts): does + * this text open with the residue shape as its complete first line? */ +export function containsBareRefHeadText(s: string): boolean { + if (!s.startsWith("m")) return false; + const nl = s.indexOf("\n"); + return BARE_REF_LINE.test(nl < 0 ? s : s.slice(0, nl)); +} + +/** Raw-wire pre-check for done-event / JSON-body rebuild gates: a JSON + * `text` value (Responses/Anthropic/Google) or `content` value (OpenAI chat — + * the one wire where `content` is a plain string, not an array/object) opening + * exactly with the shape (followed by an escaped newline or the closing quote). + * Coarse by design — the false positive costs one no-op strip pass; strictness + * lives in stripBareRefHead. */ +const BARE_REF_HEAD_WIRE = /"(?:text|content)"\s*:\s*"m\d{4,6}[a-zA-Z]?(?:\\n|")/; +export function containsBareRefHeadWire(s: string): boolean { + return BARE_REF_HEAD_WIRE.test(s); +} + +/** Streaming fast-path gate (per-chunk): could this chunk OPEN the shape? + * Mid-channel engagement is a no-op — the filter disarms after its first + * line decision (same doctrine as mayStartMarkerLine). */ +export function mayStartBareRefHead(s: string): boolean { + return s === "m" || /^m\d/.test(s); +} + // #468: some upstreams stream a model-imitated render tag in tokenizer-sized // fragments ("\x3cac", "p tokens", ...) so no single chunk ever trips // RENDER_TAG_DETECT. Per-chunk gates must also engage when the chunk contains @@ -1709,7 +1808,7 @@ function stripParts(content: unknown, drop: boolean, requestText?: string): unkn if (!Array.isArray(content)) return content; return content.map((part) => { if (part && typeof part === "object" && typeof (part as Record).text === "string") { - return { ...(part as Record), text: stripAcpTags((part as Record).text as string, drop, requestText) }; + return { ...(part as Record), text: stripAssistantProse((part as Record).text as string, drop, requestText) }; } return part; }); @@ -1732,7 +1831,7 @@ function stripItemContent(it: unknown, drop: boolean, requestText?: string): unk } function stripIfString(v: unknown, drop: boolean, requestText?: string): unknown { - return typeof v === "string" ? stripAcpTags(v, drop, requestText) : v; + return typeof v === "string" ? stripAssistantProse(v, drop, requestText) : v; } // Plugin-passthrough parity for the OpenAI chat-completions wire (issue #14: @@ -1806,9 +1905,9 @@ export function stripAnthropicText(obj: T, drop: boolean = false, requestText export function stripResponsesText(obj: T, drop: boolean = false, requestText?: string): T { if (!obj || typeof obj !== "object") return obj; const o = obj as Record; - if (typeof o.text === "string") o.text = stripAcpTags(o.text, drop, requestText); + if (typeof o.text === "string") o.text = stripAssistantProse(o.text, drop, requestText); if (o.part && typeof o.part === "object" && typeof (o.part as Record).text === "string") { - o.part = { ...(o.part as Record), text: stripAcpTags((o.part as Record).text as string, drop, requestText) }; + o.part = { ...(o.part as Record), text: stripAssistantProse((o.part as Record).text as string, drop, requestText) }; } if (o.item && typeof o.item === "object") { o.item = stripItemContent(o.item, drop, requestText); @@ -1916,6 +2015,95 @@ export function createMarkerLineFilter(onDrop?: (snippet: string) => void): TagE }; } +// #5259 streaming counterpart of stripBareRefHead. Line-based like +// createMarkerLineFilter: while undecided it holds at most the undecidable +// candidate prefix (≤8 chars) until a newline, a shape-breaking byte, or EOF +// decides the first line, then disarms forever — later bytes pass through +// zero-overhead. Chunk-split deterministic by construction (decisions only on +// \n / break byte / EOF). Text channels ONLY: never wire it onto signed +// thinking/reasoning filters (#1960/KDD#10) or tool-call argument streams +// (#1039). +export function createBareRefHeadFilter(onDrop?: (snippet: string) => void): TagEchoFilter { + let buf = ""; + let decided = false; + let droppedAny = false; + let notified = false; + let inputChars = 0; + let outputChars = 0; + let dropCount = 0; + + const noteDrop = (snippet: string): void => { + droppedAny = true; + dropCount++; + if (!notified) { + notified = true; + onDrop?.(snippet); + } + }; + + // Still possibly `m\d{4,6}[a-zA-Z]?` awaiting its terminating newline. + const isCandidatePrefix = (s: string): boolean => + /^m\d{0,6}$/.test(s) || /^m\d{4,6}[a-zA-Z]$/.test(s); + + const process = (chunk: string): string => { + if (chunk.length === 0) return ""; + inputChars += chunk.length; + if (decided) { + outputChars += chunk.length; + return chunk; + } + buf += chunk; + let out = ""; + for (;;) { + const nl = buf.indexOf("\n"); + if (nl >= 0) { + const line = buf.slice(0, nl); + if (BARE_REF_LINE.test(line)) noteDrop(buf.slice(0, nl + 1)); + else out += buf.slice(0, nl + 1); + buf = buf.slice(nl + 1); + decided = true; + out += buf; + buf = ""; + break; + } + if (isCandidatePrefix(buf)) return out; + out += buf; + buf = ""; + decided = true; + break; + } + outputChars += out.length; + return out; + }; + + return { + push: (delta: string): string => process(delta), + flush(): string { + if (decided || buf.length === 0) return ""; + // #2023: an undecided bare-ref line at EOF never saw a newline, so + // it is the whole answer (a citation) — release it verbatim. The + // residue shape always has a newline because content follows it. + const tail = buf; + buf = ""; + decided = true; + outputChars += tail.length; + return tail; + }, + dropped: () => droppedAny, + // #5216 review: pending until the filter has DECIDED the first line, + // not merely while it holds a candidate. The plugin-mode fast path + // (plugin.ts) bypasses the filter when !anyPending(); with the old + // predicate a prose first line (no candidate held) let the fast path + // swallow the true first line, so a later chunk starting with `m\d` + // was mis-read as the "first line" and dropped mid-channel — a + // chunk-split determinism violation. Staying pending until decided + // keeps the fast path off until the filter has seen the real first + // line (a no-op O(1) pass for prose), then re-enables it. + pending: () => !decided, + stats: () => ({ inputChars, outputChars, dropped: droppedAny, dropCount }), + }; +} + /** Run two streaming filters in sequence (input flows a→b), so the * marker-line stripper (#717) layers onto the render-tag echo filter * (#206/#673) without touching call sites. Stats merge: input from a, diff --git a/src/plugin.ts b/src/plugin.ts index 867038aef8..3de94c4934 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -20,7 +20,7 @@ import { effectiveRulesEnabled, rulesEnabled } from "./rules-feature.js"; import { executeProxyToolAsync } from "./loop/core.js"; import type { ProxyToolResult } from "./proxy-tool-result.js"; import { normalizeSseLineEndings, finalizeSseLineEndings } from "./sse-util.js"; -import { composeStreamFilters, containsBiliInternalText, containsEchoResidue, containsMarkerLineText, containsRenderTagText, containsToolCallEmissionText, containsToolCallXmlFragment, createBiliArtifactFilter, createIdentityStreamFilter, createMarkerLineFilter, createTagEchoFilter, isOrphanMarkupText, mayStartBiliInternal, mayStartDegenerateRenderTag, mayStartMarkerLine, mayStartRenderTag, mayStartToolCallEmission, stripAcpTags, stripAnthropicText, stripOpenaiChatText, stripResponsesText, type TagEchoFilter } from "./loop/tag-echo-filter.js"; +import { composeStreamFilters, containsBareRefHeadWire, containsBiliInternalText, containsEchoResidue, containsMarkerLineText, containsRenderTagText, containsToolCallEmissionText, containsToolCallXmlFragment, createBareRefHeadFilter, createBiliArtifactFilter, createIdentityStreamFilter, createMarkerLineFilter, createTagEchoFilter, isOrphanMarkupText, mayStartBareRefHead, mayStartBiliInternal, mayStartDegenerateRenderTag, mayStartMarkerLine, mayStartRenderTag, mayStartToolCallEmission, stripAssistantProse, stripAnthropicText, stripOpenaiChatText, stripResponsesText, type TagEchoFilter } from "./loop/tag-echo-filter.js"; import { log as loggerLog } from "./logger.js"; import { scanModelOutputForPhantomAttachments } from "./phantom-attachment.js"; import { ccrEnabled, ccrLoopConfig, contentStoreOf, retrieveToolName } from "./store.js"; @@ -2859,6 +2859,10 @@ export async function pipePluginChatWithStrip( sawStrippedEcho = true; loggerLog("warn", `${who}[bili-artifact] stripped model-emitted internal artifact (plugin passthrough): ${snippet.slice(0, 80).replace(/\n/g, " ")}`); }; + const onBareRefDrop = (snippet: string) => { + sawStrippedEcho = true; + loggerLog("warn", `${who}[bare-ref-head] stripped model-emitted bare ref head (#5259): ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + }; // One state machine per (field, block/choice index) — interleaved choices // or content blocks must not share partial-tag state. Tool-call arguments // never flow through a stream (#1039): they are forwarded verbatim. @@ -2880,7 +2884,9 @@ export async function pipePluginChatWithStrip( // openai reasoning fields — the thinking channel is NEVER // rewritten, only the visible text channel is. const signedThinking = field === "thinking" || (protocol === "openai" && (field === "reasoning_content" || field === "reasoning")); - s = { filter: signedThinking ? createIdentityStreamFilter() : composeStreamFilters(composeStreamFilters(createTagEchoFilter(onTagDrop, onResidueWarn, absorbInstructed, requestText), createMarkerLineFilter(onMarkerDrop)), createBiliArtifactFilter(onBiliDrop)), field, index }; + // #5259: outermost = acts on final outgoing bytes; a bare-ref head + // is decided once per (field,index) stream and then disarmed. + s = { filter: signedThinking ? createIdentityStreamFilter() : composeStreamFilters(composeStreamFilters(composeStreamFilters(createTagEchoFilter(onTagDrop, onResidueWarn, absorbInstructed, requestText), createMarkerLineFilter(onMarkerDrop)), createBiliArtifactFilter(onBiliDrop)), createBareRefHeadFilter(onBareRefDrop)), field, index }; streams.set(key, s); } return s; @@ -3476,7 +3482,7 @@ export async function pipePluginChatWithStrip( // tool-call emission: route it to the filter so the // whole-field decision runs (m00885). Degenerate-close // residue (#2190) rides the same routing. - if (!mayStartRenderTag(v) && !mayStartMarkerLine(v) && !mayStartBiliInternal(v) && !mayStartDegenerateRenderTag(v) && !(absorbInstructed === true && mayStartToolCallEmission(v)) && !anyPending()) { + if (!mayStartRenderTag(v) && !mayStartMarkerLine(v) && !mayStartBiliInternal(v) && !mayStartBareRefHead(v) && !mayStartDegenerateRenderTag(v) && !(absorbInstructed === true && mayStartToolCallEmission(v)) && !anyPending()) { if (v.length > 0) { keptText = true; appendReply(field, typeof ch?.["index"] === "number" ? ch["index"] as number : ci, v); @@ -3657,7 +3663,7 @@ export async function pipePluginChatWithStrip( // Whole-field tool-call emission on an absorb-instructed request // (m00885): the filter's field-start hold decides on the complete // field, so the fast path must not pre-empt it. - if (!mayStartRenderTag(raw) && !mayStartMarkerLine(raw) && !mayStartBiliInternal(raw) && !mayStartDegenerateRenderTag(raw) && !(absorbInstructed === true && mayStartToolCallEmission(raw)) && !anyPending()) { + if (!mayStartRenderTag(raw) && !mayStartMarkerLine(raw) && !mayStartBiliInternal(raw) && !mayStartBareRefHead(raw) && !mayStartDegenerateRenderTag(raw) && !(absorbInstructed === true && mayStartToolCallEmission(raw)) && !anyPending()) { if (raw.length > 0) { appendReply(field, index, raw); proseAcc += raw; @@ -3770,7 +3776,7 @@ export async function pipePluginChatWithStrip( // Whole-field tool-call emission on an absorb-instructed // request (m00885) — see processOpenai. Degenerate-close // residue (#2190) rides the same routing. - if (signed || (!mayStartRenderTag(raw) && !mayStartMarkerLine(raw) && !mayStartBiliInternal(raw) && !mayStartDegenerateRenderTag(raw) && !(absorbInstructed === true && mayStartToolCallEmission(raw)) && !anyPending())) { + if (signed || (!mayStartRenderTag(raw) && !mayStartMarkerLine(raw) && !mayStartBiliInternal(raw) && !mayStartBareRefHead(raw) && !mayStartDegenerateRenderTag(raw) && !(absorbInstructed === true && mayStartToolCallEmission(raw)) && !anyPending())) { if (raw.length > 0) { keptText = true; appendReply(field, index, raw); @@ -4436,6 +4442,10 @@ export async function pipePluginResponsesWithStrip( const onBiliDrop = (snippet: string) => { loggerLog("warn", `${who}[bili-artifact] stripped model-emitted internal artifact (plugin passthrough): ${snippet.slice(0, 80).replace(/\n/g, " ")}`); }; + const onBareRefDrop = (snippet: string) => { + loggerLog("warn", `${who}[bare-ref-head] stripped model-emitted bare ref head (#5259): ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + }; + // #5259: outermost — the bare-ref head guard acts on final outgoing bytes. const tagFilter = composeStreamFilters( composeStreamFilters( createTagEchoFilter(onTagDrop, onResidueWarn, absorbInstructed, requestText), @@ -4443,7 +4453,7 @@ export async function pipePluginResponsesWithStrip( loggerLog("warn", `${who}[marker-echo] stripped model-emitted ACP confirmation marker (plugin passthrough): ${snippet.slice(0, 80).replace(/\n/g, " ")}`); }), ), - createBiliArtifactFilter(onBiliDrop), + composeStreamFilters(createBiliArtifactFilter(onBiliDrop), createBareRefHeadFilter(onBareRefDrop)), ); // #673: turn-level observability for degenerate terminal turns. let sawFunctionCall = false; @@ -4971,7 +4981,7 @@ export async function pipePluginResponsesWithStrip( // Whole-field tool-call emission (m00885) — an absorb-instructed // turn may answer as prose; drop the span, not just the tags. const dropEmission = absorbInstructed === true && containsToolCallEmissionText(jsonStr); - const hadEchoText = containsRenderTagText(jsonStr) || containsMarkerLineText(jsonStr) || containsBiliInternalText(jsonStr) || containsEchoResidue(jsonStr) || dropEmission; + const hadEchoText = containsRenderTagText(jsonStr) || containsMarkerLineText(jsonStr) || containsBiliInternalText(jsonStr) || containsBareRefHeadWire(jsonStr) || containsEchoResidue(jsonStr) || dropEmission; if (hadEchoText) sawStrippedEcho = true; let evOut = ev; let rebuild = hadEchoText || retryRewritePending(); @@ -5028,7 +5038,7 @@ export async function pipePluginResponsesWithStrip( // Whole-field tool-call emission (m00885) — an absorb-instructed // turn may answer as prose; drop the span, not just the tags. const dropEmission = absorbInstructed === true && containsToolCallEmissionText(jsonStr); - const hadEchoText = containsRenderTagText(jsonStr) || containsMarkerLineText(jsonStr) || containsBiliInternalText(jsonStr) || containsEchoResidue(jsonStr) || dropEmission; + const hadEchoText = containsRenderTagText(jsonStr) || containsMarkerLineText(jsonStr) || containsBiliInternalText(jsonStr) || containsBareRefHeadWire(jsonStr) || containsEchoResidue(jsonStr) || dropEmission; if (hadEchoText) sawStrippedEcho = true; let evOut = ev; let rebuild = hadEchoText || retryRewritePending(); @@ -5058,7 +5068,7 @@ export async function pipePluginResponsesWithStrip( // Whole-field emission head (m00885): the filter's // field-start hold must see the first bytes. Degenerate // close (#2190) rides the same routing. - if (!retryRewritePending() && !mayStartRenderTag(delta) && !mayStartMarkerLine(delta) && !mayStartBiliInternal(delta) && !mayStartDegenerateRenderTag(delta) && !(absorbInstructed === true && mayStartToolCallEmission(delta)) && !tagFilter.pending()) { + if (!retryRewritePending() && !mayStartRenderTag(delta) && !mayStartMarkerLine(delta) && !mayStartBiliInternal(delta) && !mayStartBareRefHead(delta) && !mayStartDegenerateRenderTag(delta) && !(absorbInstructed === true && mayStartToolCallEmission(delta)) && !tagFilter.pending()) { proseAcc += delta; visibleTextChars += delta.length; fastPathChars += delta.length; @@ -5188,10 +5198,10 @@ function rebuildEvent(rawEvent: string, ev: Record): string { } // Plugin-passthrough parity for the Gemini wire: strip the model prose that -// lives in `candidates[*].content.parts[*].text` — both plain text parts and -// `thought:true` reasoning parts share that one field. Mirrors -// stripOpenaiChatText / stripAnthropicText; mutates in place (the returned -// reference is the input's). +// lives in `candidates[*].content.parts[*].text` — plain text parts only; +// `thought:true` reasoning parts share the field but stay byte-for-byte +// (#1960/KDD#10). Mirrors stripOpenaiChatText / stripAnthropicText; mutates +// in place (the returned reference is the input's). function stripGoogleChunk(obj: T, drop: boolean = false, requestText?: string): T { if (!obj || typeof obj !== "object") return obj; const o = obj as Record; @@ -5215,7 +5225,7 @@ function stripGoogleChunk(obj: T, drop: boolean = false, requestText?: string return part["thought"] !== true && !(typeof part["thoughtSignature"] === "string" && part["thoughtSignature"].length > 0) && typeof part["text"] === "string" - ? { ...part, text: stripAcpTags(part["text"], drop, requestText) } + ? { ...part, text: stripAssistantProse(part["text"], drop, requestText) } : p; }), }, @@ -5324,7 +5334,7 @@ export async function pipePluginJson( // tool-call emission written as prose — the raw-body probe is // escape-tolerant so it fires on the serialized JSON too. const dropEmission = absorbInstructed === true && containsToolCallEmissionText(text); - if (json && (dropEmission || containsRenderTagText(text) || containsMarkerLineText(text) || containsBiliInternalText(text) || containsEchoResidue(text))) { + if (json && (dropEmission || containsRenderTagText(text) || containsMarkerLineText(text) || containsBiliInternalText(text) || containsBareRefHeadWire(text) || containsEchoResidue(text))) { // #206 parity for the non-streaming plugin path: the compress loop's // JSON branch strips render tags from every round; a verbatim plugin // JSON response would re-feed the model's tag echoes. Strips mutate in diff --git a/src/stream-google.ts b/src/stream-google.ts index a722e2119a..8d863b70e6 100644 --- a/src/stream-google.ts +++ b/src/stream-google.ts @@ -5,7 +5,7 @@ import { effectiveAbsorbConfig, isProxyToolFor } from "./absorb.js"; import { executeProxyToolAsync } from "./loop/core.js"; import { drainPendingRetrievals } from "./store.js"; import { runJsonRewriteAsync, type JsonToolCall, type RewriteCtx } from "./stream.js"; -import { containsBiliInternalText, containsMarkerLineText, containsRenderTagText, containsToolCallEmissionText, stripAcpTags } from "./loop/tag-echo-filter.js"; +import { containsBareRefHeadText, containsBiliInternalText, containsEchoResidue, containsMarkerLineText, containsRenderTagText, containsToolCallEmissionText, stripAssistantProse } from "./loop/tag-echo-filter.js"; export async function rewriteGoogleJsonResponseAsync(body: unknown, ctx: RewriteCtx, signal?: AbortSignal): Promise { return runJsonRewriteAsync(rewriteGoogleJsonSteps(body, ctx), async (call) => (await executeProxyToolAsync(call.name, call.args as Record, ctx, call.id, undefined, signal)).text); @@ -28,7 +28,7 @@ function* rewriteGoogleJsonSteps(body: unknown, ctx: RewriteCtx): Generator containsRenderTagText(text) || containsMarkerLineText(text) || containsBiliInternalText(text) || (absorbArmed && containsToolCallEmissionText(text)); + const containsEcho = (text: string): boolean => containsRenderTagText(text) || containsMarkerLineText(text) || containsBiliInternalText(text) || containsBareRefHeadText(text) || containsEchoResidue(text) || (absorbArmed && containsToolCallEmissionText(text)); // Capture request evidence before a yielded proxy tool can change the context. const requestText = absorbArmed && parts.some(part => part && typeof part === "object" && (part as { thought?: boolean }).thought !== true @@ -55,7 +55,7 @@ function* rewriteGoogleJsonSteps(body: unknown, ctx: RewriteCtx): Generator 0) && typeof part.text === "string" && containsEcho(part.text)) { ctx.log(`[tag-echo] stripped: non-stream google output ACP echo (render tags/markers/internal artifacts): ${part.text.slice(0, 120).replace(/\n/g, " ")}`); - part.text = stripAcpTags(part.text, absorbArmed, requestText); + part.text = stripAssistantProse(part.text, absorbArmed, requestText); } keptParts.push(part); } diff --git a/src/stream-openai.ts b/src/stream-openai.ts index c13ce1d99c..bc0dbddfcf 100644 --- a/src/stream-openai.ts +++ b/src/stream-openai.ts @@ -4,7 +4,7 @@ import { COMPRESS_TOOL_NAME, parseCompressInput } from "./compress-tool.js"; import { applyRanges, runJsonRewrite, runJsonRewriteAsync, type JsonToolCall, type RewriteCtx } from "./stream.js"; import { applyConfiguredCompression } from "./external-summary-compress.js"; import { effectiveAbsorbConfig } from "./absorb.js"; -import { containsBiliInternalText, containsMarkerLineText, containsRenderTagText, containsToolCallEmissionText, stripAcpTags } from "./loop/tag-echo-filter.js"; +import { containsBareRefHeadText, containsBiliInternalText, containsEchoResidue, containsMarkerLineText, containsRenderTagText, containsToolCallEmissionText, stripAssistantProse } from "./loop/tag-echo-filter.js"; export function rewriteOpenaiJsonResponse(body: unknown, ctx: RewriteCtx): unknown { return runJsonRewrite(rewriteOpenaiJsonSteps(body, ctx), (call) => applyRanges(parseCompressInput(call.args, call.id), ctx).text); @@ -55,10 +55,10 @@ function* rewriteOpenaiJsonSteps(body: unknown, ctx: RewriteCtx): Generator ` (optionally + a close) that reaches +// client-visible assistant text. stripAcpTags (whole-text / prepare-layer path) +// recognizes the high-confidence signature — an anchor attr (type="text" / +// tokens=N) plus a kernel ref glued to the tag terminator — and removes it. +// +// Scope note: this pins the WHOLE-TEXT path. The live streaming filter +// (createTagEchoFilter) deliberately does NOT strip this shape yet: the residue +// has no < head to latch onto, so a chunk boundary splitting inside the attr is +// indistinguishable from prose, and a streaming fix would either miss those +// splits (chunk-split nondeterminism) or hold ordinary words like "type"/ +// "token"/"to" (prose latency) — an owner decision, tracked on the issue. + +const GTE = "\x3e"; // > +const LT = "\x3c"; // < + +const RESIDUE = /(?:type="text"|tokens="\d+")\s*\x3e\s*m\d{4,}/; + +test("#5195: stripAcpTags removes opener-less render-tag residue", () => { + // reported shape: suffix through the ref, no opening { + // A dash-joined run fully stripped when it has no trailing close… + assert.equal(stripAcpTags(` type="text"${GTE}m00106\u2013m00110`), " "); + // …with a trailing close the pre-existing orphan-close decomposition can + // take the last ref first, leaving only a bare joiner — but the residue + // SIGNATURE (anchor attr + ref against the terminator) must be gone either way. + for (const x of [ + ` type="text"${GTE}m00106\u2013m00110${LT}/acp${GTE}`, + ` type="text"${GTE}m00106,m00110${LT}/acp${GTE}`, + ` type="text"${GTE}m00106-m00110${LT}/acp${GTE}`, + ]) { + const out = stripAcpTags(x); + assert.equal(RESIDUE.test(out), false, `residue survived for ${JSON.stringify(x)} -> ${JSON.stringify(out)}`); + } +}); + +test("#5195: idempotent — re-normalizing already-cleaned bytes is stable", () => { + const inputs = [ + ` type="text"${GTE}m00106`, + ` type="text"${GTE}m00106${LT}/acp${GTE}`, + `Done. type="text"${GTE}m00106 tail`, + ` tokens="5" type="text"${GTE}m00106${LT}/acp${GTE}`, + ]; + for (const x of inputs) { + const once = stripAcpTags(x); + assert.equal(stripAcpTags(once), once, `not idempotent for ${JSON.stringify(x)}`); + } +}); + +test("#5195: controls are NOT over-stripped (signature is narrow)", () => { + // wrong attr value: not the render-tag anchor + assert.equal(stripAcpTags(` type="video"${GTE}m00106`), ` type="video"${GTE}m00106`); + // anchor attr present but no kernel ref after the terminator + assert.equal(stripAcpTags(` type="text"${GTE}hello world`), ` type="text"${GTE}hello world`); + // real HTML element carrying the same attr name + assert.equal(stripAcpTags(`use the ${LT}ai-video${GTE} element here`), `use the ${LT}ai-video${GTE} element here`); + // bare ref cited among words is prose, not residue + assert.equal(stripAcpTags(`see m00123 and m00124 done`), `see m00123 and m00124 done`); + // a full well-formed render tag still strips whole (existing behavior intact) + assert.equal(stripAcpTags(`${LT}acp tokens="5" type="text"${GTE}m00106${LT}/acp${GTE}`), ""); +}); + +test("#5195: audit predicate detects the opener-less residue at release points", () => { + assert.equal(containsEchoResidue(` type="text"${GTE}m00106`), true); + assert.equal(containsEchoResidue(` tokens="5"${GTE}m00106`), true); + // pre-existing dead-ref-close shape still detected + assert.equal(containsEchoResidue(`m00106${LT}/acp`), true); + // clean prose is not flagged + assert.equal(containsEchoResidue(`all good here`), false); +}); + +test("#5195: audit predicate fires on raw-JSON-escaped forms (gate sites test raw wire strings)", () => { + // Fast-path gate sites (pipePluginJson, Responses done/completed frames, + // adapter item events) run this predicate on RAW wire strings where every " + // inside a value arrives escaped as \". Both quote forms must match. + assert.equal(containsEchoResidue(`{"choices":[{"message":{"content":"Done. type=\\"text\\">m00106 tail"}}]}`), true); + assert.equal(containsEchoResidue(`{"content":"see tokens=\\"5\\">m00106"}`), true); + // decoded-text gate sites still match the plain form + assert.equal(containsEchoResidue(`Done. type="text"${GTE}m00106 tail`), true); + // wrong attr value stays inert in escaped form too + assert.equal(containsEchoResidue(`{"content":" type=\\"video\\">m00106"}`), false); +}); diff --git a/tests/issue5259-bare-ref-head.test.ts b/tests/issue5259-bare-ref-head.test.ts new file mode 100644 index 0000000000..ed9d8a8c81 --- /dev/null +++ b/tests/issue5259-bare-ref-head.test.ts @@ -0,0 +1,294 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + stripAcpTags, + stripAssistantProse, + stripBareRefHead, + containsBareRefHeadText, + containsBareRefHeadWire, + mayStartBareRefHead, + createBareRefHeadFilter, + createTagEchoFilter, + composeStreamFilters, + stripOpenaiChatText, + stripAnthropicText, + stripResponsesText, +} from "../src/loop/tag-echo-filter.ts"; + +// #5259: a dsh/OpenAI-lane assistant reply opened with a bare ledger ref plus +// one stray letter (`m01464b\n`) as its own first text block — no tag opener, +// no attribute text, so every shape-keyed channel (#206/#5195/#717) misses it. +// The model imitated a copyable ref literal at generation time; nothing in the +// reasoning channel planned it. Fix = position+shape guard: the WHOLE first +// line of an assistant TEXT channel equals m + 4..6 digits + ≤1 letter → drop +// that line (its \n included). Text channels only — never signed +// thinking/reasoning (#1960/KDD#10) or tool-call arguments (#1039). + +const GTE = "\x3e"; // > +const LT = "\x3c"; // < + +const PROSE = "懂了,你说的是这件事。"; + +test("#5259: stripBareRefHead drops the reported shape (whole-text)", () => { + // #2023: no newline -> the ref is the whole answer (a citation). + assert.equal(stripBareRefHead("m01464b"), "m01464b"); + // reported shape: residue line + prose + assert.equal(stripBareRefHead(`m01464b\n${PROSE}`), PROSE); + // width bounds: 4-digit floor (kernel refs start m0001)… + assert.equal(stripBareRefHead("m1234\nx"), "x"); + // …6-digit ceiling (~1M messages, past any real session) + assert.equal(stripBareRefHead("m123456\nx"), "x"); + assert.equal(stripBareRefHead("m123456z\nx"), "x"); + // stray letter case-folds both ways + assert.equal(stripBareRefHead("m01464B\nx"), "x"); +}); + +test("#5259: stripBareRefHead leaves near-miss shapes byte-exact", () => { + // two stray letters: not the shape + assert.equal(stripBareRefHead("m01464bc\nx"), "m01464bc\nx"); + // prose on the same line + assert.equal(stripBareRefHead("m014645 more\nx"), "m014645 more\nx"); + // trailing space on the line + assert.equal(stripBareRefHead("m01464b \nx"), "m01464b \nx"); + // 7 digits: beyond the census bound, honest prose + assert.equal(stripBareRefHead("m1234567\nx"), "m1234567\nx"); + // word-glued at byte 0 + assert.equal(stripBareRefHead("xm01464\nx"), "xm01464\nx"); + // leading whitespace (observed residue is byte-0) + assert.equal(stripBareRefHead(" m01464\nx"), " m01464\nx"); + // CRLF: strict \n boundary, no tolerance + assert.equal(stripBareRefHead("m01464b\r\nx"), "m01464b\r\nx"); + // uppercase M: refs are lowercase-m + assert.equal(stripBareRefHead("M01464\nx"), "M01464\nx"); + // later lines are out of scope by design + assert.equal(stripBareRefHead(`ok\nm01464b\nmore`), `ok\nm01464b\nmore`); + // empty / blank-first-line inputs pass through + assert.equal(stripBareRefHead(""), ""); + assert.equal(stripBareRefHead("\nx"), "\nx"); +}); + +test("#5259: stripAssistantProse layers the head guard onto stripAcpTags", () => { + // residue line 1, render tag line 2 → both go + const x = `m01464b\n${LT}acp tokens="2" type="text"${GTE}m00010${LT}/acp${GTE} rest`; + assert.equal(stripAssistantProse(x), " rest"); + // #5195 opener-less residue on line 2, bare ref on line 1 → both go + // (#5195 semantics: whitespace flanking the unit is content, both survive) + assert.equal(stripAssistantProse(`m01464b\n type="text"${GTE}m00106 rest`), " rest"); + // scope boundary: a stripped tag leaves a leading BLANK line, which disarms + // the byte-0 guard — residue on what becomes line 2 survives (documented) + assert.equal( + stripAssistantProse(`${LT}acp tokens="2" type="text"${GTE}m00010${LT}/acp${GTE}\nm01464b\nrest`), + `\nm01464b\nrest`, + ); +}); + +test("#5259: stripAcpTags itself stays position-independent (no fold-in)", () => { + // the bare shape has no key for the whole-text stripper — unchanged + assert.equal(stripAcpTags(`m01464b\nrest`), `m01464b\nrest`); + // bare refs cited mid-prose are prose, not residue (pre-existing behavior) + assert.equal(stripAcpTags("see m00123 and m00124 done"), "see m00123 and m00124 done"); +}); + +test("#5259: predicates (field-level, wire-level, chunk-level)", () => { + // field-level engage + assert.equal(containsBareRefHeadText("m01464b"), true); + assert.equal(containsBareRefHeadText(`m01464b\nrest`), true); + assert.equal(containsBareRefHeadText("m1234"), true); + assert.equal(containsBareRefHeadText("m123456x"), true); + assert.equal(containsBareRefHeadText(""), false); + assert.equal(containsBareRefHeadText("hello"), false); + assert.equal(containsBareRefHeadText(" m01464b"), false); + assert.equal(containsBareRefHeadText("m01464bc\nrest"), false); + assert.equal(containsBareRefHeadText("m01464b \nrest"), false); + assert.equal(containsBareRefHeadText("m1234567\nrest"), false); + // wire-level pre-check on raw JSON (escaped newline or closing quote) + assert.equal(containsBareRefHeadWire('{"text":"m01464b\\nrest"}'), true); + assert.equal(containsBareRefHeadWire('{"text":"m01464b"}'), true); + assert.equal(containsBareRefHeadWire('{"content":[{"type":"output_text","text":"m123456x"}]}'), true); + assert.equal(containsBareRefHeadWire('{"text":"m01464bc\\n"}'), false); + assert.equal(containsBareRefHeadWire('{"text":"xm01464"}'), false); + assert.equal(containsBareRefHeadWire('{"text":"prose"}'), false); + // OpenAI chat: assistant text under a string `content` field — the + // non-streaming plugin path (pipePluginJson) gates on the raw JSON body, + // so the wire check must engage on `content` too (review fix, #5216). + assert.equal(containsBareRefHeadWire('{"choices":[{"message":{"content":"m01464b\\nrest"}}]}'), true); + assert.equal(containsBareRefHeadWire('{"choices":[{"message":{"content":"m01464b"}}]}'), true); + assert.equal(containsBareRefHeadWire('{"choices":[{"message":{"content":"m01464bc\\n"}}]}'), false); + assert.equal(containsBareRefHeadWire('{"choices":[{"message":{"content":"m1234567\\n"}}]}'), false); + assert.equal(containsBareRefHeadWire('{"choices":[{"message":{"content":"m01464b more\\n"}}]}'), false); + assert.equal(containsBareRefHeadWire('{"choices":[{"message":{"content":"hello"}}]}'), false); + // chunk-level fast-path gate: could this chunk OPEN the shape? + assert.equal(mayStartBareRefHead("m"), true); + assert.equal(mayStartBareRefHead("m0"), true); + assert.equal(mayStartBareRefHead("m01464b\nx"), true); + assert.equal(mayStartBareRefHead(""), false); + assert.equal(mayStartBareRefHead("x"), false); + assert.equal(mayStartBareRefHead(" m"), false); + assert.equal(mayStartBareRefHead("M0"), false); +}); + +test("#5259: streaming filter drops the residue at every chunk split", () => { + const S = `m01464b\n${PROSE}\n`; + const EXPECTED = `${PROSE}\n`; + // property: one split anywhere → identical output (the size=1 leak class + // from the issue repro is covered by i=1) + for (let i = 1; i < S.length; i++) { + const f = createBareRefHeadFilter(); + const out = f.push(S.slice(0, i)) + f.push(S.slice(i)) + f.flush(); + assert.equal(out, EXPECTED, `split at ${i}: ${JSON.stringify(out)}`); + } + // single-char pushes throughout (tokenizer-sized fragments) + const g = createBareRefHeadFilter(); + let acc = ""; + for (const ch of S) acc += g.push(ch); + acc += g.flush(); + assert.equal(acc, EXPECTED); +}); + +test("#5259: streaming filter — EOF without newline, empty chunks, callbacks", () => { + // residue is the entire field, stream ends before any newline + // #2023: an EOF-only bare ref is the citation, not residue. + const a = createBareRefHeadFilter(); + assert.equal(a.push("m01464b") + a.flush(), "m01464b"); + assert.equal(a.dropped(), false); + assert.equal(a.stats().dropCount, 0); + // empty leading chunk must not decide the line + const b = createBareRefHeadFilter(); + assert.equal(b.push(""), ""); + assert.equal(b.push(`m01464b\n${PROSE}`) + b.flush(), PROSE); + // onDrop fires once with the dropped snippet + let seen: string | undefined; + const c = createBareRefHeadFilter((s) => { seen = s; }); + assert.equal(c.push("m01464b\n"), ""); + assert.equal(seen, "m01464b\n"); + const mid = c.push("m01465c\n"); // disarmed: second ref-like line passes + assert.equal(mid + c.push("tail") + c.flush(), "m01465c\ntail"); +}); + +test("#5259: streaming filter — negative rows stay byte-exact", () => { + // two letters break the shape at the breaking byte + let f = createBareRefHeadFilter(); + assert.equal(f.push("m01464bc\nx") + f.flush(), "m01464bc\nx"); + // prose on the same line + f = createBareRefHeadFilter(); + assert.equal(f.push("m014645 more") + f.flush(), "m014645 more"); + // 7-digit run releases as prose once the prefix stops matching + f = createBareRefHeadFilter(); + assert.equal(f.push("m1234567\nx") + f.flush(), "m1234567\nx"); + // second line immune after first-line decision + f = createBareRefHeadFilter(); + assert.equal(f.push(`ok\nm01464b\nmore`) + f.flush(), `ok\nm01464b\nmore`); + // CRLF not matched (strict \n) + f = createBareRefHeadFilter(); + assert.equal(f.push("m01464b\r\nx") + f.flush(), "m01464b\r\nx"); + // pending() is true only while the candidate prefix is held + f = createBareRefHeadFilter(); + assert.equal(f.push("m01"), ""); + assert.equal(f.pending(), true); + assert.equal(f.push("464b\n") + f.flush(), ""); + assert.equal(f.pending(), false); +}); + +test("#5216 review: fast-path guard — filter stays pending until it decides the true first line", () => { + // The plugin-mode fast path (plugin.ts:3485/3666/3779/5071) bypasses the + // filter when !mayStartBareRefHead(v) && !anyPending(). The bare-ref + // filter must report pending() until it has DECIDED the first line, so a + // prose first line (no candidate held) does NOT let the fast path swallow + // the true first line — otherwise a later chunk starting with `m\d` is + // mis-read as the "first line" and dropped mid-channel (chunk-split + // determinism violation found in #5216 review). + const route = (f: ReturnType, chunks: string[]): string => { + let out = ""; + for (const c of chunks) { + if (!mayStartBareRefHead(c) && !f.pending()) { + out += c; // fast path: bypass the filter + } else { + out += f.push(c); + } + } + out += f.flush(); + return out; + }; + // (a) prose first line, ref on line 2 — the ref must SURVIVE (it is not + // the true first line). Pre-fix, the fast path swallowed "hello\n" and the + // filter mis-read "m01464b\n" as the first line and dropped it. + let f = createBareRefHeadFilter(); + assert.equal(route(f, ["hello\n", "m01464b\nmore"]), "hello\nm01464b\nmore", "line-2 ref must survive"); + // (b) prose mid-line-1, ref completing line 1 — the ref must SURVIVE. + f = createBareRefHeadFilter(); + assert.equal(route(f, ["The answer is ", "m01464b\nmore"]), "The answer is m01464b\nmore", "mid-line-1 ref must survive"); + // (c) true first line IS a bare ref — it must still be DROPPED. + f = createBareRefHeadFilter(); + assert.equal(route(f, ["m01464b\n", "more"]), "more", "true first-line ref still dropped"); + // (d) pending() is true before any chunk (fast path off), false once the + // first chunk decides (fast path back on). + f = createBareRefHeadFilter(); + assert.equal(f.pending(), true, "pending before first chunk"); + f.push("hello\n"); + assert.equal(f.pending(), false, "decided after prose first line"); +}); + +test("#5259: composed onto the tag-echo chain, split-deterministic", () => { + // input flows tagEcho→bareRef: residue line 1 + full tag line 2 + const S = `m01464b\n${LT}acp tokens="2" type="text"${GTE}m00010${LT}/acp${GTE} done\n`; + const EXPECTED = " done\n"; + for (let i = 1; i < S.length; i++) { + const f = composeStreamFilters(createTagEchoFilter(), createBareRefHeadFilter()); + const out = f.push(S.slice(0, i)) + f.push(S.slice(i)) + f.flush(); + assert.equal(out, EXPECTED, `split at ${i}: ${JSON.stringify(out)}`); + } + // composed stats merge the drop + const f = composeStreamFilters(createTagEchoFilter(), createBareRefHeadFilter()); + f.push(S); + f.flush(); + assert.equal(f.stats().dropped, true); + assert.ok(f.stats().dropCount >= 2, `dropCount=${f.stats().dropCount}`); +}); + +test("#5259: wire strippers apply the head guard to assistant text fields only", () => { + // OpenAI chat: delta.content stripped, reasoning_content byte-verbatim + const openai = stripOpenaiChatText({ + choices: [{ delta: { content: `m01464b\n${PROSE}`, reasoning_content: "m01464b\nprivate" } }], + }); + const ch = (openai.choices as Array<{ delta: { content: string; reasoning_content: string } }>)[0]; + assert.equal(ch.delta.content, PROSE); + assert.equal(ch.delta.reasoning_content, "m01464b\nprivate"); + // Anthropic: text blocks stripped; thinking blocks carry no .text — untouched + const anth = stripAnthropicText({ + content: [ + { type: "text", text: `m01464b\n${PROSE}` }, + { type: "thinking", thinking: "m01464b\nsigned channel" }, + ], + }); + const ac = anth.content as Array<{ type?: string; text?: string; thinking?: string }>; + assert.equal(ac[0].text, PROSE); + assert.equal(ac[1].thinking, "m01464b\nsigned channel"); + // Responses: message output_text stripped; function_call arguments byte-exact (#1039) + const args = '{"cmd":"echo m01464b"}'; + const resp = stripResponsesText({ + response: { + output: [ + { type: "message", role: "assistant", content: [{ type: "output_text", text: `m01464b\n${PROSE}` }] }, + { type: "function_call", name: "bash", call_id: "call_1", arguments: args }, + ], + }, + }); + const ro = (resp.response as Record).output as Array>; + const rc = ro[0].content as Array>; + assert.equal(rc[0].text, PROSE); + assert.equal(ro[1].arguments, args); +}); + +test("#5259: idempotent — re-normalizing cleaned bytes is stable", () => { + const inputs = [ + `m01464b\n${PROSE}`, + "m01464b", + `m01464b\n${LT}acp tokens="2" type="text"${GTE}m00010${LT}/acp${GTE} rest`, + `m01464bc\n${PROSE}`, + `ok\nm01464b\nmore`, + ]; + for (const x of inputs) { + const once = stripAssistantProse(x); + assert.equal(stripAssistantProse(once), once, `not idempotent for ${JSON.stringify(x)}`); + } +});