Open History to see the last commit
1/**
2 * SandboxHandle backed by a Sprites stateful sandbox. Real isolation:
3 * fs/exec/git operate inside the remote Sprite; paths are real Sprite paths
4 * (default workdir `/home/sprite`).
5 *
6 * Filesystem data ops (read/write/list) use the Sprite's native `/fs` endpoints;
7 * metadata ops (mkdir/remove/rename/exists) desugar to `exec`. Commands run over
8 * the Sprite exec control WebSocket, which streams stdout and stderr separately
9 * — except for near-instant commands, where the Sprite agent's "fast path"
10 * replays buffered output as a single stdout stream (stderr content folds into
11 * stdout; the exit code is preserved).
12 *
13 * Checkpoints (filesystem-overlay save points) are exposed via {@link snapshot}
14 * (create) and {@link restoreCheckpoint} / {@link listCheckpoints}. Restore is
15 * in-place and restarts the Sprite.
16 */
17import {
18 UnsupportedCapabilityError,
19 createExecBackedGit,
20} from '@tanstack/ai-sandbox'
21import type {
22 ExecResult,
23 ProcessOptions,
24 SandboxCapabilities,
25 SandboxChannel,
26 SandboxHandle,
27 SnapshotRef,
28 SpawnHandle,
29 SandboxFsStat,
30} from '@tanstack/ai-sandbox'
31import type {
32 SpriteCheckpoint,
33 SpriteUrlAuth,
34 SpritesClientLike,
35} from './client'
36
37export const SPRITES_CAPS: SandboxCapabilities = {
38 fs: true,
39 exec: true,
40 env: true,
41 ports: true,
42 backgroundProcesses: true,
43 // The Sprite exec socket streams output but does not expose a host→process
44 // stdin channel here, so adapters that feed a prompt over stdin must deliver
45 // it via a file + shell redirection instead.
46 writableStdin: false,
47 // UNVERIFIED AGAINST A LIVE SPRITE, and deliberately still `true` — unlike the
48 // docker / local-process / vercel / daytona declarations, this one does NOT rest
49 // on a client-side detach. `spawnProcess.kill()` delegates to the exec stream's
50 // `kill()`, which resolves the session id (waiting up to 5s for the
51 // `session_info` frame) and issues a real SERVER-side
52 // `POST /v1/sprites/<name>/exec/<sessionId>/kill` BEFORE closing the socket; the
53 // caller's `signal` runs the same path. Dropping the WebSocket alone would be the
54 // proven-broken shape, and `client.ts` is explicit that it must not be (see
55 // `terminate`, and the two `client.test.ts` cases that assert the kill endpoint
56 // is hit — including when the kill races ahead of `session_info`).
57 //
58 // What is NOT established, and cannot be from here, is WHAT that endpoint
59 // signals. Sprites publishes no SDK or docs in this repo, so whether the kill is
60 // process-group-wide or pid-only is unknown, and `journalFollowCommand` is a
61 // three-statement command (`mkdir …; : >> …; tail -f …`) that no shell can
62 // exec-optimize — so the `tail -f` is necessarily a CHILD of the `bash -c` this
63 // handle spawns. A pid-only kill would therefore leak a `tail -f` per follow read,
64 // which is precisely the local-process defect. `killSession` also swallows a
65 // non-2xx response, so a refused kill is silent.
66 //
67 // Measuring it needs a live Sprite: `tests/journal.conformance.test.ts` registers
68 // the follow cases and runs them the moment `SPRITES_API_KEY` is present,
69 // reporting a NAMED skip until then. Do not read this `true` as measured.
70 killableProcesses: true,
71 // Sprites checkpoints capture the writable filesystem overlay. Exposed via
72 // `snapshot()` (create) and the provider-specific `restoreCheckpoint()` /
73 // `listCheckpoints()`. Note: restore is in-place on the same Sprite, and a
74 // checkpoint does not survive Sprite deletion — so `SandboxProvider`'s
75 // reconstruct-after-gone `restoreSnapshot` is intentionally not implemented
76 // (the framework degrades to a fresh create instead).
77 snapshots: true,
78 networkPolicy: false,
79 // The Sprite filesystem persists for the sandbox's lifetime (across exec
80 // calls and idle suspend/resume) until it is deleted.
81 durableFilesystem: true,
82 fork: false,
83}
84
85/** The single internal HTTP port a Sprite proxies to its public URL. */
86export const SPRITE_DEFAULT_HTTP_PORT = 8080
87
88async function collect(stream: AsyncIterable<string>): Promise<string> {
89 let out = ''
90 for await (const chunk of stream) out += chunk
91 return out
92}
93
94export interface SpritesHandleDeps {
95 client: SpritesClientLike
96 /** Sprite name — the durable id used to reconnect/destroy. */
97 name: string
98 /** Public URL of the Sprite (`https://<name>-<suffix>.sprites.app`). */
99 url: string
100 /** Working directory inside the Sprite; the `/workspace` virtual root maps here. */
101 workdir: string
102 /** Internal port proxied to the public URL. Defaults to 8080. */
103 httpPort?: number
104 /**
105 * The Sprite's URL auth mode. `ports.connect()` returns a token-authenticated
106 * channel when this is `'sprite'`, and a plain public URL when `'public'`;
107 * it never mutates the mode. Defaults to `'public'`.
108 */
109 urlAuth?: SpriteUrlAuth
110}
111
112export class SpritesHandle implements SandboxHandle {
113 readonly id: string
114 readonly provider = 'sprites'
115 readonly workspaceRoot: string
116 readonly capabilities = SPRITES_CAPS
117 readonly fs: SandboxHandle['fs']
118 readonly git: SandboxHandle['git']
119 readonly process: SandboxHandle['process']
120 readonly ports: SandboxHandle['ports']
121 readonly env: SandboxHandle['env']
122
123 private readonly client: SpritesClientLike
124 private readonly name: string
125 private readonly url: string
126 private readonly workdir: string
127 private readonly httpPort: number
128 private readonly urlAuth: SpriteUrlAuth
129 private readonly envVars: Record<string, string> = {}
130
131 constructor(deps: SpritesHandleDeps) {
132 this.client = deps.client
133 this.name = deps.name
134 this.url = deps.url
135 this.workdir = deps.workdir
136 this.workspaceRoot = deps.workdir
137 this.httpPort = deps.httpPort ?? SPRITE_DEFAULT_HTTP_PORT
138 this.urlAuth = deps.urlAuth ?? 'public'
139 this.id = deps.name
140
141 this.process = {
142 exec: (command, opts) => this.exec(command, opts),
143 spawn: (command, opts) => this.spawnProcess(command, opts),
144 }
145
146 this.fs = {
147 read: async (p) =>
148 new TextDecoder().decode(
149 await this.client.fsRead(this.name, this.abs(p)),
150 ),
151 readBytes: (p) => this.client.fsRead(this.name, this.abs(p)),
152 write: (p, data) =>
153 this.client.fsWrite(
154 this.name,
155 this.abs(p),
156 typeof data === 'string' ? new TextEncoder().encode(data) : data,
157 ),
158 list: async (p) => {
159 const entries = await this.client.fsList(this.name, this.abs(p))
160 // Native paths are absolute Sprite paths; re-root them under the
161 // caller's virtual path so consumers stay provider-agnostic.
162 const base = p.replace(/\/$/, '')
163 return entries.map((entry) => ({
164 name: entry.name,
165 path: `${base}/${entry.name}`,
166 type: entry.type,
167 }))
168 },
169 lstat: async (p) => this.lstat(this.abs(p)),
170 mkdir: async (p) => {
171 const r = await this.exec(`mkdir -p ${q(this.abs(p))}`)
172 if (r.exitCode !== 0) throw new Error(`mkdir failed: ${errText(r)}`)
173 },
174 remove: async (p) => {
175 const r = await this.exec(`rm -rf ${q(this.abs(p))}`)
176 if (r.exitCode !== 0) throw new Error(`remove failed: ${errText(r)}`)
177 },
178 rename: async (from, to) => {
179 const r = await this.exec(`mv ${q(this.abs(from))} ${q(this.abs(to))}`)
180 if (r.exitCode !== 0) throw new Error(`rename failed: ${errText(r)}`)
181 },
182 exists: async (p) => {
183 const r = await this.exec(`test -e ${q(this.abs(p))}`)
184 return r.exitCode === 0
185 },
186 }
187
188 this.git = createExecBackedGit(this.process, this.workdir)
189
190 this.ports = {
191 connect: (port) => this.connectPort(port),
192 }
193
194 this.env = {
195 set: (vars) => {
196 Object.assign(this.envVars, vars)
197 return Promise.resolve()
198 },
199 }
200 }
201
202 /** Map the conventional `/workspace` virtual root to the Sprite workdir. */
203 private abs(p: string): string {
204 if (this.workdir === '/workspace') return p
205 if (p === '/workspace') return this.workdir
206 if (p.startsWith('/workspace/'))
207 return `${this.workdir}/${p.slice('/workspace/'.length)}`
208 return p
209 }
210
211 private async lstat(path: string): Promise<SandboxFsStat | undefined> {
212 const r = await this.exec(lstatCommand(path))
213 if (r.exitCode === 0 && r.stdout.trim() === LSTAT_MISSING) return undefined
214 if (r.exitCode !== 0) {
215 throw new Error(`lstat failed: ${errText(r)}`)
216 }
217 return parseLstatOutput(r.stdout)
218 }
219
220 private mergedEnv(extra?: Record<string, string>): Record<string, string> {
221 return { ...this.envVars, ...extra }
222 }
223
224 private async exec(
225 command: string,
226 opts?: ProcessOptions,
227 ): Promise<ExecResult> {
228 const stream = this.client.exec(this.name, {
229 argv: ['bash', '-c', command],
230 cwd: opts?.cwd ? this.abs(opts.cwd) : this.workdir,
231 env: this.mergedEnv(opts?.env),
232 ...(opts?.signal ? { signal: opts.signal } : {}),
233 })
234 const [stdout, stderr, exitCode] = await Promise.all([
235 collect(stream.stdout),
236 collect(stream.stderr),
237 stream.wait(),
238 ])
239 return { stdout, stderr, exitCode }
240 }
241
242 private spawnProcess(
243 command: string,
244 opts?: ProcessOptions,
245 ): Promise<SpawnHandle> {
246 const stream = this.client.exec(this.name, {
247 argv: ['bash', '-c', command],
248 cwd: opts?.cwd ? this.abs(opts.cwd) : this.workdir,
249 env: this.mergedEnv(opts?.env),
250 ...(opts?.signal ? { signal: opts.signal } : {}),
251 })
252 return Promise.resolve({
253 pid: -1, // Sprite exec sessions do not surface a host-visible pid.
254 stdout: stream.stdout,
255 stderr: stream.stderr,
256 stdin: {
257 write: () =>
258 Promise.reject(
259 new Error(
260 'sprites: background process stdin is not writable (see capabilities.writableStdin)',
261 ),
262 ),
263 end: () => Promise.resolve(),
264 },
265 wait: () => stream.wait(),
266 kill: () => stream.kill(),
267 })
268 }
269
270 private connectPort(port: number): Promise<SandboxChannel> {
271 if (port !== this.httpPort) {
272 return Promise.reject(
273 new Error(
274 `sprites: only the proxied HTTP port ${this.httpPort} is reachable via the public URL; port ${port} is not exposed.`,
275 ),
276 )
277 }
278 // Honor the configured auth mode rather than silently forcing the URL public
279 // (which would strip access control a caller deliberately asked for). A
280 // `public` Sprite is reachable as-is; a `sprite`-auth Sprite needs the org
281 // bearer token attached to each request.
282 if (this.urlAuth === 'public') {
283 return Promise.resolve({ url: this.url })
284 }
285 return Promise.resolve({
286 url: this.url,
287 headers: this.client.authHeader(),
288 })
289 }
290
291 /**
292 * Create a checkpoint of the Sprite's writable filesystem overlay. Returns a
293 * {@link SnapshotRef} whose `id` is `<spriteName>#<version>` (e.g.
294 * `my-sprite#v3`) so it round-trips through {@link restoreCheckpoint}.
295 */
296 async snapshot(label?: string): Promise<SnapshotRef> {
297 const version = await this.client.createCheckpoint(this.name, {
298 ...(label !== undefined ? { comment: label } : {}),
299 })
300 return {
301 id: `${this.name}#${version}`,
302 ...(label !== undefined ? { label } : {}),
303 }
304 }
305
306 /** List this Sprite's checkpoints (newest live overlay shows as `Current`). */
307 listCheckpoints(): Promise<Array<SpriteCheckpoint>> {
308 return this.client.listCheckpoints(this.name)
309 }
310
311 /**
312 * Restore a checkpoint in place and wait for the Sprite to restart. Accepts a
313 * bare version (`v3`) or a {@link SnapshotRef} id (`<spriteName>#v3`).
314 *
315 * Restore is destructive: it replaces the current overlay. Take a
316 * {@link snapshot} first if you need to keep the present state.
317 */
318 restoreCheckpoint(
319 idOrRef: string,
320 options?: { readyTimeoutMs?: number },
321 ): Promise<void> {
322 let version = idOrRef
323 if (idOrRef.includes('#')) {
324 const hash = idOrRef.indexOf('#')
325 const refName = idOrRef.slice(0, hash)
326 version = idOrRef.slice(hash + 1)
327 if (refName !== this.name) {
328 return Promise.reject(
329 new Error(
330 `sprites: checkpoint ref "${idOrRef}" belongs to "${refName}", not this Sprite "${this.name}".`,
331 ),
332 )
333 }
334 }
335 return this.client.restoreCheckpoint(this.name, version, {
336 ...options,
337 // Probe the workdir so readiness reflects the restored overlay, not just
338 // the (always-listable) root.
339 probePath: this.workdir,
340 })
341 }
342
343 fork = (): Promise<SandboxHandle> => {
344 throw new UnsupportedCapabilityError('sprites', 'fork')
345 }
346
347 async destroy(): Promise<void> {
348 await this.client.deleteSprite(this.name)
349 }
350}
351
352/** POSIX single-quote escape for embedding paths in `bash -c`. */
353function q(value: string): string {
354 return `'${value.replace(/'/g, `'\\''`)}'`
355}
356const LSTAT_MISSING = '__TANSTACK_LSTAT_MISSING__'
357
358/** Verify a missing path by listing parent entries. `test -e` also fails for inaccessible parents. */
359function lstatCommand(path: string): string {
360 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`
361}
362function parseLstatOutput(output: string): SandboxFsStat {
363 const fields = /^(?<mode>[0-9a-fA-F]{4}):(?<size>\d+)\n?$/.exec(output)
364 const mode = fields?.groups?.mode
365 const size = fields?.groups?.size
366 if (!mode || !size) throw new Error(`invalid lstat output: ${output}`)
367 const parsedMode = Number.parseInt(mode, 16)
368 const parsedSize = Number(size)
369 if (
370 !Number.isSafeInteger(parsedMode) ||
371 !Number.isSafeInteger(parsedSize) ||
372 parsedSize < 0
373 )
374 throw new Error(`invalid lstat output: ${output}`)
375 const type = parsedMode & 0xf000
376 if (type === 0x8000)
377 return { type: 'file', mode: parsedMode, size: parsedSize }
378 if (type === 0x4000) return { type: 'dir', mode: parsedMode }
379 if (type === 0xa000) return { type: 'symlink', mode: parsedMode }
380 return { type: 'other', mode: parsedMode }
381}
382
383/**
384 * Best error text from an exec result. Near-instant commands hit the Sprite
385 * agent's fast path, which folds stderr into stdout, so prefer stderr but fall
386 * back to stdout to avoid throwing with an empty reason.
387 */
388function errText(r: { stdout: string; stderr: string }): string {
389 return r.stderr.trim() || r.stdout.trim() || '(no output)'
390}