From 66fd95325ceca721b21b0977be6beed13dd73ba5 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 26 Sep 2026 04:17:54 +0800 Subject: [PATCH 1/2] fix: warn on tool-call-shaped XML in plugin passthrough prose (#1368) --- src/plugin.ts | 56 ++++- .../plugin-passthrough-tool-xml-warn.test.ts | 208 ++++++++++++++++++ 2 files changed, 258 insertions(+), 6 deletions(-) create mode 100644 tests/plugin-passthrough-tool-xml-warn.test.ts diff --git a/src/plugin.ts b/src/plugin.ts index 70ad9f3545..806268547e 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -10,7 +10,7 @@ import { absorbEnabled, effectiveAbsorbConfig, isProxyToolFor } from "./absorb.j import { effectiveRulesConfig, rulesEnabled } from "./rules-feature.js"; import { executeProxyTool } from "./loop/core.js"; import { normalizeSseLineEndings } from "./sse-util.js"; -import { composeStreamFilters, containsMarkerLineText, containsRenderTagText, createMarkerLineFilter, createTagEchoFilter, mayStartMarkerLine, mayStartRenderTag, stripAcpTags, stripAnthropicText, stripOpenaiChatText, stripResponsesText, type TagEchoFilter } from "./loop/tag-echo-filter.js"; +import { composeStreamFilters, containsMarkerLineText, containsRenderTagText, containsToolCallXmlFragment, createMarkerLineFilter, createTagEchoFilter, mayStartMarkerLine, mayStartRenderTag, stripAcpTags, stripAnthropicText, stripOpenaiChatText, stripResponsesText, type TagEchoFilter } from "./loop/tag-echo-filter.js"; import { log as loggerLog } from "./logger.js"; import { ccrEnabled, contentStoreOf, retrieveToolName } from "./store.js"; import { imageUsageSuffix } from "./image-compress.js"; @@ -1180,6 +1180,9 @@ export async function pipePluginChatWithStrip( let sawToolUse = false; let sawThinking = false; let visibleTextChars = 0; + /** Post-filter prose of every attempt, for the once-per-request #361 + * tool-call-XML warn at stream end (#1368): warn only, never stripped. */ + let proseAcc = ""; /** Of that text, the chars released from a held markup span (the * unclosed-tag case): markup the filter declined to swallow. A turn whose * only visible output is this is as dead to the host as an empty one. */ @@ -1290,6 +1293,7 @@ export async function pipePluginChatWithStrip( const tail = s.filter.flush(); if (tail.length > 0) { out += syntheticTail(s, tail); + proseAcc += tail; if (s.field === "content" || s.field === "text") { visibleTextChars += tail.length; releasedMarkupChars += tail.length; @@ -1339,9 +1343,22 @@ export async function pipePluginChatWithStrip( log?.(msg); } }; + // #1368: parity with the proxy pipe's #361 detector (src/server.ts) — model + // prose carrying tool-call-shaped XML (a call drafted as literal text) is + // logged once per request for attribution. Warn only: stripping is + // forbidden, a shape-based match cannot tell an echo from legitimate prose + // discussing such markup (#295/#361). Off the per-frame hot path by design. + const maybeWarnProtocolFragment = () => { + if (proseAcc.length === 0 || !containsToolCallXmlFragment(proseAcc)) return; + const who = session ? `[${session.id}] ` : ""; + const msg = `[tag-echo] ${who}plugin passthrough: response text contains tool-call XML fragment (possible tag echo; not stripped)`; + loggerLog("warn", msg); + log?.(msg); + }; const pushField = (field: string, index: number, text: string): [string, boolean] => { const s = filterFor(field, index); const clean = s.filter.push(text); + if (clean.length > 0) proseAcc += clean; return [clean, clean !== text]; }; const processOpenai = (ev: Record, rawEvent: string): string => { @@ -1372,7 +1389,10 @@ export async function pipePluginChatWithStrip( hadText = true; if (field !== "content" && v.length > 0) sawThinking = true; if (!mayStartRenderTag(v) && !mayStartMarkerLine(v) && !anyPending()) { - if (v.length > 0) keptText = true; + if (v.length > 0) { + keptText = true; + proseAcc += v; + } if (field === "content") visibleTextChars += v.length; continue; } @@ -1434,6 +1454,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 (raw.length > 0) proseAcc += raw; if (field === "text" && raw.length > 0) visibleTextChars += raw.length; return rawEvent + "\n\n"; } @@ -1501,7 +1522,10 @@ export async function pipePluginChatWithStrip( // shares held-back state. const field = p["thought"] === true ? "thinking" : "text"; if (!mayStartRenderTag(raw) && !mayStartMarkerLine(raw) && !anyPending()) { - if (raw.length > 0) keptText = true; + if (raw.length > 0) { + keptText = true; + proseAcc += raw; + } if (field === "text") visibleTextChars += raw.length; continue; } @@ -1636,6 +1660,7 @@ export async function pipePluginChatWithStrip( // stream completes, and those must already see this usage. settleUsage(); maybeWarnDegenerate(); + maybeWarnProtocolFragment(); if (truncated) { emitUpstreamTruncation(res, protocol, finalFinishReason !== undefined, log); return; @@ -1770,6 +1795,9 @@ export async function pipePluginResponsesWithStrip( let inRetry = false; /** Text the client actually assembled from this attempt's deltas. */ let visibleTextChars = 0; + /** Post-filter prose for the once-per-request #361 tool-call-XML warn at + * stream end (#1368): warn only, never stripped. */ + let proseAcc = ""; /** Done-family events held for the attempt in flight. */ let heldEvents: string[] = []; /** Text those held events would hand the client, post-strip. */ @@ -1813,6 +1841,15 @@ export async function pipePluginResponsesWithStrip( log?.(msg); } }; + // #1368: once-per-request #361 detector for the Responses pipe — see the + // chat-pipe twin above for the warn-only rationale (#295/#361). + const maybeWarnProtocolFragment = () => { + if (proseAcc.length === 0 || !containsToolCallXmlFragment(proseAcc)) return; + const who = session ? `[${session.id}] ` : ""; + const msg = `[tag-echo] ${who}plugin passthrough: response text contains tool-call XML fragment (possible tag echo; not stripped)`; + loggerLog("warn", msg); + log?.(msg); + }; let lastDeltaMeta: { item_id?: unknown; output_index?: unknown } | null = null; const flushTail = (after: string) => { const tail = tagFilter.flush(); @@ -1826,7 +1863,7 @@ export async function pipePluginResponsesWithStrip( /** Visible (post-strip) text a done-family event carries — what the client * would assemble from it. It decides the turn's degeneracy together with * the deltas already forwarded. */ - const responsesEventTextLength = (ev: Record): number => { + const responsesEventText = (ev: Record): string => { let text = typeof ev["text"] === "string" ? (ev["text"] as string) : ""; const part = ev["part"]; if (part && typeof part === "object" && typeof (part as Record)["text"] === "string") { @@ -1841,7 +1878,7 @@ export async function pipePluginResponsesWithStrip( } } } - return text.length; + return text; }; /** Whether a serialized event must be rebuilt rather than forwarded: the * retry's ids are rewritten in the parsed event, and a processor with @@ -2027,6 +2064,7 @@ export async function pipePluginResponsesWithStrip( const hadEcho = containsRenderTagText(jsonStr) || containsMarkerLineText(jsonStr); if (hadEcho) sawStrippedEcho = true; const evOut = hadEcho ? stripResponsesText(ev) : ev; + proseAcc += responsesEventText(evOut); const out = hadEcho ? rebuildEvent(rawEvent, evOut) : rawEvent + "\n\n"; await write(flushArgTails() + flushTail(out)); continue; @@ -2042,7 +2080,9 @@ export async function pipePluginResponsesWithStrip( let rebuild = hadEchoText || retryRewritePending(); if (rebuild) evOut = stripResponsesText(ev); rewriteRetryIds(evOut); - heldVisibleChars += responsesEventTextLength(evOut); + const doneText = responsesEventText(evOut); + heldVisibleChars += doneText.length; + proseAcc += doneText; heldEvents.push(rebuild ? rebuildEvent(rawEvent, evOut) : rawEvent + "\n\n"); continue; } @@ -2100,6 +2140,7 @@ export async function pipePluginResponsesWithStrip( continue; } if (!retryRewritePending() && !mayStartRenderTag(delta) && !mayStartMarkerLine(delta) && !tagFilter.pending()) { + proseAcc += delta; await write(rawEvent + "\n\n"); continue; } @@ -2114,6 +2155,7 @@ export async function pipePluginResponsesWithStrip( continue; } visibleTextChars += clean.length; + proseAcc += clean; if (clean === delta && !retryRewritePending()) { await write(rawEvent + "\n\n"); continue; @@ -2140,6 +2182,7 @@ export async function pipePluginResponsesWithStrip( const s = argStreamFor(type, argField, ev); const clean = s.filter.push(v); if (clean.length === 0) continue; + proseAcc += clean; if (clean === v) { await write(flushArgTails() + rawEvent + "\n\n"); continue; @@ -2159,6 +2202,7 @@ export async function pipePluginResponsesWithStrip( if (rest.length > 0) await write(rest); } maybeWarnDegenerate(); + maybeWarnProtocolFragment(); settleUsage(); // #721: same as the chat-pipe twin — never close bare on a missing // done-family event. Responses has no separate finish-reason concept diff --git a/tests/plugin-passthrough-tool-xml-warn.test.ts b/tests/plugin-passthrough-tool-xml-warn.test.ts new file mode 100644 index 0000000000..05b9b12924 --- /dev/null +++ b/tests/plugin-passthrough-tool-xml-warn.test.ts @@ -0,0 +1,208 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { pipePluginChatWithStrip, pipePluginResponsesWithStrip } from "../src/plugin.ts"; +import { setLogCapture } from "../src/logger.ts"; +import type { Session } from "../src/session.ts"; + +// #1366 shape: the model drafts a tool call as literal text inside its prose. +const LT = "\x3c"; +const GT = "\x3e"; +const FRAG = `${LT}invoke name="compress"${GT}call it${LT}/invoke${GT}`; +const ESC_FRAG = "\\u003cinvoke\\u003e\\u003c/invoke\\u003e"; +const WARN = "tool-call XML fragment"; + +function makeSession(id: string, protocol: string): Session { + return { + id, + protocol, + upstreamOrigin: "http://127.0.0.1:9/v1", + label: "test", + createdAt: 0, + lastUsedAt: 0, + requests: 0, + lastInputTokens: 0, + stats: {}, + dirty: false, + } as unknown as Session; +} + +function makeRes(chunks: string[]) { + return { + writes: chunks, + write(b: Buffer | string) { + chunks.push(typeof b === "string" ? b : b.toString("utf8")); + return true; + }, + end(b?: Buffer | string) { + if (b !== undefined) chunks.push(typeof b === "string" ? b : b.toString("utf8")); + }, + once() {}, + destroyed: false, + writableEnded: false, + } as unknown as import("node:http").ServerResponse; +} + +function streamOf(events: string[]): ReadableStream { + const enc = new TextEncoder(); + let i = 0; + return new ReadableStream({ + pull(controller) { + if (i < events.length) { + controller.enqueue(enc.encode(events[i])); + i += 1; + } else { + controller.close(); + } + }, + }); +} + +function chatChunk(delta: Record, extra: Record = {}): string { + return `data: ${JSON.stringify({ id: "chatcmpl-1", object: "chat.completion.chunk", created: 1, model: "qwen", choices: [{ index: 0, delta, finish_reason: null }], ...extra })}\n\n`; +} + +const DONE = "data: [DONE]\n\n"; + +function sse(ev: Record): string { + return `event: ${String(ev.type)}\ndata: ${JSON.stringify(ev)}\n\n`; +} + +// Decode what the client would actually assemble - raw SSE bytes carry JSON +// escaping (\" etc.) so byte-level includes() cannot prove verbatim forwarding. +function dataLines(raw: string): Array> { + const out: Array> = []; + for (const line of raw.split("\n")) { + if (!line.startsWith("data: ")) continue; + const d = line.slice(6); + if (d === "[DONE]") continue; + out.push(JSON.parse(d) as Record); + } + return out; +} + +function openaiContent(raw: string): string { + let s = ""; + for (const ev of dataLines(raw)) { + const choices = ev["choices"]; + if (!Array.isArray(choices)) continue; + const choice = (choices[0] ?? {}) as Record; + const delta = choice["delta"] as Record | undefined; + if (delta && typeof delta["content"] === "string") s += delta["content"]; + } + return s; +} + +function anthropicText(raw: string): string { + let s = ""; + for (const ev of dataLines(raw)) { + const delta = ev["delta"] as Record | undefined; + if (delta && delta["type"] === "text_delta" && typeof delta["text"] === "string") s += delta["text"]; + } + return s; +} + +function responsesDeltaText(raw: string): string { + let s = ""; + for (const ev of dataLines(raw)) { + if (ev["type"] === "response.output_text.delta" && typeof ev["delta"] === "string") s += ev["delta"]; + } + return s; +} + +test("plugin openai passthrough warns once on tool-call-shaped XML in prose and forwards it verbatim (#1368)", async () => { + const out: string[] = []; + const logs: string[] = []; + setLogCapture((_level, msg) => logs.push(msg)); + try { + const events = [ + chatChunk({ role: "assistant" }), + chatChunk({ content: `draft ${FRAG} end` }), + chatChunk({}, { choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 100, completion_tokens: 5 } }), + DONE, + ]; + await pipePluginChatWithStrip(streamOf(events), makeRes(out), "openai", makeSession("sess-1368", "openai")); + } finally { + setLogCapture(null); + } + assert.equal(openaiContent(out.join("")), `draft ${FRAG} end`, "decoded prose forwarded verbatim - never stripped"); + const warns = logs.filter((l) => l.includes(WARN)); + assert.equal(warns.length, 1, `expected exactly one warn, got: ${logs.join(" | ")}`); + assert.ok(warns[0].includes("[tag-echo]"), warns[0]); + assert.ok(warns[0].includes("[sess-1368]"), warns[0]); +}); + +test("plugin openai passthrough warns on JSON-escaped tool-call XML in prose (#1368)", async () => { + const out: string[] = []; + const logs: string[] = []; + setLogCapture((_level, msg) => logs.push(msg)); + try { + const events = [ + chatChunk({ content: `see ${ESC_FRAG} here` }), + chatChunk({}, { choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 10, completion_tokens: 2 } }), + DONE, + ]; + await pipePluginChatWithStrip(streamOf(events), makeRes(out), "openai", makeSession("sess-1368e", "openai")); + } finally { + setLogCapture(null); + } + assert.equal(openaiContent(out.join("")), `see ${ESC_FRAG} here`, "escaped-form prose forwarded verbatim"); + assert.equal(logs.filter((l) => l.includes(WARN)).length, 1, `expected exactly one warn, got: ${logs.join(" | ")}`); +}); + +test("plugin anthropic passthrough warns once on tool-call-shaped XML in text_delta (#1368)", async () => { + const out: string[] = []; + const logs: string[] = []; + setLogCapture((_level, msg) => logs.push(msg)); + try { + const events = [ + `event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: `hi ${FRAG} bye` } })}\n\n`, + `event: message_delta\ndata: ${JSON.stringify({ type: "message_delta", delta: { stop_reason: "end_turn" } })}\n\n`, + ]; + await pipePluginChatWithStrip(streamOf(events), makeRes(out), "anthropic", makeSession("sess-a1368", "anthropic")); + } finally { + setLogCapture(null); + } + assert.equal(anthropicText(out.join("")), `hi ${FRAG} bye`, "decoded text_delta forwarded verbatim"); + const warns = logs.filter((l) => l.includes(WARN)); + assert.equal(warns.length, 1, `expected exactly one warn, got: ${logs.join(" | ")}`); + assert.ok(warns[0].includes("[sess-a1368]"), warns[0]); +}); + +test("plugin responses passthrough warns once on tool-call-shaped XML in output_text.delta (#1368)", async () => { + const out: string[] = []; + const logs: string[] = []; + setLogCapture((_level, msg) => logs.push(msg)); + try { + const events = [ + sse({ type: "response.output_item.added", output_index: 0, item: { type: "message", id: "msg_1" } }), + sse({ type: "response.output_text.delta", item_id: "msg_1", output_index: 0, delta: `draft ${FRAG} end` }), + sse({ type: "response.output_text.done", item_id: "msg_1", output_index: 0, text: `draft ${FRAG} end` }), + sse({ type: "response.completed", response: { usage: { input_tokens: 100, output_tokens: 5 } } }), + ]; + await pipePluginResponsesWithStrip(streamOf(events), makeRes(out), makeSession("sess-r1368", "responses")); + } finally { + setLogCapture(null); + } + assert.equal(responsesDeltaText(out.join("")), `draft ${FRAG} end`, "decoded output text forwarded verbatim"); + const warns = logs.filter((l) => l.includes(WARN)); + assert.equal(warns.length, 1, `expected exactly one warn, got: ${logs.join(" | ")}`); + assert.ok(warns[0].includes("[sess-r1368]"), warns[0]); +}); + +test("plugin passthrough does not warn on plain prose (#1368)", async () => { + const out: string[] = []; + const logs: string[] = []; + setLogCapture((_level, msg) => logs.push(msg)); + try { + const events = [ + chatChunk({ role: "assistant" }), + chatChunk({ content: "just words, no markup at all" }), + chatChunk({}, { choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 100, completion_tokens: 5 } }), + DONE, + ]; + await pipePluginChatWithStrip(streamOf(events), makeRes(out), "openai", makeSession("sess-clean", "openai")); + } finally { + setLogCapture(null); + } + assert.ok(!logs.some((l) => l.includes(WARN)), `no tool-call XML warn expected, got: ${logs.join(" | ")}`); +}); From 927a5e735d4e7df8913690679d8fb4860eebe4ef Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 26 Sep 2026 04:32:45 +0800 Subject: [PATCH 2/2] fix: account for fast-path reasoning-summary deltas in passthrough proseAcc (#1368) The Responses pipe accumulated reasoning summary text into proseAcc only via the filter path; chunks that never engaged the tag/marker heuristics were forwarded to the client unaccounted, so a tool-call-shaped fragment carried there would leave no warn. Account them at the same site as every sibling fast path, pinned by a stream that ends after the delta so the delta's own accounting is the only prose source. --- src/plugin.ts | 1 + .../plugin-passthrough-tool-xml-warn.test.ts | 27 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/plugin.ts b/src/plugin.ts index 806268547e..0b0fb30186 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -2176,6 +2176,7 @@ export async function pipePluginResponsesWithStrip( continue; } if (!mayStartRenderTag(v) && !argAnyPending() && !tagFilter.pending()) { + proseAcc += v; await write(rawEvent + "\n\n"); continue; } diff --git a/tests/plugin-passthrough-tool-xml-warn.test.ts b/tests/plugin-passthrough-tool-xml-warn.test.ts index 05b9b12924..4ab718eb42 100644 --- a/tests/plugin-passthrough-tool-xml-warn.test.ts +++ b/tests/plugin-passthrough-tool-xml-warn.test.ts @@ -189,6 +189,33 @@ test("plugin responses passthrough warns once on tool-call-shaped XML in output_ assert.ok(warns[0].includes("[sess-r1368]"), warns[0]); }); +test("plugin responses passthrough warns on tool-call-shaped XML in reasoning summary deltas alone (#1368)", async () => { + // Stream ends after the delta - no done-family or completion frame - so the + // delta's own accounting is the ONLY prose source: this pins the fast-path + // accumulation the done-family path cannot cover. + const out: string[] = []; + const logs: string[] = []; + setLogCapture((_level, msg) => logs.push(msg)); + try { + const events = [ + sse({ type: "response.output_item.added", output_index: 0, item: { type: "reasoning", id: "rs_1" } }), + sse({ type: "response.reasoning_summary_part.added", item_id: "rs_1", summary_index: 0, part: { type: "summary_text", text: "" } }), + sse({ type: "response.reasoning_summary_text.delta", item_id: "rs_1", summary_index: 0, delta: `draft ${FRAG} end` }), + ]; + await pipePluginResponsesWithStrip(streamOf(events), makeRes(out), makeSession("sess-rs1368", "responses")); + } finally { + setLogCapture(null); + } + let deltaText = ""; + for (const ev of dataLines(out.join(""))) { + if (ev["type"] === "response.reasoning_summary_text.delta" && typeof ev["delta"] === "string") deltaText += ev["delta"]; + } + assert.equal(deltaText, `draft ${FRAG} end`, "decoded reasoning summary forwarded verbatim"); + const warns = logs.filter((l) => l.includes(WARN)); + assert.equal(warns.length, 1, `expected exactly one warn, got: ${logs.join(" | ")}`); + assert.ok(warns[0].includes("[sess-rs1368]"), warns[0]); +}); + test("plugin passthrough does not warn on plain prose (#1368)", async () => { const out: string[] = []; const logs: string[] = [];