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

handle.ts

332 lines12.7 KB

1/**
2 * SandboxHandle backed by a Cloudflare Sandbox (Containers + Durable Objects),
3 * via `@cloudflare/sandbox`. Runs at the edge inside a Worker.
4 *
5 * fs is implemented over `exec` with chunked base64 piping (binary-safe),
6 * matching the Docker provider. The container disk is EPHEMERAL (wiped to the image on
7 * restart) and snapshots are not yet GA, so `capabilities.snapshots` and
8 * `durableFilesystem` are false — `withSandbox` re-bootstraps under the same
9 * identity across cold starts.
10 *
11 * LIMITATION: Cloudflare background processes do not expose a writable host→
12 * process stdin, so `spawn().stdin.write` throws. This is advertised via
13 * `capabilities.writableStdin: false`; harness adapters that feed a prompt over
14 * stdin (e.g. the Claude Code adapter) detect this and instead deliver the
15 * prompt via a file + shell stdin-redirection (`claude -p … < file`), which the
16 * in-container shell handles with no host-side stdin write. `exec` (one-shot)
17 * and streamed stdout from `spawn` both work fully.
18 *
19 * NOTE: not runtime-verified in this repo (requires a Workers runtime); it
20 * compiles against the real `@cloudflare/sandbox` types and follows the proven
21 * provider contract.
22 */
23import { createExecBackedGit } from '@tanstack/ai-sandbox'
24import { fsWriteCommands } from './fs-write'
25import type { Sandbox } from '@cloudflare/sandbox'
26import type {
27 ExecResult,
28 ProcessOptions,
29 SandboxCapabilities,
30 SandboxChannel,
31 SandboxHandle,
32 SpawnHandle,
33 SandboxFsStat,
34} from '@tanstack/ai-sandbox'
35​
36export const CLOUDFLARE_CAPS: SandboxCapabilities = {
37 fs: true,
38 exec: true,
39 env: true,
40 ports: true,
41 backgroundProcesses: true,
42 // No writable host→process stdin; stdin-fed harnesses use file-redirection.
43 writableStdin: false,
44 // `spawnProcess.kill()` is a no-op (see the comment in `spawnProcess`) and
45 // the caller's abort signal is never forwarded to `sandbox.exec` — on
46 // `exec` as well as `spawn` — so a spawned follower process (e.g. `tail -f`)
47 // can never be stopped by the caller here.
48 killableProcesses: false,
49 snapshots: false,
50 networkPolicy: false,
51 durableFilesystem: false,
52 fork: false,
54​
55/** POSIX single-quote escape for embedding paths in `sh -c`. */
56function q(value: string): string {
57 return `'${value.replace(/'/g, `'\\''`)}'`
59​
60const LSTAT_MISSING = '__TANSTACK_LSTAT_MISSING__'
61​
62/** Verify a missing path by listing parent entries. `test -e` also fails for inaccessible parents. */
63function lstatCommand(path: string): string {
64 return `tanstack_lstat_path=${q(path)}; tanstack_lstat_output=$(stat -c '%f:%s' -- "$tanstack_lstat_path" 2>&1); tanstack_lstat_status=$?; if [ "$tanstack_lstat_status" -eq 0 ]; then printf '%s\n' "$tanstack_lstat_output"; else tanstack_lstat_missing() { tanstack_missing_path=$1; case "$tanstack_missing_path" in /|.) return 1 ;; */*) tanstack_parent=${'$'}{tanstack_missing_path%/*}; tanstack_name=${'$'}{tanstack_missing_path##*/}; [ -n "$tanstack_parent" ] || tanstack_parent=/ ;; *) tanstack_parent=.; tanstack_name=$tanstack_missing_path ;; esac; tanstack_parent_mode=$(stat -L -c '%f' -- "$tanstack_parent" 2>/dev/null); tanstack_parent_status=$?; if [ "$tanstack_parent_status" -ne 0 ]; then tanstack_lstat_missing "$tanstack_parent"; else case "$tanstack_parent_mode" in 4[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]) case "$tanstack_parent" in /*) tanstack_find_parent=$tanstack_parent ;; *) tanstack_find_parent=./$tanstack_parent ;; esac; tanstack_match=$(find -H "$tanstack_find_parent" -mindepth 1 -maxdepth 1 -exec sh -c 'tanstack_target=$1; shift; for tanstack_candidate do [ "${'$'}{tanstack_candidate##*/}" = "$tanstack_target" ] && { printf 1; exit 0; }; done; exit 0' sh "$tanstack_name" '{}' + 2>/dev/null); tanstack_find_status=$?; [ "$tanstack_find_status" -eq 0 ] && [ -z "$tanstack_match" ] ;; *) return 1 ;; esac; fi; }; if tanstack_lstat_missing "$tanstack_lstat_path"; then printf '%s' '${LSTAT_MISSING}'; else printf '%s\n' "$tanstack_lstat_output" >&2; exit "$tanstack_lstat_status"; fi; fi`
66​
67function parseLstatOutput(output: string): SandboxFsStat {
68 const fields = /^(?<mode>[0-9a-fA-F]{4}):(?<size>\d+)\n?$/.exec(output)
69 const mode = fields?.groups?.mode
70 const size = fields?.groups?.size
71 if (!mode || !size) throw new Error(`invalid lstat output: ${output}`)
72 const parsedMode = Number.parseInt(mode, 16)
73 const parsedSize = Number(size)
74 if (
75 !Number.isSafeInteger(parsedMode) ||
76 !Number.isSafeInteger(parsedSize) ||
77 parsedSize < 0
78 )
79 throw new Error(`invalid lstat output: ${output}`)
80 const type = parsedMode & 0xf000
81 if (type === 0x8000)
82 return { type: 'file', mode: parsedMode, size: parsedSize }
83 if (type === 0x4000) return { type: 'dir', mode: parsedMode }
84 if (type === 0xa000) return { type: 'symlink', mode: parsedMode }
85 return { type: 'other', mode: parsedMode }
87​
88/** A push-driven async string queue used to adapt CF's onOutput callback. */
89class OutputQueue {
90 private readonly buffer: Array<string> = []
91 private readonly waiters: Array<(r: IteratorResult<string>) => void> = []
92 private ended = false
93​
94 push(value: string): void {
95 const waiter = this.waiters.shift()
96 if (waiter) waiter({ value, done: false })
97 else this.buffer.push(value)
98 }
99​
100 end(): void {
101 this.ended = true
102 let waiter = this.waiters.shift()
103 while (waiter) {
104 waiter({ value: undefined, done: true })
105 waiter = this.waiters.shift()
106 }
107 }
108​
109 async *[Symbol.asyncIterator](): AsyncIterator<string> {
110 while (!this.ended || this.buffer.length > 0) {
111 if (this.buffer.length > 0) {
112 yield this.buffer.shift() as string
113 continue
114 }
115 const next = await new Promise<IteratorResult<string>>((resolve) =>
116 this.waiters.push(resolve),
117 )
118 if (next.done) return
119 yield next.value
120 }
121 }
123​
124export class CloudflareHandle implements SandboxHandle {
125 readonly id: string
126 readonly provider = 'cloudflare'
127 readonly workspaceRoot: string
128 readonly capabilities = CLOUDFLARE_CAPS
129 readonly fs: SandboxHandle['fs']
130 readonly git: SandboxHandle['git']
131 readonly process: SandboxHandle['process']
132 readonly ports: SandboxHandle['ports']
133 readonly env: SandboxHandle['env']
134​
135 private readonly sandbox: Sandbox
136 private readonly workdir: string
137 private readonly previewHostname: string | undefined
138​
139 constructor(
140 id: string,
141 sandbox: Sandbox,
142 workdir: string,
143 previewHostname?: string,
144 ) {
145 this.id = id
146 this.sandbox = sandbox
147 this.workdir = workdir
148 this.workspaceRoot = workdir
149 this.previewHostname = previewHostname
150​
151 this.process = {
152 exec: (command, opts) => this.exec(command, opts),
153 spawn: (command, opts) => this.spawnProcess(command, opts),
154 }
155​
156 this.fs = {
157 read: async (p) => {
158 const r = await this.exec(`base64 ${q(this.abs(p))}`)
159 if (r.exitCode !== 0) throw new Error(`read failed: ${r.stderr.trim()}`)
160 return Buffer.from(r.stdout, 'base64').toString('utf8')
161 },
162 readBytes: async (p) => {
163 const r = await this.exec(`base64 ${q(this.abs(p))}`)
164 if (r.exitCode !== 0) throw new Error(`read failed: ${r.stderr.trim()}`)
165 return new Uint8Array(Buffer.from(r.stdout, 'base64'))
166 },
167 write: async (p, data) => {
168 for (const command of fsWriteCommands(this.abs(p), data)) {
169 const r = await this.exec(command)
170 if (r.exitCode !== 0)
171 throw new Error(`write failed: ${r.stderr.trim()}`)
172 }
173 },
174 list: async (p) => {
175 const r = await this.exec(`ls -1Ap ${q(this.abs(p))}`)
176 if (r.exitCode !== 0) throw new Error(`list failed: ${r.stderr.trim()}`)
177 return r.stdout
178 .split('\n')
179 .filter((line) => line.trim() !== '')
180 .map((entry) => {
181 const isDir = entry.endsWith('/')
182 const name = isDir ? entry.slice(0, -1) : entry
183 return {
184 name,
185 path: `${p.replace(/\/$/, '')}/${name}`,
186 type: isDir ? ('dir' as const) : ('file' as const),
187 }
188 })
189 },
190 lstat: async (p) => this.lstat(this.abs(p)),
191 mkdir: async (p) => {
192 await this.exec(`mkdir -p ${q(this.abs(p))}`)
193 },
194 remove: async (p) => {
195 await this.exec(`rm -rf ${q(this.abs(p))}`)
196 },
197 rename: async (from, to) => {
198 await this.exec(`mv ${q(this.abs(from))} ${q(this.abs(to))}`)
199 },
200 exists: async (p) => {
201 const r = await this.exec(`test -e ${q(this.abs(p))}`)
202 return r.exitCode === 0
203 },
204 }
205​
206 this.git = createExecBackedGit(this.process, this.workdir)
207​
208 this.ports = {
209 connect: (port) => this.connectPort(port),
210 }
211​
212 this.env = {
213 set: (vars) => this.sandbox.setEnvVars(vars),
214 }
215 }
216​
217 private abs(p: string): string {
218 if (this.workdir === '/workspace') return p
219 if (p === '/workspace') return this.workdir
220 if (p.startsWith('/workspace/')) {
221 return `${this.workdir}/${p.slice('/workspace/'.length)}`
222 }
223 return p
224 }
225​
226 private async lstat(path: string): Promise<SandboxFsStat | undefined> {
227 const r = await this.exec(lstatCommand(path))
228 if (r.exitCode === 0 && r.stdout.trim() === LSTAT_MISSING) return undefined
229 if (r.exitCode !== 0) {
230 throw new Error(`lstat failed: ${r.stderr.trim()}`)
231 }
232 return parseLstatOutput(r.stdout)
233 }
234​
235 private async exec(
236 command: string,
237 opts?: ProcessOptions,
238 ): Promise<ExecResult> {
239 const result = await this.sandbox.exec(command, {
240 ...(opts?.cwd ? { cwd: this.abs(opts.cwd) } : { cwd: this.workdir }),
241 ...(opts?.env ? { env: opts.env } : {}),
242 })
243 return {
244 stdout: result.stdout,
245 stderr: result.stderr,
246 exitCode: result.exitCode,
247 }
248 }
249​
250 private spawnProcess(
251 command: string,
252 opts?: ProcessOptions,
253 ): Promise<SpawnHandle> {
254 const stdout = new OutputQueue()
255 const stderr = new OutputQueue()
256​
257 // Stream over `exec({ stream: true, onOutput })` — the SAME proven command
258 // path as one-shot `exec`. The background-process API (`startProcess` +
259 // `streamProcessLogs`) does NOT deliver its `onOutput`/`onExit` callbacks
260 // here (verified under `wrangler dev`: the process runs and exits cleanly,
261 // yet no log events ever arrive), so a stdout-NDJSON harness spawned that
262 // way hangs forever. exec's streaming path emits each chunk via `onOutput`
263 // and resolves with the exit code on completion. The prompt still reaches
264 // the CLI via in-shell stdin redirection (`… < file`), which this session
265 // shell honors — `writableStdin` stays false.
266 //
267 // The caller's AbortSignal is intentionally NOT forwarded: `exec` is a
268 // Durable Object RPC and Workers RPC cannot serialize an AbortSignal
269 // ("AbortSignal serialization is not enabled"), so passing one throws
270 // before the command runs. Mid-run cancellation is therefore unavailable
271 // on this provider; a stuck run is bounded by the coordinator's watchdog
272 // and the Durable Object lifecycle instead. `kill()` is a best-effort no-op.
273 const settled = this.sandbox.exec(command, {
274 ...(opts?.cwd ? { cwd: this.abs(opts.cwd) } : { cwd: this.workdir }),
275 ...(opts?.env ? { env: opts.env } : {}),
276 stream: true,
277 onOutput: (stream, data) => {
278 if (stream === 'stdout') stdout.push(data)
279 else stderr.push(data)
280 },
281 })
282 // End the output queues once the command settles either way (so the stdout
283 // reader terminates), but let a failure REJECT `wait()` rather than masking
284 // it as a clean exit — the harness adapter turns that into a RUN_ERROR
285 // instead of a silent zero-output run.
286 const exitPromise = settled.then(
287 (result) => {
288 stdout.end()
289 stderr.end()
290 return result.exitCode
291 },
292 (error: unknown) => {
293 stdout.end()
294 stderr.end()
295 throw error
296 },
297 )
298​
299 return Promise.resolve({
300 pid: -1,
301 stdout,
302 stderr,
303 stdin: {
304 write: () =>
305 Promise.reject(
306 new Error(
307 'cloudflare: background processes do not expose stdin. Use exec(), or a stdin-capable provider (local-process / docker) for stdin-fed harnesses.',
308 ),
309 ),
310 end: () => Promise.resolve(),
311 },
312 wait: () => exitPromise,
313 kill: () => Promise.resolve(),
314 })
315 }
316​
317 private async connectPort(port: number): Promise<SandboxChannel> {
318 if (this.previewHostname === undefined) {
319 throw new Error(
320 'cloudflare: ports.connect requires a previewHostname. Pass previewHostname (your Worker request hostname) to cloudflareSandbox(...).',
321 )
322 }
323 const { url } = await this.sandbox.exposePort(port, {
324 hostname: this.previewHostname,
325 })
326 return { url }
327 }
328​
329 async destroy(): Promise<void> {
330 await this.sandbox.destroy()
331 }