Open History to see the last commit
1/**
2 * SandboxHandle backed by a Vercel Sandbox microVM (via `@vercel/sandbox`).
3 * Real isolation: fs/exec/git operate inside the remote microVM; paths are real
4 * sandbox paths (default workdir `/vercel/sandbox`).
5 *
6 * Vercel's `runCommand` executes a program directly (no implicit shell), so we
7 * run shell command strings as `sh -c "<command>"`. fs is implemented over that
8 * exec with chunked base64 piping (binary-safe); the runtime image provides
9 * `sh`, `base64`, and coreutils.
10 */
11import {
12 UnsupportedCapabilityError,
13 createExecBackedGit,
14} from '@tanstack/ai-sandbox'
15import { fsWriteCommands } from './fs-write'
16import type { Command, Sandbox } from '@vercel/sandbox'
17import type {
18 ExecResult,
19 ProcessOptions,
20 SandboxCapabilities,
21 SandboxChannel,
22 SandboxHandle,
23 SpawnHandle,
24 SandboxFsStat,
25} from '@tanstack/ai-sandbox'
26
27export const VERCEL_CAPS: SandboxCapabilities = {
28 fs: true,
29 exec: true,
30 env: true,
31 ports: true,
32 backgroundProcesses: true,
33 // Vercel detached commands stream logs out but expose no host→process stdin,
34 // so adapters that feed a prompt over stdin must use a file + shell redirect.
35 writableStdin: false,
36 // FALSE, and it must not be flipped back without a MEASUREMENT against a real
37 // sandbox. It read `true` on the claim that aborting the `signal` threaded into
38 // `sandbox.runCommand` tears the detached command down. That claim is false, and
39 // it is false in the SDK's own source rather than merely unproven: in
40 // `@vercel/sandbox`'s `session.runCommand`, the `detached` branch forwards
41 // `signal` to `client.runCommand` — the HTTP request that STARTS the command —
42 // and to `pipeLogs`, which returns immediately here because this handle passes
43 // no `stdout`/`stderr` writables. That start request has already resolved by the
44 // time `spawnProcess` returns, so the abort had nothing left to cancel and
45 // `kill()` was a total no-op that left the remote process running. Same shape as
46 // the docker defect: a client-side detach advertised as a kill.
47 //
48 // `kill()` now calls the SDK's real `Command.kill` (a server-side kill), so it
49 // is no longer a no-op — but what that endpoint signals is undocumented, and
50 // `journalFollowCommand` is a THREE-statement shell command
51 // (`mkdir …; : >> …; tail -f …`), so no shell can exec-optimize it and the
52 // `tail -f` is necessarily a CHILD of the `sh` that `runCommand` started. If the
53 // kill is pid-only rather than process-group-wide, every follow read leaks a
54 // `tail -f` — which is exactly the local-process defect. Until that is measured
55 // (see `tests/journal.conformance.test.ts`, gated on real credentials) this stays
56 // false and `journalReadStrategy` picks the slower-but-correct `'poll'`.
57 killableProcesses: false,
58 snapshots: false,
59 networkPolicy: false,
60 // The microVM filesystem persists for the sandbox's lifetime.
61 durableFilesystem: true,
62 fork: false,
63}
64
65/** POSIX single-quote escape for embedding paths in `sh -c`. */
66function q(value: string): string {
67 return `'${value.replace(/'/g, `'\\''`)}'`
68}
69const LSTAT_MISSING = '__TANSTACK_LSTAT_MISSING__'
70
71/** Verify a missing path by listing parent entries. `test -e` also fails for inaccessible parents. */
72function lstatCommand(path: string): string {
73 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`
74}
75function parseLstatOutput(output: string): SandboxFsStat {
76 const fields = /^(?<mode>[0-9a-fA-F]{4}):(?<size>\d+)\n?$/.exec(output)
77 const mode = fields?.groups?.mode
78 const size = fields?.groups?.size
79 if (!mode || !size) throw new Error(`invalid lstat output: ${output}`)
80 const parsedMode = Number.parseInt(mode, 16)
81 const parsedSize = Number(size)
82 if (
83 !Number.isSafeInteger(parsedMode) ||
84 !Number.isSafeInteger(parsedSize) ||
85 parsedSize < 0
86 )
87 throw new Error(`invalid lstat output: ${output}`)
88 const type = parsedMode & 0xf000
89 if (type === 0x8000)
90 return { type: 'file', mode: parsedMode, size: parsedSize }
91 if (type === 0x4000) return { type: 'dir', mode: parsedMode }
92 if (type === 0xa000) return { type: 'symlink', mode: parsedMode }
93 return { type: 'other', mode: parsedMode }
94}
95
96/**
97 * A push-driven async iterable. The streamer pushes decoded chunks and calls
98 * `end()` once; consumers `for await` over it and terminate cleanly.
99 */
100class AsyncChunkQueue implements AsyncIterable<string> {
101 private readonly chunks: Array<string> = []
102 private readonly waiters: Array<(r: IteratorResult<string>) => void> = []
103 private ended = false
104
105 push(chunk: string): void {
106 if (chunk === '') return
107 const waiter = this.waiters.shift()
108 if (waiter) waiter({ value: chunk, done: false })
109 else this.chunks.push(chunk)
110 }
111
112 end(): void {
113 this.ended = true
114 let waiter = this.waiters.shift()
115 while (waiter) {
116 waiter({ value: undefined, done: true })
117 waiter = this.waiters.shift()
118 }
119 }
120
121 [Symbol.asyncIterator](): AsyncIterator<string> {
122 return {
123 next: () => {
124 const chunk = this.chunks.shift()
125 if (chunk !== undefined) {
126 return Promise.resolve({ value: chunk, done: false })
127 }
128 if (this.ended) {
129 return Promise.resolve({ value: undefined, done: true })
130 }
131 return new Promise((resolve) => this.waiters.push(resolve))
132 },
133 }
134 }
135}
136
137export interface VercelHandleDeps {
138 /** The live Vercel sandbox object. */
139 sandbox: Sandbox
140 /** Working directory inside the sandbox (the `/workspace` virtual root maps here). */
141 workdir: string
142 /** Ports declared at create time (reachable via `sandbox.domain(port)`). */
143 ports: Array<number>
144}
145
146export class VercelHandle implements SandboxHandle {
147 readonly id: string
148 readonly provider = 'vercel'
149 readonly workspaceRoot: string
150 readonly capabilities = VERCEL_CAPS
151 readonly fs: SandboxHandle['fs']
152 readonly git: SandboxHandle['git']
153 readonly process: SandboxHandle['process']
154 readonly ports: SandboxHandle['ports']
155 readonly env: SandboxHandle['env']
156
157 private readonly sandbox: Sandbox
158 private readonly workdir: string
159 private readonly exposedPorts: Array<number>
160 private readonly envVars: Record<string, string> = {}
161
162 constructor(deps: VercelHandleDeps) {
163 this.sandbox = deps.sandbox
164 this.workdir = deps.workdir
165 this.workspaceRoot = deps.workdir
166 this.exposedPorts = deps.ports
167 // v2 of `@vercel/sandbox` identifies a sandbox by its `name`; that name is
168 // what `Sandbox.get({ name })` reconnects with.
169 this.id = deps.sandbox.name
170
171 this.process = {
172 exec: (command, opts) => this.exec(command, opts),
173 spawn: (command, opts) => this.spawnProcess(command, opts),
174 }
175
176 this.fs = {
177 read: async (p) => {
178 const r = await this.exec(`base64 ${q(this.abs(p))}`)
179 if (r.exitCode !== 0) throw new Error(`read failed: ${r.stderr.trim()}`)
180 return Buffer.from(r.stdout, 'base64').toString('utf8')
181 },
182 readBytes: async (p) => {
183 const r = await this.exec(`base64 ${q(this.abs(p))}`)
184 if (r.exitCode !== 0) throw new Error(`read failed: ${r.stderr.trim()}`)
185 return new Uint8Array(Buffer.from(r.stdout, 'base64'))
186 },
187 write: async (p, data) => {
188 for (const command of fsWriteCommands(this.abs(p), data)) {
189 const r = await this.exec(command)
190 if (r.exitCode !== 0)
191 throw new Error(`write failed: ${r.stderr.trim()}`)
192 }
193 },
194 list: async (p) => {
195 const r = await this.exec(`ls -1Ap ${q(this.abs(p))}`)
196 if (r.exitCode !== 0) throw new Error(`list failed: ${r.stderr.trim()}`)
197 return r.stdout
198 .split('\n')
199 .filter((line) => line.trim() !== '')
200 .map((entry) => {
201 const isDir = entry.endsWith('/')
202 const name = isDir ? entry.slice(0, -1) : entry
203 return {
204 name,
205 path: `${p.replace(/\/$/, '')}/${name}`,
206 type: isDir ? ('dir' as const) : ('file' as const),
207 }
208 })
209 },
210 lstat: async (p) => this.lstat(this.abs(p)),
211 mkdir: async (p) => {
212 await this.exec(`mkdir -p ${q(this.abs(p))}`)
213 },
214 remove: async (p) => {
215 await this.exec(`rm -rf ${q(this.abs(p))}`)
216 },
217 rename: async (from, to) => {
218 await this.exec(`mv ${q(this.abs(from))} ${q(this.abs(to))}`)
219 },
220 exists: async (p) => {
221 const r = await this.exec(`test -e ${q(this.abs(p))}`)
222 return r.exitCode === 0
223 },
224 }
225
226 this.git = createExecBackedGit(this.process, this.workdir)
227
228 this.ports = {
229 connect: (port) => this.connectPort(port),
230 }
231
232 this.env = {
233 set: (vars) => {
234 Object.assign(this.envVars, vars)
235 return Promise.resolve()
236 },
237 }
238 }
239
240 /** Map the conventional `/workspace` virtual root to the sandbox workdir. */
241 private abs(p: string): string {
242 if (this.workdir === '/workspace') return p
243 if (p === '/workspace') return this.workdir
244 if (p.startsWith('/workspace/'))
245 return `${this.workdir}/${p.slice('/workspace/'.length)}`
246 return p
247 }
248
249 private async lstat(path: string): Promise<SandboxFsStat | undefined> {
250 const r = await this.exec(lstatCommand(path))
251 if (r.exitCode === 0 && r.stdout.trim() === LSTAT_MISSING) return undefined
252 if (r.exitCode !== 0) {
253 throw new Error(`lstat failed: ${r.stderr.trim()}`)
254 }
255 return parseLstatOutput(r.stdout)
256 }
257
258 private mergedEnv(extra?: Record<string, string>): Record<string, string> {
259 return { ...this.envVars, ...extra }
260 }
261
262 private async exec(
263 command: string,
264 opts?: ProcessOptions,
265 ): Promise<ExecResult> {
266 const finished = await this.sandbox.runCommand({
267 cmd: 'sh',
268 args: ['-c', command],
269 cwd: opts?.cwd ? this.abs(opts.cwd) : this.workdir,
270 env: this.mergedEnv(opts?.env),
271 ...(opts?.signal ? { signal: opts.signal } : {}),
272 })
273 const [stdout, stderr] = await Promise.all([
274 finished.output('stdout'),
275 finished.output('stderr'),
276 ])
277 return { stdout, stderr, exitCode: finished.exitCode }
278 }
279
280 private async spawnProcess(
281 command: string,
282 opts?: ProcessOptions,
283 ): Promise<SpawnHandle> {
284 const controller = new AbortController()
285 // Bounds the START request only — see the `killableProcesses` comment. Once
286 // `runCommand` has resolved this signal can no longer reach the process.
287 const abortStart = (): void => controller.abort()
288 opts?.signal?.addEventListener('abort', abortStart, { once: true })
289
290 const cmd: Command = await this.sandbox.runCommand({
291 cmd: 'sh',
292 args: ['-c', command],
293 cwd: opts?.cwd ? this.abs(opts.cwd) : this.workdir,
294 env: this.mergedEnv(opts?.env),
295 detached: true,
296 signal: controller.signal,
297 })
298
299 // Terminate the REMOTE command and then detach locally. `Command.kill` is the
300 // SDK's server-side kill (`POST killCommand`); aborting `controller` alone
301 // reaches nothing once the start request has resolved, which is why `kill()`
302 // used to leave the process running. Registered only after `runCommand`
303 // resolves, because `cmd` is what carries the kill.
304 const terminate = async (): Promise<void> => {
305 controller.abort()
306 try {
307 await cmd.kill('SIGKILL')
308 } catch {
309 // Teardown path: the command may already have exited (so the kill 404s)
310 // and the caller has stopped caring about it either way. A throw here
311 // would wedge the caller instead of freeing anything.
312 }
313 }
314 if (opts?.signal) {
315 if (opts.signal.aborted) void terminate()
316 else {
317 opts.signal.addEventListener('abort', () => void terminate(), {
318 once: true,
319 })
320 }
321 }
322
323 const stdoutQ = new AsyncChunkQueue()
324 const stderrQ = new AsyncChunkQueue()
325
326 // Fan the single interleaved log stream out into stdout/stderr iterables.
327 const pump = (async (): Promise<void> => {
328 try {
329 for await (const log of cmd.logs()) {
330 if (log.stream === 'stderr') stderrQ.push(log.data)
331 else stdoutQ.push(log.data)
332 }
333 } catch {
334 // Stream torn down (kill/abort) — fall through and close the queues.
335 } finally {
336 stdoutQ.end()
337 stderrQ.end()
338 }
339 })()
340
341 return {
342 pid: -1, // Vercel commands do not surface a host-visible pid.
343 stdout: stdoutQ,
344 stderr: stderrQ,
345 stdin: {
346 write: () =>
347 Promise.reject(
348 new Error(
349 'vercel: background process stdin is not writable (see capabilities.writableStdin)',
350 ),
351 ),
352 end: () => Promise.resolve(),
353 },
354 wait: async () => {
355 const finished = await cmd.wait()
356 await pump
357 return finished.exitCode
358 },
359 kill: () => terminate(),
360 }
361 }
362
363 private connectPort(port: number): Promise<SandboxChannel> {
364 if (!this.exposedPorts.includes(port)) {
365 return Promise.reject(
366 new Error(
367 `vercel: port ${port} is not exposed. Pass ports: [${port}] to vercelSandbox() so it can be reached via sandbox.domain().`,
368 ),
369 )
370 }
371 return Promise.resolve({ url: this.sandbox.domain(port) })
372 }
373
374 // Vercel snapshots/fork are not wired through the uniform handle yet.
375 snapshot = undefined
376
377 fork = (): Promise<SandboxHandle> => {
378 throw new UnsupportedCapabilityError('vercel', 'fork')
379 }
380
381 async destroy(): Promise<void> {
382 await this.sandbox.stop()
383 }
384}