Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

sandbox.ts

418 lines15.1 KB

1/**
2 * `defineSandbox()` returns a LAZY controller — it never creates a sandbox at
3 * definition time. `withSandbox()` (and advanced users) call `ensure()` to
4 * resume-or-create, following: provider.resume → provider.restoreSnapshot →
5 * create + bootstrap. The controller folds provider/workspace/policy/lifecycle
6 * into a stable instance key and coordinates through the (optional) lock +
7 * sandbox stores.
8 */
9import { bootstrapWorkspace } from './bootstrap'
10import { resolveAllSecrets } from './secrets'
11import { computeSandboxKey } from './key'
12import { InMemoryLockStore } from '@tanstack/ai/locks'
13import type { LockStore } from '@tanstack/ai/locks'
14import type { SandboxFileHookEvent } from '@tanstack/ai'
15import { InMemorySandboxInstanceStore } from './instance-store'
16import type { SandboxInstanceStore } from './instance-store'
17import type { SandboxHandle, SandboxProvider } from './contracts'
18import type { SandboxKeyInput } from './key'
19import type { SandboxPolicy } from './policy'
20import type { WorkspaceDefinition } from './workspace'
21​
22/**
23 * Sandbox-scoped hooks declared on `defineSandbox`. File hooks fire for every
24 * create/change/delete during a chat run; lifecycle hooks fire server-side.
25 */
26export interface SandboxHooks {
27 onFile?: (e: SandboxFileHookEvent) => void | Promise<void>
28 onFileCreate?: (e: SandboxFileHookEvent) => void | Promise<void>
29 onFileChange?: (e: SandboxFileHookEvent) => void | Promise<void>
30 onFileDelete?: (e: SandboxFileHookEvent) => void | Promise<void>
31 onReady?: (handle: SandboxHandle) => void | Promise<void>
32 onError?: (err: unknown) => void | Promise<void>
33 onDestroy?: () => void | Promise<void>
35​
36export type ReuseStrategy = 'thread' | 'none'
37export type SnapshotStrategy = 'after-setup' | 'after-run' | 'none'
38​
39export interface SandboxLifecycle {
40 /** `'thread'` resumes one sandbox per thread; `'none'` is fresh per run. */
41 reuse?: ReuseStrategy
42 /** When to snapshot (provider-permitting). */
43 snapshot?: SnapshotStrategy
44 /** Hint for how long a provider should keep the sandbox warm between runs. */
45 keepAlive?: string
46 /** Destroy the sandbox after the run completes. */
47 destroyOnComplete?: boolean
48 /**
49 * Maximum age of a sandbox record before it is discarded and re-created
50 * instead of resumed. Accepts `'<n>h'` (hours) or `'<n>m'` (minutes),
51 * e.g. `'2h'` or `'30m'`.
52 */
53 snapshotMaxAge?: string
55​
56export interface SandboxConfig {
57 id: string
58 provider: SandboxProvider
59 workspace?: WorkspaceDefinition
60 policy?: SandboxPolicy
61 lifecycle?: SandboxLifecycle
62 /** Sandbox-scoped file/lifecycle hooks. */
63 hooks?: SandboxHooks
64 /** Watch the workspace for file events (default true). `false` disables the
65 * watcher; `{ diff: true }` also emits a per-file `sandbox.file.diff` event. */
66 fileEvents?: boolean | { diff?: boolean }
68​
69/** Context passed to `ensure()` by `withSandbox` (or advanced callers). */
70export interface SandboxEnsureContext {
71 threadId: string
72 runId: string
73 /** Persistence seam; falls back to an in-memory store when absent. */
74 store?: SandboxInstanceStore
75 /** Lock seam; falls back to an in-memory lock when absent. */
76 locks?: LockStore
77 tenant?: { userId?: string; orgId?: string }
78 signal?: AbortSignal
79 /** Harness adapter name (`grok-build`, `claude-code`, `codex`, `opencode`). Optional. */
80 adapterName?: string
82​
83export interface SandboxDefinition {
84 readonly id: string
85 readonly provider: SandboxProvider
86 readonly workspace?: WorkspaceDefinition
87 readonly policy?: SandboxPolicy
88 readonly lifecycle?: SandboxLifecycle
89 /** Sandbox-scoped file/lifecycle hooks. */
90 readonly hooks?: SandboxHooks
91 /** Watch the workspace for file events (default true). `false` disables the
92 * watcher; `{ diff: true }` also emits a per-file `sandbox.file.diff` event. */
93 readonly fileEvents?: boolean | { diff?: boolean }
94 /** Compound instance key for a given run context. */
95 key: (ctx: SandboxEnsureContext) => string
96 /** Resume-or-create the sandbox for this thread/run. */
97 ensure: (ctx: SandboxEnsureContext) => Promise<SandboxHandle>
98 /** Resume an existing sandbox only. Never creates or restores a sandbox. */
99 ensureExisting: (ctx: SandboxEnsureContext) => Promise<SandboxHandle | null>
100 /** Tear down the sandbox recorded for this key. */
101 destroy: (ctx: SandboxEnsureContext) => Promise<void>
103​
104export type SandboxEnsureOutcome = {
105 handle: SandboxHandle
106 outcome: 'resumed' | 'native-restored' | 'created'
108​
109const outcomeEnsure = new WeakMap<
110 object,
111 (ctx: SandboxEnsureContext) => Promise<SandboxEnsureOutcome>
112>()
113​
114interface SandboxEnsureExistingStage {
115 key: string
116 workspace: WorkspaceDefinition | undefined
117 resolvedSecrets: Readonly<Record<string, string>> | undefined
118 snapshotMaxAge: string | undefined
119 resume: SandboxProvider['resume']
121​
122const existingEnsure = new WeakMap<
123 object,
124 (
125 ctx: SandboxEnsureContext,
126 stage?: SandboxEnsureExistingStage,
127 ) => Promise<SandboxHandle | null>
128>()
129​
130export function stageEnsureExistingSandbox(
131 definition: SandboxDefinition,
132): (
133 ctx: SandboxEnsureContext,
134 stage: SandboxEnsureExistingStage,
135) => Promise<SandboxHandle | null> {
136 const fn = existingEnsure.get(definition)
137 if (fn) return (ctx, stage) => fn(ctx, stage)
138 const ensureExisting = definition.ensureExisting.bind(definition)
139 return (ctx) => ensureExisting(ctx)
141​
142export function ensureSandboxWithOutcome(
143 definition: SandboxDefinition,
144 ctx: SandboxEnsureContext,
145) {
146 const fn = outcomeEnsure.get(definition)
147 if (!fn)
148 throw new Error(
149 'Sandbox snapshot mode requires a definition created by defineSandbox()',
150 )
151 return fn(ctx)
153​
154/**
155 * Parse a human-readable duration string into milliseconds.
156 * Supports `'<n>h'` (hours) and `'<n>m'` (minutes).
157 * Returns `undefined` when the input is undefined or the format is unrecognised.
158 */
159function parseMaxAgeMs(value: string | undefined): number | undefined {
160 if (value === undefined) return undefined
161 const hourMatch = /^(\d+)h$/.exec(value)
162 if (hourMatch) return Number(hourMatch[1]) * 60 * 60 * 1000
163 const minuteMatch = /^(\d+)m$/.exec(value)
164 if (minuteMatch) return Number(minuteMatch[1]) * 60 * 1000
165 return undefined
167​
168/**
169 * Bound for the unfenced teardown `destroy` call (see `destroy` below). Long
170 * enough that a slow provider API still completes, short enough that a wedged
171 * one cannot pin the process forever.
172 */
173const DESTROY_TIMEOUT_MS = 60 * 1000
174​
175// Process-lifetime fallbacks shared across all definitions so concurrent
176// ensures for the same key serialize even without an injected store/lock.
177const fallbackStore = new InMemorySandboxInstanceStore()
178const fallbackLocks = new InMemoryLockStore()
179​
180/**
181 * Put workspace secrets onto a live handle. Resume and snapshot restore skip
182 * bootstrap, so this is the only path that re-injects them after reconnect.
183 * Create injects secrets via `provider.create({ env })`, but resume/restore
184 * return a handle whose process env is empty unless we set it here. sbx in
185 * particular has no Docker Env on resume, so this is the only way secrets
186 * come back for that provider.
187 */
188async function applyWorkspaceSecrets(
189 handle: SandboxHandle,
190 workspace: WorkspaceDefinition | undefined,
191 stagedSecrets?: Readonly<Record<string, string>>,
192): Promise<void> {
193 if (workspace?.secrets === undefined) return
194 const resolved = stagedSecrets ?? resolveAllSecrets(workspace.secrets)
195 if (Object.keys(resolved).length === 0) return
196 await handle.env.set(resolved)
198​
199export function defineSandbox(config: SandboxConfig): SandboxDefinition {
200 const keyInputFor = (ctx: SandboxEnsureContext): SandboxKeyInput => ({
201 threadId:
202 config.lifecycle?.reuse === 'none'
203 ? `${ctx.threadId}:${ctx.runId}`
204 : ctx.threadId,
205 sandboxId: config.id,
206 providerName: config.provider.name,
207 workspace: config.workspace,
208 tenant: ctx.tenant,
209 })
210​
211 const ensureWithOutcome = async (
212 ctx: SandboxEnsureContext,
213 ): Promise<SandboxEnsureOutcome> => {
214 const store = ctx.store ?? fallbackStore
215 const locks = ctx.locks ?? fallbackLocks
216 const key = computeSandboxKey(keyInputFor(ctx))
217 const caps = config.provider.capabilities()
218​
219 return locks.withLock(`sandbox:${key}`, async () => {
220 const effectiveSnapshot: SnapshotStrategy =
221 config.lifecycle?.snapshot ?? (caps.snapshots ? 'after-setup' : 'none')
222 const maxAgeMs = parseMaxAgeMs(config.lifecycle?.snapshotMaxAge)
223​
224 const existing = await store.get(key)
225 if (existing) {
226 // Check whether the record has exceeded snapshotMaxAge; if so,
227 // discard and fall through to a fresh create.
228 const tooOld =
229 maxAgeMs !== undefined && Date.now() - existing.updatedAt > maxAgeMs
230​
231 if (!tooOld) {
232 // 1) Try to reconnect to the still-running sandbox.
233 const resumed = await config.provider.resume({
234 id: existing.providerSandboxId,
235 signal: ctx.signal,
236 })
237 if (resumed) {
238 await applyWorkspaceSecrets(resumed, config.workspace)
239 await store.upsert({
240 ...existing,
241 latestRunId: ctx.runId,
242 updatedAt: Date.now(),
243 })
244 return { handle: resumed, outcome: 'resumed' }
245 }
246 // 2) Else restore from the latest snapshot, if supported.
247 if (
248 existing.latestSnapshotId &&
249 caps.snapshots &&
250 config.provider.restoreSnapshot
251 ) {
252 const restored = await config.provider.restoreSnapshot({
253 snapshotId: existing.latestSnapshotId,
254 workspace: config.workspace,
255 policy: config.policy,
256 env:
257 config.workspace?.secrets !== undefined
258 ? resolveAllSecrets(config.workspace.secrets)
259 : undefined,
260 signal: ctx.signal,
261 })
262 await applyWorkspaceSecrets(restored, config.workspace)
263 await store.upsert({
264 ...existing,
265 providerSandboxId: restored.id,
266 latestRunId: ctx.runId,
267 updatedAt: Date.now(),
268 })
269 return { handle: restored, outcome: 'native-restored' }
270 }
271 }
272 // 3) Else fall through and re-create under the same identity
273 // (capability-aware degradation for ephemeral-disk providers, or
274 // snapshotMaxAge TTL exceeded).
275 }
276​
277 const created = await config.provider.create({
278 // Deterministic id so consumers can reconstruct the provider sandbox
279 // address from run context (not just from the store record).
280 id: key,
281 workspace: config.workspace,
282 policy: config.policy,
283 env:
284 config.workspace?.secrets !== undefined
285 ? resolveAllSecrets(config.workspace.secrets)
286 : undefined,
287 signal: ctx.signal,
288 adapterName: ctx.adapterName,
289 })
290​
291 if (config.workspace) {
292 try {
293 await bootstrapWorkspace(created, config.workspace, {
294 signal: ctx.signal,
295 })
296 } catch (error) {
297 // Bootstrap failed after the sandbox was created but before it was
298 // recorded — destroy the orphan so a failed/retried run doesn't leak
299 // a (billed) sandbox, then surface the original error.
300 await created.destroy().catch(() => {})
301 throw error
302 }
303 }
304​
305 let latestSnapshotId: string | undefined
306 if (
307 effectiveSnapshot === 'after-setup' &&
308 caps.snapshots &&
309 created.snapshot
310 ) {
311 latestSnapshotId = (await created.snapshot('after-setup')).id
312 }
313​
314 await store.upsert({
315 key,
316 provider: config.provider.name,
317 providerSandboxId: created.id,
318 latestSnapshotId,
319 threadId: ctx.threadId,
320 latestRunId: ctx.runId,
321 updatedAt: Date.now(),
322 })
323 return { handle: created, outcome: 'created' }
324 })
325 }
326​
327 const ensure = async (ctx: SandboxEnsureContext): Promise<SandboxHandle> =>
328 (await ensureWithOutcome(ctx)).handle
329​
330 const ensureExistingWithStage = async (
331 ctx: SandboxEnsureContext,
332 stage?: SandboxEnsureExistingStage,
333 ): Promise<SandboxHandle | null> => {
334 const store = ctx.store ?? fallbackStore
335 const locks = ctx.locks ?? fallbackLocks
336 const key = stage?.key ?? computeSandboxKey(keyInputFor(ctx))
337 const workspace = stage?.workspace ?? config.workspace
338 const snapshotMaxAge = stage
339 ? stage.snapshotMaxAge
340 : config.lifecycle?.snapshotMaxAge
341 const resume = stage?.resume ?? config.provider.resume.bind(config.provider)
342 return locks.withLock(`sandbox:${key}`, async () => {
343 const existing = await store.get(key)
344 const maxAgeMs = parseMaxAgeMs(snapshotMaxAge)
345 if (
346 !existing ||
347 (maxAgeMs !== undefined && Date.now() - existing.updatedAt > maxAgeMs)
348 )
349 return null
350 const resumed = await resume({
351 id: existing.providerSandboxId,
352 signal: ctx.signal,
353 })
354 if (!resumed) return null
355 await applyWorkspaceSecrets(resumed, workspace, stage?.resolvedSecrets)
356 await store.upsert({
357 ...existing,
358 latestRunId: ctx.runId,
359 updatedAt: Date.now(),
360 })
361 return resumed
362 })
363 }
364​
365 const ensureExisting = (
366 ctx: SandboxEnsureContext,
367 ): Promise<SandboxHandle | null> => ensureExistingWithStage(ctx)
368​
369 const destroy = async (ctx: SandboxEnsureContext): Promise<void> => {
370 const store = ctx.store ?? fallbackStore
371 const key = computeSandboxKey(keyInputFor(ctx))
372 const existing = await store.get(key)
373 if (!existing) return
374 /*
375 * TEARDOWN IS DELIBERATELY NOT FENCED BY `ctx.signal`.
376 *
377 * `destroy` runs on every teardown path INCLUDING the one caused by that
378 * very signal aborting, so forwarding it hands the provider a signal that is
379 * already aborted: a provider that honors it does nothing and returns
380 * successfully, and `store.delete` below then removes the only pointer to a
381 * live, billed sandbox. `SandboxInstanceStore` has no `list` (see the note
382 * at the top of `reclaim.ts`), so that sandbox is unreachable from then on.
383 *
384 * Same reasoning as `close()` never being fenced by the run claim (see
385 * `fenceDurability` in `claim.ts`): cleanup must outlive whatever cancelled
386 * the work. A fresh controller with its own bounded timeout keeps the call
387 * from hanging forever without letting the caller's abort cancel it.
388 */
389 const teardown = new AbortController()
390 const timer = setTimeout(() => teardown.abort(), DESTROY_TIMEOUT_MS)
391 try {
392 await config.provider.destroy({
393 id: existing.providerSandboxId,
394 signal: teardown.signal,
395 })
396 } finally {
397 clearTimeout(timer)
398 }
399 await store.delete(key)
400 }
401​
402 const definition: SandboxDefinition = {
403 id: config.id,
404 provider: config.provider,
405 workspace: config.workspace,
406 policy: config.policy,
407 lifecycle: config.lifecycle,
408 hooks: config.hooks,
409 fileEvents: config.fileEvents,
410 key: (ctx) => computeSandboxKey(keyInputFor(ctx)),
411 ensure,
412 ensureExisting,
413 destroy,
414 }
415 outcomeEnsure.set(definition, ensureWithOutcome)
416 existingEnsure.set(definition, ensureExistingWithStage)
417 return definition