Skip to content
13 changes: 11 additions & 2 deletions src/server/prepare-openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { coreToOpenai, injectOpenaiSystem, openaiToCore, type BiliMessage, type
import type { CompressReasoningConfig } from "../reasoning-drop.js";
import type { ProxyOptions } from "../config.js";
import { effectivePromptCacheRouting } 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 { MSG_IDS_BODY_FIELD, applyMsgIdPin, validateMsgIds } from "../msgid-pin.js";
import { pluginAgentHeader } from "../plugin.js";
Expand Down Expand Up @@ -506,7 +506,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<string, unknown> = { ...parsed, messages: [...stable, { role: "user", content: buildDecisionPrompt(ranges) }], tools: toolsOut as OpenAITool[] | undefined, stream: false };
sideBody[typeof (parsed as Record<string, unknown>).max_completion_tokens === "number" ? "max_completion_tokens" : "max_tokens"] = decide.maxTokens;
delete sideBody.prompt_cache_retention;
Expand Down Expand Up @@ -570,6 +574,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<string, unknown>, typeof (parsed as Record<string, unknown>).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<string, unknown>, opts.routes, billingUpstream ?? upstreamOrigin, opts.sessionHeader, modelIdOf(parsed)) }, sessionId, log, (c) => { session.stats.lastOutputClamp = { ...c, at: Date.now() }; });
Expand Down
11 changes: 9 additions & 2 deletions src/server/prepare-responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { injectResponsesDeveloperMessage, type BiliMessage, type ResponseInputIt
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, strippedResponseIdWarning } from "../util.js";
import { currentCalibrationFactor, hardenResponsesFunctionCallArguments, strippedResponseIdWarning } from "../util.js";
import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, planReasoningDrop, reapOrphansLogged, resolveKnownOutputCeiling, runNudgeDecision, stripKernelSummaries, usageGradeInputBaseline, warnResponsesReasoningPairs, type Prepared } from "../server.js";
import { collectSeparatorManifest, repairResponsesAssistantOrdering, type SeparatorSlot } from "./responses-ordering.js";
import { recordNudgeObservation } from "../context-analysis.js";
Expand Down Expand Up @@ -522,9 +522,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<string, unknown> = { ...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 });
Expand Down Expand Up @@ -624,6 +628,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) {
Expand Down
82 changes: 81 additions & 1 deletion src/util.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -694,6 +694,86 @@ export function hardenOpenaiAssistantContent<T extends { role: string }>(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<T extends { role: string }>(
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
Expand Down
Loading
Loading