Open History to see the last commit
1/**
2 * Provider-agnostic sandbox contracts.
3 *
4 * A {@link SandboxProvider} owns an isolation primitive (Docker container,
5 * Cloudflare DO-backed container, a local OS process tree, …) and knows how to
6 * create / resume / restore / destroy a {@link SandboxHandle}. A
7 * `SandboxHandle` is the uniform runtime surface every consumer (harness
8 * adapters, the workspace bootstrap engine, advanced users) codes against.
9 *
10 * Providers differ in what they can do — see {@link SandboxCapabilities}. The
11 * mandatory `fs` and `exec` capabilities are guaranteed by the contract;
12 * everything else is optional and capability-gated. Calling an unsupported
13 * optional method throws {@link UnsupportedCapabilityError} rather than
14 * silently no-opping.
15 */
16import type { WorkspaceDefinition } from './workspace'
17import type { SandboxPolicy } from './policy'
18
19/** Static description of what a provider supports. */
20export interface SandboxCapabilities {
21 /** Read/write/list/… via {@link SandboxFs}. Always true (mandatory). */
22 fs: boolean
23 /** Blocking command execution via {@link SandboxProcess.exec}. Always true (mandatory). */
24 exec: boolean
25 /** Per-create / per-command environment variables. */
26 env: boolean
27 /** Expose a port and resolve a reachable channel via {@link SandboxPorts}. */
28 ports: boolean
29 /** Long-running/background processes via {@link SandboxProcess.spawn}. */
30 backgroundProcesses: boolean
31 /**
32 * A spawned process exposes a writable host→process stdin
33 * ({@link SpawnHandle.stdin}). `true` for host (`localProcessSandbox`).
34 * `false` for Docker container, Docker Sandboxes (`sbx`), Daytona, Vercel,
35 * and Cloudflare. When `false`, harness adapters that feed a prompt over
36 * stdin must instead deliver it via a file + shell redirection.
37 */
38 writableStdin: boolean
39 /**
40 * A spawned process can be forcibly terminated via {@link SpawnHandle.kill}
41 * and aborted mid-flight via the {@link ProcessOptions.signal} passed to
42 * {@link SandboxProcess.spawn}. `true` for host and Docker container.
43 * `false` for Docker Sandboxes (`sbx`) until measured, and for Daytona,
44 * Vercel, and Cloudflare. Those providers implement `kill()` as a no-op or
45 * have not been measured yet, so a long-running follower process
46 * (e.g. `tail -f`) started there can never be stopped by the caller, only
47 * polled and abandoned.
48 * Callers MUST branch on this before relying on `kill`/abort to reclaim a
49 * background process: a bring-your-own provider that omits it would
50 * otherwise be silently treated as killable, leaking an unstoppable process
51 * inside the sandbox.
52 */
53 killableProcesses: boolean
54 /** Capture/restore filesystem snapshots via {@link SandboxHandle.snapshot}. */
55 snapshots: boolean
56 /** Declarative network egress allow/deny policy. */
57 networkPolicy: boolean
58 /** Filesystem persists across sandbox stop/restart without a snapshot. */
59 durableFilesystem: boolean
60 /** Branch a new sandbox from current state via {@link SandboxHandle.fork}. */
61 fork: boolean
62}
63
64/** Result of a blocking command. */
65export interface ExecResult {
66 stdout: string
67 stderr: string
68 exitCode: number
69}
70
71/** Options for {@link SandboxProcess.exec} / {@link SandboxProcess.spawn}. */
72export interface ProcessOptions {
73 /** Working directory inside the sandbox. Defaults to the workspace root. */
74 cwd?: string
75 /** Per-command environment variables, merged over the sandbox env. */
76 env?: Record<string, string>
77 /** Abort the command/process when this signal fires. */
78 signal?: AbortSignal
79}
80
81/**
82 * A live background process. `stdout`/`stderr` are async-iterables of decoded
83 * chunks; `stdin.write` feeds the process (duplex — required for ACP harness
84 * protocols such as Codex / Gemini CLI). There is intentionally NO
85 * reconnect-to-a-running-process in v1 — that belongs to the durable-stream /
86 * persistence layer.
87 */
88export interface SpawnHandle {
89 readonly pid: number
90 readonly stdout: AsyncIterable<string>
91 readonly stderr: AsyncIterable<string>
92 readonly stdin: {
93 write: (data: string) => Promise<void>
94 end: () => Promise<void>
95 }
96 /** Resolves with the exit code when the process exits. */
97 wait: () => Promise<number>
98 kill: (signal?: NodeJS.Signals | number) => Promise<void>
99}
100
101export interface SandboxProcess {
102 /** Run a command to completion and capture stdout/stderr/exit code. */
103 exec: (command: string, options?: ProcessOptions) => Promise<ExecResult>
104 /** Start a long-running/background process with streamable, duplex IO. */
105 spawn: (command: string, options?: ProcessOptions) => Promise<SpawnHandle>
106}
107
108/** Common, portable filesystem operations every provider implements. */
109export interface SandboxFs {
110 read: (path: string) => Promise<string>
111 readBytes: (path: string) => Promise<Uint8Array>
112 write: (path: string, data: string | Uint8Array) => Promise<void>
113 list: (
114 path: string,
115 ) => Promise<Array<{ name: string; path: string; type: 'file' | 'dir' }>>
116 mkdir: (path: string) => Promise<void>
117 remove: (path: string) => Promise<void>
118 rename: (from: string, to: string) => Promise<void>
119 exists: (path: string) => Promise<boolean>
120 /**
121 * Optional metadata lookup. Implementations must not follow symlinks.
122 * Returns undefined only for a confirmed missing path. All other errors reject.
123 */
124 lstat?: (path: string) => Promise<SandboxFsStat | undefined>
125 /** Optional — present only when `capabilities.fs` providers advertise watch. */
126 watch?: (
127 path: string,
128 onEvent: (event: { type: string; path: string }) => void,
129 ) => Promise<{ stop: () => Promise<void> }>
130}
131
132export type SandboxFsStat =
133 // `mode` is the complete POSIX mode value, including the file-type bits.
134 | { type: 'file'; mode: number; size: number }
135 | { type: 'dir'; mode: number }
136 | { type: 'symlink'; mode: number }
137 | { type: 'other'; mode: number }
138
139/**
140 * Uniform git surface. Implementations either delegate to the provider's
141 * native git (when advertised) or desugar to `process.exec("git …")`, so the
142 * contract is identical across providers.
143 */
144export interface SandboxGit {
145 clone: (input: {
146 url: string
147 dir?: string
148 ref?: string
149 auth?: { username?: string; token: string }
150 depth?: number | 'full'
151 }) => Promise<void>
152 status: (dir?: string) => Promise<string>
153 add: (paths: Array<string>, dir?: string) => Promise<void>
154 commit: (message: string, dir?: string) => Promise<void>
155 push: (dir?: string) => Promise<void>
156 pull: (dir?: string) => Promise<void>
157 /** Returns the current branch name. */
158 branch: (dir?: string) => Promise<string>
159}
160
161/** A reachable channel to a port inside the sandbox. */
162export interface SandboxChannel {
163 /** URL the host can reach (localhost / host-bound port / authenticated preview URL). */
164 url: string
165 /** Bearer token gating the channel, when the provider issues one. */
166 token?: string
167 /**
168 * Ready-to-send HTTP headers that authenticate requests to {@link url}, when
169 * the provider's auth doesn't fit a plain `Authorization: Bearer <token>`
170 * (e.g. Daytona's `x-daytona-preview-token`). Consumers that speak HTTP to the
171 * channel should attach these verbatim; the provider owns the header names so
172 * consumers stay provider-agnostic.
173 */
174 headers?: Record<string, string>
175}
176
177export interface SandboxPorts {
178 /** Expose `port` and resolve the best reachable channel for the host. */
179 connect: (port: number) => Promise<SandboxChannel>
180}
181
182export interface SandboxEnv {
183 set: (vars: Record<string, string>) => Promise<void>
184}
185
186/** Opaque reference to a stored snapshot, used to restore later. */
187export interface SnapshotRef {
188 id: string
189 label?: string
190}
191
192/** The uniform runtime surface a sandbox exposes. */
193export interface SandboxHandle {
194 /** Provider-assigned id used to reconnect to this sandbox. */
195 readonly id: string
196 /** Provider name (e.g. "docker", "cloudflare", "local-process"). */
197 readonly provider: string
198 /**
199 * Real filesystem path backing the virtual workspace root (`/workspace`).
200 * Harness CLIs and ACP `newSession` interpret cwd literally — use
201 * {@link resolveHarnessCwd} rather than the virtual path when the provider
202 * maps `/workspace` elsewhere (Daytona, Vercel, local-process).
203 */
204 readonly workspaceRoot?: string
205 /** What this sandbox can do. */
206 readonly capabilities: SandboxCapabilities
207 readonly fs: SandboxFs
208 readonly git: SandboxGit
209 readonly process: SandboxProcess
210 readonly ports: SandboxPorts
211 readonly env: SandboxEnv
212 /** Capability-gated: throws UnsupportedCapabilityError if `capabilities.snapshots` is false. */
213 snapshot?: (label?: string) => Promise<SnapshotRef>
214 /** Capability-gated: throws UnsupportedCapabilityError if `capabilities.fork` is false. */
215 fork?: () => Promise<SandboxHandle>
216 destroy: () => Promise<void>
217}
218
219/** Input passed to {@link SandboxProvider.create}. */
220export interface SandboxCreateInput {
221 /**
222 * Deterministic instance id the caller wants the provider to use. `ensure()`
223 * passes the compound sandbox key here so the provider-assigned id is
224 * reconstructable from run context (thread/workspace/tenant/reuse) instead of
225 * being a random value only recoverable from the sandbox store. Providers
226 * whose native id is addressable by name (e.g. Cloudflare's DO id) SHOULD
227 * honor it (`input.id ?? <random>`); providers that mint their own opaque id
228 * MAY ignore it. Consumers that reconnect out-of-band — e.g. attaching a
229 * preview iframe to the exact sandbox an agent is editing — rely on this being
230 * honored to avoid addressing two different sandboxes.
231 */
232 id?: string
233 workspace?: WorkspaceDefinition
234 policy?: SandboxPolicy
235 env?: Record<string, string>
236 signal?: AbortSignal
237 /** Harness adapter name. Optional. Providers that do not use it ignore it. */
238 adapterName?: string
239}
240
241/** Input passed to {@link SandboxProvider.resume}. */
242export interface SandboxResumeInput {
243 /** Provider-assigned sandbox id recorded by a prior run. */
244 id: string
245 signal?: AbortSignal
246}
247
248/** Input passed to {@link SandboxProvider.restoreSnapshot}. */
249export interface SandboxRestoreInput {
250 snapshotId: string
251 workspace?: WorkspaceDefinition
252 policy?: SandboxPolicy
253 env?: Record<string, string>
254 signal?: AbortSignal
255}
256
257/** Input passed to {@link SandboxProvider.destroy}. */
258export interface SandboxDestroyInput {
259 id: string
260 signal?: AbortSignal
261}
262
263/**
264 * Owns an isolation primitive. Implemented by `@tanstack/ai-sandbox-*`
265 * provider packages.
266 */
267export interface SandboxProvider {
268 readonly name: string
269 /** Static capability descriptor. */
270 capabilities: () => SandboxCapabilities
271 create: (input: SandboxCreateInput) => Promise<SandboxHandle>
272 /** Reconnect to an existing sandbox by id; resolves null if it's gone. */
273 resume: (input: SandboxResumeInput) => Promise<SandboxHandle | null>
274 /** Capability-gated: present only when `capabilities().snapshots` is true. */
275 restoreSnapshot?: (input: SandboxRestoreInput) => Promise<SandboxHandle>
276 destroy: (input: SandboxDestroyInput) => Promise<void>
277}