Open History to see the last commit
1/**
2 * Deterministic test of the in-sandbox Claude Code adapter.
3 *
4 * Instead of the real `claude` CLI (nondeterministic, needs an API key — see
5 * the gated live smoke in testing/e2e), this runs a FAKE agent CLI: a tiny node
6 * script that reads the prompt from stdin and emits canned `stream-json`
7 * messages on stdout, exactly as `claude -p --output-format stream-json` would.
8 * It runs inside a real local-process sandbox, exercising the full
9 * spawn → stdout NDJSON → translate → StreamChunk path.
10 */
11import { afterAll, describe, expect, it } from 'vitest'
12import * as fsp from 'node:fs/promises'
13import * as os from 'node:os'
14import * as path from 'node:path'
15import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
16import { SandboxCapability } from '@tanstack/ai-sandbox'
17import { claudeCodeText } from '../src/index'
18import type { InternalLogger } from '@tanstack/ai/adapter-internals'
19import type { AdapterYieldChunk, CapabilityContext } from '@tanstack/ai'
20import type { SandboxHandle } from '@tanstack/ai-sandbox'
21
22const baseDir = path.join(os.tmpdir(), `tanstack-ai-cc-test-${Date.now()}`)
23const provider = localProcessSandbox({ baseDir, removeOnDestroy: true })
24
25afterAll(async () => {
26 await fsp.rm(baseDir, { recursive: true, force: true })
27})
28
29// A stand-in for the `claude` CLI: ignores its flags, reads the prompt from
30// stdin, then emits stream-json (system/init → assistant text → result).
31const FAKE_CLAUDE = [
32 `let input = ''`,
33 `process.stdin.on('data', (d) => { input += d })`,
34 `process.stdin.on('end', () => {`,
35 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
36 ` w({ type: 'system', subtype: 'init', session_id: 'sess-abc', model: 'haiku', tools: [] })`,
37 ` w({ type: 'stream_event', event: { type: 'message_start', message: { id: 'msg-1' } }, parent_tool_use_id: null })`,
38 ` w({ type: 'stream_event', event: { type: 'content_block_start', index: 0, content_block: { type: 'tool_use', id: 'toolu-1', name: 'Read' } }, parent_tool_use_id: null })`,
39 ` w({ type: 'stream_event', event: { type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: '{"file":' } }, parent_tool_use_id: null })`,
40 ` w({ type: 'stream_event', event: { type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: '"a.ts"}' } }, parent_tool_use_id: null })`,
41 ` w({ type: 'stream_event', event: { type: 'content_block_stop', index: 0 }, parent_tool_use_id: null })`,
42 ` w({ type: 'assistant', message: { id: 'msg-1', content: [{ type: 'tool_use', id: 'toolu-1', name: 'Read', input: { file: 'a.ts' } }] }, parent_tool_use_id: null })`,
43 ` w({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'toolu-1', content: 'file contents' }] }, parent_tool_use_id: null })`,
44 // Echo IS_SANDBOX so the test can assert local-process does not set it.
45 ` w({ type: 'assistant', message: { id: 'msg-2', content: [{ type: 'text', text: 'pong IS_SANDBOX=' + process.env.IS_SANDBOX }] }, parent_tool_use_id: null })`,
46 ` w({ type: 'result', subtype: 'success', result: 'pong', usage: { input_tokens: 1, output_tokens: 1 } })`,
47 `})`,
48].join('\n')
49
50const noopLogger = {
51 request: () => {},
52 provider: () => {},
53 errors: () => {},
54 agentLoop: () => {},
55 warnings: () => {},
56 debug: () => {},
57} as unknown as InternalLogger
58
59/** Build a capability context that hands the adapter the given sandbox. */
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('claude-code in-sandbox adapter', () => {
78 it('spawns the agent CLI in the sandbox and streams translated events', async () => {
79 const sbx = await provider.create({})
80 await sbx.fs.write('/workspace/fake-claude.mjs', FAKE_CLAUDE)
81
82 const adapter = claudeCodeText('haiku', {
83 // Relative executable + cwd=/workspace (mapped to the sandbox root).
84 claudeExecutable: 'node fake-claude.mjs',
85 emitDiff: false,
86 })
87
88 const chunks = await collect(
89 adapter.chatStream({
90 model: 'haiku',
91 messages: [{ role: 'user', content: 'say pong' }],
92 logger: noopLogger,
93 capabilities: capabilityContextWith(sbx),
94 }),
95 )
96
97 const types = chunks.map((c) => c.type as string)
98 expect(types[0]).toBe('RUN_STARTED')
99
100 const sessionEvent = chunks.find(
101 (c) =>
102 c.type === 'CUSTOM' &&
103 (c as { name?: string }).name === 'claude-code.session-id',
104 )
105 expect(sessionEvent).toBeDefined()
106 expect(
107 (sessionEvent as { value: { sessionId: string } }).value.sessionId,
108 ).toBe('sess-abc')
109
110 const text = chunks
111 .filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
112 .map((c) => (c as { delta?: string }).delta ?? '')
113 .join('')
114 expect(text).toContain('pong')
115 // Isolated sandboxes set IS_SANDBOX=1. local-process must not.
116 expect(text).toContain('IS_SANDBOX=undefined')
117
118 const args = chunks.filter((c) => c.type === 'TOOL_CALL_ARGS')
119 expect(args.map((chunk) => chunk.delta)).toEqual(['{"file":', '"a.ts"}'])
120 expect(args.every((chunk) => !('args' in chunk))).toBe(true)
121
122 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
123
124 await sbx.destroy()
125 })
126
127 it('requires a sandbox capability', async () => {
128 const adapter = claudeCodeText('haiku', { emitDiff: false })
129 const chunks = await collect(
130 adapter.chatStream({
131 model: 'haiku',
132 messages: [{ role: 'user', content: 'hi' }],
133 logger: noopLogger,
134 // no capabilities provided
135 }),
136 )
137 const err = chunks.find((c) => c.type === 'RUN_ERROR')
138 expect(err).toBeDefined()
139 expect((err as { message?: string }).message).toMatch(/requires a sandbox/i)
140 })
141
142 it('bridges chat()-provided tools (starts + tears down the MCP bridge)', async () => {
143 const sbx = await provider.create({})
144 await sbx.fs.write('/workspace/fake-claude.mjs', FAKE_CLAUDE)
145 const adapter = claudeCodeText('haiku', {
146 claudeExecutable: 'node fake-claude.mjs',
147 streamPartials: false,
148 emitDiff: false,
149 })
150 // The fake claude ignores the injected --mcp-config; this checks that
151 // passing tools no longer errors and the bridge lifecycle is clean.
152 const chunks = await collect(
153 adapter.chatStream({
154 model: 'haiku',
155 messages: [{ role: 'user', content: 'say pong' }],
156 logger: noopLogger,
157 capabilities: capabilityContextWith(sbx),
158 tools: [
159 {
160 name: 'getTime',
161 description: 'x',
162 inputSchema: { type: 'object', properties: {} },
163 execute: () => Promise.resolve('now'),
164 } as never,
165 ],
166 }),
167 )
168 expect(chunks.some((c) => c.type === 'RUN_ERROR')).toBe(false)
169 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
170 await sbx.destroy()
171 })
172
173 it('passes --json-schema and emits structured-output.complete', async () => {
174 const fake = [
175 `import { writeFileSync } from 'node:fs'`,
176 `writeFileSync('argv.txt', process.argv.slice(2).join(' '))`,
177 `let input = ''`,
178 `process.stdin.on('data', (d) => { input += d })`,
179 `process.stdin.on('end', () => {`,
180 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
181 ` w({ type: 'system', subtype: 'init', session_id: 'sess-so', model: 'haiku', tools: [] })`,
182 ` w({ type: 'assistant', message: { id: 'msg-1', content: [{ type: 'text', text: 'looking' }] }, parent_tool_use_id: null })`,
183 ` w({ type: 'result', subtype: 'success', result: 'done', structured_output: { summary: 'ok' }, usage: { input_tokens: 1, output_tokens: 1 } })`,
184 `})`,
185 ].join('\n')
186
187 const sbx = await provider.create({})
188 await sbx.fs.write('/workspace/fake-claude.mjs', fake)
189
190 const adapter = claudeCodeText('haiku', {
191 claudeExecutable: 'node fake-claude.mjs',
192 streamPartials: false,
193 emitDiff: false,
194 settingSources: ['project', 'local'],
195 })
196
197 const chunks = await collect(
198 adapter.chatStream({
199 model: 'haiku',
200 messages: [{ role: 'user', content: 'summarize' }],
201 logger: noopLogger,
202 capabilities: capabilityContextWith(sbx),
203 outputSchema: {
204 type: 'object',
205 properties: { summary: { type: 'string' } },
206 required: ['summary'],
207 },
208 }),
209 )
210
211 const argv = await sbx.fs.read('/workspace/argv.txt')
212 expect(argv).not.toContain('--bare')
213 expect(argv).toContain('--setting-sources')
214 expect(argv).toContain('project,local')
215 expect(argv).toContain('--json-schema')
216 expect(argv).toContain('"type":"object"')
217 expect(argv).toContain('"summary"')
218 expect(argv).not.toContain('tanstack-output-schema')
219 expect(argv).not.toMatch(/--json-schema\s+\./)
220
221 const complete = chunks.find(
222 (c) => c.type === 'CUSTOM' && c.name === 'structured-output.complete',
223 )
224 expect(complete).toBeDefined()
225 if (complete?.type === 'CUSTOM') {
226 expect(complete.value).toEqual(
227 expect.objectContaining({ object: { summary: 'ok' } }),
228 )
229 }
230
231 await sbx.destroy()
232 })
233
234 it('uses project as the default setting source', async () => {
235 const fake = [
236 `import { writeFileSync } from 'node:fs'`,
237 `writeFileSync('argv.txt', process.argv.slice(2).join(' '))`,
238 `let input = ''`,
239 `process.stdin.on('data', (d) => { input += d })`,
240 `process.stdin.on('end', () => {`,
241 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
242 ` w({ type: 'system', subtype: 'init', session_id: 'sess-default', model: 'haiku', tools: [] })`,
243 ` w({ type: 'result', subtype: 'success', result: 'ok', usage: { input_tokens: 1, output_tokens: 1 } })`,
244 `})`,
245 ].join('\n')
246 const sbx = await provider.create({})
247 await sbx.fs.write('/workspace/fake-claude.mjs', fake)
248
249 try {
250 const adapter = claudeCodeText('haiku', {
251 claudeExecutable: 'node fake-claude.mjs',
252 streamPartials: false,
253 emitDiff: false,
254 })
255 await collect(
256 adapter.chatStream({
257 model: 'haiku',
258 messages: [{ role: 'user', content: 'hi' }],
259 logger: noopLogger,
260 capabilities: capabilityContextWith(sbx),
261 }),
262 )
263
264 expect(await sbx.fs.read('/workspace/argv.txt')).toMatch(
265 /--setting-sources project(?:\s|$)/,
266 )
267 } finally {
268 await sbx.destroy()
269 }
270 })
271
272 it('copies ANTHROPIC_API_KEY from the host process into the CLI env', async () => {
273 const fake = [
274 `import { writeFileSync } from 'node:fs'`,
275 `writeFileSync('auth-probe.txt', process.env.ANTHROPIC_API_KEY ? 'set' : 'missing')`,
276 `let input = ''`,
277 `process.stdin.on('data', (d) => { input += d })`,
278 `process.stdin.on('end', () => {`,
279 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
280 ` w({ type: 'system', subtype: 'init', session_id: 'sess-auth', model: 'haiku', tools: [] })`,
281 ` w({ type: 'assistant', message: { id: 'msg-1', content: [{ type: 'text', text: 'ok' }] }, parent_tool_use_id: null })`,
282 ` w({ type: 'result', subtype: 'success', result: 'ok', usage: { input_tokens: 1, output_tokens: 1 } })`,
283 `})`,
284 ].join('\n')
285
286 const previous = process.env.ANTHROPIC_API_KEY
287 process.env.ANTHROPIC_API_KEY = 'sk-test-not-a-real-key'
288 const sbx = await provider.create({})
289 try {
290 await sbx.fs.write('/workspace/fake-claude.mjs', fake)
291 const adapter = claudeCodeText('haiku', {
292 claudeExecutable: 'node fake-claude.mjs',
293 streamPartials: false,
294 emitDiff: false,
295 })
296 const chunks = await collect(
297 adapter.chatStream({
298 model: 'haiku',
299 messages: [{ role: 'user', content: 'hi' }],
300 logger: noopLogger,
301 capabilities: capabilityContextWith(sbx),
302 }),
303 )
304 expect(chunks.some((c) => c.type === 'RUN_ERROR')).toBe(false)
305 expect(await sbx.fs.read('/workspace/auth-probe.txt')).toBe('set')
306 } finally {
307 if (previous === undefined) delete process.env.ANTHROPIC_API_KEY
308 else process.env.ANTHROPIC_API_KEY = previous
309 await sbx.destroy()
310 }
311 })
312})