Open History to see the last commit
1/**
2 * SandboxHandle backed by a boxd KVM microVM (https://boxd.sh). Real
3 * isolation: fs/exec/git operate inside the remote machine; paths are real
4 * machine paths (default workdir `/home/boxd/workspace`).
5 *
6 * File data ops (read/write) use the machine's file API; everything else on
7 * `fs` desugars to `exec`. Blocking commands run through the SDK's one-shot
8 * `exec` (separate stdout and stderr, real exit code). Background processes run
9 * through a streaming exec wrapped in `setsid` so the process the handle spawns
10 * leads its own process group, which is what lets `kill()` reach the whole
11 * tree. See {@link spawnCommand}.
12 *
13 * Snapshots are boxd snapshots (memory + disk, org-wide, restorable into a new
14 * machine), and `fork()` is a live boxd fork (memory and running processes
15 * included).
16 */
17import { randomUUID } from 'node:crypto'
18import { createExecBackedGit } from '@tanstack/ai-sandbox'
19import type {
20 CreatedProxy,
21 CreatedSnapshot,
22 ExecParams,
23 ExecResult as BoxdExecResult,
24 Machine,
25 MachineCreateParams,
26 MachineForkParams,
27 Proxy as BoxdProxy,
28 Snapshot,
29 StreamExecParams,
30 UploadSource,
31 WaitUntilReadyParams,
32} from '@boxd-sh/sdk'
33import type {
34 ExecResult,
35 ProcessOptions,
36 SandboxCapabilities,
37 SandboxChannel,
38 SandboxFsStat,
39 SandboxHandle,
40 SnapshotRef,
41 SpawnHandle,
42} from '@tanstack/ai-sandbox'
43
44export const BOXD_CAPS: SandboxCapabilities = {
45 fs: true,
46 exec: true,
47 env: true,
48 ports: true,
49 // A streaming exec keeps its process alive for as long as the stream is open,
50 // and (measured) closing the stream does NOT end the process, so a spawned
51 // process outlives the call that started it. `kill()` is the only way down.
52 backgroundProcesses: true,
53 // A streaming exec's stdin is writable (`write`/`end`). Measured: a spawned
54 // `sh` runs lines written to it, and a spawned `cat` exits on `end()`.
55 writableStdin: true,
56 // MEASURED against production boxd. `kill()` runs a shell inside the machine
57 // that signals the process GROUP the spawn wrapper leads (`setsid`, see
58 // `spawnCommand`), escalates to `KILL`, and verifies with `kill -0`. Closing
59 // the stream on its own is not a kill: the process survived it, so that is
60 // never what `kill()` relies on. `tests/journal.conformance.test.ts` runs the
61 // follow cases against a real machine whenever `BOXD_API_KEY` is present.
62 killableProcesses: true,
63 // boxd snapshots capture memory + disk and restore into a NEW machine, so
64 // `restoreSnapshot` reconstructs a sandbox after the original is gone.
65 snapshots: true,
66 networkPolicy: false,
67 // The 100 GB disk persists across stop/start, suspend/resume and hibernate.
68 durableFilesystem: true,
69 // `machines.fork` clones disk, memory and running processes in ~100-600 ms.
70 fork: true,
71}
72
73export const DEFAULT_WORKDIR = '/home/boxd/workspace'
74
75/** Anything with a `warn(message, meta?)`; the `InternalLogger` adapters get works. */
76export interface BoxdLogger {
77 warn: (message: string, meta?: Record<string, unknown>) => void
78}
79
80/** A live streaming exec: the subset of the SDK's `ExecStream` the handle uses. */
81export interface BoxdExecStream {
82 readonly stdout: AsyncIterable<Uint8Array>
83 readonly stderr: AsyncIterable<Uint8Array>
84 write: (data: string | Uint8Array) => void
85 end: () => void
86 wait: () => Promise<number>
87 close: () => void
88}
89
90/** The subset of the SDK client the provider and handle call. `new Boxd()` satisfies it. */
91export interface BoxdClientLike {
92 machines: {
93 create: (params: MachineCreateParams) => Promise<Machine>
94 get: (id: string) => Promise<Machine>
95 delete: (id: string) => Promise<void>
96 start: (id: string) => Promise<void>
97 wake: (id: string) => Promise<void>
98 resume: (id: string) => Promise<{ resumeUs: number }>
99 fork: (id: string, params?: MachineForkParams) => Promise<Machine>
100 exec: (id: string, params: ExecParams) => Promise<BoxdExecResult>
101 streamExec: (id: string, params: StreamExecParams) => BoxdExecStream
102 waitUntilReady: (
103 id: string,
104 params?: WaitUntilReadyParams,
105 ) => Promise<Machine>
106 files: {
107 upload: (
108 id: string,
109 path: string,
110 source: UploadSource,
111 ) => Promise<number>
112 download: (id: string, path: string) => Promise<Uint8Array>
113 }
114 proxies: {
115 create: (
116 machine: string,
117 name: string,
118 port: number,
119 ) => Promise<CreatedProxy>
120 list: (machine: string) => Promise<Array<BoxdProxy>>
121 setPort: (
122 machine: string,
123 port: number | 'auto',
124 params?: { name?: string },
125 ) => Promise<void>
126 }
127 }
128 snapshots: {
129 create: (machine: string, name: string) => Promise<CreatedSnapshot>
130 get: (name: string, params?: { org?: string }) => Promise<Snapshot>
131 }
132}
133
134export interface BoxdHandleDeps {
135 client: BoxdClientLike
136 /** The machine as the SDK returned it; `id` is the durable resume/destroy id. */
137 machine: Pick<Machine, 'id' | 'name'> & {
138 access: Pick<Machine['access'], 'url'>
139 }
140 /** Org the machine lives in. Snapshots are looked up there. */
141 org?: string
142 /** Working directory inside the machine; the `/workspace` virtual root maps here. */
143 workdir: string
144 logger?: BoxdLogger
145 /** Env vars to carry over (a fork inherits its parent's). */
146 env?: Record<string, string>
147}
148
149/**
150 * How long `snapshot()` waits for a capture to become restorable. Measured:
151 * ~25 s for an 8 GiB machine. `create({ fromSnapshot })` refuses a capture
152 * that is still `pending`, so returning earlier would hand the framework a
153 * `SnapshotRef` it cannot use yet.
154 */
155const SNAPSHOT_READY_TIMEOUT_MS = 10 * 60 * 1000
156const SNAPSHOT_POLL_MS = 1000
157
158/**
159 * Wrap `command` so the process the streaming exec starts leads its own
160 * session and process group, and records its pid before running the command.
161 *
162 * Measured on production boxd: without `setsid` the exec'd shell sits in the
163 * exec agent's process group, `kill -- -<pid>` fails, and a `sleep` child
164 * survived the bare-pid kill: the exact leak `killableProcesses` exists to
165 * rule out. With `setsid` the recorded pid IS the group leader, so one group
166 * signal reaches the shell and every child (a `tail -f` started by a
167 * multi-statement command, `cmd & …` grandchildren).
168 *
169 * `-w` makes `setsid` wait and forward the exit status in the one case where
170 * it has to fork (the caller was already a group leader). The wrapper removes
171 * its own pid file on a normal exit; the kill shell removes it on the kill
172 * path (see {@link killRecordedPidCommand}).
173 */
174function spawnCommand(command: string, cwd: string, pidFile: string): string {
175 const inner =
176 `echo $$ > ${q(pidFile)}; bash -c ${q(command)}; rc=$?; ` +
177 `rm -f ${q(pidFile)}; exit $rc`
178 return `cd ${q(cwd)} && exec setsid -w bash -c ${q(inner)}`
179}
180
181/** Marker the kill shell prints on stderr when the process survived the kill. */
182const KILL_FAILED_MARKER = 'tanstack-sandbox-kill-failed'
183/** Marker printed when the pid file never materialised. */
184const KILL_NO_PID_MARKER = 'tanstack-sandbox-kill-no-pid'
185
186/**
187 * A prompt `kill()` can race the wrapper's `echo $$ > file` (journal-reader
188 * kills its follower the instant its abort fires), so the kill shell waits,
189 * bounded, for the file.
190 */
191const PID_WAIT_TIMEOUT_MS = 2000
192const PID_WAIT_INTERVAL_MS = 50
193/** Grace period between the requested signal and the unconditional `KILL`. */
194const KILL_ESCALATION_DELAY_MS = 200
195
196/**
197 * A `kill -<sig>` argument for a Node signal name or number. Anything
198 * unrecognized degrades to `TERM` rather than interpolating caller-influenced
199 * text into a shell command.
200 */
201function killSignalArg(signal?: NodeJS.Signals | number): string {
202 if (typeof signal === 'number' && Number.isInteger(signal) && signal > 0) {
203 return String(signal)
204 }
205 if (typeof signal === 'string') {
206 const name = signal.replace(/^SIG/, '')
207 if (/^[A-Z][A-Z0-9]*$/.test(name)) return name
208 }
209 return 'TERM'
210}
211
212/**
213 * Shell that signals the process group recorded in `pidFile`, escalates to
214 * `KILL`, verifies with `kill -0`, and removes the file. It never fails (it
215 * runs from teardown paths) but it REPORTS: a survivor prints
216 * {@link KILL_FAILED_MARKER}, a missing pid file prints
217 * {@link KILL_NO_PID_MARKER}, and {@link BoxdHandle.killRecordedPid} turns
218 * either into a logger warning. Same shape as `@tanstack/ai-sandbox-docker`.
219 */
220function killRecordedPidCommand(
221 pidFile: string,
222 signal?: NodeJS.Signals | number,
223): string {
224 const sig = killSignalArg(signal)
225 const f = q(pidFile)
226 const attempts = Math.ceil(PID_WAIT_TIMEOUT_MS / PID_WAIT_INTERVAL_MS)
227 const sleepStep = (PID_WAIT_INTERVAL_MS / 1000).toFixed(3)
228 return [
229 `pid=''`,
230 `i=0`,
231 `while [ "$i" -lt ${attempts} ]; do`,
232 ` pid=$(cat ${f} 2>/dev/null)`,
233 ` [ -n "$pid" ] && break`,
234 ` sleep ${sleepStep}`,
235 ` i=$((i+1))`,
236 `done`,
237 `if [ -n "$pid" ]; then`,
238 ` kill -${sig} -- -"$pid" 2>/dev/null || kill -${sig} "$pid" 2>/dev/null`,
239 ` sleep ${(KILL_ESCALATION_DELAY_MS / 1000).toFixed(3)}`,
240 ` kill -KILL -- -"$pid" 2>/dev/null || kill -KILL "$pid" 2>/dev/null`,
241 ` if kill -0 "$pid" 2>/dev/null; then`,
242 ` echo ${KILL_FAILED_MARKER} pid="$pid" >&2`,
243 ` fi`,
244 `else`,
245 ` echo ${KILL_NO_PID_MARKER} file=${f} >&2`,
246 `fi`,
247 `rm -f ${f}`,
248 `:`,
249 ].join('\n')
250}
251
252/**
253 * Decode a byte stream as UTF-8 text without splitting multi-byte characters
254 * across chunks: a streaming `TextDecoder` holds a partial trailing sequence
255 * until the rest arrives, then flushes once the stream ends.
256 */
257async function* decodeStream(
258 source: AsyncIterable<Uint8Array>,
259): AsyncIterable<string> {
260 const decoder = new TextDecoder('utf-8')
261 for await (const chunk of source) {
262 const text = decoder.decode(chunk, { stream: true })
263 if (text !== '') yield text
264 }
265 const tail = decoder.decode()
266 if (tail !== '') yield tail
267}
268
269/** A snapshot name label: lowercase `[a-z0-9-]`, the shape machine names use. */
270function slug(value: string): string {
271 return value
272 .toLowerCase()
273 .replace(/[^a-z0-9]+/g, '-')
274 .replace(/^-+|-+$/g, '')
275}
276
277function sleep(ms: number): Promise<void> {
278 return new Promise((resolve) => setTimeout(resolve, ms))
279}
280
281export class BoxdHandle implements SandboxHandle {
282 readonly id: string
283 readonly provider = 'boxd'
284 readonly workspaceRoot: string
285 readonly capabilities = BOXD_CAPS
286 readonly fs: SandboxHandle['fs']
287 readonly git: SandboxHandle['git']
288 readonly process: SandboxHandle['process']
289 readonly ports: SandboxHandle['ports']
290 readonly env: SandboxHandle['env']
291
292 private readonly client: BoxdClientLike
293 private readonly machineName: string
294 private readonly url: string
295 private readonly org: string | undefined
296 private readonly workdir: string
297 private readonly logger: BoxdLogger | undefined
298 private readonly envVars: Record<string, string>
299
300 constructor(private readonly deps: BoxdHandleDeps) {
301 this.client = deps.client
302 this.id = deps.machine.id
303 this.machineName = deps.machine.name
304 this.url = deps.machine.access.url
305 this.org = deps.org
306 this.workdir = deps.workdir
307 this.workspaceRoot = deps.workdir
308 this.logger = deps.logger
309 this.envVars = { ...deps.env }
310
311 this.process = {
312 exec: (command, opts) => this.exec(command, opts),
313 spawn: (command, opts) => this.spawnProcess(command, opts),
314 }
315
316 this.fs = {
317 read: async (p) =>
318 new TextDecoder().decode(
319 await this.client.machines.files.download(this.id, this.abs(p)),
320 ),
321 readBytes: (p) =>
322 this.client.machines.files.download(this.id, this.abs(p)),
323 // `upload` creates missing parent directories (measured), so no mkdir.
324 write: async (p, data) => {
325 await this.client.machines.files.upload(this.id, this.abs(p), data)
326 },
327 list: async (p) => {
328 const r = await this.exec(`ls -1Ap -- ${q(this.abs(p))}`)
329 if (r.exitCode !== 0) throw new Error(`list failed: ${errText(r)}`)
330 const base = p.replace(/\/$/, '')
331 return r.stdout
332 .split('\n')
333 .filter((line) => line !== '')
334 .map((entry) => {
335 const isDir = entry.endsWith('/')
336 const name = isDir ? entry.slice(0, -1) : entry
337 return {
338 name,
339 path: `${base}/${name}`,
340 type: isDir ? ('dir' as const) : ('file' as const),
341 }
342 })
343 },
344 lstat: async (p) => this.lstat(this.abs(p)),
345 mkdir: async (p) => {
346 const r = await this.exec(`mkdir -p -- ${q(this.abs(p))}`)
347 if (r.exitCode !== 0) throw new Error(`mkdir failed: ${errText(r)}`)
348 },
349 remove: async (p) => {
350 const r = await this.exec(`rm -rf -- ${q(this.abs(p))}`)
351 if (r.exitCode !== 0) throw new Error(`remove failed: ${errText(r)}`)
352 },
353 rename: async (from, to) => {
354 const r = await this.exec(
355 `mv -- ${q(this.abs(from))} ${q(this.abs(to))}`,
356 )
357 if (r.exitCode !== 0) throw new Error(`rename failed: ${errText(r)}`)
358 },
359 exists: async (p) => {
360 const r = await this.exec(`test -e ${q(this.abs(p))}`)
361 return r.exitCode === 0
362 },
363 }
364
365 this.git = createExecBackedGit(this.process, this.workdir)
366
367 this.ports = {
368 connect: (port) => this.connectPort(port),
369 }
370
371 this.env = {
372 set: (vars) => {
373 Object.assign(this.envVars, vars)
374 return Promise.resolve()
375 },
376 }
377 }
378
379 /** Map the conventional `/workspace` virtual root to the machine workdir. */
380 private abs(p: string): string {
381 if (this.workdir === '/workspace') return p
382 if (p === '/workspace') return this.workdir
383 if (p.startsWith('/workspace/'))
384 return `${this.workdir}/${p.slice('/workspace/'.length)}`
385 return p
386 }
387
388 private async lstat(path: string): Promise<SandboxFsStat | undefined> {
389 const r = await this.exec(lstatCommand(path))
390 if (r.exitCode === 0 && r.stdout.trim() === LSTAT_MISSING) return undefined
391 if (r.exitCode !== 0) throw new Error(`lstat failed: ${errText(r)}`)
392 return parseLstatOutput(r.stdout)
393 }
394
395 private mergedEnv(extra?: Record<string, string>): Record<string, string> {
396 return { ...this.envVars, ...extra }
397 }
398
399 private cwd(opts?: ProcessOptions): string {
400 return opts?.cwd ? this.abs(opts.cwd) : this.workdir
401 }
402
403 /**
404 * One-shot exec. The SDK call has no abort hook, so `signal` is honoured
405 * before the call only; a command already running finishes on its own.
406 * There is no client-side deadline: a 65 s command completed (measured), and
407 * the server only drops a non-PTY exec after 30 min without output.
408 */
409 private async exec(
410 command: string,
411 opts?: ProcessOptions,
412 ): Promise<ExecResult> {
413 opts?.signal?.throwIfAborted()
414 const r = await this.client.machines.exec(this.id, {
415 command: ['bash', '-c', `cd ${q(this.cwd(opts))} && ${command}`],
416 env: this.mergedEnv(opts?.env),
417 })
418 return { stdout: r.stdout, stderr: r.stderr, exitCode: r.exitCode }
419 }
420
421 private spawnProcess(
422 command: string,
423 opts?: ProcessOptions,
424 ): Promise<SpawnHandle> {
425 opts?.signal?.throwIfAborted()
426 const pidFile = `/tmp/.tanstack-sandbox-spawn-${randomUUID()}.pid`
427 const stream = this.client.machines.streamExec(this.id, {
428 command: ['bash', '-c', spawnCommand(command, this.cwd(opts), pidFile)],
429 env: this.mergedEnv(opts?.env),
430 })
431
432 // ONE KILL PER WRAPPER, and a no-op once the wrapper has exited on its own
433 // (it removed its pid file, so the kill shell would only wait for a file
434 // nothing will write and then warn about a phantom orphan).
435 const state: { exited: boolean; kill?: Promise<void> } = { exited: false }
436 const kill = (signal?: NodeJS.Signals | number): Promise<void> => {
437 if (state.exited) return Promise.resolve()
438 state.kill ??= this.killRecordedPid(pidFile, signal).finally(() =>
439 stream.close(),
440 )
441 return state.kill
442 }
443
444 const onAbort = (): void => {
445 void kill()
446 }
447 opts?.signal?.addEventListener('abort', onAbort, { once: true })
448 const exit = stream.wait().finally(() => {
449 opts?.signal?.removeEventListener('abort', onAbort)
450 if (state.kill === undefined) state.exited = true
451 })
452 exit.catch(() => undefined)
453
454 return Promise.resolve({
455 // The wrapper's pid lives in the machine; the host never sees a pid.
456 pid: -1,
457 stdout: decodeStream(stream.stdout),
458 stderr: decodeStream(stream.stderr),
459 stdin: {
460 write: (data) => {
461 stream.write(data)
462 return Promise.resolve()
463 },
464 end: () => {
465 stream.end()
466 return Promise.resolve()
467 },
468 },
469 wait: () => exit,
470 kill,
471 })
472 }
473
474 /**
475 * Signal the in-machine process group that recorded its pid to `pidFile`,
476 * and REPORT anything that says it may still be alive. Never throws: this
477 * runs from teardown paths, where a rejection would wedge the caller instead
478 * of freeing anything. But a refused kill reaches the logger, so an
479 * unkillable process is visible rather than silently assumed dead.
480 */
481 private async killRecordedPid(
482 pidFile: string,
483 signal?: NodeJS.Signals | number,
484 ): Promise<void> {
485 let result: ExecResult
486 try {
487 result = await this.exec(killRecordedPidCommand(pidFile, signal), {
488 cwd: '/',
489 })
490 } catch (error) {
491 this.logger?.warn('boxd: could not run the in-machine kill', {
492 pidFile,
493 error: error instanceof Error ? error.message : String(error),
494 })
495 return
496 }
497 if (result.stderr.includes(KILL_FAILED_MARKER)) {
498 this.logger?.warn(
499 'boxd: in-machine process survived the kill; it may be orphaned',
500 { pidFile, stderr: result.stderr.trim() },
501 )
502 } else if (result.stderr.includes(KILL_NO_PID_MARKER)) {
503 this.logger?.warn(
504 'boxd: no pid was recorded for this process, so it could not be signalled',
505 { pidFile, stderr: result.stderr.trim() },
506 )
507 }
508 }
509
510 /**
511 * Every machine has one public HTTPS route, `https://<name>.boxd.sh`, whose
512 * target port is auto-detected by default. `connect(port)` pins that route
513 * to `port` and returns the URL. The URL is public: anyone who has it can
514 * reach the port.
515 */
516 private async connectPort(port: number): Promise<SandboxChannel> {
517 await this.client.machines.proxies.setPort(this.id, port)
518 return { url: this.url }
519 }
520
521 /**
522 * Capture the machine (memory + disk) as a boxd snapshot named
523 * `<machine>-<label>`, and wait until it is restorable. Re-saving under the
524 * same label adds a version; a restore always boots the latest one. The
525 * returned `id` is the snapshot NAME, which is what `create({ fromSnapshot })`
526 * and `snapshots.get` take.
527 */
528 snapshot = async (label?: string): Promise<SnapshotRef> => {
529 const name = `${this.machineName}-${slug(label ?? 'snapshot') || 'snapshot'}`
530 await this.client.snapshots.create(this.id, name)
531 const deadline = Date.now() + SNAPSHOT_READY_TIMEOUT_MS
532 for (;;) {
533 const snap = await this.client.snapshots.get(name, this.orgParams())
534 if (snap.status === 'ready') break
535 if (snap.status === 'failed') {
536 throw new Error(`boxd: snapshot "${name}" failed to capture`)
537 }
538 if (Date.now() > deadline) {
539 throw new Error(
540 `boxd: snapshot "${name}" still pending after ${SNAPSHOT_READY_TIMEOUT_MS} ms`,
541 )
542 }
543 await sleep(SNAPSHOT_POLL_MS)
544 }
545 return { id: name, ...(label !== undefined ? { label } : {}) }
546 }
547
548 /** Live fork: disk, memory and running processes, into a new machine. */
549 fork = async (): Promise<SandboxHandle> => {
550 const machine = await this.client.machines.fork(this.id, {
551 name: `${this.machineName}-fork-${randomUUID().replace(/-/g, '').slice(0, 8)}`,
552 })
553 try {
554 const ready = await this.client.machines.waitUntilReady(machine.id)
555 return new BoxdHandle({ ...this.deps, machine: ready, env: this.envVars })
556 } catch (error) {
557 // The caller never gets a handle, so nobody else can delete this fork.
558 await this.client.machines.delete(machine.id).catch(() => {})
559 throw error
560 }
561 }
562
563 private orgParams(): { org?: string } {
564 return this.org === undefined ? {} : { org: this.org }
565 }
566
567 async destroy(): Promise<void> {
568 await this.client.machines.delete(this.id)
569 }
570}
571
572/** POSIX single-quote escape for embedding text in `bash -c`. */
573function q(value: string): string {
574 return `'${value.replace(/'/g, `'\\''`)}'`
575}
576
577function errText(r: { stdout: string; stderr: string }): string {
578 return r.stderr.trim() || r.stdout.trim() || '(no output)'
579}
580
581const LSTAT_MISSING = '__TANSTACK_LSTAT_MISSING__'
582
583/** Verify a missing path by listing parent entries. `test -e` also fails for inaccessible parents. */
584function lstatCommand(path: string): string {
585 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`
586}
587
588function parseLstatOutput(output: string): SandboxFsStat {
589 const fields = /^(?<mode>[0-9a-fA-F]{4}):(?<size>\d+)\n?$/.exec(output)
590 const mode = fields?.groups?.mode
591 const size = fields?.groups?.size
592 if (!mode || !size) throw new Error(`invalid lstat output: ${output}`)
593 const parsedMode = Number.parseInt(mode, 16)
594 const parsedSize = Number(size)
595 if (
596 !Number.isSafeInteger(parsedMode) ||
597 !Number.isSafeInteger(parsedSize) ||
598 parsedSize < 0
599 )
600 throw new Error(`invalid lstat output: ${output}`)
601 const type = parsedMode & 0xf000
602 if (type === 0x8000)
603 return { type: 'file', mode: parsedMode, size: parsedSize }
604 if (type === 0x4000) return { type: 'dir', mode: parsedMode }
605 if (type === 0xa000) return { type: 'symlink', mode: parsedMode }
606 return { type: 'other', mode: parsedMode }
607}