Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(gateway): land Anthropic cache_control breakpoints on the system block, not just the call-level auto marker (#2490) (#2981)
Masa6ec3dd410e76
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex 789c2db1e9..a55dcc51cf 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -2982,6 +2982,26 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {const providerOptions: Record<string, any> = {};if (useCache) {+ // Call-level `providerOptions.anthropic.cacheControl` is NOT a no-op:+ // @ai-sdk/anthropic 3.0.47+ passes it through as a top-level+ // `cache_control` field on the Anthropic request body, which the+ // Messages API resolves as its documented "auto-cache the last+ // cacheable block in the request" shorthand (see Anthropic's+ // prompt-caching docs — "top-level auto-caching ... is the simplest+ // option when you don't need fine-grained placement"). Keep it: it's+ // what gives a growing multi-turn conversation (toolLoop()) a rolling+ // cache breakpoint on each turn's tail for free, without us having to+ // hand-roll the marker-walking logic subagent.ts's raw-SDK path uses.+ //+ // But "last cacheable block" is the wrong block for gbrain#2490's+ // actual callers (page-summary, skillopt, enrich): those are+ // single-turn calls with a STABLE system prompt and a DIFFERENT user+ // message every time, so the auto-marker lands on the ever-varying+ // tail — every call WRITES a fresh cache entry and never READS a prior+ // one (cache_read_input_tokens stays 0 forever). Caching the stable+ // prefix needs an EXPLICIT breakpoint on the system block itself,+ // which is applied below via a `SystemModelMessage` (round-trips its+ // own `providerOptions`) instead of a bare string.providerOptions.anthropic = { cacheControl: { type: 'ephemeral' } };}// OpenAI prompt_cache_key (native-openai only): a stable per-prefix routing@@ -3000,6 +3020,30 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {}applyConfiguredChatProviderOptions(providerOptions, cfg, recipe.id, modelId);+ // Derive ONE canonical cache-control value AFTER config merging and reuse+ // it for every breakpoint (system block, last tool def, call-level). If+ // `provider_chat_options.anthropic.cacheControl` overrides the TTL (e.g.+ // `{ type: 'ephemeral', ttl: '1h' }`), that override lands in+ // `providerOptions.anthropic.cacheControl` via the deep-merge above —+ // reusing it here (instead of hardcoding `{ type: 'ephemeral' }` per+ // breakpoint) keeps every marker in the request on the same TTL.+ const cacheControlValue: { type: 'ephemeral'; ttl?: '5m' | '1h' } | undefined = useCache+ ? (providerOptions.anthropic?.cacheControl ?? { type: 'ephemeral' })+ : undefined;++ // Anthropic-only secondary breakpoint: mark the LAST tool def too (mirrors+ // subagent.ts's raw-SDK path — Anthropic caches everything up to and+ // including the last `cache_control` block it sees in the request, so+ // marking the last tool extends the cached prefix through the whole tool+ // list). `tool.providerOptions.anthropic.cacheControl` is the shape+ // @ai-sdk/anthropic 3.x reads for tool-def breakpoints.+ if (cacheControlValue && opts.tools && opts.tools.length > 0 && tools) {+ const lastTool = tools[opts.tools[opts.tools.length - 1]!.name];+ if (lastTool) {+ lastTool.providerOptions = { anthropic: { cacheControl: cacheControlValue } };+ }+ }+let _budgetRecorded = false;const _recordBudget = (modelLabel: string, inputTokens: number, outputTokens: number): void => {if (!tracker || _budgetRecorded) return;@@ -3016,10 +3060,28 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {}};+ // The actual Anthropic system-prompt cache breakpoint. A bare string+ // `system` produces `{ role: 'system', content }` with no `providerOptions`+ // field (ai@6's convertToLanguageModelPrompt), so @ai-sdk/anthropic's+ // getCacheControl(providerOptions) on that block always resolves to+ // nothing. Passing a `SystemModelMessage` object instead — the shape `ai`+ // documents specifically for "additional provider options (e.g. for+ // caching)" — round-trips `providerOptions` onto that block. Byte-identical+ // to the old bare-string form when useCache is false. Reuses+ // `cacheControlValue` (the config-merged value) so this breakpoint's TTL+ // always matches the last-tool and call-level breakpoints.+ const systemParam = cacheControlValue && opts.system+ ? {+ role: 'system' as const,+ content: opts.system,+ providerOptions: { anthropic: { cacheControl: cacheControlValue } },+ }+ : opts.system;+try {const result = await _generateTextTransport({model,- system: opts.system,+ system: systemParam,messages: toModelMessages(repairToolPairing(opts.messages)) as any,tools: opts.tools && opts.tools.length > 0 ? tools : undefined,maxOutputTokens: opts.maxTokens ?? defaultMaxOutputTokens(modelStr),diff --git a/test/ai/gateway-cache-breakpoint.test.ts b/test/ai/gateway-cache-breakpoint.test.tsnew file mode 100644index 0000000000..8a9b65ca97--- /dev/null+++ b/test/ai/gateway-cache-breakpoint.test.ts@@ -0,0 +1,195 @@+/**+ * gbrain#2490 — gateway.chat() never caches a stable system prompt across+ * varying single-turn calls (page-summary, skillopt, enrich).+ *+ * Root cause: `chat()` passed `system` as a bare string and relied solely on+ * a CALL-LEVEL `providerOptions.anthropic.cacheControl`. On `ai@6` ++ * `@ai-sdk/[email protected]`, that call-level marker is real — it's serialized+ * as a top-level `cache_control` field on the Anthropic request body, which+ * the Messages API resolves via its documented "auto-cache the LAST+ * cacheable block in the request" shorthand (see Anthropic's prompt-caching+ * docs). For a single-turn call with a stable system prompt and a DIFFERENT+ * user message every time, "the last cacheable block" is that ever-varying+ * user message — every call WRITES a fresh cache entry there and never+ * READS a prior one, so `cache_read_input_tokens` stays 0 forever even+ * though a `cache_control` breakpoint genuinely reaches Anthropic.+ *+ * Fix: ALSO pass `system` as a `SystemModelMessage` object (`{ role:+ * 'system', content, providerOptions }`) when caching is requested — the+ * shape `ai` documents specifically for attaching provider options to the+ * system block — and mark the last tool def's own `providerOptions` too+ * (mirrors the already-correct raw-SDK path in `subagent.ts`). The+ * call-level marker is KEPT (not removed): it's what gives `toolLoop()`'s+ * growing multi-turn conversation a rolling cache breakpoint on each turn's+ * tail, which the explicit system/tool markers alone don't provide.+ *+ * These tests pin the FIX by inspecting the exact args handed to the+ * `generateText` transport (via `__setGenerateTextTransportForTests`),+ * not by asserting on `providerOptions` alone — that field is exactly what+ * the bug made you believe was sufficient.+ */++import { describe, test, expect, beforeEach } from 'bun:test';+import {+ chat,+ configureGateway,+ resetGateway,+ __setGenerateTextTransportForTests,+} from '../../src/core/ai/gateway.ts';++describe('gbrain#2490 — Anthropic cache breakpoint placement', () => {+ beforeEach(() => {+ resetGateway();+ __setGenerateTextTransportForTests(null);+ });++ async function captureTransportArgs(+ opts: Partial<Parameters<typeof chat>[0]> = {},+ ): Promise<any> {+ let captured: any;+ __setGenerateTextTransportForTests(async (args: any) => {+ captured = args;+ return {+ content: [{ type: 'text', text: 'ok' }],+ finishReason: 'stop',+ usage: { inputTokens: 1, outputTokens: 1 },+ } as any;+ });+ configureGateway({+ chat_model: 'anthropic:claude-sonnet-4-6',+ env: { ANTHROPIC_API_KEY: 'fake' },+ });+ await chat({+ model: 'anthropic:claude-sonnet-4-6',+ messages: [{ role: 'user', content: 'hello' }],+ ...opts,+ });+ return captured;+ }++ test('cacheSystem:true puts a real breakpoint on the system block (SystemModelMessage, not a bare string)', async () => {+ const args = await captureTransportArgs({ system: 'You are a helpful assistant.', cacheSystem: true });++ // The regression: `system` used to stay a bare string forever, which+ // carries no per-block `providerOptions` — no breakpoint could ever land.+ expect(typeof args.system).not.toBe('string');+ expect(args.system).toEqual({+ role: 'system',+ content: 'You are a helpful assistant.',+ providerOptions: { anthropic: { cacheControl: { type: 'ephemeral' } } },+ });+ });++ test('cacheSystem:true ALSO keeps the call-level cache_control on top-level providerOptions (rolling-conversation cache for toolLoop)', async () => {+ const args = await captureTransportArgs({ system: 'SYS', cacheSystem: true });++ // Not removed: @ai-sdk/anthropic serializes this as the Anthropic API's+ // documented top-level "auto-cache the last cacheable block" shorthand,+ // which is what gives a growing multi-turn toolLoop() conversation a+ // rolling cache breakpoint on each turn's tail. The explicit+ // system-block marker (asserted above) is what actually fixes gbrain#2490+ // for single-turn callers — the two coexist, marking different blocks.+ expect(args.providerOptions?.anthropic?.cacheControl).toEqual({ type: 'ephemeral' });+ });++ test('cacheSystem:true marks the LAST tool def with its own providerOptions.anthropic.cacheControl', async () => {+ const args = await captureTransportArgs({+ system: 'SYS',+ cacheSystem: true,+ tools: [+ { name: 'search', description: 'search', inputSchema: { type: 'object', properties: {} } },+ { name: 'put_page', description: 'put_page', inputSchema: { type: 'object', properties: {} } },+ ],+ });++ expect(args.tools.search.providerOptions).toBeUndefined();+ expect(args.tools.put_page.providerOptions).toEqual({+ anthropic: { cacheControl: { type: 'ephemeral' } },+ });+ });++ test('cacheSystem:false (default) leaves system a byte-identical bare string — no behavior change', async () => {+ const args = await captureTransportArgs({ system: 'SYS', cacheSystem: false });+ expect(args.system).toBe('SYS');+ expect(args.providerOptions).toBeUndefined();+ });++ test('cacheSystem omitted entirely leaves system a byte-identical bare string — no behavior change', async () => {+ const args = await captureTransportArgs({ system: 'SYS' });+ expect(args.system).toBe('SYS');+ expect(args.providerOptions).toBeUndefined();+ });++ test('cacheSystem:true with no system prompt does not synthesize an empty cached system block', async () => {+ const args = await captureTransportArgs({ cacheSystem: true });+ expect(args.system).toBeUndefined();+ });++ test('cacheSystem:true with no tools does not throw and leaves tools undefined', async () => {+ const args = await captureTransportArgs({ system: 'SYS', cacheSystem: true });+ expect(args.tools).toBeUndefined();+ });++ test('cacheSystem:true on a non-Anthropic model is silently ignored (supports_prompt_cache=false)', async () => {+ let captured: any;+ __setGenerateTextTransportForTests(async (args: any) => {+ captured = args;+ return {+ content: [{ type: 'text', text: 'ok' }],+ finishReason: 'stop',+ usage: { inputTokens: 1, outputTokens: 1 },+ } as any;+ });+ configureGateway({+ chat_model: 'openai:gpt-4o-mini',+ env: { OPENAI_API_KEY: 'fake' },+ });+ await chat({+ model: 'openai:gpt-4o-mini',+ system: 'SYS',+ cacheSystem: true,+ messages: [{ role: 'user', content: 'hello' }],+ });+ // Still a bare string — the recipe doesn't support prompt caching, so+ // useCache is false regardless of the caller's request.+ expect(captured.system).toBe('SYS');+ });++ test('a configured cacheControl TTL override applies to every breakpoint, not just the call-level one', async () => {+ // Codex review finding: with three independently-hardcoded `{type:+ // 'ephemeral'}` markers, a `provider_chat_options.anthropic.cacheControl`+ // TTL override (e.g. `ttl: '1h'`) would only reach the call-level marker+ // via applyConfiguredChatProviderOptions()'s deep-merge — the system and+ // tool markers would stay implicit 5m, mixing TTLs across breakpoints in+ // the same request. Assert all three markers derive from ONE canonical+ // value instead.+ let captured: any;+ __setGenerateTextTransportForTests(async (args: any) => {+ captured = args;+ return {+ content: [{ type: 'text', text: 'ok' }],+ finishReason: 'stop',+ usage: { inputTokens: 1, outputTokens: 1 },+ } as any;+ });+ configureGateway({+ chat_model: 'anthropic:claude-sonnet-4-6',+ provider_chat_options: {+ anthropic: { cacheControl: { type: 'ephemeral', ttl: '1h' } },+ },+ env: { ANTHROPIC_API_KEY: 'fake' },+ });+ await chat({+ model: 'anthropic:claude-sonnet-4-6',+ system: 'SYS',+ cacheSystem: true,+ tools: [{ name: 'search', description: 'search', inputSchema: { type: 'object', properties: {} } }],+ messages: [{ role: 'user', content: 'hello' }],+ });++ const expected = { type: 'ephemeral', ttl: '1h' };+ expect(captured.providerOptions?.anthropic?.cacheControl).toEqual(expected);+ expect((captured.system as any)?.providerOptions?.anthropic?.cacheControl).toEqual(expected);+ expect(captured.tools?.search?.providerOptions?.anthropic?.cacheControl).toEqual(expected);+ });+});diff --git a/test/ai/gateway-chat.test.ts b/test/ai/gateway-chat.test.tsindex f2ba4ff211..4aee06a261 100644--- a/test/ai/gateway-chat.test.ts+++ b/test/ai/gateway-chat.test.ts@@ -297,6 +297,14 @@ describe('chat touchpoint — provider_chat_options passthrough', () => {});test('anthropic cacheControl survives provider_chat_options merging', async () => {+ // gbrain#2490: this call-level cacheControl is real (not a no-op) —+ // @ai-sdk/anthropic serializes it as the Anthropic API's documented+ // top-level "auto-cache the last cacheable block" shorthand. It's kept+ // alongside the fix (an explicit breakpoint on the system message's own+ // providerOptions — see test/ai/gateway-cache-breakpoint.test.ts) because+ // it's what gives toolLoop()'s growing multi-turn conversation a rolling+ // cache breakpoint on each turn's tail. See gateway.ts's `useCache` block+ // for the full explanation of why both markers are needed.const providerOptions = await captureProviderOptions({chat_model: 'anthropic:claude-sonnet-4-6',provider_chat_options: {