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 input.signal?.throwIfAborted()
158 const handle = this.handle(ready, input.env)
159 // From `/`: the workdir does not exist yet, and every handle exec `cd`s
160 // into its cwd first.
161 const mkdir = await handle.process.exec(`mkdir -p ${q(this.workdir)}`, {
162 cwd: '/',
163 })
164 input.signal?.throwIfAborted()
165 if (mkdir.exitCode !== 0) {
166 throw new Error(
167 `boxd: failed to create workspace directory "${this.workdir}" (exit ${mkdir.exitCode}): ${mkdir.stderr.trim()}`,
168 )
169 }
170 return handle
171 } catch (error) {
172 await this.client.machines.delete(machine.id).catch(() => undefined)
173 throw error
174 }
175 }
176
177 async create(input: SandboxCreateInput): Promise<SandboxHandle> {
178 input.signal?.throwIfAborted()
179 // Honor the deterministic id ensure() supplies (see SandboxCreateInput.id):
180 // the machine's public URL is keyed by name, so an out-of-band reconnect
181 // (a preview iframe) lands on the machine the agent is editing. A second
182 // create under a taken name is a ConflictError.
183 const name = input.id === undefined ? randomName() : machineName(input.id)
184 const machine = await this.client.machines.create(
185 this.createParams(name, this.config.fromSnapshot),
186 )
187 return this.adopt(machine, input)
188 }
189
190 async resume(input: SandboxResumeInput): Promise<SandboxHandle | null> {
191 input.signal?.throwIfAborted()
192 let machine: Machine
193 try {
194 machine = await this.client.machines.get(input.id)
195 } catch (error) {
196 if (error instanceof NotFoundError) return null
197 throw error
198 }
199 // A deleted machine keeps a record, with status `destroyed`. The record
200 // takes under a second to flip after `delete`; a resume inside that window
201 // returns a handle whose first exec fails with NotFoundError ("VM is
202 // destroyed"), and the next resume sees `destroyed`.
203 if (machine.status === 'destroyed') return null
204 // Every parked state needs its own explicit call: the readiness probe
205 // gates on status before it runs an exec, so it never wakes anything on
206 // its own. Measured: stopped -> start 2.2 s, hibernated -> wake 1.2 s,
207 // suspended -> resume sub-second; left to the probe, a suspended machine
208 // timed out after 90 s and a hibernated one took 84 s.
209 if (machine.status === 'stopped' || machine.status === 'failed') {
210 await this.client.machines.start(machine.id)
211 } else if (machine.status === 'hibernated') {
212 await this.client.machines.wake(machine.id)
213 } else if (machine.status === 'suspended') {
214 await this.client.machines.resume(machine.id)
215 }
216 if (machine.status !== 'running') {
217 machine = await this.client.machines.waitUntilReady(machine.id)
218 }
219 return this.handle(machine)
220 }
221
222 async restoreSnapshot(input: SandboxRestoreInput): Promise<SandboxHandle> {
223 input.signal?.throwIfAborted()
224 const machine = await this.client.machines.create(
225 this.createParams(randomName(), input.snapshotId),
226 )
227 return this.adopt(machine, input)
228 }
229
230 async destroy(input: SandboxDestroyInput): Promise<void> {
231 input.signal?.throwIfAborted()
232 try {
233 await this.client.machines.delete(input.id)
234 } catch (error) {
235 // Already gone is success; anything else must surface so the caller does
236 // not believe a still-running machine was destroyed.
237 if (!(error instanceof NotFoundError)) throw error
238 }
239 }
240}
241
242function q(value: string): string {
243 return `'${value.replace(/'/g, `'\\''`)}'`
244}
245
246/**
247 * boxd sandbox provider: runs harness adapters inside isolated boxd KVM
248 * microVMs through the uniform `SandboxHandle`. Needs a boxd API key
249 * (`config.apiKey` or the `BOXD_API_KEY` env var) and the org it belongs to
250 * (`config.org` or `BOXD_ORG`).
251 */
252export function boxdSandbox(config: BoxdSandboxConfig = {}): SandboxProvider {
253 return new BoxdProvider(config)
254}