Open History to see the last commit
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(),
63}
64
65const MODEL = 'anthropic/claude-sonnet-4-5'
66
67const tools: Array<AnyTool> = [
68 { name: 'getWeather', description: 'weather' },
69 { name: 'getTime', description: 'time' },
70]
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
76}
77
78function loggerWith(warn: (message: string) => void) {
79 return resolveDebugOption({
80 logger: { debug: () => {}, info: () => {}, warn, error: () => {} },
81 })
82}
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 model: MODEL,
105 messages: [{ role: 'user', content: 'hi' }],
106 logger: loggerWith(() => {}),
107 capabilities,
108 tools,
109 toolChoice,
110 }),
111 )
112 // The run gets past the bridge and stops at the server start.
113 expect(chunks.find((chunk) => chunk.type === 'RUN_ERROR')).toMatchObject({
114 message: 'no opencode server in this test',
115 })
116 return bridged
117}
118
119// The warning comes before the sandbox lookup, so these calls need no
120// sandbox. They end with a RUN_ERROR for the missing sandbox.
121async function callWithoutSandbox(
122 adapter: ReturnType<typeof opencodeText>,
123 warn: (message: string) => void,
124 toolChoice: ToolChoice | undefined,
125) {
126 await collect(
127 adapter.chatStream({
128 model: MODEL,
129 messages: [{ role: 'user', content: 'hi' }],
130 logger: loggerWith(warn),
131 tools,
132 ...(toolChoice !== undefined && { toolChoice }),
133 }),
134 )
135}
136
137describe('opencode toolChoice', () => {
138 it("'none' bridges no chat() tool", async () => {
139 expect(await bridgedFor('none')).toEqual([])
140 })
141
142 it('a named tool bridges only that tool', async () => {
143 expect(await bridgedFor({ type: 'tool', name: 'getTime' })).toEqual([
144 ['getTime'],
145 ])
146 })
147
148 it("'auto' bridges every chat() tool", async () => {
149 expect(await bridgedFor('auto')).toEqual([['getWeather', 'getTime']])
150 })
151
152 it('warns once for each value it cannot fully apply', async () => {
153 const warn = vi.fn()
154 const adapter = opencodeText(MODEL)
155 await callWithoutSandbox(adapter, warn, 'required')
156 await callWithoutSandbox(adapter, warn, 'required')
157 await callWithoutSandbox(adapter, warn, 'none')
158 await callWithoutSandbox(adapter, warn, { type: 'tool', name: 'getTime' })
159 expect(warn.mock.calls.map(([message]) => message)).toEqual([
160 expect.stringContaining(
161 "opencode: toolChoice 'required' is not supported",
162 ),
163 expect.stringContaining(
164 'opencode: toolChoice limits only the chat() tools',
165 ),
166 ])
167 })
168
169 it("'auto' and unset do not warn", async () => {
170 const warn = vi.fn()
171 const adapter = opencodeText(MODEL)
172 await callWithoutSandbox(adapter, warn, 'auto')
173 await callWithoutSandbox(adapter, warn, undefined)
174 expect(warn).not.toHaveBeenCalled()
175 })
176})