Open History to see the last commit
1import type { ToolResultPayload, ToolSchema } from './types'
2
3export const DAYTONA_RESULT_MARKER = '__TANSTACK_AI_CODE_MODE_RESULT__'
4
5const VALID_TOOL_NAME = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/
6
7const RESERVED_TOOL_NAMES = new Set([
8 'break',
9 'case',
10 'catch',
11 'class',
12 'const',
13 'continue',
14 'debugger',
15 'default',
16 'delete',
17 'do',
18 'else',
19 'enum',
20 'export',
21 'extends',
22 'false',
23 'finally',
24 'for',
25 'function',
26 'if',
27 'import',
28 'in',
29 'instanceof',
30 'new',
31 'null',
32 'return',
33 'super',
34 'switch',
35 'this',
36 'throw',
37 'true',
38 'try',
39 'typeof',
40 'var',
41 'void',
42 'while',
43 'with',
44 'yield',
45 'let',
46 'static',
47 'implements',
48 'interface',
49 'package',
50 'private',
51 'protected',
52 'public',
53 'await',
54 'async',
55])
56
57function assertSafeToolName(name: string): void {
58 if (!VALID_TOOL_NAME.test(name)) {
59 throw new Error(
60 `Invalid tool name '${name}': must match ${VALID_TOOL_NAME} (letters, digits, _, $; cannot start with a digit)`,
61 )
62 }
63 if (RESERVED_TOOL_NAMES.has(name)) {
64 throw new Error(`Invalid tool name '${name}': reserved JavaScript keyword`)
65 }
66}
67
68export function generateToolWrappers(tools: Array<ToolSchema>): string {
69 const wrappers: Array<string> = []
70
71 for (const tool of tools) {
72 assertSafeToolName(tool.name)
73
74 wrappers.push(`
75 async function ${tool.name}(input) {
76 const callId = 'tc_' + (__toolCallIdx++);
77 const result = __toolResults[callId];
78 if (!result) {
79 __pendingToolCalls.push({ id: callId, name: '${tool.name}', args: input });
80 throw new __ToolCallNeeded(callId);
81 }
82 if (!result.success) {
83 throw new Error(result.error || 'Tool call failed');
84 }
85 return result.value;
86 }
87 `)
88 }
89
90 return wrappers.join('\n')
91}
92
93export function wrapCode(
94 code: string,
95 tools: Array<ToolSchema>,
96 toolResults?: Record<string, ToolResultPayload>,
97 resultMarker = DAYTONA_RESULT_MARKER,
98): string {
99 const toolWrappers = generateToolWrappers(tools)
100 const toolResultsJson = toolResults ? JSON.stringify(toolResults) : '{}'
101
102 return `
103 const __hostConsole = globalThis.console;
104
105 function __stringProperty(__value, __key) {
106 try {
107 const __property = __value && typeof __value === 'object' ? __value[__key] : undefined;
108 return typeof __property === 'string' ? __property : undefined;
109 } catch {
110 return undefined;
111 }
112 }
113
114 function __normalizeError(__error) {
115 if (__error instanceof Error) {
116 return {
117 name: __error.name || 'Error',
118 message: __error.message || String(__error),
119 stack: __error.stack,
120 };
121 }
122
123 if (__error && typeof __error === 'object') {
124 return {
125 name: __stringProperty(__error, 'name') || 'Error',
126 message: __stringProperty(__error, 'message') || 'Error',
127 stack: __stringProperty(__error, 'stack'),
128 };
129 }
130
131 return {
132 name: 'Error',
133 message: String(__error),
134 };
135 }
136
137 function __formatConsoleArg(__arg) {
138 if (typeof __arg === 'string') {
139 return __arg;
140 }
141
142 try {
143 const __json = JSON.stringify(__arg);
144 if (__json !== undefined) {
145 return __json;
146 }
147 } catch {
148 // Fall through to String(); logging must not fail user code.
149 }
150
151 try {
152 return String(__arg);
153 } catch {
154 return '[Unserializable]';
155 }
156 }
157
158 (async function() {
159 let __toolCallIdx = 0;
160 const __pendingToolCalls = [];
161 const __toolResults = ${toolResultsJson};
162 const __logs = [];
163
164 class __ToolCallNeeded extends Error {
165 constructor(callId) {
166 super('Tool call needed: ' + callId);
167 this.callId = callId;
168 }
169 }
170
171 const console = {
172 log: (...args) => __logs.push(args.map(__formatConsoleArg).join(' ')),
173 error: (...args) => __logs.push('ERROR: ' + args.map(__formatConsoleArg).join(' ')),
174 warn: (...args) => __logs.push('WARN: ' + args.map(__formatConsoleArg).join(' ')),
175 info: (...args) => __logs.push('INFO: ' + args.map(__formatConsoleArg).join(' ')),
176 };
177
178 ${toolWrappers}
179
180 try {
181 const __userResult = await (async function() {
182 ${code}
183 })();
184
185 return {
186 status: 'done',
187 success: true,
188 value: __userResult,
189 logs: __logs,
190 };
191 } catch (__error) {
192 if (__error instanceof __ToolCallNeeded) {
193 return {
194 status: 'need_tools',
195 toolCalls: __pendingToolCalls,
196 logs: __logs,
197 };
198 }
199
200 return {
201 status: 'done',
202 success: false,
203 error: __normalizeError(__error),
204 logs: __logs,
205 };
206 }
207 })()
208 .then((__envelope) => {
209 __hostConsole.log(${JSON.stringify(resultMarker)} + JSON.stringify(__envelope));
210 })
211 .catch((__error) => {
212 __hostConsole.log(${JSON.stringify(resultMarker)} + JSON.stringify({
213 status: 'error',
214 error: __normalizeError(__error),
215 }));
216 });
217 `
218}