Open History to see the last commit
1/**
2 * `chat({ toolChoice })` on the Claude Code adapter. A fake `claude` CLI
3 * writes its argv to a file, and a fake bridge provisioner records which
4 * chat() tools reach the bridge.
5 */
6import { afterAll, describe, expect, it, vi } from 'vitest'
7import * as fsp from 'node:fs/promises'
8import * as os from 'node:os'
9import * as path from 'node:path'
10import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
11import {
12 provideSandbox,
13 provideToolBridgeProvisioner,
14} from '@tanstack/ai-sandbox'
15import { resolveDebugOption } from '@tanstack/ai/adapter-internals'
16import { claudeCodeText } from '../src/index'
17import type { AnyTool, CapabilityContext, ToolChoice } from '@tanstack/ai'
18
19const baseDir = path.join(os.tmpdir(), `tanstack-ai-cc-choice-${Date.now()}`)
20const provider = localProcessSandbox({ baseDir, removeOnDestroy: true })
21
22afterAll(async () => {
23 await fsp.rm(baseDir, { recursive: true, force: true })
24})
25
26const FAKE_CLAUDE = [
27 `import { writeFileSync } from 'node:fs'`,
28 `writeFileSync('argv.json', JSON.stringify(process.argv.slice(2)))`,
29 `process.stdin.resume()`,
30 `process.stdin.on('end', () => {`,
31 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
32 ` w({ type: 'system', subtype: 'init', session_id: 's', model: 'haiku', tools: [] })`,
33 ` w({ type: 'result', subtype: 'success', result: 'ok', usage: { input_tokens: 1, output_tokens: 1 } })`,
34 `})`,
35].join('\n')
36
37const tools: Array<AnyTool> = [
38 { name: 'getWeather', description: 'weather' },
39 { name: 'getTime', description: 'time' },
40]
41
42async function collect<T>(stream: AsyncIterable<T>): Promise<Array<T>> {
43 const out: Array<T> = []
44 for await (const chunk of stream) out.push(chunk)
45 return out
46}
47
48function loggerWith(warn: (message: string) => void) {
49 return resolveDebugOption({
50 logger: { debug: () => {}, info: () => {}, warn, error: () => {} },
51 })
52}
53
54/** Run the adapter once in a real sandbox. Returns the argv and bridged tools. */
55async function run(toolChoice: ToolChoice) {
56 const sbx = await provider.create({})
57 try {
58 await sbx.fs.write('/workspace/fake-claude.mjs', FAKE_CLAUDE)
59 const bridged: Array<Array<string>> = []
60 const capabilities = {
61 capabilities: { markProvided: () => {}, has: () => true },
62 } as unknown as CapabilityContext
63 provideSandbox(capabilities, sbx)
64 provideToolBridgeProvisioner(capabilities, {
65 provision: (provisioned) => {
66 bridged.push(provisioned.map((tool) => tool.name))
67 return Promise.resolve({
68 name: 'tanstack',
69 url: 'http://127.0.0.1:1/mcp',
70 token: 'token',
71 close: () => Promise.resolve(),
72 })
73 },
74 })
75 const adapter = claudeCodeText('haiku', {
76 claudeExecutable: 'node fake-claude.mjs',
77 streamPartials: false,
78 emitDiff: false,
79 })
80 const chunks = await collect(
81 adapter.chatStream({
82 model: 'haiku',
83 messages: [{ role: 'user', content: 'hi' }],
84 logger: loggerWith(() => {}),
85 capabilities,
86 tools,
87 toolChoice,
88 }),
89 )
90 expect(chunks.find((chunk) => chunk.type === 'RUN_ERROR')).toBeUndefined()
91 const argv: unknown = JSON.parse(await sbx.fs.read('/workspace/argv.json'))
92 return { argv, bridged }
93 } finally {
94 await sbx.destroy()
95 }
96}
97
98describe('claude-code toolChoice', () => {
99 it("'none' bridges no chat() tool and turns off every other tool", async () => {
100 const { argv, bridged } = await run('none')
101 expect(bridged).toEqual([])
102 expect(argv).toEqual(
103 expect.arrayContaining(['--tools', '', '--strict-mcp-config']),
104 )
105 })
106
107 it('a named tool bridges only that tool and turns off the others', async () => {
108 const { argv, bridged } = await run({ type: 'tool', name: 'getTime' })
109 expect(bridged).toEqual([['getTime']])
110 expect(argv).toEqual(
111 expect.arrayContaining(['--tools', '', '--strict-mcp-config']),
112 )
113 })
114
115 it("'auto' bridges every chat() tool and keeps the built-in tools", async () => {
116 const { argv, bridged } = await run('auto')
117 expect(bridged).toEqual([['getWeather', 'getTime']])
118 expect(argv).not.toContain('--tools')
119 expect(argv).not.toContain('--strict-mcp-config')
120 })
121
122 // The warning comes before the sandbox lookup, so these calls need no
123 // sandbox. They end with a RUN_ERROR for the missing sandbox.
124 async function callWithoutSandbox(
125 adapter: ReturnType<typeof claudeCodeText>,
126 warn: (message: string) => void,
127 toolChoice: ToolChoice | undefined,
128 ) {
129 await collect(
130 adapter.chatStream({
131 model: 'haiku',
132 messages: [{ role: 'user', content: 'hi' }],
133 logger: loggerWith(warn),
134 tools,
135 ...(toolChoice !== undefined && { toolChoice }),
136 }),
137 )
138 }
139
140 it("'required' warns once per adapter instance", async () => {
141 const warn = vi.fn()
142 const adapter = claudeCodeText('haiku')
143 await callWithoutSandbox(adapter, warn, 'required')
144 await callWithoutSandbox(adapter, warn, 'required')
145 expect(warn).toHaveBeenCalledTimes(1)
146 expect(warn.mock.calls[0]?.[0]).toContain(
147 "claude-code: toolChoice 'required' is not supported",
148 )
149 })
150
151 it("'auto', unset, 'none', and a named tool do not warn", async () => {
152 const warn = vi.fn()
153 const adapter = claudeCodeText('haiku')
154 await callWithoutSandbox(adapter, warn, 'auto')
155 await callWithoutSandbox(adapter, warn, undefined)
156 await callWithoutSandbox(adapter, warn, 'none')
157 await callWithoutSandbox(adapter, warn, { type: 'tool', name: 'getTime' })
158 expect(warn).not.toHaveBeenCalled()
159 })
160})