MCPcopy Create free account
hub / github.com/TanStack/ai / executeCode

Function executeCode

packages/ai-isolate-cloudflare/src/worker/index.ts:87–203  ·  view source on GitHub ↗

* Execute code in a freshly loaded child Worker isolate.

(
  request: ExecuteRequest,
  env: Env,
)

Source from the content-addressed store, hash-verified

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 }

Callers 1

fetchFunction · 0.85

Calls 8

wrapCodeFunction · 0.90
wrapAsSandboxModuleFunction · 0.85
rejectFunction · 0.85
getEntrypointMethod · 0.80
jsonMethod · 0.80
abortMethod · 0.65
loadMethod · 0.65
fetchMethod · 0.65

Tested by

no test coverage detected