Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

tool-choice.test.ts

178 lines5.2 KB

1/**
2 * `chat({ toolChoice })` on the OpenCode adapter. A fake bridge provisioner
3 * records which chat() tools reach the bridge (the bridge becomes the MCP
4 * server of `opencode serve`). The server start is mocked to fail, so no
5 * `opencode` process starts.
6 */
7import { describe, expect, it, vi } from 'vitest'
8import {
9 provideSandbox,
10 provideToolBridgeProvisioner,
11} from '@tanstack/ai-sandbox'
12import { resolveDebugOption } from '@tanstack/ai/adapter-internals'
13import { opencodeText } from '../src/index'
14import type { AnyTool, CapabilityContext, ToolChoice } from '@tanstack/ai'
15import type { SandboxHandle } from '@tanstack/ai-sandbox'
16​
17vi.mock('../src/process/sandbox-server', () => ({
18 startOpencodeServerInSandbox: () =>
19 Promise.reject(new Error('no opencode server in this test')),
20}))
21​
22// The run stops at the mocked server start, before it uses the sandbox.
23const unused = () => Promise.reject(new Error('unused in this test'))
24const sandbox: SandboxHandle = {
25 id: 'sbx',
26 provider: 'mock',
27 capabilities: {
28 fs: false,
29 exec: false,
30 env: false,
31 ports: false,
32 backgroundProcesses: false,
33 writableStdin: false,
34 killableProcesses: false,
35 snapshots: false,
36 networkPolicy: false,
37 durableFilesystem: false,
38 fork: false,
39 },
40 fs: {
41 read: unused,
42 readBytes: unused,
43 write: unused,
44 list: unused,
45 mkdir: unused,
46 remove: unused,
47 rename: unused,
48 exists: unused,
49 },
50 git: {
51 clone: unused,
52 status: unused,
53 add: unused,
54 commit: unused,
55 push: unused,
56 pull: unused,
57 branch: unused,
58 },
59 process: { exec: unused, spawn: unused },
60 ports: { connect: unused },
61 env: { set: unused },
62 destroy: () => Promise.resolve(),
64​
65const MODEL = 'anthropic/claude-sonnet-4-5'
66​
67const tools: Array<AnyTool> = [
68 { name: 'getWeather', description: 'weather' },
69 { name: 'getTime', description: 'time' },
71​
72async function collect<T>(stream: AsyncIterable<T>): Promise<Array<T>> {
73 const out: Array<T> = []
74 for await (const chunk of stream) out.push(chunk)
75 return out
77​
78function loggerWith(warn: (message: string) => void) {
79 return resolveDebugOption({
80 logger: { debug: () => {}, info: () => {}, warn, error: () => {} },
81 })
83​
84/** Run the adapter up to the server start. Returns the bridged tool names. */
85async function bridgedFor(toolChoice: ToolChoice) {
86 const bridged: Array<Array<string>> = []
87 const capabilities = {
88 capabilities: { markProvided: () => {}, has: () => true },
89 } as unknown as CapabilityContext
90 provideSandbox(capabilities, sandbox)
91 provideToolBridgeProvisioner(capabilities, {
92 provision: (provisioned) => {
93 bridged.push(provisioned.map((tool) => tool.name))
94 return Promise.resolve({
95 name: 'tanstack',
96 url: 'http://127.0.0.1:1/mcp',
97 token: 'token',
98 close: () => Promise.resolve(),
99 })
100 },
101 })
102 const chunks = await collect(
103 opencodeText(MODEL).chatStream({
104 threadId: 'thread-1',
105 model: MODEL,
106 messages: [{ role: 'user', content: 'hi' }],
107 logger: loggerWith(() => {}),
108 capabilities,
109 tools,
110 toolChoice,
111 }),
112 )
113 // The run gets past the bridge and stops at the server start.
114 expect(chunks.find((chunk) => chunk.type === 'RUN_ERROR')).toMatchObject({
115 message: 'no opencode server in this test',
116 })
117 return bridged
119​
120// The warning comes before the sandbox lookup, so these calls need no
121// sandbox. They end with a RUN_ERROR for the missing sandbox.
122async function callWithoutSandbox(
123 adapter: ReturnType<typeof opencodeText>,
124 warn: (message: string) => void,
125 toolChoice: ToolChoice | undefined,
126) {
127 await collect(
128 adapter.chatStream({
129 threadId: 'thread-1',
130 model: MODEL,
131 messages: [{ role: 'user', content: 'hi' }],
132 logger: loggerWith(warn),
133 tools,
134 ...(toolChoice !== undefined && { toolChoice }),
135 }),
136 )
138​
139describe('opencode toolChoice', () => {
140 it("'none' bridges no chat() tool", async () => {
141 expect(await bridgedFor('none')).toEqual([])
142 })
143​
144 it('a named tool bridges only that tool', async () => {
145 expect(await bridgedFor({ type: 'tool', name: 'getTime' })).toEqual([
146 ['getTime'],
147 ])
148 })
149​
150 it("'auto' bridges every chat() tool", async () => {
151 expect(await bridgedFor('auto')).toEqual([['getWeather', 'getTime']])
152 })
153​
154 it('warns once for each value it cannot fully apply', async () => {
155 const warn = vi.fn()
156 const adapter = opencodeText(MODEL)
157 await callWithoutSandbox(adapter, warn, 'required')
158 await callWithoutSandbox(adapter, warn, 'required')
159 await callWithoutSandbox(adapter, warn, 'none')
160 await callWithoutSandbox(adapter, warn, { type: 'tool', name: 'getTime' })
161 expect(warn.mock.calls.map(([message]) => message)).toEqual([
162 expect.stringContaining(
163 "opencode: toolChoice 'required' is not supported",
164 ),
165 expect.stringContaining(
166 'opencode: toolChoice limits only the chat() tools',
167 ),
168 ])
169 })
170​
171 it("'auto' and unset do not warn", async () => {
172 const warn = vi.fn()
173 const adapter = opencodeText(MODEL)
174 await callWithoutSandbox(adapter, warn, 'auto')
175 await callWithoutSandbox(adapter, warn, undefined)
176 expect(warn).not.toHaveBeenCalled()
177 })
178})