Open History to see the last commit
1import { randomUUID } from 'node:crypto'
2import { Boxd, NotFoundError } from '@boxd-sh/sdk'
3import { BOXD_CAPS, BoxdHandle, DEFAULT_WORKDIR } from './handle'
4import type { BoxdClientLike, BoxdLogger } from './handle'
5import type { Machine, MachineConfig, MachineCreateParams } from '@boxd-sh/sdk'
6import type {
7 SandboxCapabilities,
8 SandboxCreateInput,
9 SandboxDestroyInput,
10 SandboxHandle,
11 SandboxProvider,
12 SandboxRestoreInput,
13 SandboxResumeInput,
14} from '@tanstack/ai-sandbox'
15
16export interface BoxdSandboxConfig {
17 /**
18 * boxd API key (`bxd_…`). Falls back to the `BOXD_API_KEY` env var (or a
19 * session token in `BOXD_TOKEN`), read by the SDK, when omitted. Inside a
20 * boxd machine the SDK authenticates on its own.
21 */
22 apiKey?: string
23 /** API endpoint. Falls back to `BOXD_BASE_URL`, then production. */
24 baseUrl?: string
25 /**
26 * Organization to create machines in. Falls back to `BOXD_ORG`. An API key
27 * is fenced to one org, so set this to the org the key was minted for.
28 */
29 org?: string
30 /**
31 * Machine size class. boxd resolves memory from it: 1 vCPU/4 GiB,
32 * 2 vCPU/8 GiB, 4 vCPU/16 GiB. Defaults to the org's default size.
33 */
34 vcpu?: 1 | 2 | 4
35 /**
36 * boxd snapshot (name or id) to boot new sandboxes from, instead of the
37 * default image. Bake one after `setup` and every later create skips it.
38 */
39 fromSnapshot?: string
40 /**
41 * Working directory inside the machine. The `/workspace` virtual root maps
42 * here. Defaults to `/home/boxd/workspace`.
43 */
44 workdir?: string
45 /**
46 * Seconds of idleness before the machine suspends to RAM. `0` disables.
47 * Defaults to the platform default. Idle means no inbound connection, so a
48 * long CPU-only run with nothing talking to the machine counts as idle.
49 */
50 autoSuspendTimeout?: number
51 /**
52 * Seconds after start before the machine is destroyed, as a safety net for
53 * abandoned sandboxes. `0` (the default) never auto-destroys: a boxd machine
54 * is persistent until `destroy()`.
55 */
56 autoDestroyTimeout?: number
57 /** Sink for non-fatal teardown diagnostics (a kill the machine refused). */
58 logger?: BoxdLogger
59}
60
61const NAME_PREFIX = 'tanstack-ai'
62
63/**
64 * Machine name for a sandbox: `tanstack-ai-<id>`, with the id lowercased and
65 * anything outside `[a-z0-9-]` folded to `-`. boxd names must start with a
66 * lowercase letter (measured: the framework's hex key `3f…` was refused), so
67 * the prefix is what makes the deterministic id usable as a name. Names are
68 * unique per org.
69 */
70function machineName(id: string): string {
71 return `${NAME_PREFIX}-${id.toLowerCase().replace(/[^a-z0-9-]+/g, '-')}`
72}
73
74function randomName(): string {
75 return machineName(randomUUID().replace(/-/g, '').slice(0, 12))
76}
77
78class BoxdProvider implements SandboxProvider {
79 readonly name = 'boxd'
80 private readonly client: BoxdClientLike
81 private readonly org: string | undefined
82
83 constructor(private readonly config: BoxdSandboxConfig) {
84 this.client = new Boxd({
85 ...(config.apiKey !== undefined ? { apiKey: config.apiKey } : {}),
86 ...(config.baseUrl !== undefined ? { baseURL: config.baseUrl } : {}),
87 })
88 this.org = config.org ?? process.env.BOXD_ORG
89 }
90
91 capabilities(): SandboxCapabilities {
92 return BOXD_CAPS
93 }
94
95 private get workdir(): string {
96 return this.config.workdir ?? DEFAULT_WORKDIR
97 }
98
99 private machineConfig(fromSnapshot: boolean): MachineConfig | undefined {
100 const cfg: MachineConfig = {}
101 // A restore keeps the size the snapshot was captured at; boxd refuses
102 // per-request sizing there (measured), so `vcpu` only applies to fresh creates.
103 if (this.config.vcpu !== undefined && !fromSnapshot)
104 cfg.vcpu = this.config.vcpu
105 if (this.config.autoSuspendTimeout !== undefined)
106 cfg.autoSuspendTimeout = this.config.autoSuspendTimeout
107 if (this.config.autoDestroyTimeout !== undefined)
108 cfg.autoDestroyTimeout = this.config.autoDestroyTimeout
109 return Object.keys(cfg).length ? cfg : undefined
110 }
111
112 private createParams(
113 name: string,
114 fromSnapshot: string | undefined,
115 ): MachineCreateParams {
116 const config = this.machineConfig(fromSnapshot !== undefined)
117 const common = {
118 name,
119 // Always isolated: the machine runs agent-authored code. Isolation strips
120 // the in-VM boxd CLI, the metadata endpoint and org integrations, and
121 // keeps the machine off the org's default network. One-way, inherited
122 // by forks and snapshot restores. Not configurable on purpose.
123 isolated: true as const,
124 ...(this.org !== undefined ? { org: this.org } : {}),
125 ...(config !== undefined ? { config } : {}),
126 }
127 return fromSnapshot === undefined ? common : { ...common, fromSnapshot }
128 }
129
130 private handle(machine: Machine, env?: Record<string, string>): BoxdHandle {
131 return new BoxdHandle({
132 client: this.client,
133 machine,
134 ...(this.org !== undefined ? { org: this.org } : {}),
135 workdir: this.workdir,
136 ...(this.config.logger !== undefined
137 ? { logger: this.config.logger }
138 : {}),
139 ...(env !== undefined ? { env } : {}),
140 })
141 }
142
143 /**
144 * Turn a just-created machine into a handle: wait until exec works (`create`
145 * returns as soon as the machine is scheduled), make the workdir, inject env.
146 * The SDK cannot cancel an in-flight create, so on any failure here,
147 * including an abort that landed mid-call, the machine is deleted rather
148 * than left running with no one holding its id.
149 */
150 private async adopt(
151 machine: Machine,
152 input: { env?: Record<string, string>; signal?: AbortSignal },
153 ): Promise<SandboxHandle> {
154 try {
155 input.signal?.throwIfAborted()
156 const ready = await this.client.machines.waitUntilReady(machine.id)
157 const handle = this.handle(ready, input.env)
158 // From `/`: the workdir does not exist yet, and every handle exec `cd`s
159 // into its cwd first.
160 const mkdir = await handle.process.exec(`mkdir -p ${q(this.workdir)}`, {
161 cwd: '/',
162 })
163 if (mkdir.exitCode !== 0) {
164 throw new Error(
165 `boxd: failed to create workspace directory "${this.workdir}" (exit ${mkdir.exitCode}): ${mkdir.stderr.trim()}`,
166 )
167 }
168 return handle
169 } catch (error) {
170 await this.client.machines.delete(machine.id).catch(() => undefined)
171 throw error
172 }
173 }
174
175 async create(input: SandboxCreateInput): Promise<SandboxHandle> {
176 input.signal?.throwIfAborted()
177 // Honor the deterministic id ensure() supplies (see SandboxCreateInput.id):
178 // the machine's public URL is keyed by name, so an out-of-band reconnect
179 // (a preview iframe) lands on the machine the agent is editing. A second
180 // create under a taken name is a ConflictError.
181 const name = input.id === undefined ? randomName() : machineName(input.id)
182 const machine = await this.client.machines.create(
183 this.createParams(name, this.config.fromSnapshot),
184 )
185 return this.adopt(machine, input)
186 }
187
188 async resume(input: SandboxResumeInput): Promise<SandboxHandle | null> {
189 input.signal?.throwIfAborted()
190 let machine: Machine
191 try {
192 machine = await this.client.machines.get(input.id)
193 } catch (error) {
194 if (error instanceof NotFoundError) return null
195 throw error
196 }
197 // A deleted machine keeps a record, with status `destroyed`. The record
198 // takes under a second to flip after `delete`; a resume inside that window
199 // returns a handle whose first exec fails with NotFoundError ("VM is
200 // destroyed"), and the next resume sees `destroyed`.
201 if (machine.status === 'destroyed') return null
202 // Every parked state needs its own explicit call: the readiness probe
203 // gates on status before it runs an exec, so it never wakes anything on
204 // its own. Measured: stopped -> start 2.2 s, hibernated -> wake 1.2 s,
205 // suspended -> resume sub-second; left to the probe, a suspended machine
206 // timed out after 90 s and a hibernated one took 84 s.
207 if (machine.status === 'stopped' || machine.status === 'failed') {
208 await this.client.machines.start(machine.id)
209 } else if (machine.status === 'hibernated') {
210 await this.client.machines.wake(machine.id)
211 } else if (machine.status === 'suspended') {
212 await this.client.machines.resume(machine.id)
213 }
214 if (machine.status !== 'running') {
215 machine = await this.client.machines.waitUntilReady(machine.id)
216 }
217 return this.handle(machine)
218 }
219
220 async restoreSnapshot(input: SandboxRestoreInput): Promise<SandboxHandle> {
221 input.signal?.throwIfAborted()
222 const machine = await this.client.machines.create(
223 this.createParams(randomName(), input.snapshotId),
224 )
225 return this.adopt(machine, input)
226 }
227
228 async destroy(input: SandboxDestroyInput): Promise<void> {
229 input.signal?.throwIfAborted()
230 try {
231 await this.client.machines.delete(input.id)
232 } catch (error) {
233 // Already gone is success; anything else must surface so the caller does
234 // not believe a still-running machine was destroyed.
235 if (!(error instanceof NotFoundError)) throw error
236 }
237 }
238}
239
240function q(value: string): string {
241 return `'${value.replace(/'/g, `'\\''`)}'`
242}
243
244/**
245 * boxd sandbox provider: runs harness adapters inside isolated boxd KVM
246 * microVMs through the uniform `SandboxHandle`. Needs a boxd API key
247 * (`config.apiKey` or the `BOXD_API_KEY` env var) and the org it belongs to
248 * (`config.org` or `BOXD_ORG`).
249 */
250export function boxdSandbox(config: BoxdSandboxConfig = {}): SandboxProvider {
251 return new BoxdProvider(config)
252}