Open History to see the last commit
1import { toolDefinition } from '@tanstack/ai'
2import {
3 createEventAwareBindings,
4 stripTypeScript,
5 toolsToBindings,
6} from '@tanstack/ai-code-mode'
7import { z } from 'zod'
8import type {
9 SchemaInput,
10 ServerTool,
11 ToolExecutionContext,
12} from '@tanstack/ai'
13import type {
14 CodeModeTool,
15 IsolateDriver,
16 ToolBinding,
17} from '@tanstack/ai-code-mode'
18import type { Snippet, SnippetStorage } from './types'
19
20/**
21 * Options for converting a single snippet to a tool
22 */
23export interface SnippetToToolOptions {
24 /**
25 * The snippet to convert
26 */
27 snippet: Snippet
28
29 /**
30 * Isolate driver for executing snippet code
31 */
32 driver: IsolateDriver
33
34 /**
35 * Pre-computed bindings for external_* functions
36 */
37 bindings: Record<string, ToolBinding>
38
39 /**
40 * Storage for updating execution stats
41 */
42 storage: SnippetStorage
43
44 /**
45 * Timeout for snippet execution in ms
46 * @default 30000
47 */
48 timeout?: number
49
50 /**
51 * Memory limit in bytes
52 * @default 128
53 */
54 memoryLimit?: number
55}
56
57interface SnippetsToToolsOptions {
58 /**
59 * Snippets to convert to tools
60 */
61 snippets: Array<Snippet>
62
63 /**
64 * Isolate driver for executing snippet code
65 */
66 driver: IsolateDriver
67
68 /**
69 * Original tools that become external_* bindings
70 * (so snippets can call external_* functions)
71 */
72 tools: Array<CodeModeTool>
73
74 /**
75 * Storage for updating execution stats
76 */
77 storage: SnippetStorage
78
79 /**
80 * Timeout for snippet execution in ms
81 * @default 30000
82 */
83 timeout?: number
84
85 /**
86 * Memory limit in bytes
87 * @default 128
88 */
89 memoryLimit?: number
90}
91
92/**
93 * Convert JSON Schema to Zod schema.
94 * This is a simplified converter that handles common cases.
95 */
96function jsonSchemaToZod(schema: Record<string, unknown>): z.ZodType {
97 const type = schema.type as string
98
99 if (type === 'string') {
100 let zodString = z.string()
101 if (schema.description) {
102 zodString = zodString.describe(schema.description as string)
103 }
104 return zodString
105 }
106 if (type === 'number' || type === 'integer') {
107 let zodNum = z.number()
108 if (schema.description) {
109 zodNum = zodNum.describe(schema.description as string)
110 }
111 return zodNum
112 }
113 if (type === 'boolean') {
114 let zodBool = z.boolean()
115 if (schema.description) {
116 zodBool = zodBool.describe(schema.description as string)
117 }
118 return zodBool
119 }
120 if (type === 'array') {
121 const items = schema.items as Record<string, unknown> | undefined
122 if (items) {
123 return z.array(jsonSchemaToZod(items))
124 }
125 return z.array(z.unknown())
126 }
127 if (type === 'object') {
128 const properties = schema.properties as
129 | Record<string, Record<string, unknown>>
130 | undefined
131 const required = (schema.required as Array<string> | undefined) ?? []
132
133 if (properties) {
134 const shape: Record<string, z.ZodType> = {}
135 for (const [key, propSchema] of Object.entries(properties)) {
136 let zodProp = jsonSchemaToZod(propSchema)
137 if (!required.includes(key)) {
138 zodProp = zodProp.optional()
139 }
140 shape[key] = zodProp
141 }
142 return z.object(shape)
143 }
144 return z.record(z.string(), z.unknown())
145 }
146
147 // Fallback
148 return z.unknown()
149}
150
151/**
152 * Convert a single snippet to a ServerTool that the LLM can call directly.
153 * The snippet executes its code in the sandbox with access to external_* bindings.
154 */
155export function snippetToTool({
156 snippet,
157 driver,
158 bindings,
159 storage,
160 timeout = 30000,
161 memoryLimit = 128,
162}: SnippetToToolOptions): ServerTool<SchemaInput, SchemaInput, string> {
163 // Generate input and output schemas from JSON Schema
164 const inputSchema = jsonSchemaToZod(snippet.inputSchema)
165 const outputSchema = jsonSchemaToZod(snippet.outputSchema)
166
167 return toolDefinition({
168 name: snippet.name,
169 description: `[SNIPPET] ${snippet.description}`,
170 inputSchema,
171 outputSchema,
172 }).server(async (input: unknown, context?: ToolExecutionContext) => {
173 const startTime = Date.now()
174 const emitCustomEvent = context?.emitCustomEvent || (() => {})
175
176 // Emit snippet call event
177 emitCustomEvent('code_mode:snippet_call', {
178 snippet: snippet.name,
179 input,
180 timestamp: startTime,
181 })
182
183 let isolateContext = null
184
185 try {
186 console.log(
187 `[Snippet:${snippet.name}] Starting execution with input:`,
188 JSON.stringify(input).substring(0, 200),
189 )
190
191 // Wrap the snippet code to receive input as a variable
192 const wrappedCode = `
193 const input = ${JSON.stringify(input)};
194 ${snippet.code}
195 `
196 console.log(
197 `[Snippet:${snippet.name}] Wrapped code (first 500 chars):`,
198 wrappedCode.substring(0, 500),
199 )
200
201 // Strip TypeScript to JavaScript
202 const strippedCode = await stripTypeScript(wrappedCode)
203 console.log(
204 `[Snippet:${snippet.name}] Stripped code (first 500 chars):`,
205 strippedCode.substring(0, 500),
206 )
207
208 // Create event-aware bindings
209 const eventAwareBindings = createEventAwareBindings(
210 bindings,
211 emitCustomEvent,
212 context,
213 )
214 console.log(
215 `[Snippet:${snippet.name}] Event-aware bindings:`,
216 Object.keys(eventAwareBindings),
217 )
218
219 // Create sandbox context
220 console.log(`[Snippet:${snippet.name}] Creating sandbox context...`)
221 isolateContext = await driver.createContext({
222 bindings: eventAwareBindings,
223 timeout,
224 memoryLimit,
225 })
226 console.log(`[Snippet:${snippet.name}] Sandbox context created`)
227
228 // Execute the code
229 console.log(`[Snippet:${snippet.name}] Executing code...`)
230 const executionResult = await isolateContext.execute(strippedCode)
231 console.log(`[Snippet:${snippet.name}] Execution result:`, {
232 success: executionResult.success,
233 hasValue: 'value' in executionResult,
234 error: executionResult.error,
235 logs: executionResult.logs,
236 })
237
238 const duration = Date.now() - startTime
239
240 if (!executionResult.success) {
241 console.error(
242 `[Snippet:${snippet.name}] Execution failed:`,
243 executionResult.error,
244 )
245 throw new Error(
246 executionResult.error?.message || 'Snippet execution failed',
247 )
248 }
249
250 // Emit success event
251 emitCustomEvent('code_mode:snippet_result', {
252 snippet: snippet.name,
253 result: executionResult.value,
254 duration,
255 timestamp: Date.now(),
256 })
257
258 // Update stats (async, don't await to not block)
259 storage.updateStats(snippet.name, true).catch(() => {
260 // Silently ignore stats update failures
261 })
262
263 return executionResult.value
264 } catch (error) {
265 const duration = Date.now() - startTime
266 console.error(`[Snippet:${snippet.name}] CAUGHT ERROR:`, {
267 message: error instanceof Error ? error.message : String(error),
268 stack: error instanceof Error ? error.stack : undefined,
269 duration,
270 })
271
272 // Emit error event
273 emitCustomEvent('code_mode:snippet_error', {
274 snippet: snippet.name,
275 error: error instanceof Error ? error.message : String(error),
276 duration,
277 timestamp: Date.now(),
278 })
279
280 // Update stats (async, don't await)
281 storage.updateStats(snippet.name, false).catch(() => {
282 // Silently ignore stats update failures
283 })
284
285 throw error
286 } finally {
287 if (isolateContext) {
288 await isolateContext.dispose()
289 }
290 }
291 })
292}
293
294/**
295 * Convert multiple snippets to ServerTools that the LLM can call directly.
296 * Snippets become real tools that execute their code in the sandbox.
297 */
298export function snippetsToTools({
299 snippets,
300 driver,
301 tools,
302 storage,
303 timeout = 30000,
304 memoryLimit = 128,
305}: SnippetsToToolsOptions): Array<
306 ServerTool<SchemaInput, SchemaInput, string>
307> {
308 // Pre-compute bindings from tools (these are shared across all snippet executions)
309 console.log(
310 '[SnippetsToTools] Creating bindings from tools:',
311 tools.map((t) => t.name),
312 )
313 const bindings = toolsToBindings(tools, 'external_')
314 console.log('[SnippetsToTools] Created bindings:', Object.keys(bindings))
315
316 return snippets.map((snippet) =>
317 snippetToTool({
318 snippet,
319 driver,
320 bindings,
321 storage,
322 timeout,
323 memoryLimit,
324 }),
325 )
326}