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