Open History to see the last commit
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
67}
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
75}
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 model: 'gpt-5.5-codex',
89 messages: [{ role: 'user', content: 'say pong' }],
90 logger: noopLogger,
91 capabilities: capabilityContextWith(sbx),
92 }),
93 )
94
95 expect((chunks[0] as { type: string }).type).toBe('RUN_STARTED')
96 const text = chunks
97 .filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
98 .map((c) => (c as { delta?: string }).delta ?? '')
99 .join('')
100 expect(text).toContain('pong')
101 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
102 await sbx.destroy()
103 })
104
105 it('bridges chat() tools via http_headers, not the streamable-http-rejected bearer_token', async () => {
106 // Codex's streamable-HTTP MCP transport REJECTS inline `bearer_token`
107 // ("bearer_token is not supported for streamable_http"); the per-run bearer
108 // must ride an `Authorization` header instead. Stub the provisioner so the
109 // bridge url/token are deterministic, then assert the generated CLI flags.
110 const sbx = await provider.create({})
111 await sbx.fs.write('/workspace/fake-codex.mjs', FAKE_CODEX)
112
113 const ctx = capabilityContextWith(sbx)
114 provideToolBridgeProvisioner(ctx, {
115 provision: () =>
116 Promise.resolve({
117 name: 'tanstack',
118 url: 'http://bridge.test/_bridge/run1',
119 token: 'secret-token-xyz',
120 close: () => Promise.resolve(),
121 }),
122 })
123
124 const adapter = codexText('gpt-5.5-codex', {
125 codexExecutable: 'node fake-codex.mjs',
126 })
127 await collect(
128 adapter.chatStream({
129 model: 'gpt-5.5-codex',
130 messages: [{ role: 'user', content: 'use a tool' }],
131 logger: noopLogger,
132 capabilities: ctx,
133 // Non-empty tools array activates the bridge path; the stub provisioner
134 // ignores the contents, so a placeholder is enough.
135 tools: [{ name: 'demo' } as unknown as AnyTool],
136 }),
137 )
138
139 const argv = await sbx.fs.read('/workspace/codex-argv.txt')
140 expect(argv).toContain(
141 'mcp_servers.tanstack.url="http://bridge.test/_bridge/run1"',
142 )
143 expect(argv).toContain(
144 'mcp_servers.tanstack.http_headers={ "Authorization" = "Bearer secret-token-xyz" }',
145 )
146 expect(argv).not.toContain('bearer_token')
147 await sbx.destroy()
148 })
149
150 it('defaults to danger-full-access on Daytona-like providers', async () => {
151 const sbx = await provider.create({})
152 await sbx.fs.write('/workspace/fake-codex.mjs', FAKE_CODEX)
153 const daytonaHandle: SandboxHandle = { ...sbx, provider: 'daytona' }
154
155 const adapter = codexText('gpt-5.5-codex', {
156 codexExecutable: 'node fake-codex.mjs',
157 })
158 await collect(
159 adapter.chatStream({
160 model: 'gpt-5.5-codex',
161 messages: [{ role: 'user', content: 'say pong' }],
162 logger: noopLogger,
163 capabilities: capabilityContextWith(daytonaHandle),
164 }),
165 )
166
167 const argv = await sbx.fs.read('/workspace/codex-argv.txt')
168 expect(argv).toContain('--sandbox danger-full-access')
169 expect(argv).not.toContain('--sandbox workspace-write')
170
171 await sbx.destroy()
172 })
173
174 it('keeps workspace-write on local-process when no sandboxMode is set', async () => {
175 const sbx = await provider.create({})
176 await sbx.fs.write('/workspace/fake-codex.mjs', FAKE_CODEX)
177
178 const adapter = codexText('gpt-5.5-codex', {
179 codexExecutable: 'node fake-codex.mjs',
180 })
181 await collect(
182 adapter.chatStream({
183 model: 'gpt-5.5-codex',
184 messages: [{ role: 'user', content: 'say pong' }],
185 logger: noopLogger,
186 capabilities: capabilityContextWith(sbx),
187 }),
188 )
189
190 const argv = await sbx.fs.read('/workspace/codex-argv.txt')
191 expect(argv).toContain('--sandbox workspace-write')
192
193 await sbx.destroy()
194 })
195
196 it('requires a sandbox capability', async () => {
197 const adapter = codexText('gpt-5.5-codex')
198 const chunks = await collect(
199 adapter.chatStream({
200 model: 'gpt-5.5-codex',
201 messages: [{ role: 'user', content: 'hi' }],
202 logger: noopLogger,
203 }),
204 )
205 const err = chunks.find((c) => c.type === 'RUN_ERROR')
206 expect((err as { message?: string }).message).toMatch(/requires a sandbox/i)
207 })
208
209 it('passes --output-schema and emits structured-output.complete', async () => {
210 const fake = [
211 `import { writeFileSync } from 'node:fs'`,
212 `writeFileSync('codex-argv.txt', process.argv.join(' '))`,
213 `let input = ''`,
214 `process.stdin.on('data', (d) => { input += d })`,
215 `process.stdin.on('end', () => {`,
216 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
217 ` w({ type: 'thread.started', thread_id: 'th-so' })`,
218 ` w({ type: 'turn.started' })`,
219 ` w({ type: 'item.completed', item: { id: 'i1', type: 'agent_message', text: '{"ok":true}' } })`,
220 ` w({ type: 'turn.completed', usage: { input_tokens: 1, output_tokens: 1 } })`,
221 `})`,
222 ].join('\n')
223
224 const sbx = await provider.create({})
225 await sbx.fs.write('/workspace/fake-codex.mjs', fake)
226
227 const adapter = codexText('gpt-5.5-codex', {
228 codexExecutable: 'node fake-codex.mjs',
229 })
230
231 const chunks = await collect(
232 adapter.chatStream({
233 model: 'gpt-5.5-codex',
234 messages: [{ role: 'user', content: 'summarize' }],
235 logger: noopLogger,
236 capabilities: capabilityContextWith(sbx),
237 outputSchema: {
238 type: 'object',
239 properties: { ok: { type: 'boolean' } },
240 required: ['ok'],
241 },
242 }),
243 )
244
245 const argv = await sbx.fs.read('/workspace/codex-argv.txt')
246 expect(argv).toContain('--output-schema')
247
248 const complete = chunks.find(
249 (c) => c.type === 'CUSTOM' && c.name === 'structured-output.complete',
250 )
251 expect(complete).toBeDefined()
252 if (complete?.type === 'CUSTOM') {
253 expect(complete.value).toEqual(
254 expect.objectContaining({ object: { ok: true } }),
255 )
256 }
257
258 await sbx.destroy()
259 })
260})