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

tool-choice.test.ts

148 lines4.8 KB

1/**
2 * `chat({ toolChoice })` on the Codex adapter. A fake `codex` CLI runs in a
3 * real local-process sandbox, 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 { codexText } from '../src/index'
17import type { AnyTool, CapabilityContext, ToolChoice } from '@tanstack/ai'
18​
19const baseDir = path.join(os.tmpdir(), `tanstack-ai-codex-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_CODEX = [
27 `process.stdin.resume()`,
28 `process.stdin.on('end', () => {`,
29 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
30 ` w({ type: 'thread.started', thread_id: 'th-1' })`,
31 ` w({ type: 'turn.completed', usage: { input_tokens: 1, output_tokens: 1 } })`,
32 `})`,
33].join('\n')
34​
35const MODEL = 'gpt-5.5-codex'
36​
37const tools: Array<AnyTool> = [
38 { name: 'getWeather', description: 'weather' },
39 { name: 'getTime', description: 'time' },
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
47​
48function loggerWith(warn: (message: string) => void) {
49 return resolveDebugOption({
50 logger: { debug: () => {}, info: () => {}, warn, error: () => {} },
51 })
53​
54/** Run the adapter once in a real sandbox. Returns the bridged tool names. */
55async function bridgedFor(toolChoice: ToolChoice) {
56 const sbx = await provider.create({})
57 try {
58 await sbx.fs.write('/workspace/fake-codex.mjs', FAKE_CODEX)
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 = codexText(MODEL, { codexExecutable: 'node fake-codex.mjs' })
76 const chunks = await collect(
77 adapter.chatStream({
78 threadId: 'thread-1',
79 model: MODEL,
80 messages: [{ role: 'user', content: 'hi' }],
81 logger: loggerWith(() => {}),
82 capabilities,
83 tools,
84 toolChoice,
85 }),
86 )
87 expect(chunks.find((chunk) => chunk.type === 'RUN_ERROR')).toBeUndefined()
88 return bridged
89 } finally {
90 await sbx.destroy()
91 }
93​
94// The warning comes before the sandbox lookup, so these calls need no
95// sandbox. They end with a RUN_ERROR for the missing sandbox.
96async function callWithoutSandbox(
97 adapter: ReturnType<typeof codexText>,
98 warn: (message: string) => void,
99 toolChoice: ToolChoice | undefined,
100) {
101 await collect(
102 adapter.chatStream({
103 threadId: 'thread-1',
104 model: MODEL,
105 messages: [{ role: 'user', content: 'hi' }],
106 logger: loggerWith(warn),
107 tools,
108 ...(toolChoice !== undefined && { toolChoice }),
109 }),
110 )
112​
113describe('codex toolChoice', () => {
114 it("'none' bridges no chat() tool", async () => {
115 expect(await bridgedFor('none')).toEqual([])
116 })
117​
118 it('a named tool bridges only that tool', async () => {
119 expect(await bridgedFor({ type: 'tool', name: 'getTime' })).toEqual([
120 ['getTime'],
121 ])
122 })
123​
124 it("'auto' bridges every chat() tool", async () => {
125 expect(await bridgedFor('auto')).toEqual([['getWeather', 'getTime']])
126 })
127​
128 it('warns once for each value it cannot fully apply', async () => {
129 const warn = vi.fn()
130 const adapter = codexText(MODEL)
131 await callWithoutSandbox(adapter, warn, 'required')
132 await callWithoutSandbox(adapter, warn, 'required')
133 await callWithoutSandbox(adapter, warn, 'none')
134 await callWithoutSandbox(adapter, warn, { type: 'tool', name: 'getTime' })
135 expect(warn.mock.calls.map(([message]) => message)).toEqual([
136 expect.stringContaining("codex: toolChoice 'required' is not supported"),
137 expect.stringContaining('codex: toolChoice limits only the chat() tools'),
138 ])
139 })
140​
141 it("'auto' and unset do not warn", async () => {
142 const warn = vi.fn()
143 const adapter = codexText(MODEL)
144 await callWithoutSandbox(adapter, warn, 'auto')
145 await callWithoutSandbox(adapter, warn, undefined)
146 expect(warn).not.toHaveBeenCalled()
147 })
148})