From 99e1d89b8e732d811bad32e1c4abb3a377d23a58 Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 2 Nov 2026 20:06:11 +0800 Subject: [PATCH 1/4] fix: repair non-JSON tool-call arguments at the OpenAI/Responses egress chokepoint (#5534) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue #5534: the kernel's ref-keyed text replay (emergencyTruncateLatch) can stamp fold/checkpoint prose onto whatever message currently holds a latched ref. When that message is a tool-call core, coreToOpenai/coreToResponses emit the prose verbatim as function.arguments and strict-JSON upstreams reject every later request with parse_error.101 — permanently poisoning the session until some fold resets the latch. This PR adds the egress last line of defense suggested in the issue: validate every outbound tool_calls[*].function.arguments (OpenAI chat wire) and every type==function_call item's arguments (Responses wire) at the prepare chokepoints, covering both the kernel-processed path and the catch-fallback path that forwards parsed.messages verbatim. A payload failing JSON.parse is replaced with a valid placeholder object plus a [wire-guard] warn log carrying its first bytes for diagnosis. Parsing payloads (including empty strings) pass byte-exact, and the same array reference is returned when nothing was repaired — valid traffic is untouched, per the #1039 discipline of never rewriting possibly-legitimate bytes. Behavior change: previously non-JSON arguments produced by bili's own egress fault were forwarded verbatim -> upstream 500 + permanent session poison; now they are replaced with a valid placeholder + warn log. Model-produced malformed args on the loop/replay path were already repaired there (src/loop/core.ts MALFORMED_PROXY_TOOL_ARGS_REPLAY); this guard covers the prepare/history-rebuild path those never touch. Root cause (identity-less latch entries + cold-load ledger restamp renumbering under surviving entries) is a kernel change and owner-gated; see the decision request on issue #5534. --- src/server/prepare-openai.ts | 7 +- src/server/prepare-responses.ts | 5 +- src/util.ts | 82 ++++++++- tests/issue5536-tool-args-guard.test.ts | 213 ++++++++++++++++++++++++ 4 files changed, 304 insertions(+), 3 deletions(-) create mode 100644 tests/issue5536-tool-args-guard.test.ts diff --git a/src/server/prepare-openai.ts b/src/server/prepare-openai.ts index 7e2aa4fc01..91be7c69e3 100644 --- a/src/server/prepare-openai.ts +++ b/src/server/prepare-openai.ts @@ -4,7 +4,7 @@ import { isRenderedSummaryMessage, renderNudgeText, viableRanges } from "acp-ker import { coreToOpenai, injectOpenaiSystem, openaiToCore, type BiliMessage, type OpenAIRequestBody, type OpenAITool } from "acp-kernel/wire"; import type { CompressReasoningConfig } from "../reasoning-drop.js"; import type { ProxyOptions } from "../config.js"; -import { currentCalibrationFactor, hardenOpenaiAssistantContent, systemToUser } from "../util.js"; +import { currentCalibrationFactor, hardenOpenaiAssistantContent, hardenOpenaiToolCallArguments, systemToUser } from "../util.js"; import { conversationHeaderSource, resolveRelayAffinityPck } from "../session-id.js"; import { pluginAgentHeader } from "../plugin.js"; import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, planReasoningDrop, reapOrphansLogged, resolveKnownOutputCeiling, runNudgeDecision, stripKernelSummaries, warnDroppedOpenaiParts, warnReasoningPairs, type Prepared } from "../server.js"; @@ -447,6 +447,11 @@ export async function prepareOpenai( // #762: repair the strict-echo rejection class BEFORE the sentinel sees // the array — a normalized body must not fire its own canary. rebuiltMessages = normalizeStrictEchoReasoning(rebuiltMessages, isStrictReasoningEcho(session, upstreamOrigin, modelIdOf(parsed)), log, sessionId); + // #5534: last line of defense for strict-JSON upstreams — a latch replay + // can land clipped prose into a tool-call core's text (= arguments JSON). + // Covers BOTH paths: kernel-processed and the catch fallback above (which + // forwards parsed.messages verbatim, poison included). + rebuiltMessages = hardenOpenaiToolCallArguments(rebuiltMessages, log, sessionId); const rebuilt: OpenAIRequestBody = { ...parsed, messages: rebuiltMessages, tools: toolsOut as OpenAITool[] | undefined }; warnReasoningPairs(rebuiltMessages, log, sessionId); clampOutgoingOutput(rebuilt as Record, typeof (parsed as Record).max_completion_tokens === "number" ? "max_completion_tokens" : "max_tokens", { systemText: openaiSystemText, tools: toolsOut, processedMessages, lastInputTokens: session.stats.lastInputTokens, lastInputTokensSource: session.stats.lastInputTokensSource, nativeWindow, headroomWindow: config.modelContextLimit, imageTokens: imageReserveFor(session, "openai", rebuilt, opts, billingUpstream ?? upstreamOrigin), kFactor: currentCalibrationFactor(session.stats, session.metadata?.lastModel), kOrigin: session.stats.calibratedEstimateOrigin, origin: billingUpstream ?? upstreamOrigin, ledgerFloorTokens: dshLedgerFloorTokens(session.metadata), knownOutputCeiling: resolveKnownOutputCeiling(req.headers, parsed as Record, opts.routes, billingUpstream ?? upstreamOrigin, opts.sessionHeader, modelIdOf(parsed)) }, sessionId, log, (c) => { session.stats.lastOutputClamp = { ...c, at: Date.now() }; }); diff --git a/src/server/prepare-responses.ts b/src/server/prepare-responses.ts index 7765110082..6d34c484c2 100644 --- a/src/server/prepare-responses.ts +++ b/src/server/prepare-responses.ts @@ -5,7 +5,7 @@ import { injectResponsesDeveloperMessage, type BiliMessage, type ResponseInputIt import type { CompressReasoningConfig } from "../reasoning-drop.js"; import { resolveAbsorbSettings } from "../compress-settings.js"; import { resolveCompressProtocol, type CompressSettings, type ProxyOptions } from "../config.js"; -import { currentCalibrationFactor, strippedResponseIdWarning } from "../util.js"; +import { currentCalibrationFactor, hardenResponsesFunctionCallArguments, strippedResponseIdWarning } from "../util.js"; import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, planReasoningDrop, repairResponsesAssistantOrdering, reapOrphansLogged, resolveKnownOutputCeiling, runNudgeDecision, stripKernelSummaries, usageGradeInputBaseline, warnResponsesReasoningPairs, type Prepared } from "../server.js"; import { yieldToEventLoop } from "../yield-loop.js"; import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js"; @@ -599,6 +599,9 @@ reconcileFoldCoverage(session, msgs, { mode: foldMode, sessionId, log, markerStr // can leave a tool-call run without its reasoning item. Repair BEFORE the // sentinel sees the array (a normalized body must not fire its own canary). if (Array.isArray(rebuiltInput)) rebuiltInput = normalizeStrictEchoResponsesInput(rebuiltInput, isStrictReasoningEcho(session, upstreamOrigin, modelIdOf(parsed)), log, sessionId); + // #5534: Responses-wire twin — function_call.arguments carries the same + // tool-call core text; custom_tool_call.input stays free-form. + if (Array.isArray(rebuiltInput)) rebuiltInput = hardenResponsesFunctionCallArguments(rebuiltInput, log, sessionId); const rebuilt: ResponsesRequestBody = { ...parsed, input: rebuiltInput, tools: toolsOut }; warnResponsesReasoningPairs(Array.isArray(rebuiltInput) ? rebuiltInput : [], log, sessionId); if (!isCompactionTrigger) { diff --git a/src/util.ts b/src/util.ts index c960263f5a..0878116063 100644 --- a/src/util.ts +++ b/src/util.ts @@ -1,5 +1,5 @@ import { createHash } from "node:crypto"; -import type { AnthropicRequestBody } from "acp-kernel/wire"; +import type { AnthropicRequestBody, ResponseInputItem } from "acp-kernel/wire"; // #920: stamped per request by the opencode thin plugin for LEGACY // opencode-acp sessions (acp state on disk). The proxy (server.ts) forwards @@ -650,6 +650,86 @@ export function hardenOpenaiAssistantContent(message }); } +/** #5534: strict-JSON upstreams (e.g. infernix-serve) JSON-parse EVERY history + * `tool_calls[*].function.arguments` and reject the whole request on the first + * unparseable payload (500 parse_error.101). bili's own egress can produce such + * payloads: the emergency-truncate / view latches replay clipped text keyed by + * REF alone (kernel/src/compress.ts emergencyTruncateNode, kernel/src/view-latch.ts), + * and a ref renumbered under a live entry (cold-load ledger restamp, + * src/persist.ts maybeRestampToLedger) lands the clip onto whatever message now + * holds the number — including an assistant tool-call core whose `text` IS the + * arguments JSON. This guard is the last line of defense at egress: it replaces + * an already-invalid arguments string with a valid placeholder so strict-JSON + * upstreams accept the request and the session can heal forward. It fires ONLY + * on non-empty strings that fail JSON.parse — valid payloads pass byte-exact + * (#1039 discipline: never rewrite what may be user intent; this rewrites bytes + * no executor could ever use). Precedents: src/loop/adapter-google.ts (google + * wire), src/loop/core.ts MALFORMED_PROXY_TOOL_ARGS_REPLAY (model-side variant). + */ +export const NON_JSON_TOOL_ARGS_PLACEHOLDER = '{"_bili":"outbound tool-call arguments were not valid JSON (poisoned by an earlier bili egress fault); replaced with this valid placeholder so strict-JSON upstreams accept the request"}'; + +function isValidJsonPayload(args: string): boolean { + try { + JSON.parse(args); + return true; + } catch { + return false; + } +} + +function previewBytes(s: string): string { + const p = s.slice(0, 64); + return p.length < s.length ? `${p}…` : p; +} + +/** OpenAI chat wire: repair non-JSON `tool_calls[*].function.arguments`. + * No-op (returns the same array) when every payload is already valid. */ +export function hardenOpenaiToolCallArguments( + messages: T[], + log: (level: string, msg: string) => void, + sessionId: string, +): T[] { + let repaired = 0; + const out = messages.map((m) => { + if (m.role !== "assistant") return m; + const tcs = (m as { tool_calls?: unknown }).tool_calls; + if (!Array.isArray(tcs)) return m; + let touched = false; + const nextTcs = tcs.map((tc) => { + const fn = (tc as { function?: { name?: unknown; arguments?: unknown } }).function; + const args = fn ? fn.arguments : undefined; + if (typeof args !== "string" || args.length === 0 || isValidJsonPayload(args)) return tc; + touched = true; + repaired += 1; + log("warn", `[${sessionId}] [wire-guard] outbound tool-call arguments failed JSON validation (tool=${String(fn?.name ?? "?")}, first bytes: ${JSON.stringify(previewBytes(args))}) — replacing with placeholder (#5534)`); + return { ...tc, function: { ...fn, arguments: NON_JSON_TOOL_ARGS_PLACEHOLDER } }; + }); + if (!touched) return m; + return { ...m, tool_calls: nextTcs } as T; + }); + return repaired > 0 ? out : messages; +} + +/** Responses wire: repair non-JSON `function_call` items' `arguments`. + * `custom_tool_call.input` is free-form (not JSON by contract) and untouched. + * No-op (returns the same array) when every payload is already valid. */ +export function hardenResponsesFunctionCallArguments( + items: ResponseInputItem[], + log: (level: string, msg: string) => void, + sessionId: string, +): ResponseInputItem[] { + let repaired = 0; + const out = items.map((item) => { + if (item.type !== "function_call") return item; + const args = item.arguments; + if (typeof args !== "string" || args.length === 0 || isValidJsonPayload(args)) return item; + repaired += 1; + log("warn", `[${sessionId}] [wire-guard] outbound Responses function_call arguments failed JSON validation (name=${String(item.name)}, first bytes: ${JSON.stringify(previewBytes(args))}) — replacing with placeholder (#5534)`); + return { ...item, arguments: NON_JSON_TOOL_ARGS_PLACEHOLDER }; + }); + return repaired > 0 ? out : items; +} + // #1876: rebuild the outbound Anthropic `system` by APPENDING bili's added // text (the compress prompt) instead of merging it into one block. The kernel's // buildSystem(flattenedText, original) collapses a client's N-block system into diff --git a/tests/issue5536-tool-args-guard.test.ts b/tests/issue5536-tool-args-guard.test.ts new file mode 100644 index 0000000000..43f4cf9867 --- /dev/null +++ b/tests/issue5536-tool-args-guard.test.ts @@ -0,0 +1,213 @@ +// #5534: strict-JSON upstreams (infernix-serve) JSON-parse EVERY history +// tool_calls[*].function.arguments and reject the whole request on the first +// unparseable payload (500 parse_error.101). bili's emergency-truncate latch +// replays clipped text keyed by REF alone (kernel/src/compress.ts +// emergencyTruncateNode); when a cold-load ledger restamp +// (src/persist.ts maybeRestampToLedger) renumbers refs under a surviving +// latch entry, the clip lands on whatever message now holds the number — +// including an assistant tool-call core whose `text` IS the arguments JSON. +// The egress guards (src/util.ts hardenOpenaiToolCallArguments / +// hardenResponsesFunctionCallArguments) replace already-invalid payloads with +// a valid placeholder so strict-JSON upstreams accept the request. Gate +// discipline (#3617): every guard row below is asserted in BOTH directions. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createCore, createInitialState, defaultConfig, type CoreMessage } from "acp-kernel"; +import { coreToOpenai, coreToResponses } from "acp-kernel/wire"; +import { NON_JSON_TOOL_ARGS_PLACEHOLDER, hardenOpenaiToolCallArguments, hardenResponsesFunctionCallArguments } from "../src/util.js"; + +const logs: string[] = []; +const log = (level: string, msg: string) => { logs.push(`${level}: ${msg}`); }; +const resetLogs = () => { logs.length = 0; }; + +const CHECKPOINT_PROSE = "This is an automatically generated checkpoint summarizing the conversation so far."; +const TAG_PREFIXED = "\x3cacp tokens=\"2\" type=\"text\"\x3em00001\x3c/acp\x3e stale clipped bytes"; + +test("chat guard: non-JSON arguments prose is replaced with the valid placeholder", () => { + resetLogs(); + const input = [ + { role: "user", content: "hi" }, + { role: "assistant", content: null, tool_calls: [{ id: "call_1", type: "function", function: { name: "bash", arguments: CHECKPOINT_PROSE } }] }, + { role: "tool", tool_call_id: "call_1", content: "ok" }, + ]; + const out = hardenOpenaiToolCallArguments(input, log, "sess-a"); + assert.notEqual(out, input, "touched array is replaced"); + const fn = out[1]!.tool_calls![0]!.function!; + assert.equal(fn.arguments, NON_JSON_TOOL_ARGS_PLACEHOLDER); + JSON.parse(fn.arguments); + assert.equal(fn.name, "bash"); + assert.equal(out[1]!.tool_calls![0]!.id, "call_1"); + assert.equal(out[1]!.content, null, "content untouched"); + assert.deepEqual(out[0], input[0], "user message untouched"); + assert.ok(logs.some((l) => l.includes("[wire-guard]") && l.includes("sess-a") && l.includes("bash")), "warn logged with session + tool name"); +}); + +test("chat guard: tag-prefixed (incident 2 signature) arguments are repaired", () => { + resetLogs(); + const input = [ + { role: "assistant", tool_calls: [{ id: "call_2", type: "function", function: { name: "read", arguments: TAG_PREFIXED } }] }, + ]; + const out = hardenOpenaiToolCallArguments(input, log, "sess-b"); + assert.equal(out[0]!.tool_calls![0]!.function!.arguments, NON_JSON_TOOL_ARGS_PLACEHOLDER); +}); + +test("chat guard: mixed tool_calls — only the invalid payload is touched", () => { + resetLogs(); + const input = [ + { role: "assistant", tool_calls: [ + { id: "call_a", type: "function", function: { name: "bash", arguments: CHECKPOINT_PROSE } }, + { id: "call_b", type: "function", function: { name: "read", arguments: "{\"path\":\"x\"}" } }, + ] }, + ]; + const out = hardenOpenaiToolCallArguments(input, log, "sess-c"); + assert.equal(out[0]!.tool_calls![0]!.function!.arguments, NON_JSON_TOOL_ARGS_PLACEHOLDER); + assert.equal(out[0]!.tool_calls![1]!.function!.arguments, "{\"path\":\"x\"}", "valid sibling byte-exact"); +}); + +test("chat guard negative rows: every valid shape passes byte-exact (same array returned)", () => { + const rows: Array<{ label: string; args: unknown }> = [ + { label: "object", args: "{}" }, + { label: "nested", args: "{\"a\":[1,2,{\"b\":null}]}" }, + { label: "json null literal", args: "null" }, + { label: "json number", args: "42" }, + { label: "json string", args: "\"hello\"" }, + { label: "empty string", args: "" }, + { label: "undefined", args: undefined }, + { label: "object-typed", args: { already: "parsed" } }, + ]; + for (const r of rows) { + const input = [{ role: "assistant", tool_calls: [{ id: "c", type: "function", function: { name: "t", arguments: r.args } }] }]; + const out = hardenOpenaiToolCallArguments(input, log, "sess-neg"); + assert.equal(out, input, `${r.label}: untouched input returns the same array`); + } + // Non-assistant roles and missing tool_calls are never scanned. + const misc = [ + { role: "user", content: CHECKPOINT_PROSE }, + { role: "tool", tool_call_id: "c", content: CHECKPOINT_PROSE }, + { role: "assistant", content: CHECKPOINT_PROSE }, + { role: "assistant", tool_calls: "not-an-array" }, + ]; + assert.equal(hardenOpenaiToolCallArguments(misc, log, "sess-neg2"), misc, "non-tool-call shapes untouched"); +}); + +test("responses guard: dirty function_call.arguments is replaced; custom_tool_call.input stays free-form", () => { + resetLogs(); + const input = [ + { type: "message", role: "user", content: [{ type: "input_text", text: "hi" }] }, + { type: "function_call", call_id: "fc_1", name: "bash", arguments: CHECKPOINT_PROSE }, + { type: "custom_tool_call", call_id: "ct_1", name: "snippet", input: CHECKPOINT_PROSE }, + { type: "function_call", call_id: "fc_2", name: "read", arguments: "{\"path\":\"y\"}" }, + ]; + const out = hardenResponsesFunctionCallArguments(input, log, "sess-r"); + assert.notEqual(out, input); + assert.equal((out[1] as { arguments?: string }).arguments, NON_JSON_TOOL_ARGS_PLACEHOLDER); + JSON.parse((out[1] as { arguments?: string }).arguments!); + assert.equal((out[1] as { name: string }).name, "bash", "name preserved"); + assert.equal((out[2] as { input?: string }).input, CHECKPOINT_PROSE, "custom_tool_call.input free-form — untouched"); + assert.equal((out[3] as { arguments?: string }).arguments, "{\"path\":\"y\"}", "valid function_call byte-exact"); + assert.deepEqual(out[0], input[0], "message item untouched"); + assert.ok(logs.some((l) => l.includes("[wire-guard]") && l.includes("sess-r")), "warn logged"); +}); + +test("responses guard negative rows: valid/empty payloads and other item types pass untouched", () => { + const input = [ + { type: "function_call", call_id: "f1", name: "t", arguments: "{}" }, + { type: "function_call", call_id: "f2", name: "t", arguments: "" }, + { type: "message", role: "assistant", content: [{ type: "output_text", text: CHECKPOINT_PROSE }] }, + ]; + assert.equal(hardenResponsesFunctionCallArguments(input, log, "sess-rneg"), input, "all-valid input returns the same array"); +}); + +// --- mechanism reproduction (host-level, built kernel) ----------------------- + +const WINDOW = 100_000; +const BIG = "alpha-beta ".repeat(4000); +const filler = (t: string) => `filler ${t} ` + "x".repeat(800); +const tiny = (t: string): CoreMessage[] => [ + { id: `raw-${t}`, role: "user", contentType: "text", text: "hi " + t + " " + filler(t) }, + { id: `raw-${t}-a`, role: "assistant", contentType: "text", text: "ok " + t }, +]; +const hist = (): CoreMessage[] => [ + ...tiny("warm"), + { id: "raw-big", role: "user", contentType: "text", text: BIG }, + ...tiny("tail1"), + ...tiny("tail2"), + ...tiny("tail3"), + ...tiny("tail4"), +]; +const TOOL_CALL_CORE: CoreMessage = { + id: "raw-toolcall", + role: "assistant", + contentType: "tool-call", + toolName: "bash", + toolCallId: "call_poi", + text: "{\"command\":\"ls\"}", +}; + +/** Turn 1 clips the oversized text and latches it; then simulate the + * cold-load ledger restamp: the clipped message leaves the view and a NEW + * assistant tool-call core is bound to the OLD latched ref — exactly what + * restampRefsToLedger produces when the latch survives hydration while the + * ref map is renumbered (src/persist.ts maybeRestampToLedger). */ +function poisonedTurn() { + const core = createCore(); + const t1 = core.processTurn({ messages: hist(), state: createInitialState(), config: defaultConfig(WINDOW), tokenCount: 96_000, renderTags: "none" }); + const clip = t1.messages.find((m) => m.id === "raw-big")!.text!; + assert.ok(clip.includes("[truncated for context space]"), "turn 1 clips the oversized text"); + const entry = t1.state.emergencyTruncateLatch?.find((e) => e.text === clip); + assert.ok(entry, "clip is latched"); + const st = structuredClone(t1.state); + const oldRef = entry!.ref; + delete st.messageRefs.byRaw["raw-big"]; + delete st.messageRefs.byRef[oldRef]; + st.messageRefs.byRaw["raw-toolcall"] = oldRef; + st.messageRefs.byRef[oldRef] = "raw-toolcall"; + const t2 = core.processTurn({ + messages: [...hist().filter((m) => m.id !== "raw-big"), TOOL_CALL_CORE], + state: st, + config: defaultConfig(WINDOW), + tokenCount: 60_000, + renderTags: "none", + }); + return { t2, clip }; +} + +test("repro #5534 (known kernel defect pin): latch replay lands clip text on the renumbered tool-call core", () => { + const { t2, clip } = poisonedTurn(); + const tc = t2.messages.find((m) => m.id === "raw-toolcall"); + assert.ok(tc, "tool-call core survives the turn"); + assert.equal(tc!.text, clip, "stale latch entry overwrites the tool-call core's text (= arguments JSON)"); + + const wire = coreToOpenai(t2.messages); + const dirty = wire.flatMap((m) => (Array.isArray(m.tool_calls) ? m.tool_calls : [])).find((tc2) => tc2.function?.arguments === clip); + assert.ok(dirty, "coreToOpenai faithfully emits the poisoned text as function.arguments"); + assert.throws(() => JSON.parse(dirty!.function!.arguments), "payload is not JSON — strict-JSON upstreams 500 on this"); +}); + +test("egress guard repairs the poisoned chat wire end-to-end (outbound arguments always valid JSON)", () => { + const { t2 } = poisonedTurn(); + const wire = coreToOpenai(t2.messages); + const out = hardenOpenaiToolCallArguments(wire, log, "sess-e2e"); + for (const m of out) { + for (const tc of Array.isArray(m.tool_calls) ? m.tool_calls : []) { + const args = tc.function?.arguments; + if (typeof args === "string" && args.length > 0) JSON.parse(args); + } + } + const fixed = out.flatMap((m) => (Array.isArray(m.tool_calls) ? m.tool_calls : [])).find((tc) => tc.function?.arguments === NON_JSON_TOOL_ARGS_PLACEHOLDER); + assert.ok(fixed, "placeholder present where the poison was"); +}); + +test("egress guard repairs the poisoned responses wire end-to-end", () => { + const { t2, clip } = poisonedTurn(); + const items = coreToResponses(t2.messages); + const dirty = items.find((it) => it.type === "function_call" && it.arguments === clip); + assert.ok(dirty, "coreToResponses carries the poisoned text into function_call.arguments"); + const out = hardenResponsesFunctionCallArguments(items, log, "sess-e2e-r"); + for (const it of out) { + if (it.type !== "function_call") continue; + const args = it.arguments; + if (typeof args === "string" && args.length > 0) JSON.parse(args); + } + assert.ok(out.some((it) => it.type === "function_call" && it.arguments === NON_JSON_TOOL_ARGS_PLACEHOLDER)); +}); From 1d73dcccfdbbc7c25a4629024f003cf180834a55 Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 2 Nov 2026 20:29:59 +0800 Subject: [PATCH 2/4] test(#5534): rename the guard suite to its actual issue number The suite was filed as issue5536-* but #5536 is an unrelated storage issue (unified store auto-disable); this PR's bug is #5534, which every other reference in the PR already cites. --- ...-tool-args-guard.test.ts => issue5534-tool-args-guard.test.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tests/{issue5536-tool-args-guard.test.ts => issue5534-tool-args-guard.test.ts} (100%) diff --git a/tests/issue5536-tool-args-guard.test.ts b/tests/issue5534-tool-args-guard.test.ts similarity index 100% rename from tests/issue5536-tool-args-guard.test.ts rename to tests/issue5534-tool-args-guard.test.ts From ea20aa563d073bfe34e1d89d1fb739eadc57770a Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 2 Nov 2026 20:29:59 +0800 Subject: [PATCH 3/4] fix(#5534): extend the egress args guard to the nudge-decide side bodies Review finding: the useDecide branch builds its side call from a copy of the prefix taken BEFORE the main-body guard runs, so in a poisoned session on a strict-JSON upstream every decide round-trip still 500s and the nudge-decide arm fails for the whole poisoned stretch. Apply the same guard to the side call's prefix on both wires. --- src/server/prepare-openai.ts | 6 +++++- src/server/prepare-responses.ts | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/server/prepare-openai.ts b/src/server/prepare-openai.ts index 69a76c5a21..5e3ae0b0ba 100644 --- a/src/server/prepare-openai.ts +++ b/src/server/prepare-openai.ts @@ -396,7 +396,11 @@ export async function prepareOpenai( const ranges = turn.nudge.compressibleRanges ?? []; // Mirror the post-try strict-echo repair on the stable prefix so // the side call's bytes match the main request's cache line. - const stable = normalizeStrictEchoReasoning([...rebuiltMessages], isStrictReasoningEcho(session, upstreamOrigin, modelIdOf(parsed)), log, sessionId); + const stablePrefix = normalizeStrictEchoReasoning([...rebuiltMessages], isStrictReasoningEcho(session, upstreamOrigin, modelIdOf(parsed)), log, sessionId); + // #5534: the main-body args guard below runs AFTER this branch — + // repair the side call's prefix here too, or a poisoned prefix + // 500s every decide round-trip on strict-JSON upstreams. + const stable = hardenOpenaiToolCallArguments(stablePrefix, log, sessionId); const sideBody: Record = { ...parsed, messages: [...stable, { role: "user", content: buildDecisionPrompt(ranges) }], tools: toolsOut as OpenAITool[] | undefined, stream: false }; sideBody[typeof (parsed as Record).max_completion_tokens === "number" ? "max_completion_tokens" : "max_tokens"] = decide.maxTokens; delete sideBody.prompt_cache_retention; diff --git a/src/server/prepare-responses.ts b/src/server/prepare-responses.ts index e9fefa71ba..a3c9eedfd0 100644 --- a/src/server/prepare-responses.ts +++ b/src/server/prepare-responses.ts @@ -509,9 +509,13 @@ reconcileFoldCoverage(session, msgs, { mode: foldMode, sessionId, log, markerStr const ranges = turn.nudge.compressibleRanges ?? []; // Mirror the post-try strict-echo repair on the stable prefix so // the side call's bytes match the main request's cache line. - const stableItems: ResponseInputItem[] = typeof rebuiltInput === "string" + const normalizedItems: ResponseInputItem[] = typeof rebuiltInput === "string" ? [{ type: "message", role: "user", content: rebuiltInput }] : normalizeStrictEchoResponsesInput([...rebuiltInput], isStrictReasoningEcho(session, upstreamOrigin, modelIdOf(parsed)), log, sessionId); + // #5534: the main-body args guard below runs AFTER this branch — + // repair the side call's prefix here too, or a poisoned prefix + // 500s every decide round-trip on strict-JSON upstreams. + const stableItems: ResponseInputItem[] = hardenResponsesFunctionCallArguments(normalizedItems, log, sessionId); const sideBody: Record = { ...parsed, input: [...stableItems, { type: "message", role: "user", content: buildDecisionPrompt(ranges) }], tools: toolsOut, stream: false, max_output_tokens: decide.maxTokens }; stripDecisionReasoningFields("responses", sideBody); const outcome = await runNudgeDecision({ req, opts, protocol: "responses", sideBody, session, log }); From 5eded539010fc246390601a9e2c79e3889ff44a3 Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 2 Nov 2026 20:42:05 +0800 Subject: [PATCH 4/4] fix(#5534): correct a bad identifier introduced by the merge conflict resolution MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The merged import line carried imageRescaleFor — an identifier that does not exist (server.ts exports imageReserveFor). Every Responses-wire request died with ReferenceError -> 502 before turn processing. Restored the master spelling and aligned the import order with master. --- src/server/prepare-responses.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server/prepare-responses.ts b/src/server/prepare-responses.ts index a3c9eedfd0..6776090a44 100644 --- a/src/server/prepare-responses.ts +++ b/src/server/prepare-responses.ts @@ -6,7 +6,7 @@ import type { CompressReasoningConfig } from "../reasoning-drop.js"; import { resolveAbsorbSettings } from "../compress-settings.js"; import { effectivePromptCacheRouting, resolveCompressProtocol, type CompressSettings, type ProxyOptions } from "../config.js"; import { currentCalibrationFactor, hardenResponsesFunctionCallArguments, strippedResponseIdWarning } from "../util.js"; -import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageRescaleFor, imageTokenCapFor, isAutoInjectedNotification, planReasoningDrop, makeFoldPointReasoningDroppable, repairResponsesAssistantOrdering, reapOrphansLogged, resolveKnownOutputCeiling, runNudgeDecision, stripKernelSummaries, usageGradeInputBaseline, warnResponsesReasoningPairs, type Prepared } from "../server.js"; +import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, makeFoldPointReasoningDroppable, planReasoningDrop, repairResponsesAssistantOrdering, reapOrphansLogged, resolveKnownOutputCeiling, runNudgeDecision, stripKernelSummaries, usageGradeInputBaseline, warnResponsesReasoningPairs, type Prepared } from "../server.js"; import { yieldToEventLoop } from "../yield-loop.js"; import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js"; import { excludeDeadRefRanges } from "../acp-status.js";