From e42b624c04c0e39da97c379d055b23abcbed011e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 00:22:32 +0900 Subject: [PATCH 1/4] fix(ai): keep Anthropic cache hits after messages with many blocks Anthropic looks back at most 20 block positions from each breakpoint for an earlier cache entry. When one new message holds 20 or more blocks, such as a prompt with about ten attached images or twenty text files, the tail breakpoint no longer reaches the previous request's entry and the whole conversation is written to the cache again. On Anthropic's own route, auto now also marks the second newest message, which is where the previous request's tail breakpoint sat. The slot comes from the first system part, which only adds the base prompt to the tools prefix; it keeps its breakpoint whenever one is left over, as on a Session's first request, so cross-session reuse is unchanged. Breakpoints are now filled in the order tools, last system part, newest messages, first system part, and a tail longer than the budget keeps its newest messages. Previously the oldest message in the tail took the last slot, leaving the newest content uncached. The long tool turn cassette pins the single-tail placement it was recorded with until it is re-recorded. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01X7arppEkkX1wg1Yy1nq7tw --- packages/ai/src/cache-policy.ts | 49 +++++-- packages/ai/src/schema/options.ts | 3 +- packages/ai/test/cache-policy.test.ts | 132 ++++++++++++++++-- packages/ai/test/effort-updates.test.ts | 3 +- .../anthropic-messages-cache.recorded.test.ts | 3 + 5 files changed, 163 insertions(+), 27 deletions(-) diff --git a/packages/ai/src/cache-policy.ts b/packages/ai/src/cache-policy.ts index b50992c47a2..eaebfccfe61 100644 --- a/packages/ai/src/cache-policy.ts +++ b/packages/ai/src/cache-policy.ts @@ -8,8 +8,16 @@ // advancing the tail after each tool result keeps recent conversation prefixes // reusable during long agent runs. // +// Anthropic reads an earlier cache entry only within 20 block positions of a +// breakpoint, so one new message with 20+ blocks (a batch of attached files) +// hides the previous request's entry and the whole conversation is written +// again. On Anthropic's own API, auto therefore marks the two newest messages; +// the first system part, which only adds the base prompt to the tools prefix, +// keeps its breakpoint only when one is left over, as on a Session's first request. +// // Manual `cache: CacheHint` placements on individual parts are preserved and -// count against the four-breakpoint budget; auto only fills remaining slots. +// count against the four-breakpoint budget; auto only fills remaining slots, +// in the order tools, last system part, newest messages, first system part. import { CacheHint, type CachePolicy, type CachePolicyObject, type CacheTTL } from "./schema/options.js" import { AssistantMessage, @@ -35,7 +43,9 @@ const BREAKPOINT_CAP = 4 // Resolution rules: // - undefined → "auto" — caching is on by default. -// - "auto" → tools + first/last system + final message boundary. +// - "auto" → tools + first/last system + final message boundary; on +// Anthropic's API the two newest messages instead of the +// first system part when the budget runs out. // - "none" → no auto placement; manual `CacheHint`s still flow. // - `{ ttl }` → "auto" with that lifetime. // - object form → exactly what the caller asked for. @@ -114,16 +124,16 @@ const countToolHints = (tools: ReadonlyArray): number => 0, ) -const markSystemBoundaries = (system: LLMRequest["system"], hint: CacheHint, budget: Budget): LLMRequest["system"] => { - if (system.length === 0) return system - let changed = false - const next = system.map((part, index) => { - if ((index !== 0 && index !== system.length - 1) || part.cache || budget.remaining === 0) return part - budget.remaining -= 1 - changed = true - return { ...part, cache: hint } - }) - return changed ? next : system +const markSystemPart = ( + system: LLMRequest["system"], + index: number, + hint: CacheHint, + budget: Budget, +): LLMRequest["system"] => { + const part = system[index] + if (!part || part.cache || budget.remaining === 0) return system + budget.remaining -= 1 + return system.map((item, i) => (i === index ? { ...item, cache: hint } : item)) } const lastIndexOfRole = (messages: ReadonlyArray, role: Message["role"]): number => @@ -193,8 +203,9 @@ const markMessages = ( start -= 1 if (effortUpdate(messages[start]!) === undefined) remaining -= 1 } + // Newest first: when the budget runs short, the conversation tail must keep its breakpoint. let next = messages - for (let i = start; i < messages.length; i++) + for (let i = messages.length - 1; i >= start; i--) if (effortUpdate(messages[i]!) === undefined) next = markMessageAt(next, i, hint, budget) return next } @@ -219,8 +230,13 @@ export const applyCachePolicy = (request: LLMRequest): LLMRequest => { const hint = makeHint(requestTTL(request)) const budget = { remaining: Math.max(0, BREAKPOINT_CAP - countHints(request)) } const tools = policy.tools ? markLastTool(request.tools, hint, budget) : request.tools - const system = policy.system ? markSystemBoundaries(request.system, hint, budget) : request.system + // The last system part comes first; the first one only adds the base prompt to the tools prefix, so it takes a + // breakpoint only when the conversation has left one over. + const lastSystem = policy.system + ? markSystemPart(request.system, request.system.length - 1, hint, budget) + : request.system const messages = policy.messages ? markMessages(request.messages, policy.messages, hint, budget) : request.messages + const system = policy.system ? markSystemPart(lastSystem, 0, hint, budget) : lastSystem if (tools === request.tools && system === request.system && messages === request.messages) return request return { ...request, tools, system, messages } @@ -243,5 +259,10 @@ const selectPolicy = (request: LLMRequest): CachePolicyObject => { if (!auto) return resolve(request.cache) if (route === "openrouter" || route === "vercel-ai-gateway-messages") return gatewayPolicy(request.model.id) if (route === "alibaba-chat") return request.model.id.toLowerCase().startsWith("qwen") ? QWEN : NONE + // Only Anthropic's own route: other Messages-compatible endpoints may cache and bill breakpoints differently. + if (route === "anthropic-messages") return ANTHROPIC return AUTO } + +// A breakpoint on the second newest message keeps the previous request's tail within the lookback. +const ANTHROPIC: CachePolicyObject = { ...AUTO, messages: { tail: 2 } } diff --git a/packages/ai/src/schema/options.ts b/packages/ai/src/schema/options.ts index ed50b5ad72b..1739873f953 100644 --- a/packages/ai/src/schema/options.ts +++ b/packages/ai/src/schema/options.ts @@ -372,7 +372,8 @@ export class CacheHint extends Schema.Class("LLM.CacheHint")({ // usual. `"auto"` is the default for agent loops — it places // breakpoints at the last tool definition, the first and last distinct system // parts, and the conversation tail so recent prefixes remain reusable during -// tool loops. +// tool loops. On Anthropic's own API it also marks the second newest message, +// giving up the first system part's breakpoint when the budget runs out. // // Pass `"none"` to opt out entirely (the legacy behavior). Pass the granular // object form to choose placements exactly; an object with only `ttl` keeps diff --git a/packages/ai/test/cache-policy.test.ts b/packages/ai/test/cache-policy.test.ts index f7f85a6f47b..ae09158f68a 100644 --- a/packages/ai/test/cache-policy.test.ts +++ b/packages/ai/test/cache-policy.test.ts @@ -60,7 +60,7 @@ describe("applyCachePolicy", () => { }), ) - it.effect("'auto' marks the last tool, first and last system parts, and final message boundary on Anthropic", () => + it.effect("'auto' on Anthropic marks the last tool, the last system part, and the two newest messages", () => Effect.gen(function* () { const prepared = yield* compileRequest( ai.request({ @@ -79,24 +79,105 @@ describe("applyCachePolicy", () => { }), ) + expect(prepared.body).toEqual( + expect.objectContaining({ + tools: [expect.objectContaining({ name: "t1", cache_control: { type: "ephemeral" } })], + system: [ + { type: "text", text: "Base agent" }, + { type: "text", text: "Project instructions", cache_control: { type: "ephemeral" } }, + ], + messages: [ + { role: "user", content: [{ type: "text", text: "first user" }] }, + { + role: "assistant", + content: [{ type: "text", text: "assistant reply", cache_control: { type: "ephemeral" } }], + }, + { + role: "user", + content: [{ type: "text", text: "latest user message", cache_control: { type: "ephemeral" } }], + }, + ], + }), + ) + }), + ) + + it.effect("'auto' on Anthropic keeps the first system part's breakpoint while a slot is left", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: anthropicModel, + system: [ + { type: "text", text: "Base agent" }, + { type: "text", text: "Project instructions" }, + ], + tools: [{ name: "t1", description: "t1", inputSchema: { type: "object", properties: {} } }], + prompt: "first prompt", + cache: "auto", + }), + ) + expect(prepared.body).toMatchObject({ - tools: [{ name: "t1", cache_control: { type: "ephemeral" } }], system: [ { type: "text", text: "Base agent", cache_control: { type: "ephemeral" } }, { type: "text", text: "Project instructions", cache_control: { type: "ephemeral" } }, ], messages: [ - { role: "user", content: [{ type: "text", text: "first user" }] }, - { role: "assistant", content: [{ type: "text", text: "assistant reply" }] }, - { - role: "user", - content: [{ type: "text", text: "latest user message", cache_control: { type: "ephemeral" } }], - }, + { role: "user", content: [{ type: "text", text: "first prompt", cache_control: { type: "ephemeral" } }] }, ], }) }), ) + it.effect("'auto' on Anthropic keeps the previous tail marked when one new message has many blocks", () => + Effect.gen(function* () { + const attachments = Array.from({ length: 24 }, (_, index) => Message.text(`Attached file: f${index}.md`)) + const prepared = yield* compileRequest( + ai.request({ + model: anthropicModel, + messages: [ + Message.user("start"), + Message.assistant([ToolCallPart.make({ id: "tc_1", name: "lookup", input: {} })]), + Message.tool({ id: "tc_1", name: "lookup", result: "found" }), + Message.user([Message.text("look at these"), ...attachments]), + ], + cache: "auto", + }), + ) + + const body = prepared.body as { messages: Array<{ content: Array<{ cache_control?: unknown }> }> } + // The tool result is where the previous request's tail breakpoint sat, 25 positions before the new one. + expect(body.messages[2]?.content[0]?.cache_control).toEqual({ type: "ephemeral" }) + expect(body.messages[3]?.content.at(-1)?.cache_control).toEqual({ type: "ephemeral" }) + }), + ) + + it.effect("'auto' keeps the first and last system parts and one message boundary off Anthropic's own API", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: AnthropicCompatible.configure({ baseURL: "https://compatible.test/v1/", apiKey: "test" }).model( + "claude-compatible", + ), + system: [ + { type: "text", text: "Base agent" }, + { type: "text", text: "Project instructions" }, + ], + messages: [Message.user("first user"), Message.assistant("assistant reply"), Message.user("latest")], + cache: "auto", + }), + ) + + const body = prepared.body as { + system: Array<{ cache_control?: unknown }> + messages: Array<{ content: Array<{ cache_control?: unknown }> }> + } + expect(body.system.map((part) => part.cache_control)).toEqual([{ type: "ephemeral" }, { type: "ephemeral" }]) + expect(body.messages[1]?.content[0]?.cache_control).toBeUndefined() + expect(body.messages[2]?.content[0]?.cache_control).toEqual({ type: "ephemeral" }) + }), + ) + it.effect("'auto' emits Anthropic cache markers on Vertex", () => Effect.gen(function* () { const prepared = yield* compileRequest( @@ -427,9 +508,10 @@ describe("applyCachePolicy", () => { }) const applied = applyCachePolicy(request) expect(applied.tools[0]?.cache).toBeDefined() - expect(applied.system.map((part) => part.cache !== undefined)).toEqual([true, true, true]) + // The conversation tail outranks the first system part when a manual hint takes a slot. + expect(applied.system.map((part) => part.cache !== undefined)).toEqual([false, true, true]) const tail = applied.messages[0]!.content[0]! - expect("cache" in tail ? tail.cache : undefined).toBeUndefined() + expect("cache" in tail ? tail.cache : undefined).toBeDefined() expect(applyCachePolicy(applied)).toBe(applied) const prepared = yield* compileRequest(request) @@ -446,7 +528,35 @@ describe("applyCachePolicy", () => { ].filter((cache) => cache !== undefined) expect(marked).toHaveLength(4) expect(body.system[1]?.cache_control).toEqual({ type: "ephemeral", ttl: "1h" }) - expect(body.messages[0]?.content[0]?.cache_control).toBeUndefined() + expect(body.messages[0]?.content[0]?.cache_control).toEqual({ type: "ephemeral" }) + }), + ) + + it.effect("a tail that outgrows the budget keeps the newest messages", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: anthropicModel, + system: [ + { type: "text", text: "Base agent" }, + { type: "text", text: "Project instructions" }, + ], + messages: [Message.user("u1"), Message.assistant("a1"), Message.user("u2"), Message.assistant("a2")], + cache: { system: true, messages: { tail: 3 } }, + }), + ) + + const body = prepared.body as { + system: Array<{ cache_control?: unknown }> + messages: Array<{ content: Array<{ cache_control?: unknown }> }> + } + expect(body.system.map((part) => part.cache_control)).toEqual([undefined, { type: "ephemeral" }]) + expect(body.messages.map((message) => message.content[0]?.cache_control)).toEqual([ + undefined, + { type: "ephemeral" }, + { type: "ephemeral" }, + { type: "ephemeral" }, + ]) }), ) diff --git a/packages/ai/test/effort-updates.test.ts b/packages/ai/test/effort-updates.test.ts index 468ed2ea5c9..9ff4dac905e 100644 --- a/packages/ai/test/effort-updates.test.ts +++ b/packages/ai/test/effort-updates.test.ts @@ -73,9 +73,10 @@ describe("cache policy", () => { }), ) + // Anthropic's auto policy marks the two newest messages; the effort marker counts as neither. expect(prepared.body.messages).toEqual([ { role: "user", content: [{ type: "text", text: "first" }] }, - { role: "assistant", content: [{ type: "text", text: "reply" }] }, + { role: "assistant", content: [{ type: "text", text: "reply", cache_control: { type: "ephemeral" } }] }, { role: "user", content: [{ type: "text", text: "latest", cache_control: { type: "ephemeral" } }] }, { role: "system", content: [], output_config: { effort: "low" } }, ]) diff --git a/packages/ai/test/provider/anthropic-messages-cache.recorded.test.ts b/packages/ai/test/provider/anthropic-messages-cache.recorded.test.ts index d98c1ba0688..81940259d76 100644 --- a/packages/ai/test/provider/anthropic-messages-cache.recorded.test.ts +++ b/packages/ai/test/provider/anthropic-messages-cache.recorded.test.ts @@ -54,6 +54,9 @@ const longToolTurnRequest = ai.request({ system: LARGE_CACHEABLE_SYSTEM, messages: longToolTurn, tools: [lookup], + // The cassette was recorded with a single tail breakpoint, before auto marked Anthropic's two newest messages. + // Re-record with `RECORD=true` and an Anthropic key to cover the current default instead. + cache: { tools: true, system: true, messages: { tail: 1 } }, generation: { maxTokens: 16, temperature: 0 }, }) From 1f45968a39d9bcf642263721d1b160427fff2834 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 01:23:00 +0900 Subject: [PATCH 2/4] fix(ai): mark the previous request's tail and keep cache TTLs in order The second newest message is usually the reply the model just generated, not the previous request's tail. In a tool loop that reply often holds only thinking and tool_use blocks, which never carry cache_control, so its hint spent a slot, was dropped when lowering, and pushed out the first system part's breakpoint. With parallel tool calls, the second newest message was another result from the same step. Auto on Anthropic's route now marks the message before the newest assistant reply instead. The previous request put its tail breakpoint there, so the new request reads that entry directly, however many blocks the reply and the new message add. Message hints now go only on blocks a protocol can send a marker on: non-blank text, media and client tool results. A message without one keeps its slot. Anthropic rejects a ttl="1h" marker after a 5m one. An auto hint now takes the longest lifetime of any manual hint after it, so a manual 1h hint on the newest message no longer turns the request into a 400. The prefix up to that hint is written at 1h anyway, so this costs nothing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01X7arpnFR8AZSgGeYEyZcfh --- packages/ai/src/cache-policy.ts | 123 +++++++++++----- packages/ai/src/schema/options.ts | 5 +- packages/ai/test/cache-policy.test.ts | 132 ++++++++++++++++-- packages/ai/test/effort-updates.test.ts | 7 +- .../anthropic-messages-cache.recorded.test.ts | 2 +- 5 files changed, 213 insertions(+), 56 deletions(-) diff --git a/packages/ai/src/cache-policy.ts b/packages/ai/src/cache-policy.ts index eaebfccfe61..9758e236b72 100644 --- a/packages/ai/src/cache-policy.ts +++ b/packages/ai/src/cache-policy.ts @@ -9,15 +9,21 @@ // reusable during long agent runs. // // Anthropic reads an earlier cache entry only within 20 block positions of a -// breakpoint, so one new message with 20+ blocks (a batch of attached files) -// hides the previous request's entry and the whole conversation is written -// again. On Anthropic's own API, auto therefore marks the two newest messages; -// the first system part, which only adds the base prompt to the tools prefix, -// keeps its breakpoint only when one is left over, as on a Session's first request. +// breakpoint. When the newest reply and message add 20+ blocks (a batch of +// attached files, say), the tail breakpoint can't reach the previous request's +// entry and the whole conversation is written again. On Anthropic's own API, +// auto therefore also marks the message before the newest assistant reply, +// where the previous request put its tail breakpoint, so that entry is read +// directly. The first system part, which only adds the base prompt to the tools +// prefix, keeps its breakpoint only when one is left over, as on a Session's +// first request. // // Manual `cache: CacheHint` placements on individual parts are preserved and // count against the four-breakpoint budget; auto only fills remaining slots, -// in the order tools, last system part, newest messages, first system part. +// in the order tools, last system part, conversation tail, previous tail, first +// system part. Anthropic rejects a longer lifetime after a shorter one, so an +// auto hint takes the longest lifetime of any manual hint after it. The prefix +// up to that manual hint is written at its lifetime anyway, so this costs nothing. import { CacheHint, type CachePolicy, type CachePolicyObject, type CacheTTL } from "./schema/options.js" import { AssistantMessage, @@ -41,11 +47,19 @@ const AUTO: CachePolicyObject = { const NONE: CachePolicyObject = {} const BREAKPOINT_CAP = 4 +// `previousTail` is internal: it marks the message before the newest assistant reply. +type Placement = CachePolicyObject & { readonly previousTail?: boolean } + +// A marker's place in the order Anthropic reads them: tools, then system parts, then message parts. +type Position = readonly [region: number, index: number, part: number] +type HintAt = (at: Position) => CacheHint +const TOOLS: Position = [0, 0, 0] + // Resolution rules: // - undefined → "auto" — caching is on by default. // - "auto" → tools + first/last system + final message boundary; on -// Anthropic's API the two newest messages instead of the -// first system part when the budget runs out. +// Anthropic's API also the previous request's tail, which +// takes the first system part's slot when the budget runs out. // - "none" → no auto placement; manual `CacheHint`s still flow. // - `{ ttl }` → "auto" with that lifetime. // - object form → exactly what the caller asked for. @@ -102,6 +116,16 @@ const gatewayPolicy = (modelID: string): CachePolicyObject => { const makeHint = (ttl: CacheTTL | undefined): CacheHint => ttl !== undefined ? new CacheHint({ type: "ephemeral", ttl }) : new CacheHint({ type: "ephemeral" }) +const UNITS = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 } + +// An omitted ttl is the provider default, five minutes on Anthropic. +const lifetime = (ttl: CacheTTL | undefined) => { + const match = ttl?.match(/^(\d+)(ms|s|m|h|d)$/) + return match ? Number(match[1]) * UNITS[match[2] as keyof typeof UNITS] : UNITS.m * 5 +} + +const compare = (a: Position, b: Position) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2] + interface Budget { remaining: number } @@ -127,13 +151,13 @@ const countToolHints = (tools: ReadonlyArray): number => const markSystemPart = ( system: LLMRequest["system"], index: number, - hint: CacheHint, + hint: HintAt, budget: Budget, ): LLMRequest["system"] => { const part = system[index] if (!part || part.cache || budget.remaining === 0) return system budget.remaining -= 1 - return system.map((item, i) => (i === index ? { ...item, cache: hint } : item)) + return system.map((item, i) => (i === index ? { ...item, cache: hint([1, index, 0]) } : item)) } const lastIndexOfRole = (messages: ReadonlyArray, role: Message["role"]): number => @@ -144,24 +168,31 @@ type CacheablePart = Exclude part.type !== "compaction" && part.type !== "effort" +// Protocols send a marker only on blocks that can carry one: tool calls and reasoning never do, provider-executed +// results are replayed as-is, and blank text is dropped. A hint on any of them would spend a slot and send nothing. +const isMarkable = (part: ContentPart): part is CacheablePart => { + if (part.type === "text") return part.text.trim().length > 0 + if (part.type === "tool-result") return part.providerExecuted !== true + return part.type === "media" +} + // Mark the last text part of `messages[index]`. If no text part exists, mark -// the last cacheable content part — that's the breakpoint position -// in tool-result-only messages too. +// the last markable content part — that's the breakpoint position in +// tool-result-only messages too. A message with nothing markable keeps its slot. const markMessageAt = ( messages: ReadonlyArray, index: number, - hint: CacheHint, + hint: HintAt, budget: Budget, ): ReadonlyArray => { if (index < 0 || index >= messages.length) return messages const target = messages[index]! - if (target.content.length === 0) return messages - const lastTextIndex = target.content.findLastIndex((part) => part.type === "text") - const markAt = lastTextIndex >= 0 ? lastTextIndex : target.content.findLastIndex(isCacheablePart) + const lastTextIndex = target.content.findLastIndex((part) => part.type === "text" && isMarkable(part)) + const markAt = lastTextIndex >= 0 ? lastTextIndex : target.content.findLastIndex(isMarkable) const existing = target.content[markAt] - if (!existing || !isCacheablePart(existing) || existing.cache || budget.remaining === 0) return messages + if (!existing || !isMarkable(existing) || existing.cache || budget.remaining === 0) return messages budget.remaining -= 1 - const next = cachePartAt(target, markAt, hint) + const next = cachePartAt(target, markAt, hint([2, index, markAt])) // Single pass over `messages`, substituting the one updated entry. Long // conversations call this on every request, so avoid `.map()` here — its // closure dispatch and identity copies show up in profiling. @@ -189,7 +220,7 @@ const cacheContentAt = (content: ReadonlyArray, const markMessages = ( messages: ReadonlyArray, strategy: NonNullable, - hint: CacheHint, + hint: HintAt, budget: Budget, ): ReadonlyArray => { if (messages.length === 0) return messages @@ -210,32 +241,51 @@ const markMessages = ( return next } -const countHints = (request: LLMRequest) => - countToolHints(request.tools) + - request.system.reduce((count, part) => count + (part.cache === undefined ? 0 : 1), 0) + - request.messages.reduce( - (count, message) => - count + - message.content.reduce( - (contentCount, part) => contentCount + (isCacheablePart(part) && part.cache !== undefined ? 1 : 0), - 0, - ), - 0, +// The previous request ended at the message before the newest assistant reply and wrote its tail entry there. +// Marking that message again reads the entry directly, however many blocks the reply and the newest message add. +const markPreviousTail = (messages: ReadonlyArray, hint: HintAt, budget: Budget) => { + const reply = lastIndexOfRole(messages, "assistant") + const index = messages.findLastIndex((message, i) => i < reply && effortUpdate(message) === undefined) + return markMessageAt(messages, index, hint, budget) +} + +// Hints the caller already placed on system and message parts. Manual tool hints only count against the budget: +// auto marks just the last tool, so none of them come after it. +const manualHints = (request: LLMRequest) => { + const hints: Array<{ readonly at: Position; readonly ttl: CacheTTL | undefined }> = [] + request.system.forEach((part, index) => { + if (part.cache) hints.push({ at: [1, index, 0], ttl: part.cache.ttl }) + }) + request.messages.forEach((message, index) => + message.content.forEach((part, i) => { + if (isCacheablePart(part) && part.cache) hints.push({ at: [2, index, i], ttl: part.cache.ttl }) + }), ) + return hints +} export const applyCachePolicy = (request: LLMRequest): LLMRequest => { const policy = selectPolicy(request) if (!policy.tools && !policy.system && !policy.messages) return request - const hint = makeHint(requestTTL(request)) - const budget = { remaining: Math.max(0, BREAKPOINT_CAP - countHints(request)) } - const tools = policy.tools ? markLastTool(request.tools, hint, budget) : request.tools + const manual = manualHints(request) + const requested = makeHint(requestTTL(request)) + const hint = (at: Position) => { + const ttl = manual.reduce( + (longest, later) => (compare(later.at, at) > 0 && lifetime(later.ttl) > lifetime(longest) ? later.ttl : longest), + requested.ttl, + ) + return ttl === requested.ttl ? requested : makeHint(ttl) + } + const budget = { remaining: Math.max(0, BREAKPOINT_CAP - countToolHints(request.tools) - manual.length) } + const tools = policy.tools ? markLastTool(request.tools, hint(TOOLS), budget) : request.tools // The last system part comes first; the first one only adds the base prompt to the tools prefix, so it takes a // breakpoint only when the conversation has left one over. const lastSystem = policy.system ? markSystemPart(request.system, request.system.length - 1, hint, budget) : request.system - const messages = policy.messages ? markMessages(request.messages, policy.messages, hint, budget) : request.messages + const tail = policy.messages ? markMessages(request.messages, policy.messages, hint, budget) : request.messages + const messages = policy.previousTail ? markPreviousTail(tail, hint, budget) : tail const system = policy.system ? markSystemPart(lastSystem, 0, hint, budget) : lastSystem if (tools === request.tools && system === request.system && messages === request.messages) return request @@ -249,7 +299,7 @@ export const placesMarkers = (request: LLMRequest) => { } // A declared cache format overrides the route allowlist and its model-ID heuristics. -const selectPolicy = (request: LLMRequest): CachePolicyObject => { +const selectPolicy = (request: LLMRequest): Placement => { const format = request.model.compatibility?.cacheFormat const route = request.model.route.id const auto = isAuto(request.cache) @@ -264,5 +314,4 @@ const selectPolicy = (request: LLMRequest): CachePolicyObject => { return AUTO } -// A breakpoint on the second newest message keeps the previous request's tail within the lookback. -const ANTHROPIC: CachePolicyObject = { ...AUTO, messages: { tail: 2 } } +const ANTHROPIC: Placement = { ...AUTO, previousTail: true } diff --git a/packages/ai/src/schema/options.ts b/packages/ai/src/schema/options.ts index 1739873f953..37e5c7e8cf1 100644 --- a/packages/ai/src/schema/options.ts +++ b/packages/ai/src/schema/options.ts @@ -372,8 +372,9 @@ export class CacheHint extends Schema.Class("LLM.CacheHint")({ // usual. `"auto"` is the default for agent loops — it places // breakpoints at the last tool definition, the first and last distinct system // parts, and the conversation tail so recent prefixes remain reusable during -// tool loops. On Anthropic's own API it also marks the second newest message, -// giving up the first system part's breakpoint when the budget runs out. +// tool loops. On Anthropic's own API it also marks the message before the newest +// assistant reply, where the previous request's tail breakpoint was, giving up +// the first system part's breakpoint when the budget runs out. // // Pass `"none"` to opt out entirely (the legacy behavior). Pass the granular // object form to choose placements exactly; an object with only `ttl` keeps diff --git a/packages/ai/test/cache-policy.test.ts b/packages/ai/test/cache-policy.test.ts index ae09158f68a..8706ed03417 100644 --- a/packages/ai/test/cache-policy.test.ts +++ b/packages/ai/test/cache-policy.test.ts @@ -60,7 +60,7 @@ describe("applyCachePolicy", () => { }), ) - it.effect("'auto' on Anthropic marks the last tool, the last system part, and the two newest messages", () => + it.effect("'auto' on Anthropic marks the last tool, the last system part, the tail, and the previous tail", () => Effect.gen(function* () { const prepared = yield* compileRequest( ai.request({ @@ -86,12 +86,10 @@ describe("applyCachePolicy", () => { { type: "text", text: "Base agent" }, { type: "text", text: "Project instructions", cache_control: { type: "ephemeral" } }, ], + // The previous request ended at "first user" and wrote its tail entry there. messages: [ - { role: "user", content: [{ type: "text", text: "first user" }] }, - { - role: "assistant", - content: [{ type: "text", text: "assistant reply", cache_control: { type: "ephemeral" } }], - }, + { role: "user", content: [{ type: "text", text: "first user", cache_control: { type: "ephemeral" } }] }, + { role: "assistant", content: [{ type: "text", text: "assistant reply" }] }, { role: "user", content: [{ type: "text", text: "latest user message", cache_control: { type: "ephemeral" } }], @@ -139,6 +137,7 @@ describe("applyCachePolicy", () => { Message.user("start"), Message.assistant([ToolCallPart.make({ id: "tc_1", name: "lookup", input: {} })]), Message.tool({ id: "tc_1", name: "lookup", result: "found" }), + Message.assistant("Done."), Message.user([Message.text("look at these"), ...attachments]), ], cache: "auto", @@ -146,9 +145,104 @@ describe("applyCachePolicy", () => { ) const body = prepared.body as { messages: Array<{ content: Array<{ cache_control?: unknown }> }> } - // The tool result is where the previous request's tail breakpoint sat, 25 positions before the new one. + // The previous request ended at the tool result, 26 positions before the new tail breakpoint. expect(body.messages[2]?.content[0]?.cache_control).toEqual({ type: "ephemeral" }) - expect(body.messages[3]?.content.at(-1)?.cache_control).toEqual({ type: "ephemeral" }) + expect(body.messages[3]?.content[0]?.cache_control).toBeUndefined() + expect(body.messages[4]?.content.at(-1)?.cache_control).toEqual({ type: "ephemeral" }) + }), + ) + + it.effect("'auto' on Anthropic marks the previous tail, not another result of the same step", () => + Effect.gen(function* () { + const call = (id: string) => ToolCallPart.make({ id, name: "lookup", input: {} }) + const result = (id: string) => Message.tool({ id, name: "lookup", result: "found" }) + const prepared = yield* compileRequest( + ai.request({ + model: anthropicModel, + messages: [ + Message.user("start"), + Message.assistant([call("tc_1"), call("tc_2"), call("tc_3")]), + result("tc_1"), + result("tc_2"), + result("tc_3"), + ], + cache: "auto", + }), + ) + + const body = prepared.body as { messages: Array<{ content: Array<{ cache_control?: unknown }> }> } + // The three results lower into one user turn; the previous request ended at "start". + expect(body.messages.map((message) => message.content.map((part) => part.cache_control))).toEqual([ + [{ type: "ephemeral" }], + [undefined, undefined, undefined], + [undefined, undefined, { type: "ephemeral" }], + ]) + }), + ) + + it.effect("a message with nothing that carries a marker leaves its slot to the system prompt", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: anthropicModel, + system: [ + { type: "text", text: "Base agent" }, + { type: "text", text: "Project instructions" }, + ], + tools: [{ name: "lookup", description: "lookup", inputSchema: { type: "object", properties: {} } }], + messages: [ + Message.user("start"), + Message.assistant([ + { type: "reasoning", text: "thinking", encrypted: "signature" }, + ToolCallPart.make({ id: "tc_1", name: "lookup", input: {} }), + ]), + Message.tool({ id: "tc_1", name: "lookup", result: "found" }), + ], + cache: { tools: true, system: true, messages: { tail: 2 } }, + }), + ) + + const body = prepared.body as { + system: Array<{ cache_control?: unknown }> + messages: Array<{ content: Array<{ cache_control?: unknown }> }> + } + // Thinking and tool_use blocks never carry cache_control, so the reply takes no slot. + expect(body.messages[1]?.content.map((part) => part.cache_control)).toEqual([undefined, undefined]) + expect(body.messages[2]?.content[0]?.cache_control).toEqual({ type: "ephemeral" }) + expect(body.system.map((part) => part.cache_control)).toEqual([{ type: "ephemeral" }, { type: "ephemeral" }]) + }), + ) + + it.effect("auto hints never put a shorter lifetime before a manual one", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: anthropicModel, + system: [ + { type: "text", text: "Base agent" }, + { type: "text", text: "Project instructions" }, + ], + tools: [{ name: "t1", description: "t1", inputSchema: { type: "object", properties: {} } }], + messages: [ + Message.user("first user"), + Message.assistant("assistant reply"), + Message.user([{ ...Message.text("latest"), cache: new CacheHint({ type: "ephemeral", ttl: "1h" }) }]), + ], + cache: "auto", + }), + ) + + const body = prepared.body as { + tools: Array<{ cache_control?: unknown }> + system: Array<{ cache_control?: unknown }> + messages: Array<{ content: Array<{ cache_control?: unknown }> }> + } + // Anthropic rejects a ttl="1h" marker after a 5m one. Everything before the manual hint is written for an + // hour anyway, so the earlier markers cost the same at 1h. + const hour = { type: "ephemeral", ttl: "1h" } + expect(body.tools[0]?.cache_control).toEqual(hour) + expect(body.system.map((part) => part.cache_control)).toEqual([undefined, hour]) + expect(body.messages.map((message) => message.content[0]?.cache_control)).toEqual([hour, undefined, hour]) }), ) @@ -527,7 +621,10 @@ describe("applyCachePolicy", () => { ...body.messages.flatMap((message) => message.content.map((part) => part.cache_control)), ].filter((cache) => cache !== undefined) expect(marked).toHaveLength(4) + // Only the tools marker comes before the manual 1h hint; the markers after it keep the default lifetime. + expect(body.tools[0]?.cache_control).toEqual({ type: "ephemeral", ttl: "1h" }) expect(body.system[1]?.cache_control).toEqual({ type: "ephemeral", ttl: "1h" }) + expect(body.system[2]?.cache_control).toEqual({ type: "ephemeral" }) expect(body.messages[0]?.content[0]?.cache_control).toEqual({ type: "ephemeral" }) }), ) @@ -652,22 +749,31 @@ describe("applyCachePolicy", () => { }), ) - test("skips non-cacheable parts when placing message breakpoints", () => { + test("skips parts that can't carry a marker when placing message breakpoints", () => { const compaction = CompactionPart.make({ provider: ProviderID.make("anthropic"), text: "summary" }) const toolCall = ToolCallPart.make({ id: "tc_1", name: "lookup", input: {} }) const mixed = ai.request({ model: anthropicModel, - messages: [Message.assistant([toolCall, compaction])], + messages: [Message.assistant([Message.text("Checking."), toolCall, compaction])], cache: { messages: "latest-assistant" }, }) const appliedMixed = applyCachePolicy(mixed) expect(appliedMixed.messages[0]?.content[0]).toMatchObject({ - type: "tool-call", - id: "tc_1", + type: "text", + text: "Checking.", cache: { type: "ephemeral" }, }) - expect(appliedMixed.messages[0]?.content[1]).toEqual(compaction) + expect(appliedMixed.messages[0]?.content[1]).toEqual(toolCall) + expect(appliedMixed.messages[0]?.content[2]).toEqual(compaction) + + // No protocol sends cache_control on a tool call, so a message without text keeps its slot. + const callOnly = ai.request({ + model: anthropicModel, + messages: [Message.assistant([toolCall, compaction])], + cache: { messages: "latest-assistant" }, + }) + expect(applyCachePolicy(callOnly)).toBe(callOnly) const compactionOnly = ai.request({ model: anthropicModel, diff --git a/packages/ai/test/effort-updates.test.ts b/packages/ai/test/effort-updates.test.ts index 9ff4dac905e..90f652be47b 100644 --- a/packages/ai/test/effort-updates.test.ts +++ b/packages/ai/test/effort-updates.test.ts @@ -73,10 +73,11 @@ describe("cache policy", () => { }), ) - // Anthropic's auto policy marks the two newest messages; the effort marker counts as neither. + // Anthropic's auto policy marks the newest message and the one before the latest reply; the effort marker + // counts as neither. expect(prepared.body.messages).toEqual([ - { role: "user", content: [{ type: "text", text: "first" }] }, - { role: "assistant", content: [{ type: "text", text: "reply", cache_control: { type: "ephemeral" } }] }, + { role: "user", content: [{ type: "text", text: "first", cache_control: { type: "ephemeral" } }] }, + { role: "assistant", content: [{ type: "text", text: "reply" }] }, { role: "user", content: [{ type: "text", text: "latest", cache_control: { type: "ephemeral" } }] }, { role: "system", content: [], output_config: { effort: "low" } }, ]) diff --git a/packages/ai/test/provider/anthropic-messages-cache.recorded.test.ts b/packages/ai/test/provider/anthropic-messages-cache.recorded.test.ts index 81940259d76..d8a4e69c64f 100644 --- a/packages/ai/test/provider/anthropic-messages-cache.recorded.test.ts +++ b/packages/ai/test/provider/anthropic-messages-cache.recorded.test.ts @@ -54,7 +54,7 @@ const longToolTurnRequest = ai.request({ system: LARGE_CACHEABLE_SYSTEM, messages: longToolTurn, tools: [lookup], - // The cassette was recorded with a single tail breakpoint, before auto marked Anthropic's two newest messages. + // The cassette was recorded with a single tail breakpoint, before auto also marked Anthropic's previous tail. // Re-record with `RECORD=true` and an Anthropic key to cover the current default instead. cache: { tools: true, system: true, messages: { tail: 1 } }, generation: { maxTokens: 16, temperature: 0 }, From 98a6ec9b89c47c4a7ae9edb98aeb1d79ce0bdac3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 09:03:28 +0900 Subject: [PATCH 3/4] fix(ai): put cache marker lifetimes in send order when lowering The previous commit raised an auto hint to the longest manual hint after it in request order, but requests could still send a 1h marker after a 5m one, which Anthropic rejects with a 400: - A shorter manual hint before an auto hint: `cache: { ttl: "1h" }` with a manual 5m hint on an earlier message sent the tail and the previous tail at 1h after it. - Manual tool hints, which only counted against the budget. - System updates on models that take native system messages. Anthropic Messages sends an update after the user turn that follows it, so a 1h hint on the update went out after the 5m marker the cache policy had placed on that turn. Request order can't settle this, so the cache policy gives every auto hint the requested lifetime again, and Anthropic Messages, Bedrock Converse and OpenAI Chat raise each marker to the longest lifetime after it once the body is built. Raising never moves the last 1h marker, so it costs nothing, and it also repairs manual hints the caller placed out of order. A wrapped system update kept only its last part's hint, so the tail breakpoint the cache policy puts on its last non-blank part was dropped when a blank part followed. The wrapped block now takes the last hint on any of its parts. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01X7arpmRb395Ye7ukWMUdSp --- packages/ai/src/cache-policy.ts | 72 ++---- .../ai/src/protocols/anthropic-messages.ts | 10 + packages/ai/src/protocols/bedrock-converse.ts | 7 +- packages/ai/src/protocols/openai-chat.ts | 23 +- packages/ai/src/protocols/shared.ts | 7 +- packages/ai/src/protocols/utils/cache.ts | 20 ++ packages/ai/test/cache-policy.test.ts | 231 ++++++++++++++++++ 7 files changed, 313 insertions(+), 57 deletions(-) diff --git a/packages/ai/src/cache-policy.ts b/packages/ai/src/cache-policy.ts index 9758e236b72..17928ae5655 100644 --- a/packages/ai/src/cache-policy.ts +++ b/packages/ai/src/cache-policy.ts @@ -21,9 +21,10 @@ // Manual `cache: CacheHint` placements on individual parts are preserved and // count against the four-breakpoint budget; auto only fills remaining slots, // in the order tools, last system part, conversation tail, previous tail, first -// system part. Anthropic rejects a longer lifetime after a shorter one, so an -// auto hint takes the longest lifetime of any manual hint after it. The prefix -// up to that manual hint is written at its lifetime anyway, so this costs nothing. +// system part. Every auto hint takes the requested lifetime. Anthropic rejects a +// longer lifetime after a shorter one, so the protocols that send lifetimes put +// them in order once the body is built (`orderLifetimes`), when the send order +// of every marker is known. import { CacheHint, type CachePolicy, type CachePolicyObject, type CacheTTL } from "./schema/options.js" import { AssistantMessage, @@ -50,11 +51,6 @@ const BREAKPOINT_CAP = 4 // `previousTail` is internal: it marks the message before the newest assistant reply. type Placement = CachePolicyObject & { readonly previousTail?: boolean } -// A marker's place in the order Anthropic reads them: tools, then system parts, then message parts. -type Position = readonly [region: number, index: number, part: number] -type HintAt = (at: Position) => CacheHint -const TOOLS: Position = [0, 0, 0] - // Resolution rules: // - undefined → "auto" — caching is on by default. // - "auto" → tools + first/last system + final message boundary; on @@ -116,16 +112,6 @@ const gatewayPolicy = (modelID: string): CachePolicyObject => { const makeHint = (ttl: CacheTTL | undefined): CacheHint => ttl !== undefined ? new CacheHint({ type: "ephemeral", ttl }) : new CacheHint({ type: "ephemeral" }) -const UNITS = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 } - -// An omitted ttl is the provider default, five minutes on Anthropic. -const lifetime = (ttl: CacheTTL | undefined) => { - const match = ttl?.match(/^(\d+)(ms|s|m|h|d)$/) - return match ? Number(match[1]) * UNITS[match[2] as keyof typeof UNITS] : UNITS.m * 5 -} - -const compare = (a: Position, b: Position) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2] - interface Budget { remaining: number } @@ -151,13 +137,13 @@ const countToolHints = (tools: ReadonlyArray): number => const markSystemPart = ( system: LLMRequest["system"], index: number, - hint: HintAt, + hint: CacheHint, budget: Budget, ): LLMRequest["system"] => { const part = system[index] if (!part || part.cache || budget.remaining === 0) return system budget.remaining -= 1 - return system.map((item, i) => (i === index ? { ...item, cache: hint([1, index, 0]) } : item)) + return system.map((item, i) => (i === index ? { ...item, cache: hint } : item)) } const lastIndexOfRole = (messages: ReadonlyArray, role: Message["role"]): number => @@ -182,7 +168,7 @@ const isMarkable = (part: ContentPart): part is CacheablePart => { const markMessageAt = ( messages: ReadonlyArray, index: number, - hint: HintAt, + hint: CacheHint, budget: Budget, ): ReadonlyArray => { if (index < 0 || index >= messages.length) return messages @@ -192,7 +178,7 @@ const markMessageAt = ( const existing = target.content[markAt] if (!existing || !isMarkable(existing) || existing.cache || budget.remaining === 0) return messages budget.remaining -= 1 - const next = cachePartAt(target, markAt, hint([2, index, markAt])) + const next = cachePartAt(target, markAt, hint) // Single pass over `messages`, substituting the one updated entry. Long // conversations call this on every request, so avoid `.map()` here — its // closure dispatch and identity copies show up in profiling. @@ -220,7 +206,7 @@ const cacheContentAt = (content: ReadonlyArray, const markMessages = ( messages: ReadonlyArray, strategy: NonNullable, - hint: HintAt, + hint: CacheHint, budget: Budget, ): ReadonlyArray => { if (messages.length === 0) return messages @@ -243,42 +229,32 @@ const markMessages = ( // The previous request ended at the message before the newest assistant reply and wrote its tail entry there. // Marking that message again reads the entry directly, however many blocks the reply and the newest message add. -const markPreviousTail = (messages: ReadonlyArray, hint: HintAt, budget: Budget) => { +const markPreviousTail = (messages: ReadonlyArray, hint: CacheHint, budget: Budget) => { const reply = lastIndexOfRole(messages, "assistant") const index = messages.findLastIndex((message, i) => i < reply && effortUpdate(message) === undefined) return markMessageAt(messages, index, hint, budget) } -// Hints the caller already placed on system and message parts. Manual tool hints only count against the budget: -// auto marks just the last tool, so none of them come after it. -const manualHints = (request: LLMRequest) => { - const hints: Array<{ readonly at: Position; readonly ttl: CacheTTL | undefined }> = [] - request.system.forEach((part, index) => { - if (part.cache) hints.push({ at: [1, index, 0], ttl: part.cache.ttl }) - }) - request.messages.forEach((message, index) => - message.content.forEach((part, i) => { - if (isCacheablePart(part) && part.cache) hints.push({ at: [2, index, i], ttl: part.cache.ttl }) - }), +const countHints = (request: LLMRequest) => + countToolHints(request.tools) + + request.system.reduce((count, part) => count + (part.cache === undefined ? 0 : 1), 0) + + request.messages.reduce( + (count, message) => + count + + message.content.reduce( + (contentCount, part) => contentCount + (isCacheablePart(part) && part.cache !== undefined ? 1 : 0), + 0, + ), + 0, ) - return hints -} export const applyCachePolicy = (request: LLMRequest): LLMRequest => { const policy = selectPolicy(request) if (!policy.tools && !policy.system && !policy.messages) return request - const manual = manualHints(request) - const requested = makeHint(requestTTL(request)) - const hint = (at: Position) => { - const ttl = manual.reduce( - (longest, later) => (compare(later.at, at) > 0 && lifetime(later.ttl) > lifetime(longest) ? later.ttl : longest), - requested.ttl, - ) - return ttl === requested.ttl ? requested : makeHint(ttl) - } - const budget = { remaining: Math.max(0, BREAKPOINT_CAP - countToolHints(request.tools) - manual.length) } - const tools = policy.tools ? markLastTool(request.tools, hint(TOOLS), budget) : request.tools + const hint = makeHint(requestTTL(request)) + const budget = { remaining: Math.max(0, BREAKPOINT_CAP - countHints(request)) } + const tools = policy.tools ? markLastTool(request.tools, hint, budget) : request.tools // The last system part comes first; the first one only adds the base prompt to the tools prefix, so it takes a // breakpoint only when the conversation has left one over. const lastSystem = policy.system diff --git a/packages/ai/src/protocols/anthropic-messages.ts b/packages/ai/src/protocols/anthropic-messages.ts index d6eee0f4eb3..2ccf9cba4f2 100644 --- a/packages/ai/src/protocols/anthropic-messages.ts +++ b/packages/ai/src/protocols/anthropic-messages.ts @@ -976,6 +976,16 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques })) const messages = yield* lowerMessages(flattened.request, breakpoints) yield* Cache.warnDropped(breakpoints, "Anthropic Messages", ANTHROPIC_BREAKPOINT_CAP) + // Read the markers from the finished body: a held system update goes out after the user turns that follow it. + Cache.orderLifetimes( + [ + ...(tools ?? []).map((tool) => tool.cache_control), + ...(system ?? []).map((part) => part.cache_control), + ...messages.flatMap((message) => + message.content.map((block) => ("cache_control" in block ? block.cache_control : undefined)), + ), + ].filter((marker) => marker !== undefined), + ) const output_config = updates.effort === undefined && format === undefined ? undefined : { effort: updates.effort, format } const maxTokens = generation?.maxTokens ?? DEFAULT_MAX_TOKENS diff --git a/packages/ai/src/protocols/bedrock-converse.ts b/packages/ai/src/protocols/bedrock-converse.ts index 6495524c681..75965324d8e 100644 --- a/packages/ai/src/protocols/bedrock-converse.ts +++ b/packages/ai/src/protocols/bedrock-converse.ts @@ -24,7 +24,7 @@ import { classifyProviderFailure } from "../provider-error.js" import { JsonObject, optionalArray, ProviderShared } from "./shared.js" import { BedrockAuth } from "./utils/bedrock-auth.js" import { BedrockCache } from "./utils/bedrock-cache.js" -import { warnDropped } from "./utils/cache.js" +import { orderLifetimes, warnDropped } from "./utils/cache.js" import { BedrockMedia } from "./utils/bedrock-media.js" import { claudeVersion, supportsThinkingBlockBinding, THINKING_BINDING_BETA } from "./utils/claude-model.js" import { Lifecycle } from "./utils/lifecycle.js" @@ -605,6 +605,11 @@ const fromRequest = Effect.fn("BedrockConverse.fromRequest")(function* (request: const system = lowerSystem(breakpoints, request.system) const messages = yield* lowerMessages(flattened.request, breakpoints) yield* warnDropped(breakpoints, "Bedrock Converse", BedrockCache.BEDROCK_BREAKPOINT_CAP) + orderLifetimes( + [...(toolConfig?.tools ?? []), ...(system ?? []), ...messages.flatMap((message) => message.content)] + .filter((block): block is BedrockCache.CachePointBlock => "cachePoint" in block) + .map((block) => block.cachePoint), + ) const inferenceConfig = (() => { if ( maxTokens === undefined && diff --git a/packages/ai/src/protocols/openai-chat.ts b/packages/ai/src/protocols/openai-chat.ts index cd76637892c..af16d1766f4 100644 --- a/packages/ai/src/protocols/openai-chat.ts +++ b/packages/ai/src/protocols/openai-chat.ts @@ -871,15 +871,24 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* ( const hasActiveTools = flattened.tools.length > 0 const custom = OpenAIFreeform.tools(request) const lowering = { ...options, cacheControl: options.cacheControl ?? declaredCacheControl(request), custom } + const messages = yield* lowerMessages(flattened.request, lowering) + const tools = + flattened.tools.length === 0 + ? hasHistory + ? [] + : undefined + : flattened.tools.map((tool) => lowerTool(tool, lowering, supportsStrictMode, custom.get(tool.name))) + // Gateways hand markers to Anthropic as tools, then system, then messages; the system prompt is the first message. + Cache.orderLifetimes( + [ + ...(tools ?? []), + ...messages.flatMap((message) => (Array.isArray(message.content) ? message.content : [])), + ].flatMap((item) => ("cache_control" in item && item.cache_control !== undefined ? [item.cache_control] : [])), + ) return { model: request.model.id, - messages: yield* lowerMessages(flattened.request, lowering), - tools: - flattened.tools.length === 0 - ? hasHistory - ? [] - : undefined - : flattened.tools.map((tool) => lowerTool(tool, lowering, supportsStrictMode, custom.get(tool.name))), + messages, + tools, tool_choice: hasActiveTools && request.toolChoice ? yield* lowerToolChoice(request.toolChoice, custom) : undefined, stream: true as const, ...((request.model.compatibility?.streamUsage ?? true) ? { stream_options: { include_usage: true } } : {}), diff --git a/packages/ai/src/protocols/shared.ts b/packages/ai/src/protocols/shared.ts index 6913ab77168..1a9b1b72cb3 100644 --- a/packages/ai/src/protocols/shared.ts +++ b/packages/ai/src/protocols/shared.ts @@ -220,7 +220,12 @@ export const wrappedSystemUpdate = Effect.fnUntraced(function* ( message: LLMRequest["messages"][number], ) { const content = yield* systemUpdateText(route, message) - return { type: "text" as const, text: wrapSystemUpdate(content), cache: content.at(-1)?.cache } + // The parts become one block, which takes the last hint on any of them: a trailing blank part never carries one. + return { + type: "text" as const, + text: wrapSystemUpdate(content), + cache: content.findLast((part) => part.cache !== undefined)?.cache, + } }) /** diff --git a/packages/ai/src/protocols/utils/cache.ts b/packages/ai/src/protocols/utils/cache.ts index 4a46b6f4f8e..318ba733ec4 100644 --- a/packages/ai/src/protocols/utils/cache.ts +++ b/packages/ai/src/protocols/utils/cache.ts @@ -34,6 +34,26 @@ export const cacheControl = () => { } } +const UNITS = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 } + +// An omitted ttl is the provider default, five minutes on Anthropic. +const lifetime = (ttl: string | undefined) => { + const match = ttl?.match(/^(\d+)(ms|s|m|h|d)$/) + return match ? Number(match[1]) * UNITS[match[2] as keyof typeof UNITS] : UNITS.m * 5 +} + +// Anthropic reads cache markers in the order tools, system, messages and rejects a longer lifetime after a shorter +// one, such as a 1h marker after a 5m one. Raising each marker to the longest lifetime after it keeps the request +// valid at no cost: the prefix up to the last 1h marker is written for an hour either way. Pass the markers of a +// finished body in the order they are sent; they are updated in place. +export const orderLifetimes = (markers: ReadonlyArray<{ ttl?: string }>) => + markers.forEach((marker, index) => { + const longest = markers + .slice(index + 1) + .reduce((ttl, later) => (lifetime(later.ttl) > lifetime(ttl) ? later.ttl : ttl), marker.ttl) + if (longest !== marker.ttl) marker.ttl = longest + }) + // OpenAI's request-level lifetime. `prompt_cache_retention` takes only "24h" (or "in_memory") and is the only // control before GPT-5.6; every other lifetime goes to `prompt_cache_options.ttl`, which GPT-5.6+, Kimi and // DeepInfra read. diff --git a/packages/ai/test/cache-policy.test.ts b/packages/ai/test/cache-policy.test.ts index 8706ed03417..89377f92072 100644 --- a/packages/ai/test/cache-policy.test.ts +++ b/packages/ai/test/cache-policy.test.ts @@ -13,6 +13,7 @@ import { Meta, MiniMax, Moonshot, + OpenRouter, ZAICodingPlan, } from "../src/providers.js" import * as AnthropicMessages from "../src/protocols/anthropic-messages.js" @@ -246,6 +247,236 @@ describe("applyCachePolicy", () => { }), ) + it.effect("a manual hint takes the longer lifetime of a marker after it", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: anthropicModel, + system: "Base agent", + messages: [ + Message.user([{ ...Message.text("pinned"), cache: new CacheHint({ type: "ephemeral", ttl: "5m" }) }]), + Message.assistant("first reply"), + Message.user("second user"), + Message.assistant("second reply"), + Message.user("latest"), + ], + cache: { ttl: "1h" }, + }), + ) + + const body = prepared.body as { + system: Array<{ cache_control?: unknown }> + messages: Array<{ content: Array<{ cache_control?: unknown }> }> + } + // The tail and the previous tail go out at 1h after the manual 5m hint, which Anthropic rejects. Everything up + // to the last 1h marker is written for an hour anyway, so the manual hint takes the hour at no cost. + const hour = { type: "ephemeral", ttl: "1h" } + expect(body.system[0]?.cache_control).toEqual(hour) + expect(body.messages.map((message) => message.content[0]?.cache_control)).toEqual([ + hour, + undefined, + hour, + undefined, + hour, + ]) + }), + ) + + it.effect("a manual tool hint takes the longer lifetime of the markers after it", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: anthropicModel, + system: "Base agent", + tools: [ + { + name: "t1", + description: "t1", + inputSchema: { type: "object", properties: {} }, + cache: new CacheHint({ type: "ephemeral", ttl: "5m" }), + }, + { name: "t2", description: "t2", inputSchema: { type: "object", properties: {} } }, + ], + prompt: "hi", + cache: { ttl: "1h" }, + }), + ) + + const body = prepared.body as { + tools: Array<{ cache_control?: unknown }> + system: Array<{ cache_control?: unknown }> + messages: Array<{ content: Array<{ cache_control?: unknown }> }> + } + const hour = { type: "ephemeral", ttl: "1h" } + expect(body.tools.map((tool) => tool.cache_control)).toEqual([hour, hour]) + expect(body.system[0]?.cache_control).toEqual(hour) + expect(body.messages[0]?.content[0]?.cache_control).toEqual(hour) + }), + ) + + it.effect("lifetimes stay in send order when a system update moves after the next user turn", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + // Opus 4.8 takes native system messages, which go out after the user turn that follows them. + model: AnthropicMessages.route + .with({ endpoint: { baseURL: "https://api.anthropic.test/v1/" }, auth: Auth.header("x-api-key", "test") }) + .model({ id: "claude-opus-4-8" }), + system: [ + { type: "text", text: "Base agent" }, + { type: "text", text: "Project instructions" }, + ], + tools: [{ name: "t1", description: "t1", inputSchema: { type: "object", properties: {} } }], + messages: [ + Message.user("first user"), + Message.assistant("assistant reply"), + Message.system([ + { type: "text", text: "Use parameterized SQL.", cache: new CacheHint({ type: "ephemeral", ttl: "1h" }) }, + ]), + Message.user("latest"), + ], + cache: "auto", + }), + ) + + const body = prepared.body as { + tools: Array<{ cache_control?: unknown }> + system: Array<{ cache_control?: unknown }> + messages: Array<{ role: string; content: Array<{ cache_control?: unknown }> }> + } + // The tail sits after the update in the request but goes out before it, so it takes the update's hour too. + const hour = { type: "ephemeral", ttl: "1h" } + expect(body.tools[0]?.cache_control).toEqual(hour) + expect(body.system.map((part) => part.cache_control)).toEqual([undefined, hour]) + expect(body.messages.map((message) => [message.role, message.content[0]?.cache_control])).toEqual([ + ["user", undefined], + ["assistant", undefined], + ["user", hour], + ["system", hour], + ]) + }), + ) + + it.effect("lifetimes follow the body when a held system update goes out before a reply", () => + Effect.gen(function* () { + const hour = new CacheHint({ type: "ephemeral", ttl: "1h" }) + const five = new CacheHint({ type: "ephemeral", ttl: "5m" }) + const prepared = yield* compileRequest( + ai.request({ + model: AnthropicMessages.route + .with({ endpoint: { baseURL: "https://api.anthropic.test/v1/" }, auth: Auth.header("x-api-key", "test") }) + .model({ id: "claude-opus-4-8" }), + system: "Base agent", + messages: [ + Message.user("first user"), + Message.system([ + { type: "text", text: "Use parameterized SQL.", cache: hour }, + { type: "text", text: "Prefer small diffs.", cache: five }, + ]), + Message.assistant([{ ...Message.text("Understood."), cache: five }]), + Message.user("latest"), + ], + cache: "auto", + }), + ) + + const body = prepared.body as { + system: Array<{ cache_control?: unknown }> + messages: Array<{ role: string; content: Array<{ cache_control?: unknown }> }> + } + // The reply's blocks are lowered before the held update, which goes out ahead of them. + expect(body.system[0]?.cache_control).toEqual({ type: "ephemeral", ttl: "1h" }) + expect( + body.messages.map((message) => [message.role, message.content.map((block) => block.cache_control)]), + ).toEqual([ + ["user", [undefined]], + [ + "system", + [ + { type: "ephemeral", ttl: "1h" }, + { type: "ephemeral", ttl: "5m" }, + ], + ], + ["assistant", [{ type: "ephemeral", ttl: "5m" }]], + ["user", [undefined]], + ]) + }), + ) + + it.effect("a wrapped system update keeps its marker when its last part is blank", () => + Effect.gen(function* () { + const prepared = yield* compileRequest( + ai.request({ + model: anthropicModel, + messages: [ + Message.user("first user"), + Message.system([ + { type: "text", text: "Use parameterized SQL." }, + { type: "text", text: " " }, + ]), + ], + cache: "auto", + }), + ) + + const body = prepared.body as { messages: Array<{ content: Array<{ cache_control?: unknown }> }> } + // The tail hint lands on the last non-blank part; the update is wrapped into the user turn as one block. + expect(body.messages.map((message) => message.content.map((block) => block.cache_control))).toEqual([ + [undefined, { type: "ephemeral" }], + ]) + }), + ) + + it.effect("gateway and Bedrock markers before a manual 1h hint take its hour", () => + Effect.gen(function* () { + const input = { + system: "Base agent", + tools: [{ name: "t1", description: "t1", inputSchema: { type: "object" as const, properties: {} } }], + messages: [ + Message.user("first user"), + Message.assistant("assistant reply"), + Message.user([{ ...Message.text("latest"), cache: new CacheHint({ type: "ephemeral", ttl: "1h" }) }]), + ], + cache: "auto" as const, + } + const gateway = yield* compileRequest( + ai.request({ + ...input, + model: OpenRouter.configure({ apiKey: "test", baseURL: "https://openrouter.test/api/v1" }).model( + "anthropic/claude-sonnet-4.5", + ), + }), + ) + const bedrock = yield* compileRequest( + ai.request({ + ...input, + model: AmazonBedrock.configure({ + credentials: { region: "us-east-1", accessKeyId: "fixture", secretAccessKey: "fixture" }, + }).model("anthropic.claude-sonnet-4-5-20250929-v1:0"), + }), + ) + + const hour = { type: "ephemeral", ttl: "1h" } + const gatewayBody = gateway.body as { + tools: Array<{ cache_control?: unknown }> + messages: Array<{ content: unknown }> + } + expect(gatewayBody.tools[0]?.cache_control).toEqual(hour) + expect(gatewayBody.messages[0]?.content).toEqual([{ type: "text", text: "Base agent", cache_control: hour }]) + expect(gatewayBody.messages.at(-1)?.content).toEqual([{ type: "text", text: "latest", cache_control: hour }]) + + const point = { cachePoint: { type: "default", ttl: "1h" } } + const bedrockBody = bedrock.body as { + toolConfig: { tools: Array } + system: Array + messages: Array<{ content: Array }> + } + expect(bedrockBody.toolConfig.tools.at(-1)).toEqual(point) + expect(bedrockBody.system.at(-1)).toEqual(point) + expect(bedrockBody.messages.at(-1)?.content.at(-1)).toEqual(point) + }), + ) + it.effect("'auto' keeps the first and last system parts and one message boundary off Anthropic's own API", () => Effect.gen(function* () { const prepared = yield* compileRequest( From 5e6f8469bb44403d4bc73096b5d7685c0f747f40 Mon Sep 17 00:00:00 2001 From: swf-cmd <284101019+swf-cmd@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:53:22 +0900 Subject: [PATCH 4/4] fix(ai): keep the previous tail and lifetime order across tool changes dev's #64166 adds `Message.tools(...)` markers. Anthropic takes them in place as a system message with `tool_addition` and `tool_removal` blocks. The tail breakpoint skips such a marker, so the previous request's entry ends on the message before it. The previous-tail breakpoint now skips markers the same way. Before, it picked the marker, which has nothing to mark, and the entry was only in reach of the 20-block lookback. A tool added by a marker carries its cache marker on the definition inside the block. Lifetime ordering now reads it there, so a manual 5m hint on such a tool no longer goes out before a 1h marker. Co-Authored-By: Claude --- packages/ai/src/cache-policy.ts | 3 +- .../ai/src/protocols/anthropic-messages.ts | 6 +- packages/ai/test/cache-policy.test.ts | 71 +++++++++++++++++++ 3 files changed, 78 insertions(+), 2 deletions(-) diff --git a/packages/ai/src/cache-policy.ts b/packages/ai/src/cache-policy.ts index 7d32d763726..e94554d19c7 100644 --- a/packages/ai/src/cache-policy.ts +++ b/packages/ai/src/cache-policy.ts @@ -232,9 +232,10 @@ const isMarker = (message: Message) => effortUpdate(message) !== undefined || to // The previous request ended at the message before the newest assistant reply and wrote its tail entry there. // Marking that message again reads the entry directly, however many blocks the reply and the newest message add. +// The tail breakpoint skips markers, so this one does too. const markPreviousTail = (messages: ReadonlyArray, hint: CacheHint, budget: Budget) => { const reply = lastIndexOfRole(messages, "assistant") - const index = messages.findLastIndex((message, i) => i < reply && effortUpdate(message) === undefined) + const index = messages.findLastIndex((message, i) => i < reply && !isMarker(message)) return markMessageAt(messages, index, hint, budget) } diff --git a/packages/ai/src/protocols/anthropic-messages.ts b/packages/ai/src/protocols/anthropic-messages.ts index 27bed6ddff0..68305aed023 100644 --- a/packages/ai/src/protocols/anthropic-messages.ts +++ b/packages/ai/src/protocols/anthropic-messages.ts @@ -1044,12 +1044,16 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques const messages = yield* lowerMessages(flattened.request, breakpoints) yield* Cache.warnDropped(breakpoints, "Anthropic Messages", ANTHROPIC_BREAKPOINT_CAP) // Read the markers from the finished body: a held system update goes out after the user turns that follow it. + // A tool added mid-conversation carries its marker on the definition inside the block. Cache.orderLifetimes( [ ...(tools ?? []).map((tool) => tool.cache_control), ...(system ?? []).map((part) => part.cache_control), ...messages.flatMap((message) => - message.content.map((block) => ("cache_control" in block ? block.cache_control : undefined)), + message.content.map((block) => { + if (block.type === "tool_addition") return block.tool.definition.cache_control + return "cache_control" in block ? block.cache_control : undefined + }), ), ].filter((marker) => marker !== undefined), ) diff --git a/packages/ai/test/cache-policy.test.ts b/packages/ai/test/cache-policy.test.ts index 89377f92072..d594948c38b 100644 --- a/packages/ai/test/cache-policy.test.ts +++ b/packages/ai/test/cache-policy.test.ts @@ -181,6 +181,46 @@ describe("applyCachePolicy", () => { }), ) + it.effect("'auto' on Anthropic marks the previous tail before a tool change", () => + Effect.gen(function* () { + const tool = (name: string) => ({ name, description: name, inputSchema: { type: "object", properties: {} } }) + const prepared = yield* compileRequest( + ai.request({ + // Opus 5 takes tool changes in place, as a system message after the user turn. + model: AnthropicMessages.route + .with({ endpoint: { baseURL: "https://api.anthropic.test/v1/" }, auth: Auth.header("x-api-key", "test") }) + .model({ id: "claude-opus-5", capabilities: { tools: { updates: ["add", "remove", "replace"] } } }), + tools: [tool("read"), tool("edit")], + messages: [ + Message.user("first"), + Message.assistant("reply"), + Message.user("latest"), + Message.tools({ add: [tool("write")], remove: ["edit"] }), + Message.assistant("second reply"), + Message.user("newest"), + ], + cache: "auto", + }), + ) + + const body = prepared.body as { + messages: Array<{ role: string; content: Array<{ type: string; cache_control?: unknown }> }> + } + // The previous request ended with the tool change and put its tail breakpoint on "latest", before it. + expect(body.messages.map((message) => [message.role, message.content.map((part) => part.cache_control)])).toEqual( + [ + ["user", [undefined]], + ["assistant", [undefined]], + ["user", [{ type: "ephemeral" }]], + ["system", [undefined, undefined]], + ["assistant", [undefined]], + ["user", [{ type: "ephemeral" }]], + ], + ) + expect(body.messages[3]?.content.map((part) => part.type)).toEqual(["tool_addition", "tool_removal"]) + }), + ) + it.effect("a message with nothing that carries a marker leaves its slot to the system prompt", () => Effect.gen(function* () { const prepared = yield* compileRequest( @@ -314,6 +354,37 @@ describe("applyCachePolicy", () => { }), ) + it.effect("a hinted tool added mid-conversation takes the longer lifetime of the markers after it", () => + Effect.gen(function* () { + const tool = (name: string) => ({ name, description: name, inputSchema: { type: "object", properties: {} } }) + const prepared = yield* compileRequest( + ai.request({ + model: AnthropicMessages.route + .with({ endpoint: { baseURL: "https://api.anthropic.test/v1/" }, auth: Auth.header("x-api-key", "test") }) + .model({ id: "claude-opus-5", capabilities: { tools: { updates: ["add", "remove", "replace"] } } }), + tools: [tool("read")], + messages: [ + Message.user("first"), + Message.tools({ add: [{ ...tool("write"), cache: new CacheHint({ type: "ephemeral", ttl: "5m" }) }] }), + Message.assistant("reply"), + Message.user("latest"), + ], + cache: { ttl: "1h" }, + }), + ) + + const body = prepared.body as { + messages: Array<{ + content: Array<{ cache_control?: unknown; tool?: { definition?: { cache_control?: unknown } } }> + }> + } + // The added tool's marker sits on its definition, before the hour-long tail breakpoint. + const hour = { type: "ephemeral", ttl: "1h" } + expect(body.messages[1]?.content[0]?.tool?.definition?.cache_control).toEqual(hour) + expect(body.messages[3]?.content[0]?.cache_control).toEqual(hour) + }), + ) + it.effect("lifetimes stay in send order when a system update moves after the next user turn", () => Effect.gen(function* () { const prepared = yield* compileRequest(