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

wrap-code.test.ts

275 lines7.6 KB

1import { createContext, runInContext } from 'node:vm'
2import { describe, expect, it } from 'vitest'
3import {
4 DAYTONA_RESULT_MARKER,
5 generateToolWrappers,
6 wrapCode,
7} from '../src/wrap-code'
8import type {
9 DaytonaExecutionEnvelope,
10 ToolResultPayload,
11 ToolSchema,
12} from '../src/types'
13​
14function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
15 return (
16 typeof value === 'object' &&
17 value !== null &&
18 'then' in value &&
19 typeof value.then === 'function'
20 )
22​
23async function runWrappedCode(
24 code: string,
25 tools: Array<ToolSchema> = [],
26 toolResults?: Record<string, ToolResultPayload>,
27): Promise<DaytonaExecutionEnvelope> {
28 const output: Array<string> = []
29 const context = createContext({
30 console: {
31 log: (value: unknown) => output.push(String(value)),
32 },
33 })
34​
35 const result: unknown = runInContext(
36 wrapCode(code, tools, toolResults),
37 context,
38 )
39 if (isPromiseLike(result)) {
40 await result
41 }
42​
43 const markedOutput = output.find((line) =>
44 line.startsWith(DAYTONA_RESULT_MARKER),
45 )
46 if (!markedOutput) {
47 throw new Error('wrapped code did not emit Daytona marker')
48 }
49​
50 return JSON.parse(
51 markedOutput.slice(DAYTONA_RESULT_MARKER.length),
52 ) as DaytonaExecutionEnvelope
54​
55describe('generateToolWrappers', () => {
56 const tools: Array<ToolSchema> = [
57 { name: 'add', description: 'Add numbers', inputSchema: {} },
58 { name: 'fetchData', description: 'Fetch data', inputSchema: {} },
59 ]
60​
61 it('generates first-pass wrappers that collect missing tool calls', () => {
62 const code = generateToolWrappers(tools)
63 expect(code).toContain('async function add(input)')
64 expect(code).toContain("__pendingToolCalls.push({ id: callId, name: 'add'")
65 expect(code).toContain('__ToolCallNeeded')
66 expect(code).toContain('async function fetchData(input)')
67 })
68​
69 it('generates wrappers that return cached results when present', () => {
70 const code = generateToolWrappers(tools)
71 expect(code).toContain('const result = __toolResults[callId]')
72 expect(code).toContain('result.success')
73 expect(code).toContain('return result.value')
74 })
75​
76 it('rejects unsafe tool names', () => {
77 const invalid = [
78 'has space',
79 'with`backtick',
80 "with'quote",
81 'with"quote',
82 'with;semi',
83 'with\nnewline',
84 '123tool',
85 'return',
86 'class',
87 'await',
88 ]
89​
90 for (const name of invalid) {
91 expect(() =>
92 generateToolWrappers([{ name, description: '', inputSchema: {} }]),
93 ).toThrow(/Invalid tool name/)
94 }
95 })
96​
97 it('accepts conventional JavaScript identifiers', () => {
98 const valid = ['camelCase', 'snake_case', '_leading', '$dollar']
99​
100 for (const name of valid) {
101 expect(() =>
102 generateToolWrappers([{ name, description: '', inputSchema: {} }]),
103 ).not.toThrow()
104 }
105 })
106})
107​
108describe('wrapCode', () => {
109 it('prints a marked JSON envelope instead of relying on codeRun return value', () => {
110 const wrapped = wrapCode('return 1 + 1', [])
111 expect(wrapped).toContain(DAYTONA_RESULT_MARKER)
112 expect(wrapped).toContain('__hostConsole.log')
113 expect(wrapped).toContain("status: 'done'")
114 expect(wrapped).toContain('return 1 + 1')
115 })
116​
117 it('includes cached tool results for replay rounds', () => {
118 const wrapped = wrapCode(
119 'return await add({ a: 2, b: 3 })',
120 [{ name: 'add', description: 'Add numbers', inputSchema: {} }],
121 { tc_0: { success: true, value: 5 } },
122 )
123​
124 expect(wrapped).toContain('"tc_0"')
125 expect(wrapped).toContain('"success":true')
126 expect(wrapped).toContain('"value":5')
127 })
128​
129 it('captures user console output in the protocol logs', () => {
130 const wrapped = wrapCode('console.log("hello")', [])
131 expect(wrapped).toContain('const console =')
132 expect(wrapped).toContain('__logs.push')
133 expect(wrapped).toContain('logs: __logs')
134 })
135​
136 it('executes wrapped code and emits a done envelope', async () => {
137 const envelope = await runWrappedCode('return 1 + 1')
138​
139 expect(envelope).toEqual({
140 status: 'done',
141 success: true,
142 value: 2,
143 logs: [],
144 })
145 })
146​
147 it('captures console output in an executable wrapper', async () => {
148 const envelope = await runWrappedCode(`
149 console.log("hello", { target: "world" });
150 console.warn("careful");
151 return "ok";
152 `)
153​
154 expect(envelope.status).toBe('done')
155 if (envelope.status === 'done') {
156 expect(envelope.logs).toEqual([
157 'hello {"target":"world"}',
158 'WARN: careful',
159 ])
160 }
161 })
162​
163 it('does not fail execution when console arguments cannot JSON serialize', async () => {
164 const envelope = await runWrappedCode(`
165 const circular = {};
166 circular.self = circular;
167 console.log("circular", circular);
168 console.info("bigint", 1n);
169 return "ok";
170 `)
171​
172 expect(envelope.status).toBe('done')
173 if (envelope.status === 'done') {
174 expect(envelope.success).toBe(true)
175 expect(envelope.logs).toEqual([
176 'circular [object Object]',
177 'INFO: bigint 1',
178 ])
179 }
180 })
181​
182 it('normalizes non-Error thrown values in the failure envelope', async () => {
183 const nullEnvelope = await runWrappedCode('throw null')
184 const undefinedEnvelope = await runWrappedCode('throw undefined')
185 const stringEnvelope = await runWrappedCode('throw "boom"')
186​
187 expect(nullEnvelope).toMatchObject({
188 status: 'done',
189 success: false,
190 error: { name: 'Error', message: 'null' },
191 })
192 expect(undefinedEnvelope).toMatchObject({
193 status: 'done',
194 success: false,
195 error: { name: 'Error', message: 'undefined' },
196 })
197 expect(stringEnvelope).toMatchObject({
198 status: 'done',
199 success: false,
200 error: { name: 'Error', message: 'boom' },
201 })
202 })
203​
204 it('emits need_tools for missing tool results', async () => {
205 const envelope = await runWrappedCode('return await add({ a: 2, b: 3 })', [
206 { name: 'add', description: 'Add numbers', inputSchema: {} },
207 ])
208​
209 expect(envelope).toEqual({
210 status: 'need_tools',
211 toolCalls: [{ id: 'tc_0', name: 'add', args: { a: 2, b: 3 } }],
212 logs: [],
213 })
214 })
215​
216 it('replays successful cached tool results', async () => {
217 const envelope = await runWrappedCode(
218 'return await add({ a: 2, b: 3 })',
219 [{ name: 'add', description: 'Add numbers', inputSchema: {} }],
220 { tc_0: { success: true, value: 5 } },
221 )
222​
223 expect(envelope).toEqual({
224 status: 'done',
225 success: true,
226 value: 5,
227 logs: [],
228 })
229 })
230​
231 it('replays failed cached tool results as execution errors', async () => {
232 const envelope = await runWrappedCode(
233 'return await add({ a: 2, b: 3 })',
234 [{ name: 'add', description: 'Add numbers', inputSchema: {} }],
235 { tc_0: { success: false, error: 'Tool failed' } },
236 )
237​
238 expect(envelope.status).toBe('done')
239 if (envelope.status === 'done') {
240 expect(envelope.success).toBe(false)
241 expect(envelope.error?.message).toBe('Tool failed')
242 }
243 })
244​
245 it('emits an outer error envelope when the result marker cannot serialize', async () => {
246 const envelope = await runWrappedCode(`
247 const value = {};
248 value.self = value;
249 return value;
250 `)
251​
252 expect(envelope.status).toBe('error')
253 if (envelope.status === 'error') {
254 expect(envelope.error.message).toContain('circular')
255 }
256 })
257​
258 it('normalizes non-Error outer serialization failures', async () => {
259 const envelope = await runWrappedCode(`
260 return {
261 toJSON() {
262 throw null;
263 }
264 };
265 `)
266​
267 expect(envelope).toEqual({
268 status: 'error',
269 error: {
270 name: 'Error',
271 message: 'null',
272 },
273 })
274 })
275})