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 threadId: 'thread-1',
75 adapter,
76 messages: [{ role: 'user', content: 'hi' }],
77 tools: [tool as never],
78 })) {
79 chunks.push(c)
80 }
81 const [rawParams] = mockSend.mock.calls[0]!
82 const serialized = ChatRequest$outboundSchema.parse(
83 rawParams.chatRequest,
84 ) as { tools?: Array<any> }
85 return serialized.tools?.[0]
86}
87
88const baseTool: Tool = {
89 name: 'shared_context',
90 description: 'Standing constraints carried as a cacheable tool.',
91 inputSchema: { type: 'object', properties: {}, required: [] },
92}
93
94describe('OpenRouter function-tool cacheControl (post-SDK serialization)', () => {
95 beforeEach(() => {
96 vi.clearAllMocks()
97 })
98
99 it('forwards metadata.cacheControl as `cache_control` on the wire', async () => {
100 const wireTool = await captureSerializedTool({
101 ...baseTool,
102 metadata: { cacheControl: { type: 'ephemeral' } },
103 })
104 expect(wireTool).toMatchObject({
105 type: 'function',
106 function: { name: 'shared_context' },
107 cache_control: { type: 'ephemeral' },
108 })
109 })
110
111 it('forwards the cache TTL when supplied', async () => {
112 const wireTool = await captureSerializedTool({
113 ...baseTool,
114 metadata: { cacheControl: { type: 'ephemeral', ttl: '1h' } },
115 })
116 expect(wireTool).toMatchObject({
117 cache_control: { type: 'ephemeral', ttl: '1h' },
118 })
119 })
120
121 it('omits cache_control entirely when no cacheControl metadata is supplied', async () => {
122 const wireTool = await captureSerializedTool(baseTool)
123 expect(wireTool).toMatchObject({
124 type: 'function',
125 function: { name: 'shared_context' },
126 })
127 expect(wireTool).not.toHaveProperty('cache_control')
128 })
129})