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

contracts.ts

298 lines11.4 KB

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
63​
64/** Result of a blocking command. */
65export interface ExecResult {
66 stdout: string
67 stderr: string
68 exitCode: number
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
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>
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>
107​
108/**
109 * The options of a `SandboxFs` call. When `signal` is aborted, the call
110 * rejects. A provider gives the signal to its SDK when the SDK takes one.
111 * Otherwise it checks the signal before the call.
112 */
113export interface SandboxFsOptions {
114 signal?: AbortSignal
116​
117/** Common, portable filesystem operations every provider implements. */
118export interface SandboxFs {
119 read: (path: string, options?: SandboxFsOptions) => Promise<string>
120 readBytes: (path: string, options?: SandboxFsOptions) => Promise<Uint8Array>
121 write: (
122 path: string,
123 data: string | Uint8Array,
124 options?: SandboxFsOptions,
125 ) => Promise<void>
126 list: (
127 path: string,
128 options?: SandboxFsOptions,
129 ) => Promise<Array<{ name: string; path: string; type: 'file' | 'dir' }>>
130 mkdir: (path: string, options?: SandboxFsOptions) => Promise<void>
131 remove: (path: string, options?: SandboxFsOptions) => Promise<void>
132 rename: (
133 from: string,
134 to: string,
135 options?: SandboxFsOptions,
136 ) => Promise<void>
137 exists: (path: string, options?: SandboxFsOptions) => Promise<boolean>
138 /**
139 * Optional metadata lookup. Implementations must not follow symlinks.
140 * Returns undefined only for a confirmed missing path. All other errors reject.
141 */
142 lstat?: (
143 path: string,
144 options?: SandboxFsOptions,
145 ) => Promise<SandboxFsStat | undefined>
146 /** Optional — present only when `capabilities.fs` providers advertise watch. */
147 watch?: (
148 path: string,
149 onEvent: (event: { type: string; path: string }) => void,
150 ) => Promise<{ stop: () => Promise<void> }>
152​
153export type SandboxFsStat =
154 // `mode` is the complete POSIX mode value, including the file-type bits.
155 | { type: 'file'; mode: number; size: number }
156 | { type: 'dir'; mode: number }
157 | { type: 'symlink'; mode: number }
158 | { type: 'other'; mode: number }
159​
160/**
161 * Uniform git surface. Implementations either delegate to the provider's
162 * native git (when advertised) or desugar to `process.exec("git …")`, so the
163 * contract is identical across providers.
164 */
165export interface SandboxGit {
166 clone: (input: {
167 url: string
168 dir?: string
169 ref?: string
170 auth?: { username?: string; token: string }
171 depth?: number | 'full'
172 }) => Promise<void>
173 status: (dir?: string) => Promise<string>
174 add: (paths: Array<string>, dir?: string) => Promise<void>
175 commit: (message: string, dir?: string) => Promise<void>
176 push: (dir?: string) => Promise<void>
177 pull: (dir?: string) => Promise<void>
178 /** Returns the current branch name. */
179 branch: (dir?: string) => Promise<string>
181​
182/** A reachable channel to a port inside the sandbox. */
183export interface SandboxChannel {
184 /** URL the host can reach (localhost / host-bound port / authenticated preview URL). */
185 url: string
186 /** Bearer token gating the channel, when the provider issues one. */
187 token?: string
188 /**
189 * Ready-to-send HTTP headers that authenticate requests to {@link url}, when
190 * the provider's auth doesn't fit a plain `Authorization: Bearer <token>`
191 * (e.g. Daytona's `x-daytona-preview-token`). Consumers that speak HTTP to the
192 * channel should attach these verbatim; the provider owns the header names so
193 * consumers stay provider-agnostic.
194 */
195 headers?: Record<string, string>
197​
198export interface SandboxPorts {
199 /** Expose `port` and resolve the best reachable channel for the host. */
200 connect: (port: number) => Promise<SandboxChannel>
202​
203export interface SandboxEnv {
204 set: (vars: Record<string, string>) => Promise<void>
206​
207/** Opaque reference to a stored snapshot, used to restore later. */
208export interface SnapshotRef {
209 id: string
210 label?: string
212​
213/** The uniform runtime surface a sandbox exposes. */
214export interface SandboxHandle {
215 /** Provider-assigned id used to reconnect to this sandbox. */
216 readonly id: string
217 /** Provider name (e.g. "docker", "cloudflare", "local-process"). */
218 readonly provider: string
219 /**
220 * Real filesystem path backing the virtual workspace root (`/workspace`).
221 * Harness CLIs and ACP `newSession` interpret cwd literally — use
222 * {@link resolveHarnessCwd} rather than the virtual path when the provider
223 * maps `/workspace` elsewhere (Daytona, Vercel, local-process).
224 */
225 readonly workspaceRoot?: string
226 /** What this sandbox can do. */
227 readonly capabilities: SandboxCapabilities
228 readonly fs: SandboxFs
229 readonly git: SandboxGit
230 readonly process: SandboxProcess
231 readonly ports: SandboxPorts
232 readonly env: SandboxEnv
233 /** Capability-gated: throws UnsupportedCapabilityError if `capabilities.snapshots` is false. */
234 snapshot?: (label?: string) => Promise<SnapshotRef>
235 /** Capability-gated: throws UnsupportedCapabilityError if `capabilities.fork` is false. */
236 fork?: () => Promise<SandboxHandle>
237 destroy: () => Promise<void>
239​
240/** Input passed to {@link SandboxProvider.create}. */
241export interface SandboxCreateInput {
242 /**
243 * Deterministic instance id the caller wants the provider to use. `ensure()`
244 * passes the compound sandbox key here so the provider-assigned id is
245 * reconstructable from run context (thread/workspace/tenant/reuse) instead of
246 * being a random value only recoverable from the sandbox store. Providers
247 * whose native id is addressable by name (e.g. Cloudflare's DO id) SHOULD
248 * honor it (`input.id ?? <random>`); providers that mint their own opaque id
249 * MAY ignore it. Consumers that reconnect out-of-band — e.g. attaching a
250 * preview iframe to the exact sandbox an agent is editing — rely on this being
251 * honored to avoid addressing two different sandboxes.
252 */
253 id?: string
254 workspace?: WorkspaceDefinition
255 policy?: SandboxPolicy
256 env?: Record<string, string>
257 signal?: AbortSignal
258 /** Harness adapter name. Optional. Providers that do not use it ignore it. */
259 adapterName?: string
261​
262/** Input passed to {@link SandboxProvider.resume}. */
263export interface SandboxResumeInput {
264 /** Provider-assigned sandbox id recorded by a prior run. */
265 id: string
266 signal?: AbortSignal
268​
269/** Input passed to {@link SandboxProvider.restoreSnapshot}. */
270export interface SandboxRestoreInput {
271 snapshotId: string
272 workspace?: WorkspaceDefinition
273 policy?: SandboxPolicy
274 env?: Record<string, string>
275 signal?: AbortSignal
277​
278/** Input passed to {@link SandboxProvider.destroy}. */
279export interface SandboxDestroyInput {
280 id: string
281 signal?: AbortSignal
283​
284/**
285 * Owns an isolation primitive. Implemented by `@tanstack/ai-sandbox-*`
286 * provider packages.
287 */
288export interface SandboxProvider {
289 readonly name: string
290 /** Static capability descriptor. */
291 capabilities: () => SandboxCapabilities
292 create: (input: SandboxCreateInput) => Promise<SandboxHandle>
293 /** Reconnect to an existing sandbox by id; resolves null if it's gone. */
294 resume: (input: SandboxResumeInput) => Promise<SandboxHandle | null>
295 /** Capability-gated: present only when `capabilities().snapshots` is true. */
296 restoreSnapshot?: (input: SandboxRestoreInput) => Promise<SandboxHandle>
297 destroy: (input: SandboxDestroyInput) => Promise<void>