From fc00bf63d41ac99120cf5055f140aee4a73b1b3a Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 29 Sep 2026 12:37:32 +0800 Subject: [PATCH] fix: strip model-emitted bili internal artifacts from output streams (#1634) The proxy injects three artifact families into model-visible payloads (outbound checkpoint carriers, forged-compaction handoff user messages, captured summary blocks). Under sustained context pressure models restate these verbatim as their answer; the existing sanitizer only knew ACP render tags and [ACP] marker lines, so all four observed shapes passed through to the client transcript and the next turn answered metadata instead of the user (long sessions stall). Adds a third streaming filter stage (createBiliArtifactFilter) plus whole- text support folded into stripAcpTags, composed into every wire's filter stack and guarded at every hadEcho/rewrite site: - well-formed spans (validated by the frozen parser, literal or \u003c-escaped form) are stripped anywhere in prose; - line-start '[bili] context summary after compaction:' and '[Compressed conversation section]' blocks are cut to end of field; - unterminated/over-cap openings release as prose byte-exact (#1039/#644); - request-side stamped carriers are untouched; #1542 inbound backstop unchanged. Behavior change (model output only): the four shapes above are now stripped on all wires where they previously passed through verbatim. Degenerate-turn retry integration preserved: a fully-forged turn yields zero visible text and fires the existing one-time continuation nudge. Debug observability: [stamp]/[inject] debug logs at every outbound append site (chain stamping, ephemeral nudge, image note, forged-summary developer re-injection). ACP_DUMP_REQ remains the byte-level forensic. --- src/chain-checkpoint.ts | 2 +- src/codex-compact.ts | 8 +- src/loop/adapter-anthropic.ts | 17 ++- src/loop/adapter-google.ts | 17 ++- src/loop/adapter-openai.ts | 17 ++- src/loop/adapter-responses.ts | 21 +-- src/loop/tag-echo-filter.ts | 228 +++++++++++++++++++++++++++++- src/plugin.ts | 46 +++--- src/server.ts | 9 +- src/stream-google.ts | 6 +- src/stream-openai.ts | 6 +- src/stream-responses.ts | 6 +- src/stream.ts | 6 +- tests/bili-artifact-strip.test.ts | 197 ++++++++++++++++++++++++++ 14 files changed, 526 insertions(+), 60 deletions(-) create mode 100644 tests/bili-artifact-strip.test.ts diff --git a/src/chain-checkpoint.ts b/src/chain-checkpoint.ts index 1340b7567f..b5b4fa71df 100644 --- a/src/chain-checkpoint.ts +++ b/src/chain-checkpoint.ts @@ -62,7 +62,7 @@ export const DEFAULT_RECENT_CHECKPOINT_WINDOW_MS = 10 * 60 * 1000; // ≤~120 with short ids); the cap only bounds malformed-tag scanning cost. const MAX_CHECKPOINT_CHARS = 512; -const TAG_OPEN = "\x3cbili-chain "; +export const TAG_OPEN = "\x3cbili-chain "; const TAG_CLOSE = "/\x3e"; export interface ChainCheckpoint { diff --git a/src/codex-compact.ts b/src/codex-compact.ts index d58443e7f1..825d8b21a5 100644 --- a/src/codex-compact.ts +++ b/src/codex-compact.ts @@ -74,6 +74,10 @@ export function extractBiliSummary(item: unknown): string | undefined { // data loss. Marker items without an extractable blob (id-prefix-only, e.g. // minted by an older build) are still dropped; real OpenAI blobs pass through // untouched. +// #1634: exact handoff header the model sees on the responses wire; the +// output-side stripper keys off this constant (single source of truth). +export const CODEX_FORGED_HANDOFF_HEADER = "[bili] context summary after compaction:"; + export function replaceBiliCompactionItems(input: T[]): { items: T[]; replaced: number; dropped: number } { const items: T[] = []; let replaced = 0; @@ -91,7 +95,7 @@ export function replaceBiliCompactionItems(input: T[]): { items: T[]; replace items.push({ type: "message", role: "user", - content: [{ type: "input_text", text: `[bili] context summary after compaction:\n${summary}` }], + content: [{ type: "input_text", text: `${CODEX_FORGED_HANDOFF_HEADER}\n${summary}` }], } as T); replaced++; } @@ -150,7 +154,7 @@ export function buildTriggerForgeBody( // The kernel renders block summaries as system messages with this header // (acp-kernel SUMMARY_HEADER). Reuse the exact format so the model reads a // captured handoff summary the same way it reads a live kernel-rendered one. -const FORGED_SUMMARY_HEADER = "[Compressed conversation section]"; +export const FORGED_SUMMARY_HEADER = "[Compressed conversation section]"; export function renderForgedSummary(block: Pick): string { const body = block.summary.trim(); diff --git a/src/loop/adapter-anthropic.ts b/src/loop/adapter-anthropic.ts index 30a283155f..c15500f33a 100644 --- a/src/loop/adapter-anthropic.ts +++ b/src/loop/adapter-anthropic.ts @@ -2,7 +2,7 @@ import type { CoreMessage } from "acp-kernel"; import { coreToAnthropic, extractSystem, buildSystem, type AnthropicRequestBody } from "acp-kernel/wire"; import { stampAnthropicSystemCacheControl } from "./cache-control.js"; import { buildVisibilityMarker } from "./core.js"; -import { composeStreamFilters, createMarkerLineFilter, createTagEchoFilter } from "./tag-echo-filter.js"; +import { composeStreamFilters, createBiliArtifactFilter, createMarkerLineFilter, createTagEchoFilter } from "./tag-echo-filter.js"; import { degenerateTurnWarning } from "../degenerate-turn.js"; import { log as loggerLog } from "../logger.js"; import type { @@ -264,11 +264,16 @@ export function createAnthropicAdapter(requestBody: Record, ori // re-request rounds). Flush at the owning block's stop so held-back // fragments still emit while the block is open. const tagFilter = composeStreamFilters( - createTagEchoFilter((snippet) => { - loggerLog("warn", `[tag-echo] stripped model-emitted render tag: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); - }), - createMarkerLineFilter((snippet) => { - loggerLog("warn", `[marker-echo] stripped model-emitted ACP confirmation marker: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + composeStreamFilters( + createTagEchoFilter((snippet) => { + loggerLog("warn", `[tag-echo] stripped model-emitted render tag: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + }), + createMarkerLineFilter((snippet) => { + 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, " ")}`); }), ); let lastTextIndex: number | null = null; diff --git a/src/loop/adapter-google.ts b/src/loop/adapter-google.ts index 4f4b10d0ee..906f620643 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, createMarkerLineFilter, createTagEchoFilter } from "./tag-echo-filter.js"; +import { composeStreamFilters, createBiliArtifactFilter, createMarkerLineFilter, createTagEchoFilter } from "./tag-echo-filter.js"; import { degenerateTurnWarning } from "../degenerate-turn.js"; import { log as loggerLog } from "../logger.js"; @@ -288,11 +288,16 @@ export function createGoogleAdapter( // confirmation markers from text parts; both filters may hold back a // short tail, flushed on finish (and at stream end). const tagFilter = composeStreamFilters( - createTagEchoFilter((snippet) => { - loggerLog("warn", `[tag-echo] stripped model-emitted render tag: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); - }), - createMarkerLineFilter((snippet) => { - loggerLog("warn", `[marker-echo] stripped model-emitted ACP confirmation marker: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + composeStreamFilters( + createTagEchoFilter((snippet) => { + loggerLog("warn", `[tag-echo] stripped model-emitted render tag: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + }), + createMarkerLineFilter((snippet) => { + 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, " ")}`); }), ); const flushFilter = function* (): Generator { diff --git a/src/loop/adapter-openai.ts b/src/loop/adapter-openai.ts index 0ec93fb156..7a5c15e566 100644 --- a/src/loop/adapter-openai.ts +++ b/src/loop/adapter-openai.ts @@ -1,7 +1,7 @@ import type { CoreMessage } from "acp-kernel"; import { coreToOpenai, injectOpenaiSystem } from "acp-kernel/wire"; import { buildVisibilityMarker } from "./core.js"; -import { composeStreamFilters, createMarkerLineFilter, createTagEchoFilter } from "./tag-echo-filter.js"; +import { composeStreamFilters, createBiliArtifactFilter, createMarkerLineFilter, createTagEchoFilter } from "./tag-echo-filter.js"; import { degenerateTurnWarning } from "../degenerate-turn.js"; import { log as loggerLog } from "../logger.js"; import { hardenOpenaiAssistantContent, systemToUser } from "../util.js"; @@ -218,11 +218,16 @@ export function createOpenaiAdapter(requestBody: Record, client // #206: strip model-imitated render tags from content deltas; the // filter may hold back a short tail, flushed at finish/[DONE]. const tagFilter = composeStreamFilters( - createTagEchoFilter((snippet) => { - loggerLog("warn", `[tag-echo] stripped model-emitted render tag: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); - }), - createMarkerLineFilter((snippet) => { - loggerLog("warn", `[marker-echo] stripped model-emitted ACP confirmation marker: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + composeStreamFilters( + createTagEchoFilter((snippet) => { + loggerLog("warn", `[tag-echo] stripped model-emitted render tag: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + }), + createMarkerLineFilter((snippet) => { + 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, " ")}`); }), ); const flushFilter = function* (): Generator { diff --git a/src/loop/adapter-responses.ts b/src/loop/adapter-responses.ts index 1e7e791633..fed25a9aea 100644 --- a/src/loop/adapter-responses.ts +++ b/src/loop/adapter-responses.ts @@ -4,7 +4,7 @@ import { coreToResponsesWithToolImages as coreToResponses, patchResponsesInputWi import { buildVisibilityMarker } from "./core.js"; import { hoistTrappedToolItems } from "../tool-pair-order.js"; import { hashId } from "../util.js"; -import { composeStreamFilters, createMarkerLineFilter, createTagEchoFilter, stripResponsesText, containsMarkerLineText, containsRenderTagText, ACP_NAME_ALT } from "./tag-echo-filter.js"; +import { composeStreamFilters, createBiliArtifactFilter, createMarkerLineFilter, createTagEchoFilter, stripResponsesText, containsBiliInternalText, containsMarkerLineText, containsRenderTagText, ACP_NAME_ALT } from "./tag-echo-filter.js"; import { degenerateTurnWarning } from "../degenerate-turn.js"; import { log as loggerLog } from "../logger.js"; import { extractResponsesTextTriggers, PROXY_TOOL_NAMES } from "../compress-tool.js"; @@ -334,11 +334,16 @@ export function createResponsesAdapter(textProtocol?: boolean, projection?: Resp // full-text events (.done / output_item.done / completed response) // are stripped wholesale via stripResponsesText. const tagFilter = composeStreamFilters( - createTagEchoFilter((snippet) => { - loggerLog("warn", `[tag-echo] stripped model-emitted render tag: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); - }), - createMarkerLineFilter((snippet) => { - loggerLog("warn", `[marker-echo] stripped model-emitted ACP confirmation marker: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + composeStreamFilters( + createTagEchoFilter((snippet) => { + loggerLog("warn", `[tag-echo] stripped model-emitted render tag: ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + }), + createMarkerLineFilter((snippet) => { + 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, " ")}`); }), ); let lastTextRef: { itemId: string; outputIndex: number } | null = null; @@ -430,7 +435,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)) ? rebuildResponsesEvent(type, stripResponsesText(obj)) : rawBuf; + const chunk = (containsRenderTagText(eventStr) || containsMarkerLineText(eventStr) || containsBiliInternalText(eventStr)) ? rebuildResponsesEvent(type, stripResponsesText(obj)) : rawBuf; yield { kind: "meta", chunk, firstRoundOnly: true } as ParsedStreamEvent; } } else if (type === "response.output_text.delta") { @@ -515,7 +520,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)) ? rebuildResponsesEvent(type, stripResponsesText(obj)) : rawBuf; + const chunk = (containsRenderTagText(eventStr) || containsMarkerLineText(eventStr) || containsBiliInternalText(eventStr)) ? rebuildResponsesEvent(type, stripResponsesText(obj)) : rawBuf; yield { kind: "meta", chunk, firstRoundOnly: true } as ParsedStreamEvent; } } else if (item?.type !== "message" || !suppressTextLifecycle) { diff --git a/src/loop/tag-echo-filter.ts b/src/loop/tag-echo-filter.ts index 6812ee5cc1..736c312a78 100644 --- a/src/loop/tag-echo-filter.ts +++ b/src/loop/tag-echo-filter.ts @@ -1,3 +1,6 @@ +import { parseChainCheckpoint, TAG_OPEN } from "../chain-checkpoint.js"; +import { CODEX_FORGED_HANDOFF_HEADER, FORGED_SUMMARY_HEADER } from "../codex-compact.js"; + // Streaming-safe stripper for model-emitted literal ACP render tags (#206). // Compressed history is rendered to the model as render tags; models sometimes // imitate them in visible output ("tag echo"), the client replays the echoed @@ -205,13 +208,14 @@ export function stripAcpTags(text: string): string { if (wrapped === null) break; out = out.slice(0, wrapped.start) + out.slice(wrapped.end); } - return out + out = out .replace(new RegExp(PAIRED.source, "g"), "") .replace(new RegExp(LONE_OPEN.source, "g"), "") .replace(new RegExp(LONE_CLOSE.source, "g"), "") .replace(new RegExp(TRUNC_OPEN.source), "") .replace(new RegExp(TRUNC_CLOSE.source), "") .replace(MARKER_LINE, ""); + return stripBiliArtifacts(out); } // Raw-wire pre-check for forged confirmation markers (#717): the literal @@ -253,6 +257,228 @@ export function containsToolCallXmlFragment(s: string): boolean { return TOOL_CALL_XML.test(s); } +// ─── #1634: bili-owned internal artifacts echoed by the model ─────────────── +// The proxy injects three artifact families into model-visible payloads: the +// outbound checkpoint carrier (\x3cbili-chain \u2026/\x3e stamped onto forwarded requests), +// the forged-compaction handoff user message, and captured summary blocks (the +// latter two carry fixed header lines). Under sustained context pressure +// models were observed restating these verbatim as their answer to the user's +// turn, and the echoes persist turn over turn because they ride client +// history — the render-tag/marker strippers above know none of these shapes. +// Real carriers never traverse the model-output path (the proxy writes them +// itself), so any occurrence in model output is model-generated by definition: +// strip it, breaking the self-reinforcing loop. Recognition keys off the SAME +// constants the injectors use (single source of truth): chain spans validate +// through the frozen checkpoint parser, headers match literally at line start +// (a mid-line mention such as "the [Compressed conversation section] covers…" +// is prose and passes through). +const CHAIN_OPEN_ESCAPED = "\\u003c" + TAG_OPEN.slice(1); +const CHAIN_TERMINATORS = ['"/\x3e', "/\\u003e", "\\u002f\\u003e"]; +// A real carrier runs \u2264~200 chars (parser ceiling 512); a longer +// unterminated opening is fabricated, not truncated-in-transit. +const CHAIN_TAIL_CAP = 640; + +function unescapeBili(s: string): string { + return s.replace(/\\u003c/g, "\x3c").replace(/\\u003e/g, "\x3e").replace(/\\u002f/g, "/"); +} + +/** Exclusive end index of the first chain-tag terminator in rest, or -1. */ +function chainTerminatorEnd(rest: string): number { + let best = -1; + for (const t of CHAIN_TERMINATORS) { + const i = rest.indexOf(t); + if (i >= 0 && (best < 0 || i < best)) best = i + t.length; + } + return best; +} + +/** Index of the first chain-tag opening (literal or \u003c-escaped form), or -1. */ +function chainOpenIndex(s: string): number { + const i = s.indexOf(TAG_OPEN); + const ie = s.indexOf(CHAIN_OPEN_ESCAPED); + if (ie >= 0 && (i < 0 || ie < i)) return ie; + return i; +} + +/** Span of the next WELL-FORMED checkpoint carrier in s (validated by the + * frozen parser after unescaping), or null. Malformed/unterminated openings + * are NOT spans here: they stay in place for the streaming tail logic, where + * under-budget truncations are released as prose (content preservation). */ +export function nextChainSpan(s: string): { start: number; end: number } | null { + const i = chainOpenIndex(s); + if (i < 0) return null; + const rest = s.slice(i); + const end = chainTerminatorEnd(rest); + if (end <= 0) return null; + if (parseChainCheckpoint(unescapeBili(rest.slice(0, end))) === null) return null; + return { start: i, end: i + end }; +} + +/** Cut point of a header-led block: position 0 or immediately after a newline + * where the text starts with either internal-artifact header — everything + * from the cut to the END of the text field is the block (streaming flush + * discards the remainder; whole-text slicing mirrors it). */ +export function headBlockCut(s: string): number { + if (s.startsWith(CODEX_FORGED_HANDOFF_HEADER) || s.startsWith(FORGED_SUMMARY_HEADER)) return 0; + let nl = s.indexOf("\n"); + while (nl >= 0) { + const p = nl + 1; + if (s.startsWith(CODEX_FORGED_HANDOFF_HEADER, p) || s.startsWith(FORGED_SUMMARY_HEADER, p)) return p; + nl = s.indexOf("\n", nl + 1); + } + return -1; +} + +export function stripBiliArtifacts(text: string): string { + let out = text; + for (;;) { + const span = nextChainSpan(out); + if (span === null) break; + out = out.slice(0, span.start) + out.slice(span.end); + } + const cut = headBlockCut(out); + return cut >= 0 ? out.slice(0, cut) : out; +} + +// Raw-wire pre-check (SSE event or JSON body): does it carry anything the +// bili-artifact stripper would act on? Literal and \u003c-escaped chain opens +// plus the two header lines (plain ASCII, survive JSON escaping unscathed). +export function containsBiliInternalText(s: string): boolean { + return s.includes(TAG_OPEN) + || s.includes(CHAIN_OPEN_ESCAPED) + || s.includes(CODEX_FORGED_HANDOFF_HEADER) + || s.includes(FORGED_SUMMARY_HEADER); +} + +function reEscape(s: string): string { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +function prefixAlts(s: string, minLen: number): string[] { + const out: string[] = []; + for (let k = minLen; k < s.length; k++) out.push(reEscape(s.slice(0, k))); + return out; +} + +// Streaming tail probes: a buffer cut mid-opening ends in the opening's +// leading chars, so the held tail is any prefix of either open form (plus the +// complete forms); a last line that is still a prefix of a header is held +// from its first char — a lone line-start "[" must survive chunk boundaries +// because both headers begin with it and the decision splits on the second +// char (broad-hold/strict-decide, same trade as MARKER_HEAD_PREFIX). +const CHAIN_PARTIAL_TAIL = new RegExp("(" + [...new Set([ + ...prefixAlts(TAG_OPEN, 1), + reEscape(TAG_OPEN), + ...prefixAlts(CHAIN_OPEN_ESCAPED, 1), + reEscape(CHAIN_OPEN_ESCAPED), +])].join("|") + ")$"); +const HEAD_PREFIX_TAIL = new RegExp("(?:^|\n)(" + [...new Set([ + ...prefixAlts(CODEX_FORGED_HANDOFF_HEADER, 1), + ...prefixAlts(FORGED_SUMMARY_HEADER, 1), +])].join("|") + ")$"); + +/** Fast-path gate for the streaming pipes: could this chunk contain a bili + * internal artifact, or leave one undecidable across the chunk boundary? + * Coarse by design — a false positive costs one no-op filter pass, but + * skipping a chunk that carries or starts an artifact forwards it raw. */ +export function mayStartBiliInternal(s: string): boolean { + return containsBiliInternalText(s) || CHAIN_PARTIAL_TAIL.test(s) || HEAD_PREFIX_TAIL.test(s); +} + +function tailHoldLen(s: string): number { + const m = CHAIN_PARTIAL_TAIL.exec(s); + const h = HEAD_PREFIX_TAIL.exec(s); + return Math.max(m ? m[0].length : 0, h ? h[0].length : 0); +} + +export function createBiliArtifactFilter(onDrop?: (snippet: string) => void): TagEchoFilter { + let buf = ""; + let swallowing = false; + let droppedAny = false; + let notified = false; + let inputChars = 0; + let outputChars = 0; + const drop = (snippet: string) => { + droppedAny = true; + if (onDrop && !notified) { + notified = true; + onDrop(snippet); + } + }; + const process = (input: string): string => { + inputChars += input.length; + if (swallowing) return ""; + buf += input; + let out = ""; + let openHeld = false; + for (;;) { + const cut = headBlockCut(buf); + if (cut >= 0) { + out += buf.slice(0, cut); + drop(buf.slice(cut)); + swallowing = true; + buf = ""; + break; + } + const span = nextChainSpan(buf); + if (span !== null) { + out += buf.slice(0, span.start); + drop(buf.slice(span.start, span.end)); + buf = buf.slice(span.end); + continue; + } + const oi = chainOpenIndex(buf); + if (oi >= 0) { + out += buf.slice(0, oi); + const tail = buf.slice(oi); + if (tail.length > CHAIN_TAIL_CAP) { + // Over cap without a terminator: not a real carrier (those + // are bounded far below the cap) — release as prose, never + // drop (#1039 content preservation, cf. #644). + out += tail; + buf = ""; + } else { + buf = tail; + openHeld = true; + } + break; + } + break; + } + if (!swallowing && buf.length > 0 && !openHeld) { + const hold = tailHoldLen(buf); + if (hold > 0) { + out += buf.slice(0, buf.length - hold); + buf = buf.slice(buf.length - hold); + } else { + out += buf; + buf = ""; + } + } + outputChars += out.length; + return out; + }; + return { + push: process, + flush(): string { + let out = ""; + if (swallowing) { + if (buf.length > 0) drop(buf); + buf = ""; + swallowing = false; + } else if (buf.length > 0) { + out = buf; + buf = ""; + } + outputChars += out.length; + return out; + }, + dropped: () => droppedAny, + pending: () => buf.length > 0 || swallowing, + stats: () => ({ inputChars, outputChars, dropped: droppedAny }), + }; +} + export function createTagEchoFilter(onDrop?: (snippet: string) => void): TagEchoFilter { let held = ""; let swallowUntilClose = false; diff --git a/src/plugin.ts b/src/plugin.ts index c30ed03c89..1c6a691104 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -11,7 +11,7 @@ import { absorbEnabled, effectiveAbsorbConfig, isProxyToolFor } from "./absorb.j import { effectiveRulesEnabled, rulesEnabled } from "./rules-feature.js"; import { executeProxyTool } from "./loop/core.js"; import { normalizeSseLineEndings } from "./sse-util.js"; -import { composeStreamFilters, containsMarkerLineText, containsRenderTagText, containsToolCallXmlFragment, createMarkerLineFilter, createTagEchoFilter, mayStartMarkerLine, mayStartRenderTag, stripAcpTags, stripAnthropicText, stripOpenaiChatText, stripResponsesText, type TagEchoFilter } from "./loop/tag-echo-filter.js"; +import { composeStreamFilters, containsBiliInternalText, containsMarkerLineText, containsRenderTagText, containsToolCallXmlFragment, createBiliArtifactFilter, createMarkerLineFilter, createTagEchoFilter, mayStartBiliInternal, mayStartMarkerLine, mayStartRenderTag, stripAcpTags, stripAnthropicText, stripOpenaiChatText, stripResponsesText, type TagEchoFilter } from "./loop/tag-echo-filter.js"; import { log as loggerLog } from "./logger.js"; import { ccrEnabled, ccrLoopConfig, contentStoreOf, retrieveToolName } from "./store.js"; import { imageUsageSuffix } from "./image-compress.js"; @@ -1209,6 +1209,11 @@ export async function pipePluginChatWithStrip( loggerLog("warn", `[marker-echo] stripped model-emitted ACP confirmation marker (plugin passthrough): ${snippet.slice(0, 80).replace(/\n/g, " ")}`); log?.(`[marker-echo] stripped model-emitted ACP confirmation marker from plugin passthrough text`); }; + const onBiliDrop = (snippet: string) => { + sawStrippedEcho = true; + loggerLog("warn", `[bili-artifact] stripped model-emitted internal artifact (plugin passthrough): ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + log?.(`[bili-artifact] stripped model-emitted internal artifact from plugin passthrough text`); + }; // 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. @@ -1222,7 +1227,7 @@ export async function pipePluginChatWithStrip( const key = `${field}:${index}`; let s = streams.get(key); if (!s) { - s = { filter: composeStreamFilters(createTagEchoFilter(onTagDrop), createMarkerLineFilter(onMarkerDrop)), field, index }; + s = { filter: composeStreamFilters(composeStreamFilters(createTagEchoFilter(onTagDrop), createMarkerLineFilter(onMarkerDrop)), createBiliArtifactFilter(onBiliDrop)), field, index }; streams.set(key, s); } return s; @@ -1533,7 +1538,7 @@ export async function pipePluginChatWithStrip( // leap ahead of a held tail. if (v.length > 0) hadText = true; if (field !== "content" && v.length > 0) sawThinking = true; - if (!mayStartRenderTag(v) && !mayStartMarkerLine(v) && !anyPending()) { + if (!mayStartRenderTag(v) && !mayStartMarkerLine(v) && !mayStartBiliInternal(v) && !anyPending()) { if (v.length > 0) { keptText = true; proseAcc += v; @@ -1635,7 +1640,7 @@ export async function pipePluginChatWithStrip( } const raw = d[field] as string; if (field === "thinking" && raw.length > 0) sawThinking = true; - if (!mayStartRenderTag(raw) && !mayStartMarkerLine(raw) && !anyPending()) { + if (!mayStartRenderTag(raw) && !mayStartMarkerLine(raw) && !mayStartBiliInternal(raw) && !anyPending()) { if (raw.length > 0) proseAcc += raw; if (field === "text" && raw.length > 0) visibleTextChars += raw.length; return rawEvent + "\n\n"; @@ -1720,7 +1725,7 @@ export async function pipePluginChatWithStrip( // field, so an interleaved thought/text pair in one frame never // shares held-back state. const field = p["thought"] === true ? "thinking" : "text"; - if (!mayStartRenderTag(raw) && !mayStartMarkerLine(raw) && !anyPending()) { + if (!mayStartRenderTag(raw) && !mayStartMarkerLine(raw) && !mayStartBiliInternal(raw) && !anyPending()) { if (raw.length > 0) { keptText = true; proseAcc += raw; @@ -1994,12 +1999,19 @@ export async function pipePluginResponsesWithStrip( loggerLog("warn", `[tag-echo] stripped model-emitted render tag (plugin passthrough): ${snippet.slice(0, 80).replace(/\n/g, " ")}`); log?.(`[tag-echo] stripped model-emitted render tag from plugin passthrough text`); }; + const onBiliDrop = (snippet: string) => { + loggerLog("warn", `[bili-artifact] stripped model-emitted internal artifact (plugin passthrough): ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + log?.(`[bili-artifact] stripped model-emitted internal artifact from plugin passthrough text`); + }; const tagFilter = composeStreamFilters( - createTagEchoFilter(onTagDrop), - createMarkerLineFilter((snippet) => { - loggerLog("warn", `[marker-echo] stripped model-emitted ACP confirmation marker (plugin passthrough): ${snippet.slice(0, 80).replace(/\n/g, " ")}`); - log?.(`[marker-echo] stripped model-emitted ACP confirmation marker from plugin passthrough text`); - }), + composeStreamFilters( + createTagEchoFilter(onTagDrop), + createMarkerLineFilter((snippet) => { + loggerLog("warn", `[marker-echo] stripped model-emitted ACP confirmation marker (plugin passthrough): ${snippet.slice(0, 80).replace(/\n/g, " ")}`); + log?.(`[marker-echo] stripped model-emitted ACP confirmation marker from plugin passthrough text`); + }), + ), + createBiliArtifactFilter(onBiliDrop), ); // #673: turn-level observability for degenerate terminal turns. let sawFunctionCall = false; @@ -2212,7 +2224,7 @@ export async function pipePluginResponsesWithStrip( for (const k of ["item_id", "output_index", "summary_index"]) { if (ev[k] !== undefined) meta[k] = ev[k]; } - s = { filter: createTagEchoFilter(onTagDrop), type, field, meta }; + s = { filter: composeStreamFilters(createTagEchoFilter(onTagDrop), createBiliArtifactFilter(onBiliDrop)), type, field, meta }; argStreams.set(key, s); } return s; @@ -2288,7 +2300,7 @@ export async function pipePluginResponsesWithStrip( // The done is not visible text to the degenerate-turn retry below, so it // is stripped and released directly. if (type === "response.reasoning_summary_part.done") { - const hadEcho = containsRenderTagText(jsonStr) || containsMarkerLineText(jsonStr); + const hadEcho = containsRenderTagText(jsonStr) || containsMarkerLineText(jsonStr) || containsBiliInternalText(jsonStr); if (hadEcho) sawStrippedEcho = true; const evOut = hadEcho ? stripResponsesText(ev) : ev; proseAcc += responsesEventText(evOut); @@ -2301,7 +2313,7 @@ export async function pipePluginResponsesWithStrip( // retryEmptyTurn): releasing it earlier would hand the // client the echo's own text exactly when the retry is // about to replace it. - const hadEchoText = containsRenderTagText(jsonStr) || containsMarkerLineText(jsonStr); + const hadEchoText = containsRenderTagText(jsonStr) || containsMarkerLineText(jsonStr) || containsBiliInternalText(jsonStr); if (hadEchoText) sawStrippedEcho = true; let evOut = ev; let rebuild = hadEchoText || retryRewritePending(); @@ -2351,7 +2363,7 @@ export async function pipePluginResponsesWithStrip( heldVisibleChars = 0; // The completion frame itself closes the turn: strip it if it // carries echoed text, rewrite retry ids onto the first attempt's. - const hadEchoText = containsRenderTagText(jsonStr) || containsMarkerLineText(jsonStr); + const hadEchoText = containsRenderTagText(jsonStr) || containsMarkerLineText(jsonStr) || containsBiliInternalText(jsonStr); if (hadEchoText) sawStrippedEcho = true; let evOut = ev; let rebuild = hadEchoText || retryRewritePending(); @@ -2366,7 +2378,7 @@ export async function pipePluginResponsesWithStrip( await write(rawEvent + "\n\n"); continue; } - if (!retryRewritePending() && !mayStartRenderTag(delta) && !mayStartMarkerLine(delta) && !tagFilter.pending()) { + if (!retryRewritePending() && !mayStartRenderTag(delta) && !mayStartMarkerLine(delta) && !mayStartBiliInternal(delta) && !tagFilter.pending()) { proseAcc += delta; await write(rawEvent + "\n\n"); continue; @@ -2402,7 +2414,7 @@ export async function pipePluginResponsesWithStrip( await write(rawEvent + "\n\n"); continue; } - if (!mayStartRenderTag(v) && !argAnyPending() && !tagFilter.pending()) { + if (!mayStartRenderTag(v) && !mayStartBiliInternal(v) && !argAnyPending() && !tagFilter.pending()) { proseAcc += v; await write(rawEvent + "\n\n"); continue; @@ -2595,7 +2607,7 @@ export async function pipePluginJson( // #1595: parsed success body carrying no input usage report — name it. if (session && !sawInputSample) diagnoseSuccessWithoutUsage(session, "plugin-json"); } catch { /* non-JSON body — forward verbatim */ } - if (json && (containsRenderTagText(text) || containsMarkerLineText(text))) { + if (json && (containsRenderTagText(text) || containsMarkerLineText(text) || containsBiliInternalText(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/server.ts b/src/server.ts index ded51b5f4e..a199b73db1 100644 --- a/src/server.ts +++ b/src/server.ts @@ -4002,6 +4002,7 @@ async function prepareResponses( if (absorbActive) devParts.push(buildAbsorbSystemPrompt(absorbToolName(loopConfig))); const devContent = devParts.join("\n\n---\n\n"); responsesDevContent = devContent; + if (forgedSummaries.length > 0) log("debug", `[${sessionId}] [inject] ${forgedSummaries.length} captured summary block(s) re-injected into developer message`); rebuiltInput = injectResponsesDeveloperMessage(rebuiltInput, devContent); if (!process.env.ACP_NO_INJECT_TOOL && injectTools) { const respExtra = [...(absorbActive ? [absorbTools.responses] : []), ...(rulesActive ? [RULE_TOOL_RESPONSES] : []), ...(ccrEnabled(session) ? [retrieveToolsFor(retrieveToolName(session)).responses] : []), ...(imageCompressionEnabled(session) ? [IMAGE_FULL_TOOL_RESPONSES] : [])]; @@ -4012,6 +4013,7 @@ async function prepareResponses( } else if (projection.systemParts.length > 0 || forgedSummaries.length > 0) { const devContent = [...projection.systemParts, ...forgedSummaries].join("\n\n---\n\n"); responsesDevContent = devContent; + if (forgedSummaries.length > 0) log("debug", `[${sessionId}] [inject] ${forgedSummaries.length} captured summary block(s) re-injected into developer message`); rebuiltInput = injectResponsesDeveloperMessage(rebuiltInput, devContent); } if (sysNotes.length > 0) { @@ -4039,6 +4041,7 @@ async function prepareResponses( : rebuiltInput; inputItems.push({ type: "message", role: "user", content: withMarkerIntegrityNote(withSummaryBudgetNote(withStagedCompressGuidance(rendered.text)), visibilityMarkers) }); rebuiltInput = inputItems; + log("debug", `[${sessionId}] [inject] ephemeral nudge appended as trailing user turn (${rendered.text.length} chars)`); } } catch { } @@ -4054,6 +4057,7 @@ async function prepareResponses( : rebuiltInput; inputItems.push({ type: "message", role: "user", content: imgNote }); rebuiltInput = inputItems; + log("debug", `[${sessionId}] [inject] image-full restore note appended as trailing user turn (${imgNote.length} chars)`); } transformOk = true; } catch (err) { @@ -5105,7 +5109,10 @@ async function forward( if (prepared && !prepared.sidePassthrough && prepared.processedMessages.length > 0 && typeof wireBody === "string" && opts.chainContentDetection !== false) { try { const stamped = stampOutbound(JSON.parse(wireBody), prepared.protocol, instanceId); - if (stamped !== null) wireBody = JSON.stringify(stamped); + if (stamped !== null) { + wireBody = JSON.stringify(stamped); + log("debug", `[${prepared.session.id}] [stamp] outbound ${prepared.protocol} request carries checkpoint carrier`); + } } catch (err) { log("debug", `[${prepared.session.id}] [chain] outbound stamping failed (${String(err)}); forwarding unstamped`); } diff --git a/src/stream-google.ts b/src/stream-google.ts index c6cd607b61..f67528f0a5 100644 --- a/src/stream-google.ts +++ b/src/stream-google.ts @@ -5,7 +5,7 @@ import { isProxyToolFor } from "./absorb.js"; import { executeProxyTool } from "./loop/core.js"; import { drainPendingRetrievals } from "./store.js"; import type { RewriteCtx } from "./stream.js"; -import { containsMarkerLineText, containsRenderTagText, stripAcpTags } from "./loop/tag-echo-filter.js"; +import { containsBiliInternalText, containsMarkerLineText, containsRenderTagText, stripAcpTags } from "./loop/tag-echo-filter.js"; export function rewriteGoogleJsonResponse(body: unknown, ctx: RewriteCtx): unknown { if (!body || typeof body !== "object") return body; @@ -30,8 +30,8 @@ export function rewriteGoogleJsonResponse(body: unknown, ctx: RewriteCtx): unkno continue; } if (fc) sawReal = true; - if (typeof part.text === "string" && (containsRenderTagText(part.text) || containsMarkerLineText(part.text))) { - ctx.log(`[warn: tag echo] non-stream google output contains ACP echo (render tags/markers), stripped: ${part.text.slice(0, 120).replace(/\n/g, " ")}`); + if (typeof part.text === "string" && (containsRenderTagText(part.text) || containsMarkerLineText(part.text) || containsBiliInternalText(part.text))) { + ctx.log(`[warn: tag echo] non-stream google output contains ACP echo (render tags/markers/internal artifacts), stripped: ${part.text.slice(0, 120).replace(/\n/g, " ")}`); part.text = stripAcpTags(part.text); } keptParts.push(part); diff --git a/src/stream-openai.ts b/src/stream-openai.ts index 4d8ac7743d..39a66555c9 100644 --- a/src/stream-openai.ts +++ b/src/stream-openai.ts @@ -2,7 +2,7 @@ import type { CompressionCore, Config, CoreMessage } from "acp-kernel"; import type { Session } from "./session.js"; import { COMPRESS_TOOL_NAME, parseCompressInput } from "./compress-tool.js"; import { applyRanges, type RewriteCtx } from "./stream.js"; -import { containsMarkerLineText, containsRenderTagText, stripAcpTags } from "./loop/tag-echo-filter.js"; +import { containsBiliInternalText, containsMarkerLineText, containsRenderTagText, stripAcpTags } from "./loop/tag-echo-filter.js"; export function rewriteOpenaiJsonResponse(body: unknown, ctx: RewriteCtx): unknown { if (!body || typeof body !== "object") return body; @@ -41,8 +41,8 @@ export function rewriteOpenaiJsonResponse(body: unknown, ctx: RewriteCtx): unkno ctx.log(`[warn: nameless tool call] non-stream openai response carries ${namelessToolCallIdx.length} nameless tool_call(s) at index ${namelessToolCallIdx.join(",")} — forwarded verbatim (#1501 observe-only)`); } } - if (existingText && (containsRenderTagText(existingText) || containsMarkerLineText(existingText))) { - ctx.log(`[warn: tag echo] non-stream openai output contains ACP echo (render tags/markers), stripped: ${existingText.slice(0, 120).replace(/\n/g, " ")}`); + if (existingText && (containsRenderTagText(existingText) || containsMarkerLineText(existingText) || containsBiliInternalText(existingText))) { + ctx.log(`[warn: tag echo] non-stream openai output contains ACP echo (render tags/markers/internal artifacts), stripped: ${existingText.slice(0, 120).replace(/\n/g, " ")}`); existingText = stripAcpTags(existingText); msg.content = existingText; } diff --git a/src/stream-responses.ts b/src/stream-responses.ts index 5e9a396595..8442681c31 100644 --- a/src/stream-responses.ts +++ b/src/stream-responses.ts @@ -2,7 +2,7 @@ import type { CompressionCore, Config, CoreMessage } from "acp-kernel"; import type { Session } from "./session.js"; import { COMPRESS_TOOL_NAME, parseCompressInput } from "./compress-tool.js"; import { applyRanges, type RewriteCtx } from "./stream.js"; -import { containsMarkerLineText, containsRenderTagText, stripResponsesText } from "./loop/tag-echo-filter.js"; +import { containsBiliInternalText, containsMarkerLineText, containsRenderTagText, stripResponsesText } from "./loop/tag-echo-filter.js"; /** * Responses API (non-streaming) JSON rewriter: strips compress function_call @@ -25,8 +25,8 @@ export function rewriteResponsesJsonResponse(body: unknown, ctx: RewriteCtx): un // every body — before the compress note is synthesized (so the record we // inject is never edited) and before the !converted early return below // (which previously handed a tag-bearing body back untouched). - if (containsRenderTagText(probe) || containsMarkerLineText(probe)) { - ctx.log(`[warn: tag echo] non-stream responses output contains ACP echo (render tags/markers), stripped: ${probe.slice(0, 120).replace(/\n/g, " ")}`); + if (containsRenderTagText(probe) || containsMarkerLineText(probe) || containsBiliInternalText(probe)) { + ctx.log(`[warn: tag echo] non-stream responses output contains ACP echo (render tags/markers/internal artifacts), stripped: ${probe.slice(0, 120).replace(/\n/g, " ")}`); stripResponsesText(b); } let converted = false; diff --git a/src/stream.ts b/src/stream.ts index 9c813ab42e..4657175b38 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -7,7 +7,7 @@ import { effectiveAbsorbConfig, executeAbsorb, isProxyToolFor } from "./absorb.j import { executeSearchContextTarget, resolveDecompress } from "./decompress-shared.js"; import { adoptContentStore, contentStoreOf, ccrEnabled, drainPendingRetrievals, executeRetrieve, retrieveToolName } from "./store.js"; import { IMAGE_FULL_TOOL_NAME, executeImageFull, imageCompressionEnabled } from "./image-compress.js"; -import { containsMarkerLineText, containsRenderTagText, stripAcpTags } from "./loop/tag-echo-filter.js"; +import { containsBiliInternalText, containsMarkerLineText, containsRenderTagText, stripAcpTags } from "./loop/tag-echo-filter.js"; import { maxShrinkPerCompress } from "./fetch-util.js"; import { safePrefix, safeSuffix, scrubLoneSurrogates } from "./text-safe.js"; @@ -517,8 +517,8 @@ export function rewriteJsonResponse(body: unknown, ctx: RewriteCtx): unknown { if (converted && !sawRealToolUse) b.stop_reason = "end_turn"; for (const blk of newContent) { const t = (blk as { type?: string; text?: string }).text; - if (typeof t === "string" && (containsRenderTagText(t) || containsMarkerLineText(t))) { - ctx.log(`[warn: tag echo] non-stream model output contains ACP echo (render tags/markers), stripped: ${t.slice(0, 120).replace(/\n/g, " ")}`); + if (typeof t === "string" && (containsRenderTagText(t) || containsMarkerLineText(t) || containsBiliInternalText(t))) { + ctx.log(`[warn: tag echo] non-stream model output contains ACP echo (render tags/markers/internal artifacts), stripped: ${t.slice(0, 120).replace(/\n/g, " ")}`); (blk as { text?: string }).text = stripAcpTags(t); } } diff --git a/tests/bili-artifact-strip.test.ts b/tests/bili-artifact-strip.test.ts new file mode 100644 index 0000000000..495a6c8ebb --- /dev/null +++ b/tests/bili-artifact-strip.test.ts @@ -0,0 +1,197 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { renderChainCheckpoint } from "../src/chain-checkpoint.ts"; +import { CODEX_FORGED_HANDOFF_HEADER, FORGED_SUMMARY_HEADER, renderForgedSummary, replaceBiliCompactionItems } from "../src/codex-compact.ts"; +import { + stripAcpTags, + stripBiliArtifacts, + containsBiliInternalText, + mayStartBiliInternal, + createBiliArtifactFilter, + type TagEchoFilter, +} from "../src/loop/tag-echo-filter.ts"; + +const L = "\x3c"; +const R = "\x3e"; +const T0 = 1_758_864_000_000; +const GOOD_DIGEST = "sha256:" + "ab".repeat(32); +const FIELDS = { v: 1 as const, processor: "bili-a", issuedAt: T0, requestId: "req-1" }; +const tag = (over: Record = {}): string => + renderChainCheckpoint({ ...FIELDS, digest: GOOD_DIGEST, ...over }); +const ESC = "\\u003c"; +const escapedTag = (): string => tag().replace(L, ESC); +const REORDERED = `${L}bili-chain digest="${GOOD_DIGEST}" request-id="req-1" issued-at="${T0}" processor="bili-a" v="1"/${R}`; +const NO_DIGEST = `${L}bili-chain v="1" processor="bili-a" issued-at="${T0}" request-id="req-1"/${R}`; +const TRUNCATED = tag().slice(0, 40); +const H1 = CODEX_FORGED_HANDOFF_HEADER; +const H2 = FORGED_SUMMARY_HEADER; + +test("whole-text: well-formed chain carrier is stripped wherever it sits", () => { + assert.equal(stripBiliArtifacts(`before ${tag()} after`), "before after"); + assert.equal(stripBiliArtifacts(tag()), ""); + assert.equal(stripBiliArtifacts(`${tag()}mid${tag()}`), "mid"); +}); + +test("whole-text: well-formedness matrix (reorder strips, missing digest / truncation keep)", () => { + assert.equal(stripBiliArtifacts(`x ${REORDERED} y`), "x y", "attr order is irrelevant to recognition"); + assert.ok(stripBiliArtifacts(NO_DIGEST).includes("bili-chain"), "missing digest → prose preserved"); + assert.ok(stripBiliArtifacts(TRUNCATED).includes("bili-chain"), "truncated opening → prose preserved"); + assert.ok(stripBiliArtifacts(`${L}bili-chain v="99" processor="p" issued-at="${T0}" request-id="r" digest="${GOOD_DIGEST}"${R}`).includes("bili-chain"), "wrong self-close → prose preserved"); +}); + +test("whole-text: \\u003c-escaped chain form is stripped after unescaping", () => { + assert.equal(stripBiliArtifacts(`pre ${escapedTag()} post`), "pre post"); + const halfEscaped = tag().replace(L, ESC).replace(R, "\\u003e"); + assert.equal(stripBiliArtifacts(halfEscaped), "", "escaped close handled too"); +}); + +test("whole-text: header blocks cut to end of text at position 0 or line start only", () => { + assert.equal(stripBiliArtifacts(`${H1}\nsummary body\nmore`), ""); + assert.equal(stripBiliArtifacts(`intro\n${H2} — topic\nbody`), "intro\n"); + assert.equal(stripBiliArtifacts(`${H2} — topic\nbody`), ""); + assert.equal( + stripBiliArtifacts(`the ${H2} covers old turns`), + `the ${H2} covers old turns`, + "mid-line mention is prose", + ); + assert.equal( + stripBiliArtifacts(`See ${H1} for details.`), + `See ${H1} for details.`, + "mid-line mention is prose", + ); +}); + +test("whole-text: pure prose passes through byte-exact (incl. < tails and [b lines)", () => { + const prose = `a ${L} b and c\n[bob] said hi\n[Compressed data export done\nend`; + assert.equal(stripBiliArtifacts(prose), prose); +}); + +test("shared constants: every injector output is recognized by the stripper", () => { + assert.equal(stripBiliArtifacts(renderForgedSummary({ summary: "body", topic: "Topic X" })), ""); + assert.equal(stripBiliArtifacts(`${H1}\n${H2} — t\nbody`), ""); + const items = replaceBiliCompactionItems([{ type: "compaction", id: "fc_bili_x", encrypted_content: "bili:acp:summary payload" }] as never[]).items as Array<{ content?: Array<{ text?: string }> }>; + const handoff = items[0]?.content?.[0]?.text ?? ""; + assert.ok(handoff.startsWith(H1), "handoff message starts with the shared header constant"); + assert.equal(stripBiliArtifacts(handoff), "", "handoff message text is stripped as a header block"); +}); + +test("directionality: request-side stamped carrier survives request-path normalization byte-exact", () => { + // Output-side stripping targets carriers that come back FROM THE MODEL. The copy + // the proxy stamps into the outbound request itself never traverses those filters; + // pin that the request-path normalizer (responses wire, every request) leaves + // carrier-bearing message items untouched, so the direction premise ("output side + // only touches model output") survives future wire-shape changes. + const inline = { type: "message", role: "user" as const, content: [{ type: "input_text" as const, text: `real question ${tag()}` }] }; + const solo = { type: "message", role: "user" as const, content: [{ type: "input_text" as const, text: tag() }] }; + const { items, replaced, dropped } = replaceBiliCompactionItems([inline, solo] as never[]); + assert.equal(replaced, 0); + assert.equal(dropped, 0); + assert.equal(JSON.stringify(items), JSON.stringify([inline, solo]), "stamped request items pass through byte-exact"); +}); + +test("stripAcpTags folds bili artifacts: render tag + marker + chain carrier together", () => { + const mixed = `${L}acp tokens="1" type="text">m00155${R}/acp ignored\n📦 [ACP] Compressed m00876–m01100 → 1 block(s), ~54K tokens saved.\n${tag()} tail`; + const out = stripAcpTags(mixed); + assert.ok(!out.includes("acp tokens"), "render tag gone"); + assert.ok(!out.includes("[ACP]"), "marker line gone"); + assert.ok(!out.includes("bili-chain"), "chain carrier gone"); + assert.ok(out.trimEnd().endsWith("tail")); +}); + +test("pre-checks: contains/mayStart agree with the stripper on edge inputs", () => { + assert.ok(containsBiliInternalText(tag())); + assert.ok(containsBiliInternalText(escapedTag())); + assert.ok(containsBiliInternalText(H1)); + assert.ok(containsBiliInternalText(H2)); + assert.ok(!containsBiliInternalText("plain prose with and [brackets]")); + assert.ok(mayStartBiliInternal(`ends with open ${L}`)); + assert.ok(mayStartBiliInternal(`ends mid escape ${ESC.slice(0, 4)}`)); + assert.ok(mayStartBiliInternal("\n[Co")); + assert.ok(!mayStartBiliInternal("plain line ending in bracket [")); + assert.ok(!mayStartBiliInternal("[Code review notes]")); +}); + +function streamThrough(input: string, chunkSize: number, f?: TagEchoFilter): { out: string; filter: TagEchoFilter } { + const filter = f ?? createBiliArtifactFilter(); + let out = ""; + for (let i = 0; i < input.length; i += chunkSize) out += filter.push(input.slice(i, i + chunkSize)); + out += filter.flush(); + return { out, filter }; +} + +test("streaming: chain carrier stripped at every split point (literal + escaped, char-by-char)", () => { + for (const payload of [tag(), escapedTag(), `pre ${tag()} post`, `pre ${escapedTag()} post`]) { + for (const n of [1, 2, 3, 5, 7]) { + const { out, filter } = streamThrough(payload, n); + assert.ok(!out.includes("bili-chain") && !out.includes("u003c"), `chunk ${n}: carrier fully stripped, got ${JSON.stringify(out)}`); + assert.equal(filter.dropped(), true, `chunk ${n}: drop notified`); + } + const expected = payload.startsWith("pre ") ? "pre post" : ""; + assert.equal(streamThrough(payload, 1).out, expected, "char-by-char output exact"); + } +}); + +test("streaming: header block swallowed to end of field at every split point", () => { + const payload = `intro\n${H2} — topic\nbody continues`; + for (const n of [1, 2, 4, 9]) { + const { out, filter } = streamThrough(payload, n); + assert.equal(out, "intro\n", `chunk ${n}: block-to-end semantics, got ${JSON.stringify(out)}`); + assert.equal(filter.dropped(), true); + } +}); + +test("streaming: pure prose passes byte-exact including tricky boundaries", () => { + const prose = `a ${L} b\nc ${L}/d\n[bob] hi\n[Compressed data ok\nline`; + for (const n of [1, 2, 3]) { + const { out, filter } = streamThrough(prose, n); + assert.equal(out, prose, `chunk ${n}: byte-exact passthrough`); + assert.equal(filter.dropped(), false); + } +}); + +test("streaming: unterminated opening under budget is held then released as prose on flush", () => { + const filter = createBiliArtifactFilter(); + let out = filter.push(`hello ${L}bili-chain v=`); + out += filter.push(`1"`); + assert.equal(out, "hello ", "open tail withheld while decidable"); + assert.equal(filter.pending(), true); + out += filter.flush(); + assert.equal(out, `hello ${L}bili-chain v=1"`, "stream ended: truncated opening released as prose"); + assert.equal(filter.dropped(), false, "content preservation — no drop for truncated prose"); + assert.equal(filter.pending(), false); +}); + +test("streaming: over-cap unterminated opening releases as prose (never drops)", () => { + // Real carriers are bounded far below CHAIN_TAIL_CAP and always terminate; + // an over-cap unterminated tail is by definition not a carrier (truncated + // echoes, code discussion) and must pass through byte-exact (#1039/#644). + const filter = createBiliArtifactFilter(); + const input = `lead ${L}bili-chain ` + "x".repeat(700); + const out = filter.push(input) + filter.flush(); + assert.equal(out, input, "over-cap tail released as prose"); + assert.equal(filter.dropped(), false); +}); + +test("streaming: stats account for input/output/dropped consistently", () => { + const { filter } = streamThrough(tag(), 1); + const s = filter.stats(); + assert.equal(s.inputChars, tag().length); + assert.equal(s.outputChars, 0); + assert.equal(s.dropped, true); + const prose = "nothing to see"; + const p = streamThrough(prose, 3); + assert.equal(p.filter.stats().outputChars, prose.length); + assert.equal(p.filter.stats().dropped, false); +}); + +test("degenerate-turn gate parity: a fully forged turn yields zero visible output", () => { + // The retry gates (plugin.ts anthropic pipe: visibleTextChars > releasedMarkupChars || sawToolUse; + // responses pipe: visibleTextChars > 0 || heldVisibleChars > 0 || sawFunctionCall) fire when the + // clean output of a forged-metadata turn is empty. Pin that property. + for (const payload of [`${H1}\nsummary body`, `${H2} — t\nbody`, tag()]) { + const { out, filter } = streamThrough(payload, 1); + assert.equal(out.length, 0, "no visible chars survive a fully forged turn"); + assert.equal(filter.stats().outputChars, 0); + assert.equal(filter.dropped(), true); + } +});