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

text-adapter.test.ts

266 lines9.0 KB

1/**
2 * Deterministic test of the in-sandbox Codex adapter.
3 *
4 * Runs a FAKE codex CLI (a node script that reads the prompt from stdin and
5 * emits canned `codex exec --experimental-json` JSONL thread events) inside a
6 * real local-process sandbox, exercising spawn → stdout NDJSON → translate →
7 * StreamChunk. The real `codex` CLI is covered by the gated live path.
8 */
9import { afterAll, describe, expect, it } from 'vitest'
10import * as fsp from 'node:fs/promises'
11import * as os from 'node:os'
12import * as path from 'node:path'
13import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
14import {
15 SandboxCapability,
16 provideToolBridgeProvisioner,
17} from '@tanstack/ai-sandbox'
18import { codexText } from '../src/index'
19import type { InternalLogger } from '@tanstack/ai/adapter-internals'
20import type {
21 AdapterYieldChunk,
22 AnyTool,
23 CapabilityContext,
24} from '@tanstack/ai'
25import type { SandboxHandle } from '@tanstack/ai-sandbox'
26​
27const baseDir = path.join(os.tmpdir(), `tanstack-ai-codex-test-${Date.now()}`)
28const provider = localProcessSandbox({ baseDir, removeOnDestroy: true })
29​
30afterAll(async () => {
31 await fsp.rm(baseDir, { recursive: true, force: true })
32})
33​
34// Stand-in for `codex exec --experimental-json`: records the argv it was spawned
35// with (so a test can assert the generated CLI flags), reads the prompt from
36// stdin, and emits codex thread-event JSONL.
37const FAKE_CODEX = [
38 `import { writeFileSync } from 'node:fs'`,
39 `writeFileSync('codex-argv.txt', process.argv.join(' '))`,
40 `let input = ''`,
41 `process.stdin.on('data', (d) => { input += d })`,
42 `process.stdin.on('end', () => {`,
43 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
44 ` w({ type: 'thread.started', thread_id: 'th-1' })`,
45 ` w({ type: 'turn.started' })`,
46 ` w({ type: 'item.completed', item: { id: 'i1', type: 'agent_message', text: 'pong' } })`,
47 ` w({ type: 'turn.completed', usage: { input_tokens: 1, output_tokens: 1 } })`,
48 `})`,
49].join('\n')
50​
51const noopLogger = {
52 request: () => {},
53 provider: () => {},
54 errors: () => {},
55 agentLoop: () => {},
56 warnings: () => {},
57 debug: () => {},
58} as unknown as InternalLogger
59​
60function capabilityContextWith(handle: SandboxHandle): CapabilityContext {
61 const [, provideSandbox] = SandboxCapability
62 const ctx = {
63 capabilities: { markProvided: () => {}, has: () => true },
64 } as unknown as CapabilityContext
65 provideSandbox(ctx, handle)
66 return ctx
68​
69async function collect(
70 stream: AsyncIterable<AdapterYieldChunk>,
71): Promise<Array<AdapterYieldChunk>> {
72 const out: Array<AdapterYieldChunk> = []
73 for await (const chunk of stream) out.push(chunk)
74 return out
76​
77describe('codex in-sandbox adapter', () => {
78 it('spawns codex in the sandbox and streams translated events', async () => {
79 const sbx = await provider.create({})
80 await sbx.fs.write('/workspace/fake-codex.mjs', FAKE_CODEX)
81​
82 const adapter = codexText('gpt-5.5-codex', {
83 codexExecutable: 'node fake-codex.mjs',
84 })
85​
86 const chunks = await collect(
87 adapter.chatStream({
88 threadId: 'thread-1',
89 model: 'gpt-5.5-codex',
90 messages: [{ role: 'user', content: 'say pong' }],
91 logger: noopLogger,
92 capabilities: capabilityContextWith(sbx),
93 }),
94 )
95​
96 expect((chunks[0] as { type: string }).type).toBe('RUN_STARTED')
97 const text = chunks
98 .filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
99 .map((c) => (c as { delta?: string }).delta ?? '')
100 .join('')
101 expect(text).toContain('pong')
102 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
103 await sbx.destroy()
104 })
105​
106 it('bridges chat() tools via http_headers, not the streamable-http-rejected bearer_token', async () => {
107 // Codex's streamable-HTTP MCP transport REJECTS inline `bearer_token`
108 // ("bearer_token is not supported for streamable_http"); the per-run bearer
109 // must ride an `Authorization` header instead. Stub the provisioner so the
110 // bridge url/token are deterministic, then assert the generated CLI flags.
111 const sbx = await provider.create({})
112 await sbx.fs.write('/workspace/fake-codex.mjs', FAKE_CODEX)
113​
114 const ctx = capabilityContextWith(sbx)
115 provideToolBridgeProvisioner(ctx, {
116 provision: () =>
117 Promise.resolve({
118 name: 'tanstack',
119 url: 'http://bridge.test/_bridge/run1',
120 token: 'secret-token-xyz',
121 close: () => Promise.resolve(),
122 }),
123 })
124​
125 const adapter = codexText('gpt-5.5-codex', {
126 codexExecutable: 'node fake-codex.mjs',
127 })
128 await collect(
129 adapter.chatStream({
130 threadId: 'thread-1',
131 model: 'gpt-5.5-codex',
132 messages: [{ role: 'user', content: 'use a tool' }],
133 logger: noopLogger,
134 capabilities: ctx,
135 // Non-empty tools array activates the bridge path; the stub provisioner
136 // ignores the contents, so a placeholder is enough.
137 tools: [{ name: 'demo' } as unknown as AnyTool],
138 }),
139 )
140​
141 const argv = await sbx.fs.read('/workspace/codex-argv.txt')
142 expect(argv).toContain(
143 'mcp_servers.tanstack.url="http://bridge.test/_bridge/run1"',
144 )
145 expect(argv).toContain(
146 'mcp_servers.tanstack.http_headers={ "Authorization" = "Bearer secret-token-xyz" }',
147 )
148 expect(argv).not.toContain('bearer_token')
149 await sbx.destroy()
150 })
151​
152 it('defaults to danger-full-access on Daytona-like providers', async () => {
153 const sbx = await provider.create({})
154 await sbx.fs.write('/workspace/fake-codex.mjs', FAKE_CODEX)
155 const daytonaHandle: SandboxHandle = { ...sbx, provider: 'daytona' }
156​
157 const adapter = codexText('gpt-5.5-codex', {
158 codexExecutable: 'node fake-codex.mjs',
159 })
160 await collect(
161 adapter.chatStream({
162 threadId: 'thread-1',
163 model: 'gpt-5.5-codex',
164 messages: [{ role: 'user', content: 'say pong' }],
165 logger: noopLogger,
166 capabilities: capabilityContextWith(daytonaHandle),
167 }),
168 )
169​
170 const argv = await sbx.fs.read('/workspace/codex-argv.txt')
171 expect(argv).toContain('--sandbox danger-full-access')
172 expect(argv).not.toContain('--sandbox workspace-write')
173​
174 await sbx.destroy()
175 })
176​
177 it('keeps workspace-write on local-process when no sandboxMode is set', async () => {
178 const sbx = await provider.create({})
179 await sbx.fs.write('/workspace/fake-codex.mjs', FAKE_CODEX)
180​
181 const adapter = codexText('gpt-5.5-codex', {
182 codexExecutable: 'node fake-codex.mjs',
183 })
184 await collect(
185 adapter.chatStream({
186 threadId: 'thread-1',
187 model: 'gpt-5.5-codex',
188 messages: [{ role: 'user', content: 'say pong' }],
189 logger: noopLogger,
190 capabilities: capabilityContextWith(sbx),
191 }),
192 )
193​
194 const argv = await sbx.fs.read('/workspace/codex-argv.txt')
195 expect(argv).toContain('--sandbox workspace-write')
196​
197 await sbx.destroy()
198 })
199​
200 it('requires a sandbox capability', async () => {
201 const adapter = codexText('gpt-5.5-codex')
202 const chunks = await collect(
203 adapter.chatStream({
204 threadId: 'thread-1',
205 model: 'gpt-5.5-codex',
206 messages: [{ role: 'user', content: 'hi' }],
207 logger: noopLogger,
208 }),
209 )
210 const err = chunks.find((c) => c.type === 'RUN_ERROR')
211 expect((err as { message?: string }).message).toMatch(/requires a sandbox/i)
212 })
213​
214 it('passes --output-schema and emits structured-output.complete', async () => {
215 const fake = [
216 `import { writeFileSync } from 'node:fs'`,
217 `writeFileSync('codex-argv.txt', process.argv.join(' '))`,
218 `let input = ''`,
219 `process.stdin.on('data', (d) => { input += d })`,
220 `process.stdin.on('end', () => {`,
221 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
222 ` w({ type: 'thread.started', thread_id: 'th-so' })`,
223 ` w({ type: 'turn.started' })`,
224 ` w({ type: 'item.completed', item: { id: 'i1', type: 'agent_message', text: '{"ok":true}' } })`,
225 ` w({ type: 'turn.completed', usage: { input_tokens: 1, output_tokens: 1 } })`,
226 `})`,
227 ].join('\n')
228​
229 const sbx = await provider.create({})
230 await sbx.fs.write('/workspace/fake-codex.mjs', fake)
231​
232 const adapter = codexText('gpt-5.5-codex', {
233 codexExecutable: 'node fake-codex.mjs',
234 })
235​
236 const chunks = await collect(
237 adapter.chatStream({
238 threadId: 'thread-1',
239 model: 'gpt-5.5-codex',
240 messages: [{ role: 'user', content: 'summarize' }],
241 logger: noopLogger,
242 capabilities: capabilityContextWith(sbx),
243 outputSchema: {
244 type: 'object',
245 properties: { ok: { type: 'boolean' } },
246 required: ['ok'],
247 },
248 }),
249 )
250​
251 const argv = await sbx.fs.read('/workspace/codex-argv.txt')
252 expect(argv).toContain('--output-schema')
253​
254 const complete = chunks.find(
255 (c) => c.type === 'CUSTOM' && c.name === 'structured-output.complete',
256 )
257 expect(complete).toBeDefined()
258 if (complete?.type === 'CUSTOM') {
259 expect(complete.value).toEqual(
260 expect.objectContaining({ object: { ok: true } }),
261 )
262 }
263​
264 await sbx.destroy()
265 })
266})