From bb71452ca339a9b55e3a23f23cc35de4afcbcd5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Skv=C4=9Bl=C3=BD?= Date: Tue, 20 Oct 2026 16:35:33 +0200 Subject: [PATCH 1/3] kernel: keep mid-conversation anthropic system messages verbatim (#3991) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pi declares tools activated mid-session as tool_addition blocks inside a mid-conversation role:"system" message (and emits empty system messages carrying message-level output_config). anthropicToCore flattened those into the user/assistant block stream and coreToAnthropic re-emitted them as role:"user": on 0.1.202 the tool_addition blocks were dropped (tools never reached the model); on master, with #3410's unknown-block passthrough, upstream 400s ("'tool_addition'/'tool_removal' blocks are only permitted within `role: "system"` messages"). Each wire system message now maps to exactly one core message carrying the original on a rawAnthropicMessage sidecar; coreToAnthropic re-emits it verbatim without merging adjacent user turns. Kernel-synthesized system cores (no sidecar) still map to user. protected.ts classifies the sidecar as unrecoverable so a fold can never destroy a tool declaration. Records the upstream rejection as WC-022 in the wire-contract ledger. kernel-change: wire保真 — anthropic mid-conversation system messages (#3991) --- kernel/src/protected.ts | 5 + kernel/src/wire/anthropic.ts | 49 ++++- kernel/src/wire/bili-message.ts | 6 + ...thropic-system-message-passthrough.test.ts | 172 ++++++++++++++++++ tests/wire-contract-fakes.ts | 17 +- tests/wire-contract.test.ts | 19 ++ 6 files changed, 264 insertions(+), 4 deletions(-) create mode 100644 kernel/tests/anthropic-system-message-passthrough.test.ts diff --git a/kernel/src/protected.ts b/kernel/src/protected.ts index 1e60eda8b3..bffcf94e6c 100644 --- a/kernel/src/protected.ts +++ b/kernel/src/protected.ts @@ -378,6 +378,7 @@ interface MediaSidecar { rawOpenaiContent?: unknown; rawOpenaiContentParts?: unknown[]; rawAnthropicBlock?: unknown; + rawAnthropicMessage?: unknown; rawResponsesItem?: unknown; rawGoogleParts?: unknown[]; } @@ -437,6 +438,10 @@ export function hasMediaPayload(msg: CoreMessage): boolean { export function hasUnrecoverableMediaPayload(msg: CoreMessage): boolean { const m = msg as CoreMessage & MediaSidecar; + // A verbatim anthropic system message (Pi tool_addition deltas): folding it + // would silently un-declare the tools it adds — never fold. + if (m.rawAnthropicMessage != null) return true; + const roc = m.rawOpenaiContent; if (roc != null) { const part = asObj(roc); diff --git a/kernel/src/wire/anthropic.ts b/kernel/src/wire/anthropic.ts index 62eea6adf1..253c7d6d5c 100644 --- a/kernel/src/wire/anthropic.ts +++ b/kernel/src/wire/anthropic.ts @@ -52,11 +52,19 @@ export type AnthropicMessage = { content: string | AnthropicBlock[]; }; +export type AnthropicSystemMessage = { + role: "system"; + content: string | AnthropicBlock[]; + [key: string]: unknown; +}; + +export type AnthropicWireMessage = AnthropicMessage | AnthropicSystemMessage; + export type AnthropicRequestBody = { model?: string; max_tokens?: number; system?: string | AnthropicTextBlock[]; - messages: AnthropicMessage[]; + messages: AnthropicWireMessage[]; tools?: unknown[]; stream?: boolean; temperature?: number; @@ -102,6 +110,11 @@ export function anthropicToCore(body: AnthropicRequestBody): Flat { // map fold coverage (core-message space) back to wire positions without // re-deriving the converter's block-split behavior. const before = msgs.length; + if (m.role === "system") { + msgs.push(systemMessageCore(m, clusters)); + (msgs[before] as BiliMessage).wireIndex = wireIndex; + continue; + } const blocks = typeof m.content === "string" ? [{ type: "text" as const, text: m.content }] @@ -280,11 +293,36 @@ export function anthropicToCore(body: AnthropicRequestBody): Flat { return { msgs, cacheControls }; } +// Mid-conversation system messages (Pi's tool_addition / tool_removal +// deltas, message-level output_config) are host control-plane state: one +// core per wire message, re-emitted verbatim, never split into the +// user/assistant block stream. +function systemMessageCore( + m: AnthropicSystemMessage, + clusters: ClusterCounter, +): BiliMessage { + const text = + typeof m.content === "string" + ? m.content + : m.content + .map((b) => (b.type === "text" ? b.text : `[${b.type}]`)) + .join("\n"); + const label = text.length > 0 ? text : "[system]"; + const base = deriveCanonicalMessageId("system", "text", label); + return { + id: clusters.next(base), + role: "system", + contentType: "text", + text: label, + rawAnthropicMessage: m, + }; +} + export function coreToAnthropic( messages: BiliMessage[], cacheControls?: Map, -): AnthropicMessage[] { - const out: AnthropicMessage[] = []; +): AnthropicWireMessage[] { + const out: AnthropicWireMessage[] = []; let current: { role: "user" | "assistant"; blocks: AnthropicBlock[] } | null = null; const flush = () => { @@ -298,6 +336,11 @@ export function coreToAnthropic( return v ? { cache_control: v } : {}; }; for (const m of messages) { + if (m.rawAnthropicMessage) { + flush(); + out.push(m.rawAnthropicMessage as AnthropicSystemMessage); + continue; + } const target: "user" | "assistant" = m.role === "assistant" ? "assistant" : "user"; if (!current || current.role !== target) { diff --git a/kernel/src/wire/bili-message.ts b/kernel/src/wire/bili-message.ts index 4be783c8bb..4fa51484a7 100644 --- a/kernel/src/wire/bili-message.ts +++ b/kernel/src/wire/bili-message.ts @@ -29,6 +29,12 @@ export interface BiliMessage extends CoreMessage { * coreToAnthropic (redacted_thinking must reach the wire byte-exact — * Anthropic rejects modified thinking-family blocks). */ rawAnthropicBlock?: unknown; + /** Anthropic: a whole mid-conversation `role:"system"` wire message + * (Pi's `tool_addition` / `tool_removal` deltas, message-level + * `output_config`). Re-emitted verbatim by coreToAnthropic as its own + * system-role message; kernel-synthesized system cores (rendered + * summaries) never carry it and keep their user-role mapping. */ + rawAnthropicMessage?: unknown; /** OpenAI chat: the original content part for an image_url (data: or * remote URL) or the original message object for a developer-role * message. */ diff --git a/kernel/tests/anthropic-system-message-passthrough.test.ts b/kernel/tests/anthropic-system-message-passthrough.test.ts new file mode 100644 index 0000000000..ddf2de395a --- /dev/null +++ b/kernel/tests/anthropic-system-message-passthrough.test.ts @@ -0,0 +1,172 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { anthropicToCore, coreToAnthropic } from "../src/wire/anthropic.js"; +import { + hasMediaPayload, + hasUnrecoverableMediaPayload, +} from "../src/protected.js"; + +// Pi (supportsMidConvoToolChanges) declares tools added mid-session as +// `tool_addition` blocks inside mid-conversation `role:"system"` messages, +// and emits empty system messages carrying message-level `output_config`. +// anthropicToCore used to split those into the user/assistant block stream +// and coreToAnthropic re-emitted them as `user` — on 0.1.202 the blocks were +// dropped (tools never reached the model); after #3410 they survived but +// upstream rejected them: "'tool_addition'/'tool_removal' blocks are only +// permitted within `role: \"system\"` messages". + +const TOOL_ADDITION = { + type: "tool_addition", + tool: { + type: "tool_definition", + definition: { + name: "subagent", + description: "Delegate to subagents", + input_schema: { type: "object", properties: {} }, + }, + }, +}; + +const EFFORT = { + role: "system", + content: [], + output_config: { effort: "medium" }, +}; + +const TOOLS_DELTA = { + role: "system", + content: [ + { + type: "text", + text: 'Updated system prompt section "tools":\n…', + }, + TOOL_ADDITION, + ], +}; + +function piBody() { + return { + messages: [ + { role: "user", content: [{ type: "text", text: "enable subagents" }] }, + EFFORT, + { + role: "assistant", + content: [ + { + type: "tool_use", + id: "toolu_1", + name: "subagents_enable", + input: {}, + }, + ], + }, + { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: "toolu_1", + content: "Enabled: subagent.", + }, + ], + }, + TOOLS_DELTA, + EFFORT, + ], + }; +} + +test("round-trips pi mid-conversation system messages byte-exact", () => { + const body = piBody(); + const rebuilt = coreToAnthropic(anthropicToCore(body as never).msgs as never); + assert.deepEqual(rebuilt, body.messages); +}); + +test("one core per system wire message, role system, wireIndex kept", () => { + const msgs = anthropicToCore(piBody() as never).msgs as { + [k: string]: unknown; + }[]; + const systems = msgs.filter((m) => m.rawAnthropicMessage !== undefined); + assert.deepEqual( + systems.map((m) => [m.role, m.wireIndex]), + [ + ["system", 1], + ["system", 4], + ["system", 5], + ], + ); + assert.equal(systems[0]!.text, "[system]"); + assert.match( + systems[1]!.text as string, + /^Updated system prompt section "tools":/, + ); + assert.match(systems[1]!.text as string, /\[tool_addition\]$/); +}); + +test("system message between two user turns does not merge them", () => { + const body = { + messages: [ + { role: "user", content: [{ type: "text", text: "a" }] }, + TOOLS_DELTA, + { role: "user", content: [{ type: "text", text: "b" }] }, + ], + }; + const rebuilt = coreToAnthropic(anthropicToCore(body as never).msgs as never); + assert.deepEqual(rebuilt, body.messages); +}); + +test("string-content system message round-trips", () => { + const body = { + messages: [ + { role: "user", content: "hi" }, + { role: "system", content: "be brief" }, + ], + }; + const rebuilt = coreToAnthropic(anthropicToCore(body as never).msgs as never); + assert.deepEqual(rebuilt[1], { role: "system", content: "be brief" }); +}); + +test("kernel-synthesized system cores (no sidecar) still map to user", () => { + const rebuilt = coreToAnthropic([ + { + id: "s1", + role: "system", + contentType: "text", + text: "[Compressed conversation section] x", + }, + ] as never); + assert.deepEqual(rebuilt, [ + { + role: "user", + content: [{ type: "text", text: "[Compressed conversation section] x" }], + }, + ]); +}); + +test("system-message cores are never folded; plain text cores still are", () => { + const msgs = anthropicToCore(piBody() as never).msgs; + for (const m of msgs) { + const sidecar = (m as { rawAnthropicMessage?: unknown }) + .rawAnthropicMessage; + assert.equal(hasUnrecoverableMediaPayload(m), sidecar !== undefined, m.id); + } + assert.equal(hasMediaPayload(msgs[0]!), false); +}); + +test("ids are deterministic; identical system messages stay distinct", () => { + const ids = () => anthropicToCore(piBody() as never).msgs.map((m) => m.id); + assert.deepEqual(ids(), ids()); + const msgs = anthropicToCore(piBody() as never).msgs as { + [k: string]: unknown; + }[]; + const effortIds = msgs.filter((m) => m.text === "[system]").map((m) => m.id); + assert.equal(effortIds.length, 2); + assert.notEqual(effortIds[0], effortIds[1]); +}); + +test("parse is a structural fixed point over rebuild", () => { + const first = anthropicToCore(piBody() as never).msgs; + const rebuilt = coreToAnthropic(first as never); + const second = anthropicToCore({ messages: rebuilt } as never).msgs; + assert.deepEqual(second, first); +}); diff --git a/tests/wire-contract-fakes.ts b/tests/wire-contract-fakes.ts index 6148257f0d..c2aba2eda3 100644 --- a/tests/wire-contract-fakes.ts +++ b/tests/wire-contract-fakes.ts @@ -72,6 +72,14 @@ export const WIRE_RULES: readonly WireRule[] = [ provenance: 'live probe 2026-10-15: :streamRawPredict with "stream": true against the real endpoint answered 429 with an array-wrapped {"error":{"code":429,…,"status":"RESOURCE_EXHAUSTED"}}, the same request on :rawPredict answered the bare object. The fake reproduces the split so an error-path regression fails in CI rather than in production.', }, + { + id: "WC-022", + wire: "anthropic", + summary: + 'tool_addition / tool_removal content blocks are only valid inside a role:"system" message in messages[] — the same blocks under role:"user" are a 400; a mid-conversation system message must therefore round-trip with its role intact, never be re-emitted as user or merged into an adjacent user turn', + provenance: + 'live probe 2026-10-20 (pi 1.3.0 + pi-subagents 0.79.2, api.anthropic.com, claude-haiku-5-5) through a master b156c02f proxy: pi declares tools activated mid-session as tool_addition blocks inside a mid-conversation role:"system" message; #3410\'s unknown-block passthrough kept the blocks but coreToAnthropic re-emitted the message as role:"user" → upstream 400 "messages.2.content: \'tool_addition\'/\'tool_removal\' blocks are only permitted within `role: "system"` messages". On v0.1.202 the blocks were silently dropped instead (tools never reached the model). Repair: kernel/src/wire/anthropic.ts keeps each wire system message whole on the rawAnthropicMessage sidecar and re-emits it verbatim.', + }, { id: "WC-016", wire: "anthropic", @@ -249,10 +257,17 @@ function isPlainObject(v: unknown): v is Record { return typeof v === "object" && v !== null && !Array.isArray(v); } -/** WC-001..WC-003, WC-007, WC-010, WC-016 on an Anthropic /v1/messages body. Returns violation strings. */ +/** WC-001..WC-003, WC-007, WC-010, WC-016, WC-022 on an Anthropic /v1/messages body. Returns violation strings. */ function validateAnthropicBody(body: unknown): string[] { const out: string[] = []; if (!isPlainObject(body)) return out; + if (Array.isArray(body.messages)) + body.messages.forEach((m, i) => { + if (!isPlainObject(m) || m.role === "system" || !Array.isArray(m.content)) return; + for (const b of m.content) + if (isPlainObject(b) && (b.type === "tool_addition" || b.type === "tool_removal")) + out.push(`WC-022 messages[${i}].content: '${b.type}' blocks are only permitted within role:"system" messages`); + }); if ("prompt_cache_key" in body) out.push("WC-007 top-level prompt_cache_key is not part of the Anthropic Messages API (#1403)"); // WC-010 runs before the tools early-return: breakpoints can live in diff --git a/tests/wire-contract.test.ts b/tests/wire-contract.test.ts index cf5a6ac90b..e851c78080 100644 --- a/tests/wire-contract.test.ts +++ b/tests/wire-contract.test.ts @@ -77,6 +77,23 @@ test("WC-015 validates message-item IDs without constraining provider namespaces assert.match(VALIDATORS.responses({ input: [{ type: "message", role: "assistant", id: "marker-1791393957942-2", content: "x" }] })[0], /WC-015/); }); +test("WC-022 tool_addition/tool_removal blocks are only valid inside role:system messages", () => { + const addition = { type: "tool_addition", tool: { type: "tool_definition", definition: { name: "t", input_schema: { type: "object", properties: {} } } } }; + assert.deepEqual(VALIDATORS.anthropic({ + messages: [ + { role: "user", content: [{ type: "text", text: "u" }] }, + { role: "system", content: [{ type: "text", text: "tools changed" }, addition] }, + ], + }), []); + // The master-b156c02f shape: the system message re-emitted as user. + assert.match(VALIDATORS.anthropic({ + messages: [{ role: "user", content: [{ type: "text", text: "tools changed" }, addition] }], + })[0], /WC-022/); + assert.match(VALIDATORS.anthropic({ + messages: [{ role: "user", content: [{ type: "tool_removal", tool_name: "t" }] }], + })[0], /WC-022/); +}); + test("WC-016 validates global-scope breakpoint ordering (render order: tools → system → messages)", () => { // #2648 shape: unmarked tools render ahead of a global system block. assert.match(VALIDATORS.anthropic({ @@ -167,6 +184,8 @@ test("wire-contract ledger: every rule has a live enforcement clause", () => { tools: [{ name: "t", input_schema: { type: "object", properties: {} } }], system: [{ type: "text", text: "s", cache_control: { type: "ephemeral", scope: "global" } }], }, + // WC-022: a pi mid-conversation system message re-emitted as user. + { messages: [{ role: "user", content: [{ type: "tool_removal", tool_name: "t" }] }] }, ], "openai-chat": [ { model: "gemini-synthetic", tools: [{ type: "function", function: { name: "compress", parameters: { type: "object", properties: { content: { type: ["array", "string"] } } } } }] }, From b42b75f502ed5d1a81ee30b0439a1d132b48e922 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Skv=C4=9Bl=C3=BD?= Date: Tue, 20 Oct 2026 17:09:18 +0200 Subject: [PATCH 2/3] kernel: plain-text system messages stay foldable and client-cache-visible (#3991) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI caught a Claude Code lane regression: Claude Code (2.1.300, Vertex fixture) appends a plain-text environment note as a trailing role:"system" message, and on that fixture it carries the request's only message-level cache_control. - Only system messages with non-text blocks or message-level extra fields (Pi's tool_addition deltas, output_config) are unrecoverable. Plain-text ones keep a numeric ref, so the recent-zone window no longer slides back one message (tests/e2e-vertex-anthropic.test.ts). - The system message's cache_control is harvested into cacheControls like any text block's, so the host's client-managed caching detection (#1637) and WC-010's breakpoint budget still see it. - The rebuild uses m.text when the kernel rewrote a plain-text system message (e.g. emergency truncation), and puts a host-stamped mark on the last block when the original has none. - A single-text-block system message keeps the legacy per-block id, so upgraded sessions see no ref churn. kernel-change: wire保真 — anthropic mid-conversation system messages (#3991) --- kernel/src/protected.ts | 31 ++++++- kernel/src/wire/anthropic.ts | 65 +++++++++++--- ...thropic-system-message-passthrough.test.ts | 89 ++++++++++++++++++- 3 files changed, 171 insertions(+), 14 deletions(-) diff --git a/kernel/src/protected.ts b/kernel/src/protected.ts index bffcf94e6c..f202c736d0 100644 --- a/kernel/src/protected.ts +++ b/kernel/src/protected.ts @@ -438,9 +438,12 @@ export function hasMediaPayload(msg: CoreMessage): boolean { export function hasUnrecoverableMediaPayload(msg: CoreMessage): boolean { const m = msg as CoreMessage & MediaSidecar; - // A verbatim anthropic system message (Pi tool_addition deltas): folding it - // would silently un-declare the tools it adds — never fold. - if (m.rawAnthropicMessage != null) return true; + // A verbatim anthropic system message carrying control-plane state (Pi's + // tool_addition deltas, message-level output_config): folding it would + // silently un-declare the tools it adds — never fold. Plain-text ones + // (Claude Code's environment note) fold like any text message. + if (m.rawAnthropicMessage != null) + return !isPlainTextSystemMessage(m.rawAnthropicMessage); const roc = m.rawOpenaiContent; if (roc != null) { @@ -535,6 +538,28 @@ function anthropicSourceArchivable( return false; } +/** A mid-conversation anthropic `role:"system"` message whose whole payload + * is text (blocks may carry cache_control) — nothing a fold would lose. */ +export function isPlainTextSystemMessage(raw: unknown): boolean { + const m = asObj(raw); + if (!m || Object.keys(m).some((k) => k !== "role" && k !== "content")) + return false; + if (typeof m.content === "string") return true; + return ( + Array.isArray(m.content) && + m.content.length > 0 && + m.content.every((b) => { + const o = asObj(b); + return ( + o?.type === "text" && + Object.keys(o).every( + (k) => k === "type" || k === "text" || k === "cache_control", + ) + ); + }) + ); +} + function asObj(v: unknown): Record | undefined { return typeof v === "object" && v !== null ? (v as Record) diff --git a/kernel/src/wire/anthropic.ts b/kernel/src/wire/anthropic.ts index 253c7d6d5c..47d454488b 100644 --- a/kernel/src/wire/anthropic.ts +++ b/kernel/src/wire/anthropic.ts @@ -8,6 +8,7 @@ import { } from "./identity.js"; import { hashId } from "./util.js"; import { ClusterCounter } from "./message-id.js"; +import { isPlainTextSystemMessage } from "../protected.js"; export type AnthropicTextBlock = { type: "text"; @@ -111,8 +112,14 @@ export function anthropicToCore(body: AnthropicRequestBody): Flat { // re-deriving the converter's block-split behavior. const before = msgs.length; if (m.role === "system") { - msgs.push(systemMessageCore(m, clusters)); - (msgs[before] as BiliMessage).wireIndex = wireIndex; + const core = systemMessageCore(m, clusters); + core.wireIndex = wireIndex; + msgs.push(core); + // Harvest the client's breakpoint like any text block's: the host's + // client-managed-caching detection (#1637) and WC-010's 4-mark budget + // both read this map, not the verbatim sidecar. + const mark = systemMessageMark(m); + if (mark) cacheControls.set(core.id, mark); continue; } const blocks = @@ -301,13 +308,9 @@ function systemMessageCore( m: AnthropicSystemMessage, clusters: ClusterCounter, ): BiliMessage { - const text = - typeof m.content === "string" - ? m.content - : m.content - .map((b) => (b.type === "text" ? b.text : `[${b.type}]`)) - .join("\n"); - const label = text.length > 0 ? text : "[system]"; + const label = systemMessageText(m); + // A single-text-block message keeps the legacy per-block id (zero churn + // for Claude Code's trailing environment message). const base = deriveCanonicalMessageId("system", "text", label); return { id: clusters.next(base), @@ -318,6 +321,48 @@ function systemMessageCore( }; } +function systemMessageText(m: AnthropicSystemMessage): string { + const text = + typeof m.content === "string" + ? m.content + : m.content + .map((b) => (b.type === "text" ? b.text : `[${b.type}]`)) + .join("\n"); + return text.length > 0 ? text : "[system]"; +} + +function systemMessageMark(m: AnthropicSystemMessage): unknown { + if (typeof m.content === "string") return undefined; + let mark: unknown; + for (const b of m.content as { cache_control?: unknown }[]) + if (b.cache_control) mark = b.cache_control; + return mark; +} + +// Verbatim unless the kernel rewrote the text (e.g. emergency truncation of +// a plain-text message) — re-emitting the original would undo it. A mark the +// original lacks (host-stamped, #1637) lands on the last block. +function rebuildSystemMessage( + m: BiliMessage, + mark: unknown, +): AnthropicSystemMessage { + const raw = m.rawAnthropicMessage as AnthropicSystemMessage; + const cc = mark ? { cache_control: mark } : {}; + const text = m.text ?? ""; + if (text !== systemMessageText(raw) && isPlainTextSystemMessage(raw)) { + return { role: "system", content: [{ type: "text", text, ...cc }] }; + } + if (!mark || systemMessageMark(raw) || typeof raw.content === "string") { + return raw; + } + const last = raw.content.length - 1; + if (last < 0) return raw; + return { + ...raw, + content: raw.content.map((b, i) => (i === last ? { ...b, ...cc } : b)), + }; +} + export function coreToAnthropic( messages: BiliMessage[], cacheControls?: Map, @@ -338,7 +383,7 @@ export function coreToAnthropic( for (const m of messages) { if (m.rawAnthropicMessage) { flush(); - out.push(m.rawAnthropicMessage as AnthropicSystemMessage); + out.push(rebuildSystemMessage(m, cacheControls?.get(m.id))); continue; } const target: "user" | "assistant" = diff --git a/kernel/tests/anthropic-system-message-passthrough.test.ts b/kernel/tests/anthropic-system-message-passthrough.test.ts index ddf2de395a..3a3bf7763f 100644 --- a/kernel/tests/anthropic-system-message-passthrough.test.ts +++ b/kernel/tests/anthropic-system-message-passthrough.test.ts @@ -1,7 +1,9 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { anthropicToCore, coreToAnthropic } from "../src/wire/anthropic.js"; +import { deriveCanonicalMessageId } from "../src/wire/identity.js"; import { + isPlainTextSystemMessage, hasMediaPayload, hasUnrecoverableMediaPayload, } from "../src/protected.js"; @@ -143,7 +145,92 @@ test("kernel-synthesized system cores (no sidecar) still map to user", () => { ]); }); -test("system-message cores are never folded; plain text cores still are", () => { +// Claude Code (2.1.300, tests/fixtures/vertex-anthropic) appends a plain-text +// environment note as a trailing system message — and on that fixture it +// carries the request's ONLY message-level cache_control. +const CC_ENV = { + role: "system", + content: [ + { + type: "text", + text: "# Environment\n - Platform: linux", + cache_control: { type: "ephemeral" }, + }, + ], +}; + +function ccBody() { + return { + messages: [ + { role: "user", content: [{ type: "text", text: "say pong" }] }, + CC_ENV, + ], + }; +} + +test("plain-text system message: legacy id, foldable, mark harvested, byte-exact", () => { + const { msgs, cacheControls } = anthropicToCore(ccBody() as never); + const sys = msgs[1]!; + // Same id the pre-fix per-block split minted — zero ref churn on upgrade. + assert.equal( + sys.id, + deriveCanonicalMessageId("system", "text", CC_ENV.content[0]!.text), + ); + assert.equal(hasUnrecoverableMediaPayload(sys), false); + assert.equal(isPlainTextSystemMessage(CC_ENV), true); + // Client-managed caching detection (#1637) reads this map. + assert.deepEqual(cacheControls.get(sys.id), { type: "ephemeral" }); + assert.deepEqual(coreToAnthropic(msgs, cacheControls)[1], CC_ENV); +}); + +test("kernel-rewritten plain-text system message rebuilds from core text", () => { + const { msgs, cacheControls } = anthropicToCore(ccBody() as never); + const truncated = msgs.map((m, i) => + i === 1 ? { ...m, text: "# Environment [truncated]" } : m, + ); + assert.deepEqual(coreToAnthropic(truncated, cacheControls)[1], { + role: "system", + content: [ + { + type: "text", + text: "# Environment [truncated]", + cache_control: { type: "ephemeral" }, + }, + ], + }); +}); + +test("host-stamped mark lands on the last block; client marks stay put", () => { + const body = { + messages: [{ role: "user", content: "hi" }, TOOLS_DELTA, EFFORT], + }; + const { msgs } = anthropicToCore(body as never); + const marks = new Map([ + [msgs[1]!.id, { type: "ephemeral" }], + [msgs[2]!.id, { type: "ephemeral" }], + ]); + const rebuilt = coreToAnthropic(msgs, marks) as { + content: { cache_control?: unknown }[]; + }[]; + assert.deepEqual(rebuilt[1]!.content[1]!.cache_control, { + type: "ephemeral", + }); + assert.equal(rebuilt[1]!.content[0]!.cache_control, undefined); + // Nothing to carry a mark: the empty output_config message stays verbatim. + assert.deepEqual(rebuilt[2], EFFORT); + // The client's own mark is never duplicated or moved. + const pre = { + ...TOOLS_DELTA, + content: [ + { ...TOOLS_DELTA.content[0]!, cache_control: { type: "ephemeral" } }, + TOOL_ADDITION, + ], + }; + const flat = anthropicToCore({ messages: [pre] } as never); + assert.deepEqual(coreToAnthropic(flat.msgs, flat.cacheControls)[0], pre); +}); + +test("control-plane system cores are never folded; other cores still are", () => { const msgs = anthropicToCore(piBody() as never).msgs; for (const m of msgs) { const sidecar = (m as { rawAnthropicMessage?: unknown }) From 6eafb2a8e6efa31f7a0026a5ede29c4c01f04b15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Skv=C4=9Bl=C3=BD?= Date: Tue, 20 Oct 2026 17:23:29 +0200 Subject: [PATCH 3/3] kernel: bump acp-kernel to 0.0.148 (#3991) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit master took 0.0.147 while this branch was open. kernel-change: wire保真 — anthropic mid-conversation system messages (#3991) --- kernel/package-lock.json | 4 ++-- kernel/package.json | 2 +- package-lock.json | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/kernel/package-lock.json b/kernel/package-lock.json index 0ee2818fbc..030f548bd9 100644 --- a/kernel/package-lock.json +++ b/kernel/package-lock.json @@ -1,12 +1,12 @@ { "name": "acp-kernel", - "version": "0.0.147", + "version": "0.0.148", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "acp-kernel", - "version": "0.0.147", + "version": "0.0.148", "license": "MIT", "devDependencies": { "@types/node": "^22.0.0", diff --git a/kernel/package.json b/kernel/package.json index 54b48a750d..abf00497c5 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.147", + "version": "0.0.148", "description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.", "license": "MIT", "author": "ranxianglei", diff --git a/package-lock.json b/package-lock.json index e189177e7e..19a97d7053 100644 --- a/package-lock.json +++ b/package-lock.json @@ -50,7 +50,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.147", + "version": "0.0.148", "dev": true, "license": "MIT", "devDependencies": {