From 24f3313f4ab71c8458f6957fd6d2ae1c84e08bf8 Mon Sep 17 00:00:00 2001 From: awork Date: Wed, 14 Oct 2026 17:55:53 +0800 Subject: [PATCH 1/8] =?UTF-8?q?kernel:=20normalize=20user-side=20part=20or?= =?UTF-8?q?der=20for=20Vertex=20=E2=80=94=20plain=20text=20before=20functi?= =?UTF-8?q?onResponse=20(#3159)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Vertex rejects a request whose user content carries plain (unsigned, non-thought) text AFTER a functionResponse part with 400 'Requests ending with a model turn are not supported' (controlled A/B matrix in #3159; Gemini Developer API accepts both orders). coreToGoogle's flushUser reassembled every user run as [responses..., content...], so even a client sending the safe [text, functionResponse] order was forwarded defective. Add normalizeGoogleUserPartOrder (stable partition; signed/thought/non-text parts never move; byte-stable no-op when no plain text follows a functionResponse) and apply it in flushUser. Bump acp-kernel to 0.0.124. --- kernel/package.json | 2 +- kernel/src/wire/google.ts | 47 ++++++++++++++++--- kernel/tests/wire-google.test.ts | 77 ++++++++++++++++++++++++++++++++ 3 files changed, 119 insertions(+), 7 deletions(-) diff --git a/kernel/package.json b/kernel/package.json index 5f54201184..de57e579e5 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.123", + "version": "0.0.124", "description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.", "license": "MIT", "author": "ranxianglei", diff --git a/kernel/src/wire/google.ts b/kernel/src/wire/google.ts index 78cfb81159..66ae501c98 100644 --- a/kernel/src/wire/google.ts +++ b/kernel/src/wire/google.ts @@ -97,8 +97,9 @@ export function googleToCore(body: GoogleRequestBody): GoogleFlat { const parts = Array.isArray(content.parts) ? content.parts : []; const isModel = content.role === "model"; - // 1. Tool results first: the rebuilt user content must lead with its - // functionResponse parts. + // 1. Tool results first: their cores precede the content's own user core + // (pairing order); the rebuild's PART order is normalized separately + // (coreToGoogle / #3159). for (const part of parts) { const fr = part.functionResponse; if (!fr || typeof fr.name !== "string") continue; @@ -211,13 +212,44 @@ export function googleToCore(body: GoogleRequestBody): GoogleFlat { return { msgs, systemText: googleSystemText(body) }; } +/** #3159 — Vertex rejects a request whose user content carries plain text + * AFTER a functionResponse part ("Requests ending with a model turn are not + * supported"); text-before-functionResponse is accepted (controlled A/B on + * the official endpoint, gemini-4-argon). When a movable plain-text part + * trails a functionResponse, stable-partition the unsigned non-thought plain + * text ahead of every non-text part; otherwise return the input untouched so + * already-safe shapes stay byte-identical (prefix-cache anchor). Signed text + * parts, thought parts and all non-text parts keep their relative order — + * nothing is dropped, renamed or rewritten. */ +export function normalizeGoogleUserPartOrder(parts: GooglePart[]): GooglePart[] { + const firstFr = parts.findIndex((p) => p.functionResponse !== undefined); + if (firstFr === -1) return parts; + const movable = (p: GooglePart) => + typeof p.text === "string" && + p.thought !== true && + typeof p.thoughtSignature !== "string"; + let reorder = false; + for (let i = firstFr; i < parts.length; i++) { + if (movable(parts[i]!)) { + reorder = true; + break; + } + } + if (!reorder) return parts; + const moved: GooglePart[] = []; + const rest: GooglePart[] = []; + for (const p of parts) (movable(p) ? moved : rest).push(p); + return [...moved, ...rest]; +} + /** Rebuild Gemini `contents` from kernel messages. Runs of same-side cores * are merged into ONE content (Gemini rejects non-alternating roles): an * assistant run becomes a single `{"role":"model"}` content whose parts are * ordered reasoning, text, tool-call; a user-side run (user + tool-result) - * becomes a single `{"role":"user"}` content whose functionResponse parts - * lead. Mid-conversation system cores (host-synthetic; Gemini has no system - * role inside contents) ride on the user side as a text part. */ + * becomes a single `{"role":"user"}` content normalized by + * normalizeGoogleUserPartOrder (#3159: plain text leads, functionResponse + * parts trail). Mid-conversation system cores (host-synthetic; Gemini has no + * system role inside contents) ride on the user side as a text part. */ export function coreToGoogle(messages: BiliMessage[]): GoogleContent[] { const out: GoogleContent[] = []; let model: { @@ -234,7 +266,10 @@ export function coreToGoogle(messages: BiliMessage[]): GoogleContent[] { }; const flushUser = () => { if (!user) return; - const parts = [...user.responses, ...user.content]; + const parts = normalizeGoogleUserPartOrder([ + ...user.responses, + ...user.content, + ]); user = null; if (parts.length > 0) out.push({ role: "user", parts }); }; diff --git a/kernel/tests/wire-google.test.ts b/kernel/tests/wire-google.test.ts index 582499784f..2600359f55 100644 --- a/kernel/tests/wire-google.test.ts +++ b/kernel/tests/wire-google.test.ts @@ -6,6 +6,8 @@ import { googleSystemText, googleToCore, injectGoogleSystem, + normalizeGoogleUserPartOrder, + type GooglePart, type GoogleRequestBody, } from "../src/wire/google.js"; import { @@ -389,3 +391,78 @@ test("google: edited core text re-renders plain while sibling raw parts and sign { videoMetadata: { startOffset: 0 } }, ]); }); + +test("normalizeGoogleUserPartOrder: stable partition; signed/thought/non-text parts never move", () => { + const fr: GooglePart = { + functionResponse: { name: "add", response: { result: 66 }, id: "c1" }, + }; + const pure: GooglePart[] = [ + { text: "hello" }, + { inlineData: { mimeType: "image/png", data: "x" } }, + ]; + assert.equal(normalizeGoogleUserPartOrder(pure), pure); + assert.deepEqual( + normalizeGoogleUserPartOrder([ + fr, + { text: "nudge" }, + { inlineData: { mimeType: "image/png", data: "x" } }, + { text: "more" }, + ]), + [ + { text: "nudge" }, + { text: "more" }, + fr, + { inlineData: { mimeType: "image/png", data: "x" } }, + ], + ); + const signed: GooglePart = { text: "signed", thoughtSignature: "sig" }; + const thought: GooglePart = { text: "thinking", thought: true }; + assert.deepEqual( + normalizeGoogleUserPartOrder([fr, signed, thought, { text: "plain" }]), + [{ text: "plain" }, fr, signed, thought], + ); +}); + +test("coreToGoogle rebuilds a mixed user run with plain text before functionResponse parts (#3159)", () => { + const body: GoogleRequestBody = { + contents: [ + { role: "user", parts: [{ text: "go" }] }, + { + role: "model", + parts: [{ functionCall: { name: "add", args: { a: 37, b: 29 }, id: "c1" } }], + }, + { + role: "user", + parts: [ + { functionResponse: { name: "add", response: { result: 66 }, id: "c1" } }, + { text: "nudge" }, + ], + }, + ], + }; + const contents = coreToGoogle(googleToCore(body).msgs); + assert.deepEqual(contents[2]!.parts, [ + { text: "nudge" }, + { functionResponse: { name: "add", response: { result: 66 }, id: "c1" } }, + ]); +}); + +test("an already-safe user part order round-trips byte-identical through coreToGoogle (#3159)", () => { + const body: GoogleRequestBody = { + contents: [ + { role: "user", parts: [{ text: "go" }] }, + { + role: "model", + parts: [{ functionCall: { name: "add", args: { a: 37, b: 29 }, id: "c1" } }], + }, + { + role: "user", + parts: [ + { text: "nudge" }, + { functionResponse: { name: "add", response: { result: 66 }, id: "c1" } }, + ], + }, + ], + }; + assert.deepEqual(coreToGoogle(googleToCore(body).msgs), body.contents); +}); From f96e7064aa1a9552e07f2626edb987d4e16d75fd Mon Sep 17 00:00:00 2001 From: awork Date: Wed, 14 Oct 2026 17:55:53 +0800 Subject: [PATCH 2/8] fix(server): normalize google nudge/note appends so text leads the trailing content (#3159) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit appendGoogleNudge appended any trailing note or nudge text AFTER the existing parts of the last user content — after a tool response that produced the same Vertex 400 shape the kernel rebuild fixed (the note was added post-rebuild, so the kernel fix alone could not cover it). Wrap the appended parts in the kernel's normalizeGoogleUserPartOrder so the new text leads; all append callers (nudge, system-anchor notes, image notes) share this one boundary. --- src/server/prepare-google.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/server/prepare-google.ts b/src/server/prepare-google.ts index 4ef4edfb4d..e8e0f14b5f 100644 --- a/src/server/prepare-google.ts +++ b/src/server/prepare-google.ts @@ -1,7 +1,7 @@ import http from "node:http"; import type { CompressionCore, Config, CoreMessage, NudgeDecision, PackSurface, Prompts } from "acp-kernel"; import { renderNudgeText, viableRanges } from "acp-kernel"; -import { coreToGoogle, googleToCore, type BiliMessage, type GoogleContent, type GoogleRequestBody, type GoogleSystemInstruction, type GoogleTool } from "acp-kernel/wire"; +import { coreToGoogle, googleToCore, normalizeGoogleUserPartOrder, type BiliMessage, type GoogleContent, type GoogleRequestBody, type GoogleSystemInstruction, type GoogleTool } from "acp-kernel/wire"; import type { ProxyOptions } from "../config.js"; import { currentCalibrationFactor } from "../util.js"; import { diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, reapOrphansLogged, runNudgeDecision, stripKernelSummaries, usageGradeInputBaseline, type Prepared } from "../server.js"; @@ -31,7 +31,12 @@ function appendGoogleNudge(contents: GoogleContent[], text: string): GoogleConte const last = contents[contents.length - 1]; if (last && (last.role ?? "user") !== "model") { const parts = Array.isArray(last.parts) ? last.parts : []; - return [...contents.slice(0, -1), { ...last, parts: [...parts, { text }] }]; + // #3159: a plain-text tail after a functionResponse part 400s on + // Vertex — normalize so the new text leads. + return [ + ...contents.slice(0, -1), + { ...last, parts: normalizeGoogleUserPartOrder([...parts, { text }]) }, + ]; } return [...contents, { role: "user", parts: [{ text }] }]; } From 8432d29d5b66aeafc34a530761998e882d6aee22 Mon Sep 17 00:00:00 2001 From: awork Date: Wed, 14 Oct 2026 17:55:53 +0800 Subject: [PATCH 3/8] test: WC-017 wire-contract rule + #3159 regression suites MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add WC-017 to the wire-contract ledger (Vertex rejects plain unsigned non-thought text after a functionResponse part in user content; provenance: #3159 production 400 + controlled A/B matrix), enforced in the validation-parity fake on every forwarded Google body plus a unit gate and ledger self-check probe. New e2e regression drives both producers through the real proxy against the enforcing fake: a system-anchor drift note appended after a tool response, and a client's own defective [functionResponse, text] order — both must forward with text first or the fake relays its 400. --- tests/issue3159-vertex-nudge-order.test.ts | 166 +++++++++++++++++++++ tests/wire-contract-fakes.ts | 41 ++++- tests/wire-contract.test.ts | 18 +++ 3 files changed, 223 insertions(+), 2 deletions(-) create mode 100644 tests/issue3159-vertex-nudge-order.test.ts diff --git a/tests/issue3159-vertex-nudge-order.test.ts b/tests/issue3159-vertex-nudge-order.test.ts new file mode 100644 index 0000000000..995d67334f --- /dev/null +++ b/tests/issue3159-vertex-nudge-order.test.ts @@ -0,0 +1,166 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { once } from "node:events"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { startFakeUpstream, VALIDATORS } from "./wire-contract-fakes.ts"; + +// Regression for #3159: Vertex rejects a request whose user content carries +// plain text AFTER a functionResponse part ("Requests ending with a model +// turn are not supported"). Bili used to produce that shape two ways: +// appendGoogleNudge appended any trailing note/nudge text after the trailing +// functionResponse part, and coreToGoogle's flushUser reassembled user runs +// as [responses..., content...] regardless of the client's own order. Both +// boundaries now stable-partition plain text before non-text parts. The +// validation-parity fake enforces WC-018 on every forwarded body, so a +// regression relays the fake's 400 instead of passing silently. +// +// Triggers are chosen to be deterministic with the shared fake (its +// usageMetadata hardcodes promptTokenCount:10, so kernel-nudge growth arming +// can never fire here); the sysNotes drift below drives the SAME +// appendGoogleNudge call site the nudge uses, so the host boundary is covered +// either way. + +interface Harness { + proxyUrl: string; + close(): Promise; +} + +async function startHarness(fakeUrl: string): Promise { + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + const opts: ProxyOptions = { + port: 0, + host: "127.0.0.1", + upstream: fakeUrl, + routes: { [fakeUrl]: { models: { "gemini-test": { context: 1_000_000 } } } }, + modelContextLimit: 1_000_000, + kernelConfig: defaultConfig(1_000_000), + compress: { injectTool: true, injectNudge: true }, + // Explicit: ProxyOptions does not inherit the file-config default, and + // the sysNotes trigger below requires the anchor reconciler to run. + stableSystemAnchor: true, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + compat: { roles: {} }, + streamErrorShape: "protocol", + passthroughSource: null, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: false, + mitm: { enabled: false, domains: [] }, + }; + const proxy = await startServer(opts); + await once(proxy, "listening"); + const port = (proxy.address() as { port: number }).port; + return { + proxyUrl: `http://127.0.0.1:${port}/bili/${fakeUrl}`, + close: () => new Promise((resolve, reject) => proxy.close((e) => (e ? reject(e) : resolve()))), + }; +} + +const TURN_1_CONTENTS = [{ role: "user", parts: [{ text: "What is 37 plus 29?" }] }]; +// Multi-line heads: a 1→2 line change scores 0.5 on the anchor's shared-line +// ratio (DIFF_MIN_SHARED 0.7) and is treated as structural (no note); 10→11 +// lines scores 10/11 and stays a localized edit worth annotating. +const BASE_SYSTEM = Array.from({ length: 10 }, (_, i) => `line ${i + 1}`).join("\n"); +const MODEL_TURN = { role: "model", parts: [{ functionCall: { name: "add", args: { a: 37, b: 29 }, id: "call_1" } }] }; +const TOOL_RESPONSE_PART = { functionResponse: { name: "add", response: { result: 66 }, id: "call_1" } }; + +async function sendTurn(h: Harness, sessionId: string, contents: unknown[], system?: { parts: Array<{ text: string }> }): Promise { + const res = await fetch(`${h.proxyUrl}/v1beta/models/gemini-test:streamGenerateContent?alt=sse`, { + method: "POST", + headers: { "content-type": "application/json", "x-acp-session": sessionId }, + body: JSON.stringify({ contents, ...(system ? { systemInstruction: system } : {}), generationConfig: { maxOutputTokens: 4096 } }), + }); + await res.text(); + return res.status; +} + +test("#3159 vertex: trailing note appended after a tool response forwards with text BEFORE functionResponse", async () => { + const fake = await startFakeUpstream("google"); + let h: Harness | undefined; + try { + h = await startHarness(fake.url); + // Turn 1 captures the system anchor silently; turn 2's localized + // head-system change makes reconcileSystemAnchor emit a diff note, + // which appendGoogleNudge appends to the trailing user content — the + // exact #3159 shape (plain text after the functionResponse part). + assert.equal(await sendTurn(h, "issue3159-note", TURN_1_CONTENTS, { parts: [{ text: BASE_SYSTEM }] }), 200, "turn 1 baseline completes"); + const turn2Status = await sendTurn( + h, + "issue3159-note", + [...TURN_1_CONTENTS, MODEL_TURN, { role: "user", parts: [TOOL_RESPONSE_PART] }], + { parts: [{ text: `${BASE_SYSTEM}\nUPDATED LINE` }] }, + ); + assert.equal(turn2Status, 200, "turn 2 must complete — a WC-018 violation would relay the fake's 400"); + assert.equal(fake.violations.length, 0, `fake upstream violations:\n${fake.violations.join("\n")}`); + + const capturedBody = fake.requests[1]?.body as + | { contents?: Array<{ role?: string; parts?: Array> }> } + | undefined; + assert.ok(capturedBody?.contents, "upstream saw the turn-2 request with contents"); + const last = capturedBody.contents[capturedBody.contents.length - 1]!; + assert.equal(last.role, "user"); + const parts = last.parts ?? []; + assert.ok(parts.length >= 2, `expected note text + functionResponse part, got ${JSON.stringify(parts)}`); + assert.equal(typeof parts[0]?.text, "string", "forwarded user content leads with the NOTE TEXT part"); + assert.ok(String(parts[0]?.text).includes("UPDATED"), "the appended text is the system-drift diff note"); + assert.equal((parts[1]?.functionResponse as { id?: string } | undefined)?.id, "call_1", "the functionResponse trails the note text"); + + const wc017 = VALIDATORS.google(capturedBody).filter((v) => v.startsWith("WC-018")); + assert.deepEqual(wc017, [], `no WC-018 violations in the forwarded turn-2 body:\n${wc017.join("\n")}`); + } finally { + if (h) await h.close(); + await fake.close(); + } +}); + +test("#3159 vertex: defective client order (functionResponse before text) is normalized on rebuild", async () => { + const fake = await startFakeUpstream("google"); + let h: Harness | undefined; + try { + h = await startHarness(fake.url); + assert.equal(await sendTurn(h, "issue3159-reorder", TURN_1_CONTENTS), 200, "turn 1 baseline completes"); + // No system instruction ⇒ no anchor notes; tiny session with flat + // reported usage ⇒ nudge idle. Nothing appends — the forwarded shape + // is the pure rebuild of the client's own defective order. + assert.equal( + await sendTurn( + h, + "issue3159-reorder", + [...TURN_1_CONTENTS, MODEL_TURN, { role: "user", parts: [TOOL_RESPONSE_PART, { text: "carry on" }] }], + ), + 200, + "turn 2 completes — pre-fix this forwarded [functionResponse, text] and the fake relayed its 400", + ); + assert.equal(fake.violations.length, 0, `fake upstream violations:\n${fake.violations.join("\n")}`); + + const capturedBody = fake.requests[1]?.body as + | { contents?: Array<{ role?: string; parts?: Array> }> } + | undefined; + const last = capturedBody?.contents?.[capturedBody.contents.length - 1]; + assert.ok(last, "forwarded body has contents"); + const parts = last.parts ?? []; + // Tagged text parts carry the kernel's ACP ref tag (an + // mNNNNN element, hex-escaped per KDD#2) followed by + // "\n" + the original text — pre-existing Google-lane rendering + // present at turn 1 and in sessions without any functionResponse + // (control-probe verified), orthogonal to the #3159 ordering fix. + const t0 = typeof parts[0]?.text === "string" ? parts[0].text : ""; + assert.ok(t0.startsWith("\x3cacp "), "first part is the tagged text part"); + assert.ok(t0.endsWith("\ncarry on"), "client text preserved verbatim after the rendered tag"); + assert.deepEqual(parts[1], TOOL_RESPONSE_PART, "the functionResponse part follows the text, byte-exact"); + } finally { + if (h) await h.close(); + await fake.close(); + } +}); diff --git a/tests/wire-contract-fakes.ts b/tests/wire-contract-fakes.ts index 711f0209da..c3239afff9 100644 --- a/tests/wire-contract-fakes.ts +++ b/tests/wire-contract-fakes.ts @@ -38,6 +38,16 @@ export const WIRE_RULES: readonly WireRule[] = [ provenance: "bili #3063 production silent failure (codex 0.162.0-alpha.17.2 through /bili/ prefix routing on bili 0.1.183+: upstream counted input tokens, produced zero output, turn ended completed; identical via --passthrough). Cross-checked against openai/codex source: codex-rs/codex-api/src/common.rs ResponseCreateWsRequest declares stream: bool as a required serialized field (no skip_serializing_if) and serializes stream_options when present; codex-rs/core/tests/suite/client_websockets.rs asserts body[\"stream\"] == true on the wire. Repair: src/responses-ws.ts re-attaches the client's transport fields at egress (egressTransportFields); supersedes WC-013's over-generalized scope for the codex lane.", }, + { + // #3159: landed as WC-017 on the feature branch; master's #3072 took + // that id first (codex lane), so this rule renumbers to WC-018 on rebase. + id: "WC-018", + wire: "google", + summary: + "Vertex rejects a request whose user content carries plain (unsigned, non-thought) text AFTER a functionResponse part — 400 'Requests ending with a model turn are not supported'; text-before-functionResponse is accepted. bili normalizes user-side part order at both boundaries: coreToGoogle's flushUser and appendGoogleNudge (stable partition of movable plain text ahead of non-text parts; signed/thought parts never move)", + provenance: + "bili #3159 production 400 (dsh-vertex-argon 1.1.4 / DSH 0.2.0-rc.2 over billion-context 0.1.196, official Vertex endpoint, gemini-4-argon generateContent): after a successful tool call the next request 400'd because Bili appended a plain-text nudge AFTER the trailing functionResponse part. Controlled A/B matrix on the official endpoint (issue table, 2026-10-14): [functionResponse]→200, [functionResponse, text]→400, [text, functionResponse]→200. The Gemini Developer API accepts both orders — the strictness is Vertex-specific.", + }, { id: "WC-016", wire: "anthropic", @@ -454,10 +464,37 @@ export function validateCodexResponsesWsCreate(body: unknown): string[] { return out; } -/** WC-006 on a Gemini generateContent/streamGenerateContent body. */ +/** WC-006, WC-018 on a Gemini generateContent/streamGenerateContent body. */ function validateGoogleBody(body: unknown): string[] { const out: string[] = []; - if (!isPlainObject(body) || !Array.isArray(body.tools)) return out; + if (!isPlainObject(body)) return out; + // WC-018: Vertex rejects a request whose user content carries plain + // (unsigned, non-thought) text AFTER a functionResponse part — 400 + // "Requests ending with a model turn are not supported" (#3159). Runs + // before the tools early-return like every other contents-level rule. + if (Array.isArray(body.contents)) { + body.contents.forEach((content, i) => { + if (!isPlainObject(content) || content.role === "model") return; + if (!Array.isArray(content.parts)) return; + let seenFr = false; + content.parts.forEach((part, j) => { + if (!isPlainObject(part)) return; + if (part.functionResponse !== undefined) { + seenFr = true; + return; + } + if ( + seenFr && + typeof part.text === "string" && + part.thought !== true && + typeof part.thoughtSignature !== "string" + ) { + out.push(`WC-018 contents[${i}].parts[${j}]: plain text part follows a functionResponse part — Vertex rejects user content ending on a model turn (#3159)`); + } + }); + }); + } + if (!Array.isArray(body.tools)) return out; body.tools.forEach((entry, i) => { if (!isPlainObject(entry) || !Array.isArray(entry.functionDeclarations)) return; entry.functionDeclarations.forEach((d, j) => { diff --git a/tests/wire-contract.test.ts b/tests/wire-contract.test.ts index ecc68dce6a..87ead5787b 100644 --- a/tests/wire-contract.test.ts +++ b/tests/wire-contract.test.ts @@ -104,6 +104,22 @@ test("WC-016 validates global-scope breakpoint ordering (render order: tools → }), []); }); +test("WC-018 validates user-side part order on the Google wire (plain text before functionResponse)", () => { + // #3159 shape: plain text AFTER a functionResponse part → Vertex 400. + assert.match(VALIDATORS.google({ + contents: [{ role: "user", parts: [{ functionResponse: { name: "add", response: { result: 66 } } }, { text: "nudge" }] }], + })[0], /WC-018/); + // Legal: text leads, functionResponse trails (the A/B-accepted order). + assert.deepEqual(VALIDATORS.google({ + contents: [{ role: "user", parts: [{ text: "nudge" }, { functionResponse: { name: "add", response: { result: 66 } } }] }], + }), []); + // Signed plain text is excluded from the movable set (signature-bound) — the + // validator mirrors the kernel's normalizeGoogleUserPartOrder predicate. + assert.deepEqual(VALIDATORS.google({ + contents: [{ role: "user", parts: [{ functionResponse: { name: "add", response: {} } }, { text: "signed", thoughtSignature: "sig" }] }], + }), []); +}); + function syntheticBody(wire: Wire, tool: unknown): Record { if (wire === "google") return { tools: [{ functionDeclarations: [tool] }] }; return { tools: [tool] }; @@ -171,6 +187,8 @@ test("wire-contract ledger: every rule has a live enforcement clause", () => { google: [ { tools: [{ functionDeclarations: [{ name: "bad-name", parameters: { type: "object", properties: {} } }] }] }, { tools: [{ functionDeclarations: [{ name: "ok", parameters: { anyOf: [] } }] }] }, + // WC-018: the #3159 shape — plain text after a functionResponse part. + { contents: [{ role: "user", parts: [{ functionResponse: { name: "add", response: {} } }, { text: "nudge" }] }] }, ], }; for (const rule of WIRE_RULES) { From 67633bb6fdf17d8ef11be203c24e2e8b5905f1f9 Mon Sep 17 00:00:00 2001 From: awork Date: Wed, 14 Oct 2026 18:05:49 +0800 Subject: [PATCH 4/8] chore: sync package-lock with acp-kernel 0.0.124 (#3159) --- package-lock.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package-lock.json b/package-lock.json index 24672c3853..3797abaa8b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -48,7 +48,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.123", + "version": "0.0.124", "dev": true, "license": "MIT", "devDependencies": { From 540d4414221274f8b8ad75f7a834f242c2b68774 Mon Sep 17 00:00:00 2001 From: awork Date: Wed, 14 Oct 2026 19:30:25 +0800 Subject: [PATCH 5/8] test: sanction the #3159 canonical part order in the cache-friendly plugin matrix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The google lane now forwards user contents ending on tool results with new plain-text parts LEADING (Vertex rejects text after functionResponse, #3159). Between a fold turn and the next, the previous body's trailing tool units therefore shift right past an inserted run of text units from the same content — assertPrefix gains a scoped allowCanonShift that sanctions exactly that move (google lane, two call sites); every other comparison stays an exact byte-prefix. --- tests/cache-friendly-plugin.test.ts | 34 ++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/tests/cache-friendly-plugin.test.ts b/tests/cache-friendly-plugin.test.ts index 37d9d70250..f6cd006e32 100644 --- a/tests/cache-friendly-plugin.test.ts +++ b/tests/cache-friendly-plugin.test.ts @@ -22,6 +22,13 @@ // an EXACT byte-prefix of the next (mid-history never mutates); the // volatile tail slots (chain checkpoint / nudge / imgNote / retrieval // note, ≤ 4) may only appear as a contiguous tail run; +// #3159 (google lane only): Vertex rejects plain text after a +// functionResponse part inside one user content, so coreToGoogle +// forwards such a content with the plain-text parts LEADING — when a +// user content ending on tool results gains new text parts between +// turns, the previous body's trailing tool units shift right past the +// inserted text run (assertPrefix's allowCanonShift sanctions exactly +// that move); every other byte stays an exact prefix; // P2 fold transitions (client re-sends its compress pair after a // /__bili/plugin/tool fold): // P2a the pre-fold span is replaced by exactly the expected carrier @@ -290,11 +297,26 @@ function canonEq(a: Unit[], b: Unit[], label: string): void { } } -function assertPrefix(prev: Unit[], next: Unit[], label: string, expectNew: string[]): void { - for (let i = 0; i < prev.length; i++) { - assert.ok(eqUnit(prev[i]!, next[i]!), `${label}: mid-history unit[${i}] mutated\n previous=${JSON.stringify(prev[i])}\n next =${JSON.stringify(next[i])}`); +// #3159 (google lane only): a user content ending on functionResponse parts +// is forwarded with new plain-text parts LEADING, so between turns the +// previous body's trailing tool units shift right past an inserted run of +// text units from that same content. allowCanonShift sanctions exactly that +// move — text-unit insertions immediately before a surviving byte-equal tool +// unit — and nothing else; any other mutation still fails. +function assertPrefix(prev: Unit[], next: Unit[], label: string, expectNew: string[], allowCanonShift = false): void { + let pi = 0; + let ni = 0; + while (pi < prev.length) { + if (ni < next.length && eqUnit(prev[pi]!, next[ni]!)) { pi++; ni++; continue; } + const p = prev[pi]!; + const n = ni < next.length ? next[ni]! : null; + assert.ok(allowCanonShift && p.k !== "text" && n !== null && n.k === "text", `${label}: mid-history unit[${pi}] mutated\n previous=${JSON.stringify(p)}\n next =${JSON.stringify(n)}`); + let k = 0; + while (ni + k < next.length && next[ni + k]!.k === "text") k++; + assert.ok(k > 0 && ni + k < next.length && eqUnit(p, next[ni + k]!), `${label}: unit[${pi}] not realigned after ${k} inserted text unit(s)\n previous=${JSON.stringify(p)}\n next =${JSON.stringify(next.slice(ni, ni + k + 1))}`); + ni += k; } - const added = next.slice(prev.length); + const added = next.slice(ni); assert.deepEqual(added.map(keyOf), expectNew, `${label}: appended units ${JSON.stringify(added.map(keyOf))} != expected ${JSON.stringify(expectNew)}`); } @@ -590,9 +612,9 @@ for (const wire of ["anthropic", "openai", "responses", "google"] as Wire[]) { assertPrefix(cans[0]!.core, cans[1]!.core, L(1), ["q3", "a3"]); assertPrefix(cans[1]!.core, cans[2]!.core, L(2), ["q4", "a4"]); assertFoldTransition(cans[2]!.core, cans[3]!.core, ["q1", "a1"], ["q1"], L(3)); // head boundary survives; anchor stripped (#1567) - assertPrefix(cans[3]!.core, cans[4]!.core, L(4), ["q5", "a5"]); + assertPrefix(cans[3]!.core, cans[4]!.core, L(4), wire === "google" ? ["a5"] : ["q5", "a5"], wire === "google"); // google: #3159 — q5 leads the fold-pair result assertFoldTransition(cans[4]!.core, cans[5]!.core, ["q2", "a2", "q3"], [], L(5)); // anchor stripped (#1567) - assertPrefix(cans[5]!.core, cans[6]!.core, L(6), ["q7", "a7"]); + assertPrefix(cans[5]!.core, cans[6]!.core, L(6), wire === "google" ? ["a7"] : ["q7", "a7"], wire === "google"); // google: #3159 — q7 leads the fold-pair result assertPrefix(cans[6]!.core, cans[7]!.core, L(7), ["q8", "a8"]); for (let i = 3; i < cans.length; i++) { From f8f5b2f6257cda5daa3c4c30580f829390782312 Mon Sep 17 00:00:00 2001 From: awork Date: Wed, 14 Oct 2026 19:42:50 +0800 Subject: [PATCH 6/8] test: regenerate google storage-render golden for #3159 wire re-layout MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The golden scenario drives tool pairs on every even turn, so each merged user run [fr, next-text] hits exactly the shape Vertex rejects and the normalizer now re-lays out. Outbound body digests from turn 1 onward and the fold-reconciliation canon snapshot (metadata.foldPositions) reflect the new layout; state/blockContents/stats sections are unchanged. Only google.json drifts — chat/anthropic/responses regenerate byte-identical. --- tests/golden/storage-render/google.json | 32 ++++++++++++------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/tests/golden/storage-render/google.json b/tests/golden/storage-render/google.json index bf63a7de42..e7f3129df0 100644 --- a/tests/golden/storage-render/google.json +++ b/tests/golden/storage-render/google.json @@ -8,84 +8,84 @@ }, { "i": 1, - "sha": "f2304ead1cb1ba6a45d9a9fe3ee1adf428bd2da6c9b6c0868b057f5de88e5448", + "sha": "e91922e4e9c8bd804a5d70851c6eb36c35313fee08f3f8ed03c3370edc1973f1", "bytes": 28994 }, { "i": 2, - "sha": "f3caead28fe9f5463298037010de4a6da7e193893c394350ee856f88604fe10e", + "sha": "7ad79bc2a5cb75357b00a31f01a07a65ea543af87a2a84be52020c1f906512a7", "bytes": 34820 }, { "i": 3, - "sha": "8f1bb1090a0f451375e0842dd2cf6c098e27981b395d06d508095b49a076da5b", + "sha": "7d107e28634d26ee51033febb7fabc9ad3e8861180bb41a8ceaf5b393e9772c1", "bytes": 43375 }, { "i": 4, - "sha": "994526737d0e88ac920d46083bec343fcd6df1d3dab9389db578c5d05dbff902", + "sha": "6e8f516b2992ecd7b1cb8575bb272cd0a83afa0e1c48ed9172c34786f61bd11a", "bytes": 49201 }, { "i": 5, - "sha": "63da90071ec92f7ba2d3311a213ceb89d2b71fedb4c6bf36e46e72c672ea3bfd", + "sha": "448ad969da6c56cba686e0a978c93a388973d6cca1138eeb2b0e71d3e3f4e096", "bytes": 57756 }, { "i": 6, - "sha": "7973c51f87afe5c86f1db405fb35bc08adf0bb12260ebe55573d0aa47df4f385", + "sha": "c2dc7f94e11d9bf97804d38f1f2f75126c7e2d63aa252b9335f322f8ad2df6f0", "bytes": 63582 }, { "i": 7, - "sha": "a5052cf869a79bc59ff45e54b9cd54128792815c0e6e8252fcb587ffaf2d3b92", + "sha": "49a33d09117cd0bf72e6e7bd6743eefe2a2b7c0e163030f1a25f7d8a5f7b8a92", "bytes": 72137 }, { "i": 8, - "sha": "6f0f9a6e59865a099e40deae587d3d33955561a5f8e8e3a2218f8117b7c75fd9", + "sha": "20908c180801039f546635431c7c28f71b2de10f9672aff1f88bd2d3e549b9a6", "bytes": 77963 }, { "i": 9, - "sha": "48796aeee1714ad38248edbf25b78cb61a4ca3eb82fb8afeca79fb42e53260dc", + "sha": "6289a41bdefd707971fe7786e0eb427280439fdea15456a6c2820f511ab05529", "bytes": 50549 }, { "i": 10, - "sha": "884a2721898db188264dc89f82e8396cdb01d0f15c7e7cbe1f15a6ec7f15d9f7", + "sha": "99589eac7dc278aab04407c4ccf50163873c49b295c785fbe5b273d37ba2fec8", "bytes": 57952 }, { "i": 11, - "sha": "fca8f37555a5cc691f1ababdde584af0a132d29ff2bdca435c231e763751a50a", + "sha": "c7d18ef1a3f77a5650adbb7c4d186a8c68976f839b557fa5605200b38576b09d", "bytes": 63701 }, { "i": 12, - "sha": "540646448d404876a083e4073aab59e1e14ede8aea31d0a563fb4c38cfc848fe", + "sha": "1676577abc874430e62c3fcc195a8bb1a020e95aaab177503e21e833a5f4f814", "bytes": 77706 }, { "i": 13, - "sha": "447cdfbb1e875a06d8f20bdcedb79434095614e207a014ed113196673b6a7705", + "sha": "976bc5a9fc08922ec38ac5200692bc1963b7ccbf7768cbcd7329dee78c192d38", "bytes": 83455 }, { "i": 14, - "sha": "f418b52a98a55c5dd7c328fcbc256928887667e2dc46f51b14d9eaf16e358edd", + "sha": "3e44a6cc5e31953a4c6226092c1a8c8074af5140cdd9949db4956d1e72f9677a", "bytes": 91985 } ], "foldAt": 9, "editedAt": 12, "summaryFrom": 9, - "stateDigest": "a0ad11b7ba567ea6d182847f2a9a17c9700b1793f241c6e08adfe73c5172a112", + "stateDigest": "5c251c4a8a500fc632322cef332b32eb4e8317514e6db23df543af20e69293e7", "sectionDigests": { "state": "6d2f312d7bc924d7", "blockContents": "473264d9df8ba338", "stats": "5702a6493cdfe768", - "metadata": "fe714004e9ae3104" + "metadata": "dd033100655bd59d" }, "stateKeyDigests": { "blocks": "8e14f0879bf7ebd7", From 5848ce51347e220fd31660cef4ae90ad00b17622 Mon Sep 17 00:00:00 2001 From: awork Date: Wed, 14 Oct 2026 19:55:48 +0800 Subject: [PATCH 7/8] fix: normalize part order at the remaining post-assembly Google boundaries (#3159) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two more producers of the WC-017 shape survived the rebuild-level fix: appendTrailingUserText (degenerate-turn retry nudge — enabled by default, and the opt-in fake-completion hint) merges its text into the last user content's parts AFTER the body is assembled, and insertCheckpointCarrier (opt-in outbound chain stamp, relay egress) appends the carrier tag the same way. Both landed plain text after a trailing functionResponse part — exactly what Vertex rejects — invisible to the kernel rebuild and to appendGoogleNudge. Both boundaries now consume the exported normalizeGoogleUserPartOrder; safe shapes stay byte-identical. Regression gates added to the #3159 suite: exact order assertions plus a WC-017 ledger-validator check on each mutated body, and a no-defect byte-stable control. --- src/chain-checkpoint.ts | 7 ++++-- src/wire-body.ts | 5 +++- tests/issue3159-vertex-nudge-order.test.ts | 28 ++++++++++++++++++++++ 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/src/chain-checkpoint.ts b/src/chain-checkpoint.ts index d9c93ae647..cffdb20a3a 100644 --- a/src/chain-checkpoint.ts +++ b/src/chain-checkpoint.ts @@ -1,5 +1,6 @@ import { createHash } from "node:crypto"; import type { WireProtocol } from "./util.js"; +import { normalizeGoogleUserPartOrder, type GooglePart } from "acp-kernel/wire"; // #1357/#1395/#1421 — Chain Checkpoint (first-processor-wins idempotent interop). // A request-level checkpoint marks a request that already passed through a @@ -542,15 +543,17 @@ export function insertCheckpointCarrier(parsed: unknown, wire: WireProtocol, tag const role = typeof c.role === "string" ? c.role : "user"; if (role !== "model") { const parts = Array.isArray(c.parts) ? (c.parts as unknown[]) : []; + // #3159: plain text after a functionResponse part 400s on Vertex — + // normalize whichever way the carrier lands (replace-in-place or append). const pi = parts.length - 1; const pp = parts[pi]; if (pp && typeof pp === "object" && !Array.isArray(pp)) { const ppo = pp as Record; if (Object.keys(ppo).length === 1 && typeof ppo.text === "string" && parseChainCheckpoint(ppo.text)) { - return { ...body, contents: [...contents.slice(0, li), { ...c, parts: [...parts.slice(0, pi), { text: tag }] }] }; + return { ...body, contents: [...contents.slice(0, li), { ...c, parts: normalizeGoogleUserPartOrder([...parts.slice(0, pi), { text: tag }] as GooglePart[]) }] }; } } - return { ...body, contents: [...contents.slice(0, li), { ...c, parts: [...parts, { text: tag }] }] }; + return { ...body, contents: [...contents.slice(0, li), { ...c, parts: normalizeGoogleUserPartOrder([...parts, { text: tag }] as GooglePart[]) }] }; } } return { ...body, contents: [...contents, { role: "user", parts: [{ text: tag }] }] }; diff --git a/src/wire-body.ts b/src/wire-body.ts index b6e7ba7753..9470ac67b8 100644 --- a/src/wire-body.ts +++ b/src/wire-body.ts @@ -1,4 +1,5 @@ import type { WireProtocol } from "./util.js"; +import { normalizeGoogleUserPartOrder, type GooglePart } from "acp-kernel/wire"; /** Append `text` as a trailing user turn on the wire's own request body. * @@ -44,7 +45,9 @@ export function appendTrailingUserText(protocol: WireProtocol, body: string | Bu const arr = contents as Record[]; const last = arr[arr.length - 1]; if (last && typeof last === "object" && last.role === "user" && Array.isArray(last.parts)) { - last.parts = [...(last.parts as unknown[]), { text }]; + // #3159: plain text after a functionResponse part 400s on Vertex — + // keep the canonical order when merging into a tool-result tail. + last.parts = normalizeGoogleUserPartOrder([...(last.parts as unknown[]), { text }] as GooglePart[]); } else { arr.push({ role: "user", parts: [{ text }] }); } diff --git a/tests/issue3159-vertex-nudge-order.test.ts b/tests/issue3159-vertex-nudge-order.test.ts index 995d67334f..122f7d4e13 100644 --- a/tests/issue3159-vertex-nudge-order.test.ts +++ b/tests/issue3159-vertex-nudge-order.test.ts @@ -7,6 +7,8 @@ import type { ProxyOptions } from "../src/config.ts"; import { SessionStore, _setStoreForTest } from "../src/persist.ts"; import { _setForTest as setRegistryForTest } from "../src/registry.ts"; import { startFakeUpstream, VALIDATORS } from "./wire-contract-fakes.ts"; +import { appendTrailingUserText } from "../src/wire-body.ts"; +import { insertCheckpointCarrier } from "../src/chain-checkpoint.ts"; // Regression for #3159: Vertex rejects a request whose user content carries // plain text AFTER a functionResponse part ("Requests ending with a model @@ -164,3 +166,29 @@ test("#3159 vertex: defective client order (functionResponse before text) is nor await fake.close(); } }); + +// The two post-assembly boundaries that mutate an ALREADY forwarded body: +// appendTrailingUserText (degenerate-turn retry nudge / fake-completion hint) +// and insertCheckpointCarrier (opt-in outbound chain stamp). Both used to +// append text after whatever parts existed — including a trailing +// functionResponse — re-creating the WC-017 shape invisible to the rebuild. +test("#3159 vertex: post-assembly trailing-text merge keeps text before functionResponse", () => { + const out = appendTrailingUserText("google", JSON.stringify({ contents: [{ role: "user", parts: [{ text: "q" }, TOOL_RESPONSE_PART] }] }), "nudge-text")!; + const parsed = JSON.parse(out) as { contents: Array<{ role?: string; parts?: Array> }> }; + const parts = parsed.contents[0]?.parts ?? []; + assert.deepEqual(parts, [{ text: "q" }, { text: "nudge-text" }, TOOL_RESPONSE_PART], "merged text leads the trailing functionResponse"); + assert.deepEqual(VALIDATORS.google(parsed).filter((v) => v.startsWith("WC-017")), [], "merged body carries no WC-017 violation"); + // No defect ⇒ plain append, byte-stable (prefix-cache anchor untouched). + const plain = appendTrailingUserText("google", JSON.stringify({ contents: [{ role: "user", parts: [{ text: "q" }] }] }), "more")!; + assert.deepEqual(JSON.parse(plain), { contents: [{ role: "user", parts: [{ text: "q" }, { text: "more" }] }] }); +}); + +test("#3159 vertex: outbound chain-checkpoint carrier lands before a trailing functionResponse", () => { + const stamped = insertCheckpointCarrier({ contents: [{ role: "user", parts: [{ text: "q" }, TOOL_RESPONSE_PART] }] }, "google", "checkpoint-tag") as + | { contents: Array<{ role?: string; parts?: Array> }> } + | null; + assert.ok(stamped, "carrier inserted into the google body"); + const parts = stamped.contents[0]?.parts ?? []; + assert.deepEqual(parts, [{ text: "q" }, { text: "checkpoint-tag" }, TOOL_RESPONSE_PART], "carrier text leads the trailing functionResponse"); + assert.deepEqual(VALIDATORS.google(stamped).filter((v) => v.startsWith("WC-017")), [], "stamped body carries no WC-017 violation"); +}); From 5fc68be362f57a8396fac0858a09a715dcc869e9 Mon Sep 17 00:00:00 2001 From: awork Date: Wed, 14 Oct 2026 21:17:57 +0800 Subject: [PATCH 8/8] test: re-baseline storage-render google golden onto rebased master (#3159) Master moved the google golden's stateDigest/metadata section digests since our base (post-base state-level changes); re-running the generator on the rebased tree folds master's baseline in under the #3159 part-order re-layout. Turn body shas unchanged by this step; other wires byte-identical. --- tests/golden/storage-render/google.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/golden/storage-render/google.json b/tests/golden/storage-render/google.json index e7f3129df0..feb42d4b49 100644 --- a/tests/golden/storage-render/google.json +++ b/tests/golden/storage-render/google.json @@ -80,12 +80,12 @@ "foldAt": 9, "editedAt": 12, "summaryFrom": 9, - "stateDigest": "5c251c4a8a500fc632322cef332b32eb4e8317514e6db23df543af20e69293e7", + "stateDigest": "e2d98c51df1b704d6167b72081afa72599e1db51bc55170357feb4c22fbf28c3", "sectionDigests": { "state": "6d2f312d7bc924d7", "blockContents": "473264d9df8ba338", "stats": "5702a6493cdfe768", - "metadata": "dd033100655bd59d" + "metadata": "4c966b20f33b4d9b" }, "stateKeyDigests": { "blocks": "8e14f0879bf7ebd7",