Skip to content

Commit f5931f5

Browse files
Peetiegonzalezobviyus
authored andcommitted
fix(agents): carry current-turn inbound metadata in a tail runtime-context message for byte-stable prompt caching
The active user turn was decorated at request-build time with an inbound metadata block (Conversation info / reply-target / sender / forwarded / chat-history), but the session store persists the bare text and the LLM boundary strips that block from historical replay. So a user message's serialized bytes changed retroactively — decorated as the active turn, bare as history — on every turn, invalidating any prefix/exact-match provider prompt cache from that point onward, every turn. (#90811 fixed the timestamp half of this same asymmetry.) Rework of the earlier "strip the active turn" approach (which lost model-visible context — ClawSweeper's P1) into one that keeps the context AND recovers the cache cost: - Route current-turn inbound metadata out of the user prompt and into the hidden runtime-context custom message (the mechanism from #89428), and relocate that carrier to the ABSOLUTE TAIL of the wire request (after the active user turn and any tool-call scaffolding). The user turn stays bare and byte-identical in both the active and historical positions; the volatile carrier vanishes next turn exactly where the assistant reply begins anyway, so the request is an append-only prefix-extension through the active user turn. - A durable marker (UserMessage.runtimeContextCarrier, set by convertToLlm from the carrier's details) lets the Anthropic SDK transport, the managed Anthropic transport (anthropic-transport-stream / anthropic-payload-policy), and OpenAI-completions skip the carrier when selecting the deepest cache_control breakpoint, keeping the anchor on the last stable user turn. Storage stays BARE (invariant preserved); runtime-only turns (room events) keep their existing inline behavior, which is byte-stable because room-event/system context is not strip-eligible; legacy bare-stored sessions are unchanged. Reviewed with adversarial gpt-5.5/codex sweeps (correctness, byte-identity, compatibility, test adequacy): found + fixed the managed Anthropic transport cache-anchor path and added the missing OpenAI-completions/managed-transport breakpoint tests; a theoretical runtime-only mutation was verified unreachable and pinned with a test. Final sweep clean. Co-authored-by: #89428 (runtime-context handoff approach)
1 parent f7df953 commit f5931f5

16 files changed

Lines changed: 545 additions & 37 deletions

‎packages/agent-core/src/harness/messages.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,31 @@ describe("harness message timestamps", () => {
3939
expect(message?.timestamp).toBe(0);
4040
});
4141
});
42+
43+
describe("convertToLlm runtime-context carrier marking", () => {
44+
const timestamp = "2026-05-30T17:00:00.000Z";
45+
46+
it("marks a runtime-context carrier custom message so providers skip cache anchoring", () => {
47+
const [message] = convertToLlm([
48+
createCustomMessage(
49+
"openclaw.runtime-context",
50+
"current-turn metadata",
51+
false,
52+
{ source: "openclaw-runtime-context", runtimeContextCarrier: true },
53+
timestamp,
54+
),
55+
]);
56+
57+
expect(message?.role).toBe("user");
58+
expect((message as { runtimeContextCarrier?: boolean }).runtimeContextCarrier).toBe(true);
59+
});
60+
61+
it("does not mark ordinary custom messages", () => {
62+
const [message] = convertToLlm([
63+
createCustomMessage("note", "some note", false, { source: "other" }, timestamp),
64+
]);
65+
66+
expect(message?.role).toBe("user");
67+
expect((message as { runtimeContextCarrier?: boolean }).runtimeContextCarrier).toBeUndefined();
68+
});
69+
});

‎packages/agent-core/src/harness/messages.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,10 +139,16 @@ export function convertToLlm(messages: AgentMessage[]): Message[] {
139139
typeof message.content === "string"
140140
? [{ type: "text" as const, text: message.content }]
141141
: message.content;
142+
// Transient current-turn runtime-context carriers must not anchor a
143+
// provider prompt-cache breakpoint (their bytes change every turn).
144+
const runtimeContextCarrier =
145+
(message.details as { runtimeContextCarrier?: unknown } | undefined)
146+
?.runtimeContextCarrier === true;
142147
return {
143148
role: "user",
144149
content,
145150
timestamp: message.timestamp,
151+
...(runtimeContextCarrier ? { runtimeContextCarrier: true } : {}),
146152
};
147153
}
148154
case "branchSummary":

‎packages/ai/src/providers/anthropic.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1985,6 +1985,44 @@ describe("Anthropic provider", () => {
19851985
]);
19861986
});
19871987

1988+
it("anchors the message cache breakpoint on the last stable user turn, skipping a trailing runtime-context carrier", async () => {
1989+
let capturedPayload: unknown;
1990+
const stream = streamSimpleAnthropic(
1991+
makeAnthropicModel(),
1992+
{
1993+
systemPrompt: "system",
1994+
messages: [
1995+
{ role: "user", content: "stable question", timestamp: 0 },
1996+
{
1997+
role: "user",
1998+
content: "volatile current-turn metadata",
1999+
timestamp: 1,
2000+
runtimeContextCarrier: true,
2001+
},
2002+
],
2003+
},
2004+
{
2005+
apiKey: "sk-ant-provider",
2006+
onPayload: (payload) => {
2007+
capturedPayload = payload;
2008+
throw new Error("stop before network");
2009+
},
2010+
},
2011+
);
2012+
2013+
const result = await stream.result();
2014+
2015+
expect(result.stopReason).toBe("error");
2016+
const messages = (capturedPayload as { messages: { content: unknown }[] }).messages;
2017+
// Deepest breakpoint anchors on the stable user turn (converted to a block
2018+
// array with cache_control) so it stays a cacheable prefix next turn...
2019+
expect(messages[0]?.content).toEqual([
2020+
{ type: "text", text: "stable question", cache_control: { type: "ephemeral" } },
2021+
]);
2022+
// ...and NOT on the trailing volatile carrier, which is left uncached.
2023+
expect(messages[1]?.content).toBe("volatile current-turn metadata");
2024+
});
2025+
19882026
it("emits start event only after message_start so pre-stream SSE errors arrive before any non-error event", async () => {
19892027
function createSseEventResponse(lines: string): Response {
19902028
return new Response(lines, {

‎packages/ai/src/providers/anthropic.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1381,6 +1381,10 @@ function convertMessages(
13811381
replayThinkingEnabled = true,
13821382
): MessageParam[] {
13831383
const params: MessageParam[] = [];
1384+
// Param indexes for transient runtime-context carriers — excluded from
1385+
// cache_control breakpoint selection so the deepest breakpoint anchors on the
1386+
// last stable user turn, not the volatile carrier appended after it.
1387+
const cacheBreakpointOptOutParamIndexes = new Set<number>();
13841388

13851389
// Transform messages for cross-provider compatibility
13861390
const transformedMessages = transformMessages(messages, model, normalizeToolCallId);
@@ -1392,8 +1396,12 @@ function convertMessages(
13921396
const msg = transformedMessages[i];
13931397

13941398
if (msg.role === "user") {
1399+
const isRuntimeContextCarrier = msg.runtimeContextCarrier === true;
13951400
if (typeof msg.content === "string") {
13961401
if (msg.content.trim().length > 0) {
1402+
if (isRuntimeContextCarrier) {
1403+
cacheBreakpointOptOutParamIndexes.add(params.length);
1404+
}
13971405
params.push({
13981406
role: "user",
13991407
content: sanitizeSurrogates(msg.content),
@@ -1425,6 +1433,9 @@ function convertMessages(
14251433
if (filteredBlocks.length === 0) {
14261434
continue;
14271435
}
1436+
if (isRuntimeContextCarrier) {
1437+
cacheBreakpointOptOutParamIndexes.add(params.length);
1438+
}
14281439
params.push({
14291440
role: "user",
14301441
content: filteredBlocks,
@@ -1536,7 +1547,7 @@ function convertMessages(
15361547

15371548
for (let i = params.length - 1; i >= 0; i--) {
15381549
const message = params[i];
1539-
if (message.role !== "user") {
1550+
if (message.role !== "user" || cacheBreakpointOptOutParamIndexes.has(i)) {
15401551
continue;
15411552
}
15421553

‎packages/ai/src/providers/openai-completions.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -718,6 +718,49 @@ describe("OpenAI-compatible completions params", () => {
718718
});
719719
});
720720

721+
it("anchors the OpenRouter Anthropic cache marker on the last stable user turn, skipping a trailing runtime-context carrier", async () => {
722+
let capturedMessages: unknown;
723+
const stream = streamOpenAICompletions(
724+
{
725+
...createModel(32_000),
726+
id: "anthropic/claude-sonnet-4.6",
727+
provider: "openrouter",
728+
baseUrl: "https://openrouter.ai/api/v1",
729+
},
730+
{
731+
systemPrompt: "system",
732+
messages: [
733+
{ role: "user", content: "stable question", timestamp: 1 },
734+
{
735+
role: "user",
736+
content: "volatile current-turn metadata",
737+
timestamp: 2,
738+
runtimeContextCarrier: true,
739+
},
740+
],
741+
},
742+
{
743+
apiKey: "sk-test",
744+
onPayload(payload) {
745+
capturedMessages = (payload as { messages?: unknown }).messages;
746+
throw new Error("stop before network");
747+
},
748+
},
749+
);
750+
751+
const result = await stream.result();
752+
753+
expect(result.stopReason).toBe("error");
754+
const messages = capturedMessages as Array<{ role: string; content: unknown }>;
755+
const stableMsg = messages.find((m) => JSON.stringify(m.content).includes("stable question"));
756+
const carrierMsg = messages.find((m) =>
757+
JSON.stringify(m.content).includes("volatile current-turn metadata"),
758+
);
759+
// The stable user turn carries the cache breakpoint; the trailing carrier does not.
760+
expect(JSON.stringify(stableMsg)).toContain("cache_control");
761+
expect(JSON.stringify(carrierMsg)).not.toContain("cache_control");
762+
});
763+
721764
it("adds reasoning_content replay fields for Xiaomi MiMo assistant tool history", async () => {
722765
let capturedMessages: unknown;
723766
const stream = streamOpenAICompletions(

‎packages/ai/src/providers/openai-completions.ts‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -838,6 +838,12 @@ function getCompatCacheControl(
838838
return { type: "ephemeral", ...(ttl ? { ttl } : {}) };
839839
}
840840

841+
// Params built from transient runtime-context carrier user messages — excluded
842+
// from cache_control breakpoint selection so anchoring stays on the last stable
843+
// user turn, not the volatile carrier appended after it. Keyed by object
844+
// identity so concurrent conversions never collide, and never serialized.
845+
const runtimeContextCarrierParams = new WeakSet<object>();
846+
841847
function applyAnthropicCacheControl(
842848
messages: ChatCompletionMessageParam[],
843849
tools: OpenAI.Chat.Completions.ChatCompletionTool[] | undefined,
@@ -866,6 +872,9 @@ function addCacheControlToLastConversationMessage(
866872
): void {
867873
for (let i = messages.length - 1; i >= 0; i--) {
868874
const message = messages[i];
875+
if (runtimeContextCarrierParams.has(message)) {
876+
continue;
877+
}
869878
if (message.role === "user" || message.role === "assistant") {
870879
if (addCacheControlToMessage(message, cacheControl)) {
871880
return;
@@ -1017,11 +1026,16 @@ export function convertMessages(
10171026
}
10181027

10191028
if (msg.role === "user") {
1029+
const isRuntimeContextCarrier = msg.runtimeContextCarrier === true;
10201030
if (typeof msg.content === "string") {
1021-
params.push({
1031+
const userParam: ChatCompletionMessageParam = {
10221032
role: "user",
10231033
content: sanitizeSurrogates(msg.content),
1024-
});
1034+
};
1035+
if (isRuntimeContextCarrier) {
1036+
runtimeContextCarrierParams.add(userParam);
1037+
}
1038+
params.push(userParam);
10251039
} else {
10261040
const content: ChatCompletionContentPart[] = msg.content.map(
10271041
(item): ChatCompletionContentPart => {
@@ -1042,10 +1056,14 @@ export function convertMessages(
10421056
if (content.length === 0) {
10431057
continue;
10441058
}
1045-
params.push({
1059+
const userParam: ChatCompletionMessageParam = {
10461060
role: "user",
10471061
content,
1048-
});
1062+
};
1063+
if (isRuntimeContextCarrier) {
1064+
runtimeContextCarrierParams.add(userParam);
1065+
}
1066+
params.push(userParam);
10491067
}
10501068
} else if (msg.role === "assistant") {
10511069
// Some providers don't accept null content, use empty string instead

‎packages/llm-core/src/types.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,15 @@ export interface UserMessage {
285285
role: "user";
286286
content: string | (TextContent | ImageContent)[];
287287
timestamp: number; // Unix timestamp in milliseconds
288+
/**
289+
* Marks a user message that carries transient current-turn runtime context
290+
* (e.g. an OpenClaw runtime-context carrier appended after the active user
291+
* turn). Such messages are volatile — present only on the turn they belong to
292+
* and stripped on replay — so providers must NOT anchor a prompt-cache
293+
* breakpoint on them, or the breakpoint would land on bytes that change every
294+
* turn. Anchoring stays on the last stable (non-carrier) user message.
295+
*/
296+
runtimeContextCarrier?: boolean;
288297
}
289298

290299
/** Assistant turn, including provider identity and final stop state. */

‎src/agents/anthropic-payload-policy.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { SYSTEM_PROMPT_CACHE_BOUNDARY } from "@openclaw/ai/internal/shared";
66
*/
77
import { describe, expect, it } from "vitest";
88
import {
9+
anthropicRuntimeContextCarrierParams,
910
applyAnthropicPayloadPolicyToParams,
1011
resolveAnthropicPayloadPolicy,
1112
} from "./anthropic-payload-policy.js";
@@ -107,6 +108,39 @@ describe("anthropic payload policy", () => {
107108
});
108109
});
109110

111+
it("anchors the cache marker on the last stable user turn, skipping a trailing runtime-context carrier", () => {
112+
const policy = resolveAnthropicPayloadPolicy({
113+
provider: "anthropic",
114+
api: "anthropic-messages",
115+
baseUrl: "https://api.anthropic.com/v1",
116+
cacheRetention: "long",
117+
enableCacheControl: true,
118+
});
119+
const stableUser = { role: "user", content: [{ type: "text", text: "stable question" }] };
120+
const carrier = { role: "user", content: "volatile current-turn metadata" };
121+
// The managed transport marks carrier params on conversion; emulate that.
122+
anthropicRuntimeContextCarrierParams.add(carrier);
123+
const payload: TestPayload = {
124+
system: [{ type: "text", text: "system" }],
125+
messages: [stableUser, carrier],
126+
};
127+
128+
applyAnthropicPayloadPolicyToParams(payload, policy);
129+
130+
// Deepest breakpoint anchors on the stable user turn...
131+
expect(payload.messages[0]).toEqual({
132+
role: "user",
133+
content: [
134+
{ type: "text", text: "stable question", cache_control: { type: "ephemeral", ttl: "1h" } },
135+
],
136+
});
137+
// ...and NOT on the trailing volatile carrier (left uncached as a plain string).
138+
expect(payload.messages[1]).toEqual({
139+
role: "user",
140+
content: "volatile current-turn metadata",
141+
});
142+
});
143+
110144
it("keeps a stable user marker while advancing through trailing tool results", () => {
111145
const policy = resolveAnthropicPayloadPolicy({
112146
provider: "anthropic",

‎src/agents/anthropic-payload-policy.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,16 @@ import {
99
*/
1010
import { resolveProviderRequestCapabilities } from "./provider-attribution.js";
1111

12+
/**
13+
* Anthropic-message params (built by the managed transport) that carry transient
14+
* current-turn runtime context and must be excluded from cache_control
15+
* breakpoint selection — otherwise the deepest breakpoint would anchor on the
16+
* volatile carrier appended after the active user turn, whose bytes change every
17+
* turn. Keyed by object identity so concurrent conversions never collide, and
18+
* never serialized to the wire.
19+
*/
20+
export const anthropicRuntimeContextCarrierParams = new WeakSet<object>();
21+
1222
/** @deprecated Anthropic-family provider payload helper; do not use from third-party plugins. */
1323
type AnthropicServiceTier = "auto" | "standard_only";
1424

@@ -159,7 +169,7 @@ function applyAnthropicCacheControlToMessages(
159169
}
160170

161171
const record = message as Record<string, unknown>;
162-
if (record.role !== "user") {
172+
if (record.role !== "user" || anthropicRuntimeContextCarrierParams.has(record)) {
163173
continue;
164174
}
165175

‎src/agents/anthropic-transport-stream.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ import type {
6464
import "../llm/ai-transport-host.js";
6565
import { MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE } from "../shared/assistant-error-format.js";
6666
import {
67+
anthropicRuntimeContextCarrierParams,
6768
applyAnthropicPayloadPolicyToParams,
6869
resolveAnthropicPayloadPolicy,
6970
} from "./anthropic-payload-policy.js";
@@ -406,12 +407,17 @@ function convertAnthropicMessages(
406407
for (let i = 0; i < transformedMessages.length; i += 1) {
407408
const msg = transformedMessages[i];
408409
if (msg.role === "user") {
410+
const isRuntimeContextCarrier = msg.runtimeContextCarrier === true;
409411
if (typeof msg.content === "string") {
410412
if (msg.content.trim().length > 0) {
411-
params.push({
413+
const userParam = {
412414
role: "user",
413415
content: sanitizeTransportPayloadText(msg.content),
414-
});
416+
};
417+
if (isRuntimeContextCarrier) {
418+
anthropicRuntimeContextCarrierParams.add(userParam);
419+
}
420+
params.push(userParam);
415421
}
416422
continue;
417423
}
@@ -445,10 +451,14 @@ function convertAnthropicMessages(
445451
if (filteredBlocks.length === 0) {
446452
continue;
447453
}
448-
params.push({
454+
const userParam = {
449455
role: "user",
450456
content: filteredBlocks,
451-
});
457+
};
458+
if (isRuntimeContextCarrier) {
459+
anthropicRuntimeContextCarrierParams.add(userParam);
460+
}
461+
params.push(userParam);
452462
continue;
453463
}
454464
if (msg.role === "assistant") {

0 commit comments

Comments
 (0)