diff --git a/packages/ai/src/cache-policy.ts b/packages/ai/src/cache-policy.ts index 21e4627dd6e..e94554d19c7 100644 --- a/packages/ai/src/cache-policy.ts +++ b/packages/ai/src/cache-policy.ts @@ -8,8 +8,23 @@ // 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. 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. +// 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. 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, @@ -34,9 +49,14 @@ 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 } + // 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 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. @@ -115,16 +135,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 => @@ -135,9 +155,17 @@ 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, @@ -146,11 +174,10 @@ const markMessageAt = ( ): 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) // Single pass over `messages`, substituting the one updated entry. Long @@ -194,13 +221,24 @@ const markMessages = ( start -= 1 if (!isMarker(messages[start]!)) 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++) if (!isMarker(messages[i]!)) next = markMessageAt(next, i, hint, budget) + for (let i = messages.length - 1; i >= start; i--) + if (!isMarker(messages[i]!)) next = markMessageAt(next, i, hint, budget) return next } const isMarker = (message: Message) => effortUpdate(message) !== undefined || toolsUpdate(message) !== undefined +// 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 && !isMarker(message)) + return markMessageAt(messages, index, hint, budget) +} + const countHints = (request: LLMRequest) => countToolHints(request.tools) + request.system.reduce((count, part) => count + (part.cache === undefined ? 0 : 1), 0) + @@ -221,8 +259,14 @@ 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 - const messages = policy.messages ? markMessages(request.messages, policy.messages, hint, budget) : request.messages + // 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 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 return { ...request, tools, system, messages } @@ -235,7 +279,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) @@ -245,5 +289,9 @@ 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 } + +const ANTHROPIC: Placement = { ...AUTO, previousTail: true } diff --git a/packages/ai/src/protocols/anthropic-messages.ts b/packages/ai/src/protocols/anthropic-messages.ts index 092179d0a9c..538703732fd 100644 --- a/packages/ai/src/protocols/anthropic-messages.ts +++ b/packages/ai/src/protocols/anthropic-messages.ts @@ -1038,6 +1038,20 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques })) const messages = yield* lowerMessages(updates.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) => { + if (block.type === "tool_addition") return block.tool.definition.cache_control + return "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 = request.maxTokens ?? DEFAULT_MAX_TOKENS diff --git a/packages/ai/src/protocols/bedrock-converse.ts b/packages/ai/src/protocols/bedrock-converse.ts index 9bb8ae91ea0..cf4dcea7dbf 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" @@ -604,6 +604,11 @@ const fromRequest = Effect.fn("BedrockConverse.fromRequest")(function* (request: const system = lowerSystem(breakpoints, request.system) const messages = yield* lowerMessages(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 6e2a8601080..bba8f21f9d9 100644 --- a/packages/ai/src/protocols/openai-chat.ts +++ b/packages/ai/src/protocols/openai-chat.ts @@ -894,15 +894,24 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* ( const hasActiveTools = definitions.length > 0 const custom = OpenAIFreeform.tools(request) const lowering = { ...options, cacheControl: options.cacheControl ?? declaredCacheControl(request), custom } + const messages = yield* lowerMessages(request, lowering) + const tools = + definitions.length === 0 + ? hasHistory + ? [] + : undefined + : definitions.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(request, lowering), - tools: - definitions.length === 0 - ? hasHistory - ? [] - : undefined - : definitions.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.capabilities?.streamUsage ?? true) ? { stream_options: { include_usage: true } } : {}), diff --git a/packages/ai/src/protocols/shared.ts b/packages/ai/src/protocols/shared.ts index 70799f34d17..7af352fb56f 100644 --- a/packages/ai/src/protocols/shared.ts +++ b/packages/ai/src/protocols/shared.ts @@ -247,7 +247,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/src/schema/options.ts b/packages/ai/src/schema/options.ts index 10a25d13b55..f8ff442e73d 100644 --- a/packages/ai/src/schema/options.ts +++ b/packages/ai/src/schema/options.ts @@ -421,7 +421,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. +// 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 f7f85a6f47b..d594948c38b 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" @@ -60,7 +61,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, the tail, and the previous tail", () => Effect.gen(function* () { const prepared = yield* compileRequest( ai.request({ @@ -79,24 +80,500 @@ 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" } }, + ], + // The previous request ended at "first user" and wrote its tail entry there. + messages: [ + { 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" } }], + }, + ], + }), + ) + }), + ) + + 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.assistant("Done."), + Message.user([Message.text("look at these"), ...attachments]), + ], + cache: "auto", + }), + ) + + const body = prepared.body as { messages: Array<{ content: Array<{ cache_control?: unknown }> }> } + // 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[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("'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( + 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]) + }), + ) + + 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("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( + 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( + 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 +904,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) @@ -445,8 +923,39 @@ 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.messages[0]?.content[0]?.cache_control).toBeUndefined() + expect(body.system[2]?.cache_control).toEqual({ type: "ephemeral" }) + 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" }, + ]) }), ) @@ -542,22 +1051,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 7dedf329e29..746290b22b8 100644 --- a/packages/ai/test/effort-updates.test.ts +++ b/packages/ai/test/effort-updates.test.ts @@ -73,8 +73,10 @@ describe("cache policy", () => { }), ) + // 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: "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 0c3676bc2fd..130b417815c 100644 --- a/packages/ai/test/provider/anthropic-messages-cache.recorded.test.ts +++ b/packages/ai/test/provider/anthropic-messages-cache.recorded.test.ts @@ -55,6 +55,9 @@ const longToolTurnRequest = ai.request({ system: LARGE_CACHEABLE_SYSTEM, messages: longToolTurn, tools: [lookup], + // 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 } }, maxTokens: 16, temperature: 0, })