Open History to see the last commit
1import { z } from 'zod'
2import { toolDefinition } from '@tanstack/ai'
3import { resolveDebugOption } from '@tanstack/ai/adapter-internals'
4import {
5 createEventAwareBindings,
6 toolsToBindings,
7} from './bindings/tool-to-binding'
8import { stripTypeScript } from './strip-typescript'
9import { warnIfBindingsExposeSecrets } from './validate-bindings'
10import type { ServerTool, ToolExecutionContext } from '@tanstack/ai'
11import type {
12 CodeModeTool,
13 CodeModeToolConfig,
14 CodeModeToolResult,
15 IsolateContext,
16} from './types'
17
18/**
19 * Schema for the execute_typescript tool input
20 */
21const executeTypescriptInputSchema = z.object({
22 typescriptCode: z
23 .string()
24 .describe(
25 'TypeScript code to execute in the sandbox. ' +
26 'Use external_* functions to call available APIs. ' +
27 'Return a value to pass results back.',
28 ),
29})
30
31/**
32 * Schema for the execute_typescript tool output
33 */
34const executeTypescriptOutputSchema = z.object({
35 success: z.boolean().describe('Whether execution completed without errors'),
36 result: z
37 .unknown()
38 .optional()
39 .describe('Return value from the executed code'),
40 logs: z
41 .array(z.string())
42 .optional()
43 .describe('Console output captured during execution'),
44 error: z
45 .object({
46 message: z.string(),
47 name: z.string().optional(),
48 line: z.number().optional(),
49 stack: z.string().optional(),
50 })
51 .optional()
52 .describe('Error details if execution failed'),
53})
54
55export type ExecuteTypescriptInput = z.infer<
56 typeof executeTypescriptInputSchema
57>
58export type ExecuteTypescriptOutput = z.infer<
59 typeof executeTypescriptOutputSchema
60>
61
62/**
63 * Create an execute_typescript tool that can be used alongside other agent tools.
64 *
65 * This tool allows an LLM to execute TypeScript code in a secure sandbox.
66 * Tools passed in the config become `external_*` functions available inside the sandbox.
67 *
68 * @example
69 * ```typescript
70 * import { createCodeMode } from '@tanstack/ai-code-mode'
71 * import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
72 *
73 * const { tool, systemPrompt } = createCodeMode({
74 * driver: createNodeIsolateDriver(),
75 * tools: [weatherTool, dbTool], // Become external_fetchWeather, external_dbQuery
76 * timeout: 30000,
77 * })
78 *
79 * chat({
80 * systemPrompts: [myPrompt, systemPrompt],
81 * tools: [tool, searchTool, emailTool],
82 * messages,
83 * })
84 * ```
85 */
86export function createCodeModeTool(
87 config: CodeModeToolConfig,
88): ServerTool<
89 typeof executeTypescriptInputSchema,
90 typeof executeTypescriptOutputSchema,
91 'execute_typescript'
92> {
93 const {
94 driver,
95 tools,
96 timeout = 30000,
97 memoryLimit = 128,
98 getSnippetBindings,
99 onSecretParameter,
100 transpile = stripTypeScript,
101 debug,
102 aroundCalls,
103 } = config
104
105 const logger = resolveDebugOption(debug)
106
107 // Validate tools
108 if (tools.length === 0) {
109 throw new Error('At least one tool must be provided to createCodeModeTool')
110 }
111
112 // Transform tools to bindings with external_ prefix (static bindings)
113 const staticBindings = toolsToBindings(tools, 'external_')
114
115 // Shared across static + dynamic (snippet) binding scans so a given
116 // (toolName, paramPath) pair surfaces at most once per code-mode instance.
117 const secretDedupCache = new Set<string>()
118
119 warnIfBindingsExposeSecrets(Object.values(staticBindings), {
120 handler: onSecretParameter,
121 dedupCache: secretDedupCache,
122 logger,
123 })
124
125 // Create the tool definition
126 const definition = toolDefinition({
127 name: 'execute_typescript' as const,
128 description: buildToolDescription(tools),
129 inputSchema: executeTypescriptInputSchema,
130 outputSchema: executeTypescriptOutputSchema,
131 })
132
133 // Return server tool with execute function that accepts context
134 return definition.server(
135 async (
136 input,
137 toolContext?: ToolExecutionContext,
138 ): Promise<CodeModeToolResult> => {
139 const { typescriptCode } = input
140 const startedAt = Date.now()
141
142 // Get emitCustomEvent from context or use no-op
143 const emitCustomEvent = toolContext?.emitCustomEvent || (() => {})
144
145 const finish = (
146 result: CodeModeToolResult,
147 phase: string,
148 ): CodeModeToolResult => {
149 const durationMs = Date.now() - startedAt
150 const payload = {
151 timestamp: Date.now(),
152 durationMs,
153 phase,
154 success: result.success,
155 logCount: result.logs?.length ?? 0,
156 error: result.error
157 ? {
158 name: result.error.name,
159 message: result.error.message,
160 ...(result.error.stack !== undefined && {
161 stack: result.error.stack,
162 }),
163 ...(result.error.line !== undefined && {
164 line: result.error.line,
165 }),
166 }
167 : undefined,
168 }
169 emitCustomEvent('code_mode:execution_finished', payload)
170 if (!result.success) {
171 logger.errors('code-mode execute_typescript failed', payload)
172 } else {
173 logger.tools('code-mode execute_typescript ok', {
174 durationMs,
175 phase,
176 logCount: payload.logCount,
177 })
178 }
179 return result
180 }
181
182 if (!typescriptCode || typeof typescriptCode !== 'string') {
183 return finish(
184 {
185 success: false,
186 error: {
187 message: 'typescriptCode must be a non-empty string',
188 name: 'ValidationError',
189 },
190 },
191 'validate-input',
192 )
193 }
194
195 // Create a fresh sandbox context for this execution
196 let isolateContext: IsolateContext | null = null
197 // Aborts when this program ends, so a host call that still waits can stop.
198 const programEnd = new AbortController()
199
200 // Emit execution started event immediately
201 emitCustomEvent('code_mode:execution_started', {
202 timestamp: Date.now(),
203 codeLength: typescriptCode.length,
204 })
205
206 try {
207 // Step 1: Strip TypeScript (also serves as syntax validation via the
208 // transpiler — sucrase by default, or a user-supplied `transpile`)
209 let strippedCode: string
210 try {
211 strippedCode = await transpile(typescriptCode)
212 } catch (error) {
213 // Type/syntax error from the transpiler
214 return finish(
215 {
216 success: false,
217 error: {
218 message: error instanceof Error ? error.message : String(error),
219 name: 'TypeScriptError',
220 ...(error instanceof Error &&
221 error.stack !== undefined && { stack: error.stack }),
222 },
223 },
224 'transpile',
225 )
226 }
227
228 // Step 2: Get dynamic snippet bindings if available
229 const snippetBindings = getSnippetBindings
230 ? await getSnippetBindings()
231 : {}
232
233 // Scan dynamic bindings too — their schemas are equally in-scope for
234 // the same exfiltration threat. Dedup cache prevents repeat warnings
235 // when the same binding reappears across executions.
236 const snippetBindingValues = Object.values(snippetBindings)
237 if (snippetBindingValues.length > 0) {
238 warnIfBindingsExposeSecrets(snippetBindingValues, {
239 handler: onSecretParameter,
240 dedupCache: secretDedupCache,
241 logger,
242 })
243 }
244
245 // Step 3: Merge static and dynamic bindings, then wrap with event awareness
246 const allBindings = { ...staticBindings, ...snippetBindings }
247 const eventAwareBindings = createEventAwareBindings(
248 allBindings,
249 emitCustomEvent,
250 toolContext,
251 aroundCalls?.(toolContext, programEnd.signal),
252 )
253
254 // Step 4: Create sandbox context with event-aware bindings
255 try {
256 isolateContext = await driver.createContext({
257 bindings: eventAwareBindings,
258 timeout,
259 memoryLimit,
260 })
261 } catch (error) {
262 return finish(
263 {
264 success: false,
265 error: {
266 message: error instanceof Error ? error.message : String(error),
267 name:
268 error instanceof Error ? error.name : 'CreateContextError',
269 ...(error instanceof Error &&
270 error.stack !== undefined && { stack: error.stack }),
271 },
272 },
273 'create-context',
274 )
275 }
276
277 // Step 5: Execute the code in the sandbox
278 const executionResult = await isolateContext.execute(strippedCode)
279
280 // Emit console logs as custom events
281 if (executionResult.logs && executionResult.logs.length > 0) {
282 for (const log of executionResult.logs) {
283 // Parse log level from prefix (added by sandbox console implementation)
284 let level: 'log' | 'warn' | 'error' | 'info' = 'log'
285 let message = log
286
287 if (log.startsWith('ERROR: ')) {
288 level = 'error'
289 message = log.slice(7)
290 } else if (log.startsWith('WARN: ')) {
291 level = 'warn'
292 message = log.slice(6)
293 } else if (log.startsWith('INFO: ')) {
294 level = 'info'
295 message = log.slice(6)
296 }
297
298 emitCustomEvent('code_mode:console', {
299 level,
300 message,
301 timestamp: Date.now(),
302 })
303 }
304 }
305
306 if (executionResult.success) {
307 return finish(
308 {
309 success: true,
310 result: executionResult.value,
311 logs: executionResult.logs,
312 },
313 'execute',
314 )
315 }
316
317 return finish(
318 {
319 success: false,
320 error: executionResult.error
321 ? {
322 message: executionResult.error.message,
323 name: executionResult.error.name,
324 ...(executionResult.error.stack !== undefined && {
325 stack: executionResult.error.stack,
326 }),
327 }
328 : { message: 'Unknown execution error', name: 'UnknownError' },
329 logs: executionResult.logs,
330 },
331 'execute',
332 )
333 } catch (error) {
334 return finish(
335 {
336 success: false,
337 error: {
338 message: error instanceof Error ? error.message : String(error),
339 name: error instanceof Error ? error.name : 'Error',
340 ...(error instanceof Error &&
341 error.stack !== undefined && { stack: error.stack }),
342 },
343 },
344 'unhandled',
345 )
346 } finally {
347 // The program has ended (success, error, or timeout).
348 programEnd.abort()
349 // Always clean up the sandbox context
350 if (isolateContext) {
351 await isolateContext.dispose()
352 }
353 }
354 },
355 )
356}
357
358/**
359 * Build the tool description including available external functions
360 */
361function buildToolDescription(tools: Array<CodeModeTool>): string {
362 const eager = tools.filter((t) => !t.lazy)
363 const hasLazy = tools.some((t) => t.lazy)
364 const externalFunctions = eager.map((t) => `external_${t.name}`).join(', ')
365
366 const discoverable = hasLazy
367 ? ` To get more functions, call the discover_tools tool before you run code here. discover_tools is a separate tool. It is not available inside this sandbox.`
368 : ''
369
370 return (
371 `Execute TypeScript code in a secure sandbox environment. ` +
372 `The code can use these external API functions: ${externalFunctions}.${discoverable} ` +
373 `All external_* calls are async and must be awaited. ` +
374 `Return a value to pass results back. Use console.log() for debugging. ` +
375 `The tool returns { success, result, logs, error }, where result is the value your code returned.`
376 )
377}