Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): place the Anthropic cache breakpoint on the last message of each request (#595)

Rui4da4d8667b11
diff --git a/.changeset/anthropic-cache-breakpoint-on-last-message.md b/.changeset/anthropic-cache-breakpoint-on-last-message.md
new file mode 100644
index 000000000..3c0be4b92
--- /dev/null
+++ b/.changeset/anthropic-cache-breakpoint-on-last-message.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Fixed Anthropic prompt caching placing the final cache breakpoint one message too early. Fresh tool results were billed as uncached input every turn and only entered the cache on the following request, capping the effective cache hit rate near 50%; the breakpoint now sits on the last message of each request, so agentic tool loops get near-full prefix hits.
diff --git a/e2e/README.md b/e2e/README.md
index 46cc8bcfd..251d61fd5 100644
--- a/e2e/README.md
+++ b/e2e/README.md
@@ -83,7 +83,12 @@ alias env (local matrix, plain `eve eval --strict`) the eval skips.
Most fixture agents run against `anthropic/claude-sonnet-5` and judges run
against `openai/gpt-5.5`. Both are real models, so the environment must provide
-the corresponding model-provider credentials. `agent-workflow-stress` uses eve's
+the corresponding model-provider credentials. `agent-prompt-cache` is the one
+fixture that authors a direct `@ai-sdk/anthropic` model instance instead of a
+gateway model id: its eval asserts the harness's Anthropic cache-breakpoint
+placement, which only runs on that path. The instance points at the AI
+Gateway's Anthropic-compatible Messages endpoint so it uses the same
+`AI_GATEWAY_API_KEY` credential as every other fixture. `agent-workflow-stress` uses eve's
`mockModel` fixture helper so its 100-turn runs stay fast and deterministic. Its
concurrent and sequential evals cover high-volume session execution and repeated
session resumption respectively.
diff --git a/e2e/fixtures/agent-prompt-cache/agent/agent.ts b/e2e/fixtures/agent-prompt-cache/agent/agent.ts
new file mode 100644
index 000000000..a0f106c19
--- /dev/null
+++ b/e2e/fixtures/agent-prompt-cache/agent/agent.ts
@@ -0,0 +1,46 @@
+import { createAnthropic } from "@ai-sdk/anthropic";
+import { type AgentDefinition, defineAgent } from "eve";
+import { vercelOidc } from "eve/agents/auth";
+
+/**
+ * Prompt-cache e2e fixture.
+ *
+ * The harness only places explicit cache breakpoints when the model is a
+ * provider instance with an Anthropic provider name (`anthropic-direct` in
+ * `detectPromptCachePath`). Gateway model id strings take `gateway-auto`,
+ * where the gateway caches on its own and the breakpoint code never runs,
+ * so a breakpoint regression could not fail an eval there. That is why this
+ * fixture authors a direct `@ai-sdk/anthropic` instance while every other
+ * fixture uses a gateway string.
+ *
+ * CI has no `ANTHROPIC_API_KEY`, so the instance points at the AI Gateway's
+ * Anthropic-compatible Messages endpoint, which honors `cache_control` and
+ * passes `cache_read_input_tokens` / `cache_creation_input_tokens` through
+ * unchanged. The same AI Gateway credential as every other fixture is sent
+ * as a bearer token: `AI_GATEWAY_API_KEY` takes precedence, with request-scoped
+ * Vercel OIDC as the fallback.
+ */
+const resolveVercelOidc = vercelOidc();
+
+const anthropic = createAnthropic({
+ baseURL: "https://ai-gateway.vercel.sh/v1",
+ // The fetch hook replaces this placeholder with a current Gateway credential.
+ authToken: "resolved-per-request",
+ fetch: async (input, init) => {
+ const headers = new Headers(init?.headers);
+ const apiKey = process.env.AI_GATEWAY_API_KEY?.trim();
+ const authorization = apiKey
+ ? `Bearer ${apiKey}`
+ : (await resolveVercelOidc()).headers.authorization;
+
+ headers.set("authorization", authorization);
+ return fetch(input, { ...init, headers });
+ },
+});
+
+const agent: AgentDefinition = defineAgent({
+ model: anthropic("anthropic/claude-haiku-4-5"),
+ modelContextWindowTokens: 200_000,
+});
+
+export default agent;
diff --git a/e2e/fixtures/agent-prompt-cache/agent/instructions.md b/e2e/fixtures/agent-prompt-cache/agent/instructions.md
new file mode 100644
index 000000000..eb9129510
--- /dev/null
+++ b/e2e/fixtures/agent-prompt-cache/agent/instructions.md
@@ -0,0 +1,174 @@
+# District archive assistant
+
+You answer questions about the district archive. Use the `fetch-archive-page`
+tool to retrieve archive pages. Fetch pages strictly one at a time: issue one
+tool call, wait for its result, and only then request the next page. Never
+request more than one page in a single step. Answer tersely.
+
+## Shelf catalog
+
+The catalog below maps shelves to volumes. It exists partly as reference data
+and partly to keep the system prompt above Anthropic's minimum cacheable
+prefix length (2,048 tokens for Haiku-class models), which the prompt-cache
+eval in this fixture depends on.
+
+- Shelf 001 stores volume "Beta Ledger 1" covering reservoir levels for district 2.
+- Shelf 002 stores volume "Gamma Ledger 2" covering canal maintenance logs for district 3.
+- Shelf 003 stores volume "Delta Ledger 3" covering well surveys for district 4.
+- Shelf 004 stores volume "Epsilon Ledger 4" covering flood bulletins for district 5.
+- Shelf 005 stores volume "Zeta Ledger 5" covering irrigation permits for district 6.
+- Shelf 006 stores volume "Eta Ledger 6" covering drainage inspections for district 7.
+- Shelf 007 stores volume "Theta Ledger 7" covering aquifer readings for district 8.
+- Shelf 008 stores volume "Iota Ledger 8" covering rainfall records for district 9.
+- Shelf 009 stores volume "Kappa Ledger 9" covering reservoir levels for district 10.
+- Shelf 010 stores volume "Lambda Ledger 10" covering canal maintenance logs for district 11.
+- Shelf 011 stores volume "Mu Ledger 11" covering well surveys for district 12.
+- Shelf 012 stores volume "Alpha Ledger 12" covering flood bulletins for district 13.
+- Shelf 013 stores volume "Beta Ledger 13" covering irrigation permits for district 14.
+- Shelf 014 stores volume "Gamma Ledger 14" covering drainage inspections for district 15.
+- Shelf 015 stores volume "Delta Ledger 15" covering aquifer readings for district 16.
+- Shelf 016 stores volume "Epsilon Ledger 16" covering rainfall records for district 17.
+- Shelf 017 stores volume "Zeta Ledger 17" covering reservoir levels for district 18.
+- Shelf 018 stores volume "Eta Ledger 18" covering canal maintenance logs for district 19.
+- Shelf 019 stores volume "Theta Ledger 19" covering well surveys for district 20.
+- Shelf 020 stores volume "Iota Ledger 20" covering flood bulletins for district 21.
+- Shelf 021 stores volume "Kappa Ledger 21" covering irrigation permits for district 22.
+- Shelf 022 stores volume "Lambda Ledger 22" covering drainage inspections for district 23.
+- Shelf 023 stores volume "Mu Ledger 23" covering aquifer readings for district 24.
+- Shelf 024 stores volume "Alpha Ledger 24" covering rainfall records for district 25.
+- Shelf 025 stores volume "Beta Ledger 25" covering reservoir levels for district 26.
+- Shelf 026 stores volume "Gamma Ledger 26" covering canal maintenance logs for district 27.
+- Shelf 027 stores volume "Delta Ledger 27" covering well surveys for district 28.
+- Shelf 028 stores volume "Epsilon Ledger 28" covering flood bulletins for district 29.
+- Shelf 029 stores volume "Zeta Ledger 29" covering irrigation permits for district 30.
+- Shelf 030 stores volume "Eta Ledger 30" covering drainage inspections for district 31.
+- Shelf 031 stores volume "Theta Ledger 31" covering aquifer readings for district 32.
+- Shelf 032 stores volume "Iota Ledger 32" covering rainfall records for district 33.
+- Shelf 033 stores volume "Kappa Ledger 33" covering reservoir levels for district 34.
+- Shelf 034 stores volume "Lambda Ledger 34" covering canal maintenance logs for district 35.
+- Shelf 035 stores volume "Mu Ledger 35" covering well surveys for district 36.
+- Shelf 036 stores volume "Alpha Ledger 36" covering flood bulletins for district 37.
+- Shelf 037 stores volume "Beta Ledger 37" covering irrigation permits for district 38.
+- Shelf 038 stores volume "Gamma Ledger 38" covering drainage inspections for district 39.
+- Shelf 039 stores volume "Delta Ledger 39" covering aquifer readings for district 40.
+- Shelf 040 stores volume "Epsilon Ledger 40" covering rainfall records for district 1.
+- Shelf 041 stores volume "Zeta Ledger 41" covering reservoir levels for district 2.
+- Shelf 042 stores volume "Eta Ledger 42" covering canal maintenance logs for district 3.
+- Shelf 043 stores volume "Theta Ledger 43" covering well surveys for district 4.
+- Shelf 044 stores volume "Iota Ledger 44" covering flood bulletins for district 5.
+- Shelf 045 stores volume "Kappa Ledger 45" covering irrigation permits for district 6.
+- Shelf 046 stores volume "Lambda Ledger 46" covering drainage inspections for district 7.
+- Shelf 047 stores volume "Mu Ledger 47" covering aquifer readings for district 8.
+- Shelf 048 stores volume "Alpha Ledger 48" covering rainfall records for district 9.
+- Shelf 049 stores volume "Beta Ledger 49" covering reservoir levels for district 10.
+- Shelf 050 stores volume "Gamma Ledger 50" covering canal maintenance logs for district 11.
+- Shelf 051 stores volume "Delta Ledger 51" covering well surveys for district 12.
+- Shelf 052 stores volume "Epsilon Ledger 52" covering flood bulletins for district 13.
+- Shelf 053 stores volume "Zeta Ledger 53" covering irrigation permits for district 14.
+- Shelf 054 stores volume "Eta Ledger 54" covering drainage inspections for district 15.
+- Shelf 055 stores volume "Theta Ledger 55" covering aquifer readings for district 16.
+- Shelf 056 stores volume "Iota Ledger 56" covering rainfall records for district 17.
+- Shelf 057 stores volume "Kappa Ledger 57" covering reservoir levels for district 18.
+- Shelf 058 stores volume "Lambda Ledger 58" covering canal maintenance logs for district 19.
+- Shelf 059 stores volume "Mu Ledger 59" covering well surveys for district 20.
+- Shelf 060 stores volume "Alpha Ledger 60" covering flood bulletins for district 21.
+- Shelf 061 stores volume "Beta Ledger 61" covering irrigation permits for district 22.
+- Shelf 062 stores volume "Gamma Ledger 62" covering drainage inspections for district 23.
+- Shelf 063 stores volume "Delta Ledger 63" covering aquifer readings for district 24.
+- Shelf 064 stores volume "Epsilon Ledger 64" covering rainfall records for district 25.
+- Shelf 065 stores volume "Zeta Ledger 65" covering reservoir levels for district 26.
+- Shelf 066 stores volume "Eta Ledger 66" covering canal maintenance logs for district 27.
+- Shelf 067 stores volume "Theta Ledger 67" covering well surveys for district 28.
+- Shelf 068 stores volume "Iota Ledger 68" covering flood bulletins for district 29.
+- Shelf 069 stores volume "Kappa Ledger 69" covering irrigation permits for district 30.
+- Shelf 070 stores volume "Lambda Ledger 70" covering drainage inspections for district 31.
+- Shelf 071 stores volume "Mu Ledger 71" covering aquifer readings for district 32.
+- Shelf 072 stores volume "Alpha Ledger 72" covering rainfall records for district 33.
+- Shelf 073 stores volume "Beta Ledger 73" covering reservoir levels for district 34.
+- Shelf 074 stores volume "Gamma Ledger 74" covering canal maintenance logs for district 35.
+- Shelf 075 stores volume "Delta Ledger 75" covering well surveys for district 36.
+- Shelf 076 stores volume "Epsilon Ledger 76" covering flood bulletins for district 37.
+- Shelf 077 stores volume "Zeta Ledger 77" covering irrigation permits for district 38.
+- Shelf 078 stores volume "Eta Ledger 78" covering drainage inspections for district 39.
+- Shelf 079 stores volume "Theta Ledger 79" covering aquifer readings for district 40.
+- Shelf 080 stores volume "Iota Ledger 80" covering rainfall records for district 1.
+- Shelf 081 stores volume "Kappa Ledger 81" covering reservoir levels for district 2.
+- Shelf 082 stores volume "Lambda Ledger 82" covering canal maintenance logs for district 3.
+- Shelf 083 stores volume "Mu Ledger 83" covering well surveys for district 4.
+- Shelf 084 stores volume "Alpha Ledger 84" covering flood bulletins for district 5.
+- Shelf 085 stores volume "Beta Ledger 85" covering irrigation permits for district 6.
+- Shelf 086 stores volume "Gamma Ledger 86" covering drainage inspections for district 7.
+- Shelf 087 stores volume "Delta Ledger 87" covering aquifer readings for district 8.
+- Shelf 088 stores volume "Epsilon Ledger 88" covering rainfall records for district 9.
+- Shelf 089 stores volume "Zeta Ledger 89" covering reservoir levels for district 10.
+- Shelf 090 stores volume "Eta Ledger 90" covering canal maintenance logs for district 11.
+- Shelf 091 stores volume "Theta Ledger 91" covering well surveys for district 12.
+- Shelf 092 stores volume "Iota Ledger 92" covering flood bulletins for district 13.
+- Shelf 093 stores volume "Kappa Ledger 93" covering irrigation permits for district 14.
+- Shelf 094 stores volume "Lambda Ledger 94" covering drainage inspections for district 15.
+- Shelf 095 stores volume "Mu Ledger 95" covering aquifer readings for district 16.
+- Shelf 096 stores volume "Alpha Ledger 96" covering rainfall records for district 17.
+- Shelf 097 stores volume "Beta Ledger 97" covering reservoir levels for district 18.
+- Shelf 098 stores volume "Gamma Ledger 98" covering canal maintenance logs for district 19.
+- Shelf 099 stores volume "Delta Ledger 99" covering well surveys for district 20.
+- Shelf 100 stores volume "Epsilon Ledger 100" covering flood bulletins for district 21.
+- Shelf 101 stores volume "Zeta Ledger 101" covering irrigation permits for district 22.
+- Shelf 102 stores volume "Eta Ledger 102" covering drainage inspections for district 23.
+- Shelf 103 stores volume "Theta Ledger 103" covering aquifer readings for district 24.
+- Shelf 104 stores volume "Iota Ledger 104" covering rainfall records for district 25.
+- Shelf 105 stores volume "Kappa Ledger 105" covering reservoir levels for district 26.
+- Shelf 106 stores volume "Lambda Ledger 106" covering canal maintenance logs for district 27.
+- Shelf 107 stores volume "Mu Ledger 107" covering well surveys for district 28.
+- Shelf 108 stores volume "Alpha Ledger 108" covering flood bulletins for district 29.
+- Shelf 109 stores volume "Beta Ledger 109" covering irrigation permits for district 30.
+- Shelf 110 stores volume "Gamma Ledger 110" covering drainage inspections for district 31.
+- Shelf 111 stores volume "Delta Ledger 111" covering aquifer readings for district 32.
+- Shelf 112 stores volume "Epsilon Ledger 112" covering rainfall records for district 33.
+- Shelf 113 stores volume "Zeta Ledger 113" covering reservoir levels for district 34.
+- Shelf 114 stores volume "Eta Ledger 114" covering canal maintenance logs for district 35.
+- Shelf 115 stores volume "Theta Ledger 115" covering well surveys for district 36.
+- Shelf 116 stores volume "Iota Ledger 116" covering flood bulletins for district 37.
+- Shelf 117 stores volume "Kappa Ledger 117" covering irrigation permits for district 38.
+- Shelf 118 stores volume "Lambda Ledger 118" covering drainage inspections for district 39.
+- Shelf 119 stores volume "Mu Ledger 119" covering aquifer readings for district 40.
+- Shelf 120 stores volume "Alpha Ledger 120" covering rainfall records for district 1.
+- Shelf 121 stores volume "Beta Ledger 121" covering reservoir levels for district 2.
+- Shelf 122 stores volume "Gamma Ledger 122" covering canal maintenance logs for district 3.
+- Shelf 123 stores volume "Delta Ledger 123" covering well surveys for district 4.
+- Shelf 124 stores volume "Epsilon Ledger 124" covering flood bulletins for district 5.
+- Shelf 125 stores volume "Zeta Ledger 125" covering irrigation permits for district 6.
+- Shelf 126 stores volume "Eta Ledger 126" covering drainage inspections for district 7.
+- Shelf 127 stores volume "Theta Ledger 127" covering aquifer readings for district 8.
+- Shelf 128 stores volume "Iota Ledger 128" covering rainfall records for district 9.
+- Shelf 129 stores volume "Kappa Ledger 129" covering reservoir levels for district 10.
+- Shelf 130 stores volume "Lambda Ledger 130" covering canal maintenance logs for district 11.
+- Shelf 131 stores volume "Mu Ledger 131" covering well surveys for district 12.
+- Shelf 132 stores volume "Alpha Ledger 132" covering flood bulletins for district 13.
+- Shelf 133 stores volume "Beta Ledger 133" covering irrigation permits for district 14.
+- Shelf 134 stores volume "Gamma Ledger 134" covering drainage inspections for district 15.
+- Shelf 135 stores volume "Delta Ledger 135" covering aquifer readings for district 16.
+- Shelf 136 stores volume "Epsilon Ledger 136" covering rainfall records for district 17.
+- Shelf 137 stores volume "Zeta Ledger 137" covering reservoir levels for district 18.
+- Shelf 138 stores volume "Eta Ledger 138" covering canal maintenance logs for district 19.
+- Shelf 139 stores volume "Theta Ledger 139" covering well surveys for district 20.
+- Shelf 140 stores volume "Iota Ledger 140" covering flood bulletins for district 21.
+- Shelf 141 stores volume "Kappa Ledger 141" covering irrigation permits for district 22.
+- Shelf 142 stores volume "Lambda Ledger 142" covering drainage inspections for district 23.
+- Shelf 143 stores volume "Mu Ledger 143" covering aquifer readings for district 24.
+- Shelf 144 stores volume "Alpha Ledger 144" covering rainfall records for district 25.
+- Shelf 145 stores volume "Beta Ledger 145" covering reservoir levels for district 26.
+- Shelf 146 stores volume "Gamma Ledger 146" covering canal maintenance logs for district 27.
+- Shelf 147 stores volume "Delta Ledger 147" covering well surveys for district 28.
+- Shelf 148 stores volume "Epsilon Ledger 148" covering flood bulletins for district 29.
+- Shelf 149 stores volume "Zeta Ledger 149" covering irrigation permits for district 30.
+- Shelf 150 stores volume "Eta Ledger 150" covering drainage inspections for district 31.
+- Shelf 151 stores volume "Theta Ledger 151" covering aquifer readings for district 32.
+- Shelf 152 stores volume "Iota Ledger 152" covering rainfall records for district 33.
+- Shelf 153 stores volume "Kappa Ledger 153" covering reservoir levels for district 34.
+- Shelf 154 stores volume "Lambda Ledger 154" covering canal maintenance logs for district 35.
+- Shelf 155 stores volume "Mu Ledger 155" covering well surveys for district 36.
+- Shelf 156 stores volume "Alpha Ledger 156" covering flood bulletins for district 37.
+- Shelf 157 stores volume "Beta Ledger 157" covering irrigation permits for district 38.
+- Shelf 158 stores volume "Gamma Ledger 158" covering drainage inspections for district 39.
+- Shelf 159 stores volume "Delta Ledger 159" covering aquifer readings for district 40.
+- Shelf 160 stores volume "Epsilon Ledger 160" covering rainfall records for district 1.
diff --git a/e2e/fixtures/agent-prompt-cache/agent/tools/fetch-archive-page.ts b/e2e/fixtures/agent-prompt-cache/agent/tools/fetch-archive-page.ts
new file mode 100644
index 000000000..9ac710f2f
--- /dev/null
+++ b/e2e/fixtures/agent-prompt-cache/agent/tools/fetch-archive-page.ts
@@ -0,0 +1,26 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+/**
+ * Returns one deterministic ~2,500-token page of archive rows. The payload
+ * is intentionally large: the prompt-cache eval measures whether these tool
+ * results are cached in the same request that first carries them, and small
+ * results would drown the signal in per-request framing tokens.
+ */
+export default defineTool({
+ description:
+ "Returns one page of the district archive. Call once per page number and wait for the result before requesting the next page.",
+ inputSchema: z.object({
+ page: z.number().int().min(1).max(9).describe("Archive page number to fetch."),
+ }),
+ async execute({ page }) {
+ const rows: string[] = [];
+ for (let row = 1; row <= 220; row++) {
+ rows.push(
+ `page ${page} row ${String(row).padStart(3, "0")}: district ${((page * 7 + row) % 40) + 1} ` +
+ `rainfall ${(page * 31 + row * 13) % 200} mm, reservoir ${(page * 17 + row * 11) % 100}% full`,
+ );
+ }
+ return { page, rowCount: rows.length, content: rows.join("\n") };
+ },
+});
diff --git a/e2e/fixtures/agent-prompt-cache/evals/evals.config.ts b/e2e/fixtures/agent-prompt-cache/evals/evals.config.ts
new file mode 100644
index 000000000..e9b6c4d05
--- /dev/null
+++ b/e2e/fixtures/agent-prompt-cache/evals/evals.config.ts
@@ -0,0 +1,6 @@
+import { defineEvalConfig } from "eve/evals";
+
+/** Judge is unused here; assertions are numeric. Kept for config parity. */
+export default defineEvalConfig({
+ judge: { model: "openai/gpt-5.5" },
+});
diff --git a/e2e/fixtures/agent-prompt-cache/evals/prompt-cache/input-cache-rate.eval.ts b/e2e/fixtures/agent-prompt-cache/evals/prompt-cache/input-cache-rate.eval.ts
new file mode 100644
index 000000000..8d58e6205
--- /dev/null
+++ b/e2e/fixtures/agent-prompt-cache/evals/prompt-cache/input-cache-rate.eval.ts
@@ -0,0 +1,75 @@
+import { defineEval } from "eve/evals";
+import { satisfies } from "eve/evals/expect";
+
+/**
+ * Proves the harness's Anthropic cache breakpoints keep a regular
+ * (non-compacted) tool session almost fully served from the prompt cache.
+ *
+ * The metric is the input-cache rate: of the prompt tokens the model had
+ * already seen on a previous step (everything except first-time cache
+ * writes), how many were read from cache?
+ *
+ * rate = Σ cache_read / (Σ cache_read + Σ uncached_input)
+ * uncached_input = input_total − cache_read − cache_write
+ *
+ * With breakpoints on the last message of every request, each step's new
+ * content is written to the cache in the request that first carries it, so
+ * uncached input stays at a few framing tokens per step and the rate lands
+ * above 99%. When the final breakpoint lags one message (the regression this
+ * eval guards against), every tool result is billed uncached once before it
+ * enters the cache, and the rate collapses to roughly 45–60% — see
+ * `packages/eve/src/harness/prompt-cache-accounting.test.ts` for the
+ * trace-level accounting.
+ */
+export default defineEval({
+ description:
+ "Anthropic-direct prompt caching: input-cache rate stays above 99% across a multi-step tool session.",
+ async test(t) {
+ const first = await t.send(
+ "Fetch archive pages 1, 2, and 3 using the fetch-archive-page tool, strictly one page per " +
+ 'tool call, waiting for each result before the next call. Then reply with exactly "PAGES LOADED".',
+ );
+ first.expectOk();
+ first.calledTool("fetch-archive-page");
+
+ const second = await t.send(
+ 'Now fetch archive page 4 the same way, then reply with exactly "DONE".',
+ );
+ second.expectOk();
+ second.calledTool("fetch-archive-page");
+
+ let cacheRead = 0;
+ let uncachedInput = 0;
+ let stepCount = 0;
+ for (const event of t.events) {
+ if (event.type !== "step.completed") continue;
+ const usage = event.data.usage;
+ if (usage === undefined) continue;
+ stepCount += 1;
+ const read = usage.cacheReadTokens ?? 0;
+ const uncached = (usage.inputTokens ?? 0) - read - (usage.cacheWriteTokens ?? 0);
+ cacheRead += read;
+ uncachedInput += Math.max(0, uncached);
+ t.log(
+ `step ${stepCount}: input=${usage.inputTokens ?? 0} read=${read} ` +
+ `write=${usage.cacheWriteTokens ?? 0} uncached=${uncached}`,
+ );
+ }
+
+ const rate = cacheRead / (cacheRead + uncachedInput);
+ t.log(
+ `input-cache rate: ${(rate * 100).toFixed(2)}% ` +
+ `(read=${cacheRead} uncached=${uncachedInput} over ${stepCount} steps)`,
+ );
+
+ // A multi-step session is required for the metric to mean anything.
+ t.check(
+ stepCount,
+ satisfies((steps: number) => steps >= 4, "session ran at least 4 model steps"),
+ );
+ t.check(
+ rate,
+ satisfies((value: number) => value > 0.99, "input-cache rate above 99%"),
+ );
+ },
+});
diff --git a/e2e/fixtures/agent-prompt-cache/package.json b/e2e/fixtures/agent-prompt-cache/package.json
new file mode 100644
index 000000000..bd33a72fa
--- /dev/null
+++ b/e2e/fixtures/agent-prompt-cache/package.json
@@ -0,0 +1,22 @@
+{
+ "name": "agent-prompt-cache",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "build": "eve build",
+ "dev": "eve dev",
+ "start": "eve start",
+ "typecheck": "eve build && tsc",
+ "test:e2e": "eve eval --strict"
+ },
+ "dependencies": {
+ "@ai-sdk/anthropic": "catalog:",
+ "eve": "workspace:*",
+ "zod": "catalog:"
+ },
+ "devDependencies": {
+ "@types/node": "catalog:",
+ "typescript": "catalog:"
+ }
+}
diff --git a/e2e/fixtures/agent-prompt-cache/tsconfig.json b/e2e/fixtures/agent-prompt-cache/tsconfig.json
new file mode 100644
index 000000000..66f5b1ea5
--- /dev/null
+++ b/e2e/fixtures/agent-prompt-cache/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "outDir": "dist",
+ "rootDir": ".",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "declaration": true,
+ "noEmit": true,
+ "types": ["node"]
+ },
+ "include": ["agent/**/*.ts", "evals/**/*.ts", ".eve/**/*.d.ts"]
+}
diff --git a/packages/eve/src/harness/prompt-cache-accounting.test.ts b/packages/eve/src/harness/prompt-cache-accounting.test.ts
new file mode 100644
index 000000000..9be92b7dd
--- /dev/null
+++ b/packages/eve/src/harness/prompt-cache-accounting.test.ts
@@ -0,0 +1,467 @@
+import type { ModelMessage } from "ai";
+import { describe, expect, it } from "vitest";
+
+import {
+ type AnthropicCacheMarker,
+ applyConversationCacheControl,
+ getAnthropicCacheMarker,
+} from "#harness/prompt-cache.js";
+
+/**
+ * Deterministic replay of two production benchmark traces that reported
+ * ~45–48% prompt cache hit rates.
+ *
+ * A small simulator implements Anthropic's prefix-cache accounting rules:
+ *
+ * - `cache_read` = the previously cached prefix (when it still prefixes
+ * the request and ends at or before the last breakpoint),
+ * - `cache_write` = tokens between the read prefix and the last breakpoint,
+ * - `input` = tokens after the last breakpoint (billed uncached,
+ * never written).
+ *
+ * Driving the simulator with the legacy breakpoint placement (last
+ * assistant + last user, tool messages skipped) reproduces the traces'
+ * recorded `turn_usage` token-for-token on every turn after the first —
+ * proving the observed percentages were caused by breakpoint placement,
+ * not by cache invalidation. The fixed placement (last message + prior
+ * assistant anchor) run on the identical workload eliminates all uncached
+ * input: every token is written to the cache in the request that first
+ * carries it, which is the accounting optimum.
+ *
+ * Convention: 1 character = 1 token, so message sizes are exact.
+ */
+
+// ---------------------------------------------------------------------------
+// Token-sized message builders
+// ---------------------------------------------------------------------------
+
+function userMessage(tokens: number): ModelMessage {
+ return { role: "user", content: "x".repeat(tokens) };
+}
+
+function assistantMessage(tokens: number): ModelMessage {
+ return { role: "assistant", content: "x".repeat(tokens) };
+}
+
+function toolResultMessage(tokens: number): ModelMessage {
+ return {
+ role: "tool",
+ content: [
+ {
+ type: "tool-result",
+ toolCallId: "call",
+ toolName: "fetch",
+ output: { type: "text", value: "x".repeat(tokens) },
+ },
+ ],
+ };
+}
+
+function tokensOf(message: ModelMessage): number {
+ if (typeof message.content === "string") {
+ return message.content.length;
+ }
+ let total = 0;
+ for (const part of message.content) {
+ if (part.type === "text") {
+ total += part.text.length;
+ } else if (part.type === "tool-result" && part.output.type === "text") {
+ total += part.output.value.length;
+ }
+ }
+ return total;
+}
+
+function isMarked(message: ModelMessage): boolean {
+ const options = message.providerOptions as { anthropic?: { cacheControl?: unknown } } | undefined;
+ return options?.anthropic?.cacheControl !== undefined;
+}
+
+// ---------------------------------------------------------------------------
+// Anthropic prefix-cache accounting simulator
+// ---------------------------------------------------------------------------
+
+interface TurnUsage {
+ readonly input: number;
+ readonly cacheRead: number;
+ readonly cacheWrite: number;
+}
+
+class PrefixCacheAccounting {
+ private cachedPrefixTokens: number;
+
+ constructor(warmPrefixTokens: number) {
+ this.cachedPrefixTokens = warmPrefixTokens;
+ }
+
+ /**
+ * Accounts one request. `baseTokens` models the system prompt and tool
+ * definitions, which the harness always covers with their own
+ * breakpoints (`applySystemCacheBreakpoint`, `applyLastToolCacheBreakpoint`).
+ */
+ request(baseTokens: number, messages: readonly ModelMessage[]): TurnUsage {
+ let total = baseTokens;
+ let lastBreakpoint = baseTokens;
+ for (const message of messages) {
+ total += tokensOf(message);
+ if (isMarked(message)) {
+ lastBreakpoint = total;
+ }
+ }
+ const cacheRead = Math.min(this.cachedPrefixTokens, lastBreakpoint);
+ const cacheWrite = lastBreakpoint - cacheRead;
+ const input = total - lastBreakpoint;
+ this.cachedPrefixTokens = Math.max(this.cachedPrefixTokens, lastBreakpoint);
+ return { input, cacheRead, cacheWrite };
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Legacy breakpoint placement (pre-fix), preserved to prove the regression
+// ---------------------------------------------------------------------------
+
+function legacyApplyConversationCacheControl(
+ messages: readonly ModelMessage[],
+ marker: AnthropicCacheMarker,
+): ModelMessage[] {
+ const out = [...messages];
+ let foundAssistant = false;
+ let foundUser = false;
+
+ for (let i = out.length - 1; i >= 0 && (!foundAssistant || !foundUser); i--) {
+ const message = out[i];
+ if (message === undefined) continue;
+
+ if (!foundAssistant && message.role === "assistant") {
+ out[i] = { ...message, providerOptions: { ...message.providerOptions, ...marker } };
+ foundAssistant = true;
+ } else if (!foundUser && message.role === "user") {
+ out[i] = { ...message, providerOptions: { ...message.providerOptions, ...marker } };
+ foundUser = true;
+ }
+ }
+
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Benchmark trace workloads
+// ---------------------------------------------------------------------------
+
+interface TraceScenario {
+ readonly name: string;
+ /** System prompt + tool definitions, always behind their own breakpoints. */
+ readonly systemAndTools: number;
+ /** The initial user task message. */
+ readonly userTask: number;
+ /** Cache warmth carried over from a sibling run sharing the system prefix. */
+ readonly warmPrefix: number;
+ /**
+ * Serialized size of each assistant message when it re-enters the prompt.
+ * Derived from the trace identity `cache_write(t+1) - input(t)`.
+ */
+ readonly assistantTurns: readonly number[];
+ /** Tool results appended after each turn. Derived from `input(t+1)`. */
+ readonly toolResults: readonly number[];
+ /** `turn_usage` as recorded in the benchmark trace JSON. */
+ readonly observed: readonly TurnUsage[];
+ /** Exact served-from-cache rate under the legacy breakpoint placement. */
+ readonly legacyServedFromCache: number;
+ /** Exact served-from-cache rate under the fixed breakpoint placement. */
+ readonly fixedServedFromCache: number;
+}
+
+const SCENARIOS: readonly TraceScenario[] = [
+ {
+ // Run 3c803a51-bb6a-4a05-88a5-42ca75f49fa5, claude-fable-5, 5 turns.
+ name: "3c803a51 (claude-fable-5)",
+ systemAndTools: 4565,
+ userTask: 782,
+ warmPrefix: 4565,
+ assistantTurns: [168, 180, 127, 151],
+ toolResults: [4466, 568, 7702, 19286],
+ observed: [
+ { input: 2, cacheRead: 4565, cacheWrite: 782 },
+ { input: 4466, cacheRead: 5347, cacheWrite: 168 },
+ { input: 568, cacheRead: 5515, cacheWrite: 4646 },
+ { input: 7702, cacheRead: 10161, cacheWrite: 695 },
+ { input: 19286, cacheRead: 10856, cacheWrite: 7853 },
+ ],
+ // 36444 read / (36444 read + 32022 input + 14144 write) = 44.12%
+ legacyServedFromCache: 0.441157,
+ // 49180 read / (49180 read + 0 input + 33430 write) = 59.53%
+ fixedServedFromCache: 0.595327,
+ },
+ {
+ // Run e7757164-b009-4bea-9a7f-f97d2e18ea9f, claude-haiku-4-5, 7 turns.
+ name: "e7757164 (claude-haiku-4-5)",
+ systemAndTools: 4179,
+ userTask: 0,
+ warmPrefix: 0,
+ assistantTurns: [222, 205, 217, 165, 160, 167],
+ toolResults: [8149, 3547, 8144, 16433, 9911, 23482],
+ observed: [
+ { input: 3, cacheRead: 0, cacheWrite: 4179 },
+ { input: 8149, cacheRead: 4179, cacheWrite: 222 },
+ { input: 3547, cacheRead: 4401, cacheWrite: 8354 },
+ { input: 8144, cacheRead: 12755, cacheWrite: 3764 },
+ { input: 16433, cacheRead: 16519, cacheWrite: 8309 },
+ { input: 9911, cacheRead: 24828, cacheWrite: 16593 },
+ { input: 23482, cacheRead: 41421, cacheWrite: 10078 },
+ ],
+ // 104103 read / (104103 read + 69666 input + 51499 write) = 46.21%
+ legacyServedFromCache: 0.46213,
+ // 150287 read / (150287 read + 0 input + 74981 write) = 66.71%
+ fixedServedFromCache: 0.667148,
+ },
+];
+
+type BreakpointStrategy = (
+ messages: readonly ModelMessage[],
+ marker: AnthropicCacheMarker,
+) => ModelMessage[];
+
+function replayToolLoop(scenario: TraceScenario, strategy: BreakpointStrategy): TurnUsage[] {
+ const marker = getAnthropicCacheMarker();
+ const accounting = new PrefixCacheAccounting(scenario.warmPrefix);
+ const history: ModelMessage[] = [userMessage(scenario.userTask)];
+ const usage: TurnUsage[] = [];
+
+ for (let turn = 0; turn < scenario.observed.length; turn++) {
+ usage.push(accounting.request(scenario.systemAndTools, strategy(history, marker)));
+ if (turn < scenario.observed.length - 1) {
+ history.push(
+ assistantMessage(scenario.assistantTurns[turn]!),
+ toolResultMessage(scenario.toolResults[turn]!),
+ );
+ }
+ }
+
+ return usage;
+}
+
+/** Fraction of all prompt tokens served from cache: read / (read + input + write). */
+function servedFromCache(usage: readonly TurnUsage[]): number {
+ let read = 0;
+ let uncached = 0;
+ for (const turn of usage) {
+ read += turn.cacheRead;
+ uncached += turn.input + turn.cacheWrite;
+ }
+ return read / (read + uncached);
+}
+
+/** Fraction of previously seen prompt tokens served from cache: read / (read + input). */
+function inputCacheRate(usage: readonly TurnUsage[]): number {
+ let read = 0;
+ let input = 0;
+ for (const turn of usage) {
+ read += turn.cacheRead;
+ input += turn.input;
+ }
+ return read / (read + input);
+}
+
+// ---------------------------------------------------------------------------
+// Grep-heavy coding session
+// ---------------------------------------------------------------------------
+
+/**
+ * Deterministic grep-shaped output: `path:line: code` match lines, the way a
+ * search tool floods a coding agent's context. These are the largest tool
+ * results in practice, which makes them the costliest content to leave
+ * outside the final cache breakpoint.
+ */
+function grepOutput(query: string, matches: number): string {
+ const lines: string[] = [];
+ for (let i = 0; i < matches; i++) {
+ lines.push(
+ `src/module-${i % 23}/file-${i % 7}.ts:${100 + i}: ` +
+ `const ${query}Result${i} = resolve${i % 5}(${query}, ctx.session);`,
+ );
+ }
+ return lines.join("\n");
+}
+
+/** One tool message carrying one or more tool results (parallel calls). */
+function grepResultsMessage(outputs: readonly string[]): ModelMessage {
+ return {
+ role: "tool",
+ content: outputs.map((text, index) => ({
+ type: "tool-result",
+ toolCallId: `call-${index}`,
+ toolName: "grep",
+ output: { type: "text", value: text },
+ })),
+ };
+}
+
+interface GrepStep {
+ /** Assistant commentary + tool-call framing preceding the results. */
+ readonly commentary: number;
+ /** Grep outputs returned by this step's tool call(s). */
+ readonly results: readonly string[];
+}
+
+const GREP_SESSION: readonly GrepStep[] = [
+ { commentary: 140, results: [grepOutput("applyConversationCacheControl", 80)] },
+ // A broad query floods the context, the classic coding-agent step.
+ { commentary: 130, results: [grepOutput("cacheControl", 340)] },
+ // Parallel fan-out: three greps land in one tool message.
+ {
+ commentary: 160,
+ results: [
+ grepOutput("providerOptions", 200),
+ grepOutput("ephemeral", 190),
+ grepOutput("breakpoint", 210),
+ ],
+ },
+ { commentary: 120, results: [grepOutput("prepareStep", 130)] },
+ { commentary: 150, results: [grepOutput("toolResult", 760)] },
+];
+
+const GREP_BASE_TOKENS = 3200;
+const GREP_TASK_TOKENS = 900;
+
+function replayGrepSession(strategy: BreakpointStrategy): TurnUsage[] {
+ const marker = getAnthropicCacheMarker();
+ const accounting = new PrefixCacheAccounting(0);
+ const history: ModelMessage[] = [userMessage(GREP_TASK_TOKENS)];
+ const usage: TurnUsage[] = [];
+
+ for (const step of GREP_SESSION) {
+ usage.push(accounting.request(GREP_BASE_TOKENS, strategy(history, marker)));
+ history.push(assistantMessage(step.commentary), grepResultsMessage(step.results));
+ }
+
+ // Final step: the model reads the last grep results and answers.
+ usage.push(accounting.request(GREP_BASE_TOKENS, strategy(history, marker)));
+ return usage;
+}
+
+function totalGrepTokens(): number {
+ let total = 0;
+ for (const step of GREP_SESSION) {
+ for (const text of step.results) {
+ total += text.length;
+ }
+ }
+ return total;
+}
+
+// ---------------------------------------------------------------------------
+// The proof
+// ---------------------------------------------------------------------------
+
+describe("prompt cache accounting replayed from benchmark traces", () => {
+ for (const scenario of SCENARIOS) {
+ describe(scenario.name, () => {
+ it("legacy placement reproduces the recorded turn_usage token-for-token", () => {
+ const usage = replayToolLoop(scenario, legacyApplyConversationCacheControl);
+
+ // Turn 1 differs only by the trace's 2–3 structural overhead tokens
+ // (request framing not attributable to any message).
+ expect(usage[0]!.cacheRead).toBe(scenario.observed[0]!.cacheRead);
+ expect(usage[0]!.cacheWrite).toBe(scenario.observed[0]!.cacheWrite);
+
+ // Every subsequent turn matches the trace exactly on all three
+ // columns: the reported hit rate is fully explained by placement.
+ expect(usage.slice(1)).toEqual(scenario.observed.slice(1));
+ });
+
+ it("legacy placement yields the exact reported served-from-cache percentage", () => {
+ const usage = replayToolLoop(scenario, legacyApplyConversationCacheControl);
+ const simulated = servedFromCache(usage);
+ const observed = servedFromCache(scenario.observed);
+
+ // The simulated rate matches both the rate computed from the raw
+ // trace and the hardcoded expected value — 44.12% (fable) and
+ // 46.21% (haiku), the numbers behind the "45–48%" reports.
+ expect(Math.abs(simulated - observed)).toBeLessThan(0.001);
+ expect(simulated).toBeCloseTo(scenario.legacyServedFromCache, 5);
+ });
+
+ it("fixed placement yields the exact predicted served-from-cache percentage", () => {
+ const usage = replayToolLoop(scenario, applyConversationCacheControl);
+
+ // 59.53% (fable) and 66.71% (haiku) — the workload ceiling, since
+ // every remaining non-read token is a mandatory first-time write.
+ expect(servedFromCache(usage)).toBeCloseTo(scenario.fixedServedFromCache, 5);
+ });
+
+ it("fixed placement eliminates uncached input entirely on the same workload", () => {
+ const usage = replayToolLoop(scenario, applyConversationCacheControl);
+
+ for (const turn of usage) {
+ expect(turn.input).toBe(0);
+ }
+ });
+
+ it("fixed placement writes every token exactly once (accounting optimum)", () => {
+ const usage = replayToolLoop(scenario, applyConversationCacheControl);
+
+ const finalRequestTokens =
+ scenario.systemAndTools +
+ scenario.userTask +
+ scenario.assistantTurns.reduce((a, b) => a + b, 0) +
+ scenario.toolResults.reduce((a, b) => a + b, 0);
+ const totalWrites =
+ scenario.warmPrefix + usage.reduce((sum, turn) => sum + turn.cacheWrite, 0);
+
+ expect(totalWrites).toBe(finalRequestTokens);
+ });
+
+ it("fixed placement beats legacy served-from-cache on the same workload", () => {
+ const legacy = servedFromCache(
+ replayToolLoop(scenario, legacyApplyConversationCacheControl),
+ );
+ const fixed = servedFromCache(replayToolLoop(scenario, applyConversationCacheControl));
+
+ expect(fixed).toBeGreaterThan(legacy);
+ });
+ });
+ }
+});
+
+describe("grep-heavy coding session", () => {
+ it("legacy placement bills every grep result at the uncached rate exactly once", () => {
+ const usage = replayGrepSession(legacyApplyConversationCacheControl);
+
+ const uncached = usage.reduce((sum, turn) => sum + turn.input, 0);
+ expect(uncached).toBe(totalGrepTokens());
+ });
+
+ it("legacy placement caps the input-cache rate near 50%", () => {
+ const rate = inputCacheRate(replayGrepSession(legacyApplyConversationCacheControl));
+
+ expect(rate).toBeGreaterThan(0.4);
+ expect(rate).toBeLessThan(0.6);
+ });
+
+ it("fixed placement never bills a grep result uncached", () => {
+ const usage = replayGrepSession(applyConversationCacheControl);
+
+ for (const turn of usage) {
+ expect(turn.input).toBe(0);
+ }
+ // Mirrors the agent-prompt-cache e2e gate.
+ expect(inputCacheRate(usage)).toBeGreaterThan(0.99);
+ });
+
+ it("fixed placement covers parallel tool results with one trailing breakpoint", () => {
+ // Reads always chain: read(t) equals everything cached through t-1, so
+ // the multi-result fan-out step is fully re-read, never re-billed.
+ const usage = replayGrepSession(applyConversationCacheControl);
+ for (let i = 1; i < usage.length; i++) {
+ expect(usage[i]!.cacheRead).toBe(usage[i - 1]!.cacheRead + usage[i - 1]!.cacheWrite);
+ }
+
+ const finalRequestTokens =
+ GREP_BASE_TOKENS +
+ GREP_TASK_TOKENS +
+ GREP_SESSION.reduce((sum, step) => sum + step.commentary, 0) +
+ totalGrepTokens();
+ const totalWrites = usage.reduce((sum, turn) => sum + turn.cacheWrite, 0);
+ expect(totalWrites).toBe(finalRequestTokens);
+ });
+});
diff --git a/packages/eve/src/harness/prompt-cache.test.ts b/packages/eve/src/harness/prompt-cache.test.ts
index 5654c8dc2..a4005bf25 100644
--- a/packages/eve/src/harness/prompt-cache.test.ts
+++ b/packages/eve/src/harness/prompt-cache.test.ts
@@ -201,7 +201,7 @@ describe("applyConversationCacheControl", () => {
});
});
- it("marks both the last user and last assistant in a multi-turn history", () => {
+ it("marks the last message and the most recent assistant before it", () => {
const messages: ModelMessage[] = [
{ role: "user", content: "hi" },
{ role: "assistant", content: "yo" },
@@ -211,12 +211,12 @@ describe("applyConversationCacheControl", () => {
const out = applyConversationCacheControl(messages, marker);
expect(out[0]).toEqual({ role: "user", content: "hi" });
- expect(out[1]).toEqual({ role: "assistant", content: "yo" });
- expect(out[2]).toEqual({
- role: "user",
- content: "hi2",
+ expect(out[1]).toEqual({
+ role: "assistant",
+ content: "yo",
providerOptions: { anthropic: { cacheControl: { type: "ephemeral" } } },
});
+ expect(out[2]).toEqual({ role: "user", content: "hi2" });
expect(out[3]).toEqual({
role: "assistant",
content: "yo2",
@@ -224,7 +224,7 @@ describe("applyConversationCacheControl", () => {
});
});
- it("skips tool-result messages and still marks the last user and assistant", () => {
+ it("marks a trailing tool-result message so fresh tool results enter the cache", () => {
const messages: ModelMessage[] = [
{ role: "user", content: "do the thing" },
{
@@ -245,18 +245,18 @@ describe("applyConversationCacheControl", () => {
];
const out = applyConversationCacheControl(messages, marker);
- // Tool-result is not marked.
- expect(out[2]).toEqual(messages[2]);
-
- // The last assistant (index 1) is marked.
- expect((out[1] as { providerOptions?: unknown }).providerOptions).toEqual({
+ // The trailing tool-result message carries the final breakpoint.
+ expect((out[2] as { providerOptions?: unknown }).providerOptions).toEqual({
anthropic: { cacheControl: { type: "ephemeral" } },
});
- // The last user (index 0) is marked.
- expect((out[0] as { providerOptions?: unknown }).providerOptions).toEqual({
+ // The most recent assistant (index 1) is the advancement anchor.
+ expect((out[1] as { providerOptions?: unknown }).providerOptions).toEqual({
anthropic: { cacheControl: { type: "ephemeral" } },
});
+
+ // The user message is untouched.
+ expect(out[0]).toEqual(messages[0]);
});
it("preserves existing providerOptions on marked messages", () => {
@@ -289,7 +289,8 @@ describe("applyConversationCacheControl", () => {
expect(messages[0]).toBe(originalRef0);
expect(messages[1]).toBe(originalRef1);
expect(out).not.toBe(messages);
- expect(out[0]).not.toBe(originalRef0);
+ // Unmarked messages keep their identity; marked messages are copies.
+ expect(out[0]).toBe(originalRef0);
expect(out[1]).not.toBe(originalRef1);
});
});
diff --git a/packages/eve/src/harness/prompt-cache.ts b/packages/eve/src/harness/prompt-cache.ts
index 2810a2ef6..8f9ca4472 100644
--- a/packages/eve/src/harness/prompt-cache.ts
+++ b/packages/eve/src/harness/prompt-cache.ts
@@ -157,17 +157,26 @@ export function applySystemCacheBreakpoint(
}
/**
- * Walks backward through `messages` and attaches the Anthropic cache marker
- * to the most recent `assistant` and most recent `user` message. Returns a
- * new array; does not mutate the input.
+ * Attaches the Anthropic cache marker to the last message in `messages`
+ * (whatever its role) and, as a stable mid-history anchor, to the most
+ * recent `assistant` message before it. Returns a new array; does not
+ * mutate the input.
*
- * This implements the "automatic cache advancement" pattern: each turn the
- * breakpoints move forward, and the prior turn's breakpoints still warm the
- * cache prefix, so the new breakpoints just extend the cached region.
+ * The final breakpoint must sit on the very last message so that the
+ * newest content — typically a `tool` message carrying fresh tool
+ * results — is written to the cache in the same request that pays for
+ * it. Placing it any earlier (e.g. on the last assistant message) leaves
+ * the trailing tool results outside the cached region: they get billed
+ * as uncached input every turn and only enter the cache one request
+ * later, capping the effective hit rate near 50%. The AI SDK Anthropic
+ * provider maps a message-level marker on a `tool` message to its last
+ * tool-result content block.
*
- * Tool-result messages (`role: "tool"`) are intentionally skipped — the
- * adjacent assistant message's cache marker already covers the prefix
- * through any preceding tool results.
+ * The assistant anchor implements "automatic cache advancement": it
+ * guarantees a breakpoint from the prior request survives into the next
+ * one, so cache lookups always find the previous prefix even when a step
+ * appends more content blocks than Anthropic's backward boundary scan
+ * covers.
*/
export function applyConversationCacheControl(
messages: readonly ModelMessage[],
@@ -178,33 +187,27 @@ export function applyConversationCacheControl(
}
const out = [...messages];
- let foundAssistant = false;
- let foundUser = false;
- for (let i = out.length - 1; i >= 0 && (!foundAssistant || !foundUser); i--) {
- const message = out[i];
+ const mark = (index: number): void => {
+ const message = out[index];
if (message === undefined) {
- continue;
+ return;
}
+ out[index] = {
+ ...message,
+ providerOptions: {
+ ...message.providerOptions,
+ ...marker,
+ },
+ };
+ };
- if (!foundAssistant && message.role === "assistant") {
- out[i] = {
- ...message,
- providerOptions: {
- ...message.providerOptions,
- ...marker,
- },
- };
- foundAssistant = true;
- } else if (!foundUser && message.role === "user") {
- out[i] = {
- ...message,
- providerOptions: {
- ...message.providerOptions,
- ...marker,
- },
- };
- foundUser = true;
+ mark(out.length - 1);
+
+ for (let i = out.length - 2; i >= 0; i--) {
+ if (out[i]?.role === "assistant") {
+ mark(i);
+ break;
}
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2fbec2be0..a9c676925 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -625,6 +625,25 @@ importers:
specifier: 'catalog:'
version: 7.0.2
+ e2e/fixtures/agent-prompt-cache:
+ dependencies:
+ '@ai-sdk/anthropic':
+ specifier: 'catalog:'
+ version: 4.0.0([email protected])
+ eve:
+ specifier: workspace:*
+ version: link:../../../packages/eve
+ zod:
+ specifier: 'catalog:'
+ version: 4.4.3
+ devDependencies:
+ '@types/node':
+ specifier: 'catalog:'
+ version: 25.9.1
+ typescript:
+ specifier: 'catalog:'
+ version: 7.0.2
+
e2e/fixtures/agent-schedules:
dependencies:
'@opentelemetry/core':