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

index.ts

280 lines8.1 KB

1/**
2 * Cloudflare Worker for Code Mode execution
3 *
4 * Executes JavaScript code in a fresh V8 isolate on Cloudflare's edge network
5 * using the `worker_loader` (Dynamic Workers) binding. Tool calls round-trip
6 * to the driver via the same request/response protocol as before.
7 *
8 * Flow:
9 * 1. Receive code + tool schemas
10 * 2. Wrap user code in an ES module exporting a `fetch` handler that returns
11 * the IIFE result as JSON
12 * 3. Load the module into a child Worker via `env.LOADER.load(...)` and
13 * invoke its entrypoint
14 * 4. If tool calls are needed, return them to the driver
15 * 5. Driver executes tools locally, sends results back
16 * 6. Re-execute with tool results injected
17 * 7. Return final result
18 *
19 * `worker_loader` replaces the previous `unsafe_eval` binding, which is gated
20 * by Cloudflare for all customer accounts and unusable in production. See
21 * https://developers.cloudflare.com/dynamic-workers/ for the supported API.
22 */
23​
24import { wrapCode } from './wrap-code'
25import type { ExecuteRequest, ExecuteResponse, ToolCallRequest } from '../types'
26​
27/**
28 * Compatibility date for the loaded child Worker. Pinned at this layer so
29 * sandbox semantics don't drift with the parent Worker's compat date.
30 */
31const SANDBOX_COMPAT_DATE = '2026-05-01'
32​
33/**
34 * Worker Loader binding type.
35 *
36 * Provides dynamic-code execution by loading a module into a fresh V8
37 * isolate. Configure in wrangler.toml under `[[worker_loaders]]`. Requires a
38 * Workers Paid plan; see https://developers.cloudflare.com/dynamic-workers/.
39 */
40interface WorkerLoaderEntrypoint {
41 fetch: (request: Request) => Promise<Response>
43​
44interface LoadedWorker {
45 getEntrypoint: (name?: string) => WorkerLoaderEntrypoint
47​
48interface WorkerLoader {
49 load: (options: {
50 compatibilityDate: string
51 mainModule: string
52 modules: Record<string, string>
53 globalOutbound?: unknown
54 env?: Record<string, unknown>
55 }) => LoadedWorker
57​
58interface Env {
59 /**
60 * worker_loader (Dynamic Workers) binding. Configured in wrangler.toml
61 * under `[[worker_loaders]] binding = "LOADER"`.
62 */
63 LOADER?: WorkerLoader
65​
66/**
67 * Wrap the existing IIFE-returning string in an ES module that exposes a
68 * `fetch` handler. The child Worker's entrypoint runs the IIFE on each
69 * invocation and returns the structured result as JSON.
70 */
71function wrapAsSandboxModule(wrappedCode: string): string {
72 return `
73export default {
74 async fetch() {
75 const __result = await ${wrappedCode};
76 return new Response(JSON.stringify(__result), {
77 headers: { 'Content-Type': 'application/json' },
78 });
79 }
80};
83​
84/**
85 * Execute code in a freshly loaded child Worker isolate.
86 */
87async function executeCode(
88 request: ExecuteRequest,
89 env: Env,
90): Promise<ExecuteResponse> {
91 const { code, tools, toolResults, timeout = 30000 } = request
92​
93 if (!env.LOADER) {
94 return {
95 status: 'error',
96 error: {
97 name: 'WorkerLoaderNotAvailable',
98 message:
99 'LOADER binding is not available. ' +
100 'This Worker requires the worker_loader (Dynamic Workers) binding. ' +
101 'Declare it in wrangler.toml under [[worker_loaders]] with ' +
102 'binding = "LOADER" (Workers Paid plan required).',
103 },
104 }
105 }
106​
107 try {
108 const wrappedCode = wrapCode(code, tools, toolResults)
109 const moduleSource = wrapAsSandboxModule(wrappedCode)
110​
111 // AbortController propagates into the loaded Worker via Request.signal so
112 // a timeout actually cancels the in-flight fetch instead of leaking the
113 // child isolate. The Promise.race remains as a belt-and-suspenders guard
114 // for runtimes that ignore the signal.
115 const controller = new AbortController()
116 let timeoutId: ReturnType<typeof setTimeout> | undefined
117 const TIMEOUT_SENTINEL = '__SANDBOX_TIMEOUT__'
118 const timeoutPromise = new Promise<never>((_resolve, reject) => {
119 timeoutId = setTimeout(() => {
120 controller.abort()
121 reject(new Error(TIMEOUT_SENTINEL))
122 }, timeout)
123 })
124​
125 try {
126 const loaded = env.LOADER.load({
127 compatibilityDate: SANDBOX_COMPAT_DATE,
128 mainModule: 'main.js',
129 modules: { 'main.js': moduleSource },
130 globalOutbound: null,
131 env: {},
132 })
133 const entrypoint = loaded.getEntrypoint()
134 const fetchPromise = entrypoint.fetch(
135 new Request('https://sandbox.invalid/', { signal: controller.signal }),
136 )
137 const response = await Promise.race([fetchPromise, timeoutPromise])
138 if (timeoutId) clearTimeout(timeoutId)
139​
140 const result: {
141 status: string
142 success?: boolean
143 value?: unknown
144 error?: { name: string; message: string; stack?: string }
145 logs: Array<string>
146 toolCalls?: Array<ToolCallRequest>
147 } = await response.json()
148​
149 if (result.status === 'need_tools') {
150 return {
151 status: 'need_tools',
152 toolCalls: result.toolCalls || [],
153 logs: result.logs,
154 continuationId: crypto.randomUUID(),
155 }
156 }
157​
158 return {
159 status: 'done',
160 success: result.success ?? false,
161 value: result.value,
162 error: result.error,
163 logs: result.logs,
164 }
165 } catch (evalError: unknown) {
166 if (timeoutId) clearTimeout(timeoutId)
167 const error = evalError as Error
168​
169 // Either branch of the Promise.race may win on timeout: timeoutPromise
170 // rejects with TIMEOUT_SENTINEL, while the AbortController.abort() call
171 // can race-reject the in-flight fetch first. Treat both as a timeout.
172 if (error.message === TIMEOUT_SENTINEL || controller.signal.aborted) {
173 return {
174 status: 'error',
175 error: {
176 name: 'TimeoutError',
177 message: `Execution timed out after ${timeout}ms`,
178 },
179 }
180 }
181​
182 return {
183 status: 'done',
184 success: false,
185 error: {
186 name: error.name || 'EvalError',
187 message: error.message || String(error),
188 stack: error.stack,
189 },
190 logs: [],
191 }
192 }
193 } catch (error: unknown) {
194 const err = error as Error
195 return {
196 status: 'error',
197 error: {
198 name: err.name || 'Error',
199 message: err.message || String(err),
200 },
201 }
202 }
204​
205/**
206 * Main Worker fetch handler
207 */
208export default {
209 async fetch(
210 request: Request,
211 env: Env,
212 _ctx: ExecutionContext,
213 ): Promise<Response> {
214 // Handle CORS preflight
215 if (request.method === 'OPTIONS') {
216 return new Response(null, {
217 headers: {
218 'Access-Control-Allow-Origin': '*',
219 'Access-Control-Allow-Methods': 'POST, OPTIONS',
220 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
221 },
222 })
223 }
224​
225 // Only accept POST requests
226 if (request.method !== 'POST') {
227 return new Response(JSON.stringify({ error: 'Method not allowed' }), {
228 status: 405,
229 headers: {
230 'Content-Type': 'application/json',
231 'Access-Control-Allow-Origin': '*',
232 },
233 })
234 }
235​
236 try {
237 const body: ExecuteRequest = await request.json()
238​
239 // Validate request
240 if (!body.code || typeof body.code !== 'string') {
241 return new Response(JSON.stringify({ error: 'Code is required' }), {
242 status: 400,
243 headers: {
244 'Content-Type': 'application/json',
245 'Access-Control-Allow-Origin': '*',
246 },
247 })
248 }
249​
250 // Execute the code
251 const result = await executeCode(body, env)
252​
253 return new Response(JSON.stringify(result), {
254 status: 200,
255 headers: {
256 'Content-Type': 'application/json',
257 'Access-Control-Allow-Origin': '*',
258 },
259 })
260 } catch (error: unknown) {
261 const err = error as Error
262 return new Response(
263 JSON.stringify({
264 status: 'error',
265 error: {
266 name: 'RequestError',
267 message: err.message || 'Failed to process request',
268 },
269 }),
270 {
271 status: 500,
272 headers: {
273 'Content-Type': 'application/json',
274 'Access-Control-Allow-Origin': '*',
275 },
276 },
277 )
278 }
279 },