Open History to see the last commit
1import { beforeEach, describe, expect, it, vi } from 'vitest'
2import { chat } from '@tanstack/ai'
3import { ChatRequest$outboundSchema } from '@openrouter/sdk/models'
4import { createOpenRouterText } from '../src/adapters/text'
5import type { AdapterYieldChunk, Tool } from '@tanstack/ai'
6
7/**
8 * Wire-format verification for function-tool `cacheControl` forwarding.
9 *
10 * The adapter hands a `ChatRequest` to the SDK, which runs it through
11 * `ChatRequest$outboundSchema` (a Zod serializer) before sending bytes
12 * upstream. The SDK accepts `cacheControl` (camelCase) on a function tool and
13 * remaps it to `cache_control` on the wire — but a key it doesn't recognise is
14 * silently stripped. These tests replay the adapter's request through that same
15 * outbound schema to assert that a caller-supplied `metadata.cacheControl`
16 * actually reaches OpenRouter, enabling Anthropic prompt caching of tool
17 * definitions (matching `@tanstack/ai-anthropic`'s custom-tool behaviour).
18 */
19
20let mockSend: any
21
22// eslint-disable-next-line @typescript-eslint/require-await
23vi.mock('@openrouter/sdk', async () => {
24 function OpenRouter(this: {
25 chat: { send: (...args: Array<unknown>) => unknown }
26 }) {
27 this.chat = {
28 send: (...args: Array<unknown>) => mockSend(...args),
29 }
30 }
31 return { OpenRouter }
32})
33
34function createAsyncIterable<T>(chunks: Array<T>): AsyncIterable<T> {
35 return {
36 [Symbol.asyncIterator]() {
37 let index = 0
38 return {
39 // eslint-disable-next-line @typescript-eslint/require-await
40 async next() {
41 if (index < chunks.length) {
42 return { value: chunks[index++]!, done: false }
43 }
44 return { value: undefined as T, done: true }
45 },
46 }
47 },
48 }
49}
50
51function setupMockSend(): void {
52 mockSend = vi.fn().mockImplementation((params) => {
53 if (params.chatRequest?.stream) {
54 return Promise.resolve(
55 createAsyncIterable([
56 {
57 id: 'x',
58 model: 'openai/gpt-4o-mini',
59 choices: [{ delta: { content: 'ok' }, finishReason: 'stop' }],
60 usage: { promptTokens: 1, completionTokens: 1, totalTokens: 2 },
61 },
62 ]),
63 )
64 }
65 return Promise.resolve({})
66 })
67}
68
69async function captureSerializedTool(tool: Tool): Promise<any> {
70 setupMockSend()
71 const adapter = createOpenRouterText('openai/gpt-4o-mini', 'test-key')
72 const chunks: Array<AdapterYieldChunk> = []
73 for await (const c of chat({
74 adapter,
75 messages: [{ role: 'user', content: 'hi' }],
76 tools: [tool as never],
77 })) {
78 chunks.push(c)
79 }
80 const [rawParams] = mockSend.mock.calls[0]!
81 const serialized = ChatRequest$outboundSchema.parse(
82 rawParams.chatRequest,
83 ) as { tools?: Array<any> }
84 return serialized.tools?.[0]
85}
86
87const baseTool: Tool = {
88 name: 'shared_context',
89 description: 'Standing constraints carried as a cacheable tool.',
90 inputSchema: { type: 'object', properties: {}, required: [] },
91}
92
93describe('OpenRouter function-tool cacheControl (post-SDK serialization)', () => {
94 beforeEach(() => {
95 vi.clearAllMocks()
96 })
97
98 it('forwards metadata.cacheControl as `cache_control` on the wire', async () => {
99 const wireTool = await captureSerializedTool({
100 ...baseTool,
101 metadata: { cacheControl: { type: 'ephemeral' } },
102 })
103 expect(wireTool).toMatchObject({
104 type: 'function',
105 function: { name: 'shared_context' },
106 cache_control: { type: 'ephemeral' },
107 })
108 })
109
110 it('forwards the cache TTL when supplied', async () => {
111 const wireTool = await captureSerializedTool({
112 ...baseTool,
113 metadata: { cacheControl: { type: 'ephemeral', ttl: '1h' } },
114 })
115 expect(wireTool).toMatchObject({
116 cache_control: { type: 'ephemeral', ttl: '1h' },
117 })
118 })
119
120 it('omits cache_control entirely when no cacheControl metadata is supplied', async () => {
121 const wireTool = await captureSerializedTool(baseTool)
122 expect(wireTool).toMatchObject({
123 type: 'function',
124 function: { name: 'shared_context' },
125 })
126 expect(wireTool).not.toHaveProperty('cache_control')
127 })
128})