Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

isolate-driver.ts

323 lines8.4 KB

1import type {
2 ExecutionResult,
3 IsolateConfig,
4 IsolateContext,
5 IsolateDriver,
6 ToolBinding,
7} from '@tanstack/ai-code-mode'
8import type {
9 ExecuteRequest,
10 ExecuteResponse,
11 ToolResultPayload,
12 ToolSchema,
13} from './types'
14​
15/**
16 * Configuration for the Cloudflare Workers isolate driver
17 */
18export interface CloudflareIsolateDriverConfig {
19 /**
20 * URL of the deployed Cloudflare Worker
21 * For local development, use: http://localhost:8787
22 */
23 workerUrl: string
24​
25 /**
26 * Optional authorization header value
27 * Useful for protecting your Worker endpoint
28 */
29 authorization?: string
30​
31 /**
32 * Default execution timeout in ms (default: 30000)
33 */
34 timeout?: number
35​
36 /**
37 * Maximum number of tool callback rounds (default: 10)
38 * Prevents infinite loops
39 */
40 maxToolRounds?: number
42​
43/**
44 * Convert tool bindings to schemas for the Worker
45 */
46function bindingsToSchemas(
47 bindings: Record<string, ToolBinding>,
48): Array<ToolSchema> {
49 return Object.entries(bindings).map(([name, binding]) => ({
50 name,
51 description: binding.description,
52 inputSchema: binding.inputSchema,
53 }))
55​
56/**
57 * Normalize errors from various sources
58 */
59function normalizeError(error: unknown): { name: string; message: string } {
60 if (error instanceof Error) {
61 return { name: error.name, message: error.message }
62 }
63 if (typeof error === 'object' && error !== null) {
64 const e = error as Record<string, unknown>
65 return {
66 name: String(e.name || 'Error'),
67 message: String(e.message || JSON.stringify(error)),
68 }
69 }
70 return { name: 'Error', message: String(error) }
72​
73/**
74 * IsolateContext implementation using Cloudflare Workers
75 */
76class CloudflareIsolateContext implements IsolateContext {
77 private readonly workerUrl: string
78 private readonly authorization?: string
79 private readonly timeout: number
80 private readonly maxToolRounds: number
81 private readonly bindings: Record<string, ToolBinding>
82 private disposed = false
83​
84 constructor(
85 workerUrl: string,
86 bindings: Record<string, ToolBinding>,
87 timeout: number,
88 maxToolRounds: number,
89 authorization?: string,
90 ) {
91 this.workerUrl = workerUrl
92 this.bindings = bindings
93 this.timeout = timeout
94 this.maxToolRounds = maxToolRounds
95 this.authorization = authorization
96 }
97​
98 async execute<T = unknown>(code: string): Promise<ExecutionResult<T>> {
99 if (this.disposed) {
100 return {
101 success: false,
102 error: {
103 name: 'DisposedError',
104 message: 'Context has been disposed',
105 },
106 logs: [],
107 }
108 }
109​
110 const tools = bindingsToSchemas(this.bindings)
111 let toolResults: Record<string, ToolResultPayload> | undefined
112 let allLogs: Array<string> = []
113 let rounds = 0
114​
115 // Request/response loop for tool callbacks
116 while (rounds < this.maxToolRounds) {
117 rounds++
118​
119 const request: ExecuteRequest = {
120 code,
121 tools,
122 toolResults,
123 timeout: this.timeout,
124 }
125​
126 try {
127 const headers: Record<string, string> = {
128 'Content-Type': 'application/json',
129 }
130​
131 if (this.authorization) {
132 headers['Authorization'] = this.authorization
133 }
134​
135 const response = await fetch(this.workerUrl, {
136 method: 'POST',
137 headers,
138 body: JSON.stringify(request),
139 })
140​
141 if (!response.ok) {
142 const errorText = await response.text()
143 return {
144 success: false,
145 error: {
146 name: 'WorkerError',
147 message: `Worker returned ${response.status}: ${errorText}`,
148 },
149 logs: allLogs,
150 }
151 }
152​
153 const result: ExecuteResponse = await response.json()
154​
155 if (result.status === 'error') {
156 return {
157 success: false,
158 error: result.error,
159 logs: allLogs,
160 }
161 }
162​
163 if (result.status === 'done') {
164 allLogs = [...allLogs, ...result.logs]
165 const resultError = result.error
166 return {
167 success: result.success,
168 value: result.value as T,
169 ...(resultError !== undefined
170 ? {
171 error: {
172 name: resultError.name,
173 message: resultError.message,
174 ...(resultError.stack !== undefined
175 ? { stack: resultError.stack }
176 : {}),
177 },
178 }
179 : {}),
180 logs: allLogs,
181 }
182 }
183​
184 // status === 'need_tools'
185 // Collect logs from this round
186 allLogs = [...allLogs, ...result.logs]
187​
188 // Execute tool calls locally. Accumulate across rounds so prior-round
189 // results stay cached when the Worker re-executes user code.
190 // wrap-code uses sequential `tc_<idx>` ids re-derived every round; if
191 // we wipe the cache, multi-tool programs ping-pong between missing
192 // ids and exhaust `maxToolRounds` (MaxRoundsExceeded).
193 toolResults = { ...(toolResults ?? {}) }
194​
195 for (const toolCall of result.toolCalls) {
196 const binding = this.bindings[toolCall.name]
197​
198 if (!binding) {
199 toolResults[toolCall.id] = {
200 success: false,
201 error: `Unknown tool: ${toolCall.name}`,
202 }
203 continue
204 }
205​
206 try {
207 const toolResult = await binding.execute(toolCall.args)
208 toolResults[toolCall.id] = {
209 success: true,
210 value: toolResult,
211 }
212 } catch (toolError) {
213 const err = normalizeError(toolError)
214 toolResults[toolCall.id] = {
215 success: false,
216 error: err.message,
217 }
218 }
219 }
220​
221 // Continue loop to send results back to Worker
222 } catch (fetchError) {
223 const err = normalizeError(fetchError)
224 return {
225 success: false,
226 error: {
227 name: 'NetworkError',
228 message: `Failed to communicate with Worker: ${err.message}`,
229 },
230 logs: allLogs,
231 }
232 }
233 }
234​
235 // Max rounds exceeded
236 return {
237 success: false,
238 error: {
239 name: 'MaxRoundsExceeded',
240 message: `Exceeded maximum tool callback rounds (${this.maxToolRounds})`,
241 },
242 logs: allLogs,
243 }
244 }
245​
246 dispose(): Promise<void> {
247 this.disposed = true
248 return Promise.resolve()
249 }
251​
252/**
253 * Create a Cloudflare Workers isolate driver
254 *
255 * This driver executes code on Cloudflare's global edge network,
256 * providing true distributed execution capabilities.
257 *
258 * Tool calls are handled via a request/response loop:
259 * 1. Code is sent to the Worker
260 * 2. Worker executes until it needs a tool
261 * 3. Tool call is returned to the driver
262 * 4. Driver executes the tool locally
263 * 5. Result is sent back to the Worker
264 * 6. Worker continues execution
265 *
266 * @example
267 * ```typescript
268 * import { createCloudflareIsolateDriver } from '@tanstack/ai-isolate-cloudflare'
269 *
270 * // For local development with wrangler
271 * const driver = createCloudflareIsolateDriver({
272 * workerUrl: 'http://localhost:8787',
273 * })
274 *
275 * // For production
276 * const driver = createCloudflareIsolateDriver({
277 * workerUrl: 'https://code-mode-worker.your-account.workers.dev',
278 * authorization: 'Bearer your-secret-token',
279 * })
280 *
281 * const context = await driver.createContext({
282 * bindings: {
283 * readFile: {
284 * name: 'readFile',
285 * description: 'Read a file',
286 * inputSchema: { type: 'object', properties: { path: { type: 'string' } } },
287 * execute: async ({ path }) => fs.readFile(path, 'utf-8'),
288 * },
289 * },
290 * })
291 *
292 * const result = await context.execute(`
293 * const content = await readFile({ path: './data.json' })
294 * return JSON.parse(content)
295 * `)
296 * ```
297 */
298export function createCloudflareIsolateDriver(
299 config: CloudflareIsolateDriverConfig,
300): IsolateDriver {
301 const {
302 workerUrl,
303 authorization,
304 timeout: defaultTimeout = 30000,
305 maxToolRounds = 10,
306 } = config
307​
308 return {
309 createContext(isolateConfig: IsolateConfig): Promise<IsolateContext> {
310 const timeout = isolateConfig.timeout ?? defaultTimeout
311​
312 return Promise.resolve(
313 new CloudflareIsolateContext(
314 workerUrl,
315 isolateConfig.bindings,
316 timeout,
317 maxToolRounds,
318 authorization,
319 ),
320 )
321 },
322 }