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 } = config
103
104 const logger = resolveDebugOption(debug)
105
106 // Validate tools
107 if (tools.length === 0) {
108 throw new Error('At least one tool must be provided to createCodeModeTool')
109 }
110
111 // Transform tools to bindings with external_ prefix (static bindings)
112 const staticBindings = toolsToBindings(tools, 'external_')
113
114 // Shared across static + dynamic (snippet) binding scans so a given
115 // (toolName, paramPath) pair surfaces at most once per code-mode instance.
116 const secretDedupCache = new Set<string>()
117
118 warnIfBindingsExposeSecrets(Object.values(staticBindings), {
119 handler: onSecretParameter,
120 dedupCache: secretDedupCache,
121 logger,
122 })
123
124 // Create the tool definition
125 const definition = toolDefinition({
126 name: 'execute_typescript' as const,
127 description: buildToolDescription(tools),
128 inputSchema: executeTypescriptInputSchema,
129 outputSchema: executeTypescriptOutputSchema,
130 })
131
132 // Return server tool with execute function that accepts context
133 return definition.server(
134 async (
135 input,
136 toolContext?: ToolExecutionContext,
137 ): Promise<CodeModeToolResult> => {
138 const { typescriptCode } = input
139 const startedAt = Date.now()
140
141 // Get emitCustomEvent from context or use no-op
142 const emitCustomEvent = toolContext?.emitCustomEvent || (() => {})
143
144 const finish = (
145 result: CodeModeToolResult,
146 phase: string,
147 ): CodeModeToolResult => {
148 const durationMs = Date.now() - startedAt
149 const payload = {
150 timestamp: Date.now(),
151 durationMs,
152 phase,
153 success: result.success,
154 logCount: result.logs?.length ?? 0,
155 error: result.error
156 ? {
157 name: result.error.name,
158 message: result.error.message,
159 ...(result.error.stack !== undefined && {
160 stack: result.error.stack,
161 }),
162 ...(result.error.line !== undefined && {
163 line: result.error.line,
164 }),
165 }
166 : undefined,
167 }
168 emitCustomEvent('code_mode:execution_finished', payload)
169 if (!result.success) {
170 logger.errors('code-mode execute_typescript failed', payload)
171 } else {
172 logger.tools('code-mode execute_typescript ok', {
173 durationMs,
174 phase,
175 logCount: payload.logCount,
176 })
177 }
178 return result
179 }
180
181 if (!typescriptCode || typeof typescriptCode !== 'string') {
182 return finish(
183 {
184 success: false,
185 error: {
186 message: 'typescriptCode must be a non-empty string',
187 name: 'ValidationError',
188 },
189 },
190 'validate-input',
191 )
192 }
193
194 // Create a fresh sandbox context for this execution
195 let isolateContext: IsolateContext | null = null
196
197 // Emit execution started event immediately
198 emitCustomEvent('code_mode:execution_started', {
199 timestamp: Date.now(),
200 codeLength: typescriptCode.length,
201 })
202
203 try {
204 // Step 1: Strip TypeScript (also serves as syntax validation via the
205 // transpiler — sucrase by default, or a user-supplied `transpile`)
206 let strippedCode: string
207 try {
208 strippedCode = await transpile(typescriptCode)
209 } catch (error) {
210 // Type/syntax error from the transpiler
211 return finish(
212 {
213 success: false,
214 error: {
215 message: error instanceof Error ? error.message : String(error),
216 name: 'TypeScriptError',
217 ...(error instanceof Error &&
218 error.stack !== undefined && { stack: error.stack }),
219 },
220 },
221 'transpile',
222 )
223 }
224
225 // Step 2: Get dynamic snippet bindings if available
226 const snippetBindings = getSnippetBindings
227 ? await getSnippetBindings()
228 : {}
229
230 // Scan dynamic bindings too — their schemas are equally in-scope for
231 // the same exfiltration threat. Dedup cache prevents repeat warnings
232 // when the same binding reappears across executions.
233 const snippetBindingValues = Object.values(snippetBindings)
234 if (snippetBindingValues.length > 0) {
235 warnIfBindingsExposeSecrets(snippetBindingValues, {
236 handler: onSecretParameter,
237 dedupCache: secretDedupCache,
238 logger,
239 })
240 }
241
242 // Step 3: Merge static and dynamic bindings, then wrap with event awareness
243 const allBindings = { ...staticBindings, ...snippetBindings }
244 const eventAwareBindings = createEventAwareBindings(
245 allBindings,
246 emitCustomEvent,
247 toolContext,
248 )
249
250 // Step 4: Create sandbox context with event-aware bindings
251 try {
252 isolateContext = await driver.createContext({
253 bindings: eventAwareBindings,
254 timeout,
255 memoryLimit,
256 })
257 } catch (error) {
258 return finish(
259 {
260 success: false,
261 error: {
262 message: error instanceof Error ? error.message : String(error),
263 name:
264 error instanceof Error ? error.name : 'CreateContextError',
265 ...(error instanceof Error &&
266 error.stack !== undefined && { stack: error.stack }),
267 },
268 },
269 'create-context',
270 )
271 }
272
273 // Step 5: Execute the code in the sandbox
274 const executionResult = await isolateContext.execute(strippedCode)
275
276 // Emit console logs as custom events
277 if (executionResult.logs && executionResult.logs.length > 0) {
278 for (const log of executionResult.logs) {
279 // Parse log level from prefix (added by sandbox console implementation)
280 let level: 'log' | 'warn' | 'error' | 'info' = 'log'
281 let message = log
282
283 if (log.startsWith('ERROR: ')) {
284 level = 'error'
285 message = log.slice(7)
286 } else if (log.startsWith('WARN: ')) {
287 level = 'warn'
288 message = log.slice(6)
289 } else if (log.startsWith('INFO: ')) {
290 level = 'info'
291 message = log.slice(6)
292 }
293
294 emitCustomEvent('code_mode:console', {
295 level,
296 message,
297 timestamp: Date.now(),
298 })
299 }
300 }
301
302 if (executionResult.success) {
303 return finish(
304 {
305 success: true,
306 result: executionResult.value,
307 logs: executionResult.logs,
308 },
309 'execute',
310 )
311 }
312
313 return finish(
314 {
315 success: false,
316 error: executionResult.error
317 ? {
318 message: executionResult.error.message,
319 name: executionResult.error.name,
320 ...(executionResult.error.stack !== undefined && {
321 stack: executionResult.error.stack,
322 }),
323 }
324 : { message: 'Unknown execution error', name: 'UnknownError' },
325 logs: executionResult.logs,
326 },
327 'execute',
328 )
329 } catch (error) {
330 return finish(
331 {
332 success: false,
333 error: {
334 message: error instanceof Error ? error.message : String(error),
335 name: error instanceof Error ? error.name : 'Error',
336 ...(error instanceof Error &&
337 error.stack !== undefined && { stack: error.stack }),
338 },
339 },
340 'unhandled',
341 )
342 } finally {
343 // Always clean up the sandbox context
344 if (isolateContext) {
345 await isolateContext.dispose()
346 }
347 }
348 },
349 )
350}
351
352/**
353 * Build the tool description including available external functions
354 */
355function buildToolDescription(tools: Array<CodeModeTool>): string {
356 const eager = tools.filter((t) => !t.lazy)
357 const hasLazy = tools.some((t) => t.lazy)
358 const externalFunctions = eager.map((t) => `external_${t.name}`).join(', ')
359
360 const discoverable = hasLazy
361 ? ` 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.`
362 : ''
363
364 return (
365 `Execute TypeScript code in a secure sandbox environment. ` +
366 `The code can use these external API functions: ${externalFunctions}.${discoverable} ` +
367 `All external_* calls are async and must be awaited. ` +
368 `Return a value to pass results back. Use console.log() for debugging.`
369 )
370}