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

provider.ts

258 lines8.8 KB

1import { Sandbox, SandboxNotFoundError } from 'e2b'
2import { DEFAULT_WORKDIR, E2B_CAPS, E2BHandle } from './handle'
3import type { SandboxOpts } from 'e2b'
4import type {
5 SandboxCapabilities,
6 SandboxCreateInput,
7 SandboxDestroyInput,
8 SandboxHandle,
9 SandboxPolicy,
10 SandboxProvider,
11 SandboxRestoreInput,
12 SandboxResumeInput,
13} from '@tanstack/ai-sandbox'
14​
15export interface E2BSandboxConfig {
16 /**
17 * E2B API key. Falls back to the `E2B_API_KEY` env var (read by the SDK)
18 * when omitted.
19 */
20 apiKey?: string
21 /** E2B domain override (defaults to the SDK default / `E2B_DOMAIN`, `e2b.app`). */
22 domain?: string
23 /** E2B API URL override (defaults to the SDK default / `E2B_API_URL`). */
24 apiUrl?: string
25 /**
26 * Sandbox template name or ID to create sandboxes from. Defaults to the SDK
27 * default (`base`).
28 */
29 template?: string
30 /**
31 * Sandbox lifetime in milliseconds. E2B kills (or pauses, see `onTimeout`)
32 * the sandbox when it elapses; resume extends it by the same amount. Defaults
33 * to 30 minutes. E2B caps this at 1 hour on Hobby and 24 hours on Pro plans.
34 */
35 timeoutMs?: number
36 /**
37 * What E2B does when `timeoutMs` elapses. `'kill'` (default) destroys the
38 * sandbox so an abandoned run cannot keep billing. `'pause'` keeps its
39 * filesystem and memory so a later `resume` reconnects to the same sandbox.
40 */
41 onTimeout?: 'kill' | 'pause'
42 /**
43 * Working directory inside the sandbox. The `/workspace` virtual root maps
44 * here. Defaults to `/home/user/workspace` (`/workspace` itself is not
45 * writable by the sandbox user).
46 */
47 workdir?: string
48 /** Extra metadata attached to every created sandbox (visible in the E2B dashboard). */
49 metadata?: Record<string, string>
50 /**
51 * Whether sandbox ports are reachable without a token. Defaults to E2B's
52 * default (`true`). Set `false` to gate every preview URL behind the
53 * `e2b-traffic-access-token` header that `ports.connect` then returns.
54 */
55 allowPublicTraffic?: boolean
57​
58/** Metadata key carrying the deterministic id `ensure()` passes to `create`. */
59export const INSTANCE_KEY_METADATA = 'tanstack-ai-key'
60​
61const DEFAULT_TIMEOUT_MS = 30 * 60_000
62​
63/**
64 * The SDK sends the API key as a header to `apiUrl`, so a plain-http URL would
65 * leak it. Loopback is allowed for the SDK's own debug server.
66 */
67function assertHttps(apiUrl: string): void {
68 const url = new URL(apiUrl)
69 const loopback = url.hostname === 'localhost' || url.hostname === '127.0.0.1'
70 if (url.protocol !== 'https:' && !loopback) {
71 throw new Error(
72 `e2b: apiUrl must use https (got ${url.protocol}//${url.host}); the API key travels in a request header.`,
73 )
74 }
76​
77/**
78 * `Sandbox.create` that rejects promptly on abort. The SDK's `signal` only
79 * cancels the HTTP request, so an accepted create would leave a billed sandbox
80 * nobody holds the id for. On abort the caller is released at once, and the
81 * sandbox is killed whenever the create eventually settles.
82 */
83async function createSandbox(
84 opts: SandboxOpts,
85 signal: AbortSignal | undefined,
86): Promise<Sandbox> {
87 signal?.throwIfAborted()
88 const creation = Sandbox.create(opts)
89 if (!signal) return creation
90 const aborted = new Promise<never>((_, reject) => {
91 signal.addEventListener('abort', () => reject(signal.reason), {
92 once: true,
93 })
94 })
95 try {
96 return await Promise.race([creation, aborted])
97 } catch (error) {
98 if (signal.aborted) {
99 void creation.then((sandbox) => sandbox.kill()).catch(() => undefined)
100 }
101 throw error
102 }
104​
105class E2BProvider implements SandboxProvider {
106 readonly name = 'e2b'
107​
108 constructor(private readonly config: E2BSandboxConfig) {
109 if (config.apiUrl !== undefined) assertHttps(config.apiUrl)
110 }
111​
112 capabilities(): SandboxCapabilities {
113 return E2B_CAPS
114 }
115​
116 private get workdir(): string {
117 return this.config.workdir ?? DEFAULT_WORKDIR
118 }
119​
120 private get timeoutMs(): number {
121 return this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS
122 }
123​
124 /** Connection options common to every SDK call. */
125 private get connection(): Pick<SandboxOpts, 'apiKey' | 'domain' | 'apiUrl'> {
126 const opts: Pick<SandboxOpts, 'apiKey' | 'domain' | 'apiUrl'> = {}
127 if (this.config.apiKey !== undefined) opts.apiKey = this.config.apiKey
128 if (this.config.domain !== undefined) opts.domain = this.config.domain
129 if (this.config.apiUrl !== undefined) opts.apiUrl = this.config.apiUrl
130 return opts
131 }
132​
133 private createOpts(input: {
134 /** Template or snapshot id to create from; defaults to `config.template`. */
135 template?: string
136 id?: string
137 env?: Record<string, string>
138 policy?: SandboxPolicy
139 }): SandboxOpts {
140 const metadata: Record<string, string> = { ...this.config.metadata }
141 // E2B mints its own sandbox id, so the deterministic key rides along as
142 // metadata: `Sandbox.list({ query: { metadata } })` can find it again.
143 if (input.id !== undefined) metadata[INSTANCE_KEY_METADATA] = input.id
144 const template = input.template ?? this.config.template
145 return {
146 ...this.connection,
147 ...(template !== undefined ? { template } : {}),
148 timeoutMs: this.timeoutMs,
149 metadata,
150 ...(input.env !== undefined && Object.keys(input.env).length > 0
151 ? { envs: input.env }
152 : {}),
153 // The contract's network gate is coarse (allow/ask/deny): only an explicit
154 // deny maps, onto E2B's "no internet" switch.
155 ...(input.policy?.capabilities?.network === 'deny'
156 ? { allowInternetAccess: false }
157 : {}),
158 ...(this.config.allowPublicTraffic !== undefined
159 ? { network: { allowPublicTraffic: this.config.allowPublicTraffic } }
160 : {}),
161 lifecycle: { onTimeout: this.config.onTimeout ?? 'kill' },
162 }
163 }
164​
165 /**
166 * A fresh sandbox has no workdir yet, and every handle command runs in it.
167 * `makeDir` is a native call (no cwd of its own), so it is safe here. Any
168 * failure, or an abort that landed meanwhile, kills the sandbox.
169 */
170 private async prepare(
171 sandbox: Sandbox,
172 signal: AbortSignal | undefined,
173 ): Promise<SandboxHandle> {
174 try {
175 await sandbox.files.makeDir(this.workdir)
176 } catch (error) {
177 await sandbox.kill().catch(() => undefined)
178 throw error
179 }
180 if (signal?.aborted === true) {
181 await sandbox.kill().catch(() => undefined)
182 signal.throwIfAborted()
183 }
184 return new E2BHandle({
185 sandbox,
186 workdir: this.workdir,
187 timeoutMs: this.timeoutMs,
188 })
189 }
190​
191 async create(input: SandboxCreateInput): Promise<SandboxHandle> {
192 const sandbox = await createSandbox(
193 this.createOpts({
194 ...(input.id !== undefined ? { id: input.id } : {}),
195 ...(input.env !== undefined ? { env: input.env } : {}),
196 ...(input.policy !== undefined ? { policy: input.policy } : {}),
197 }),
198 input.signal,
199 )
200 return this.prepare(sandbox, input.signal)
201 }
202​
203 async restoreSnapshot(input: SandboxRestoreInput): Promise<SandboxHandle> {
204 // `SandboxRestoreInput` carries a policy too. Dropping it would restore a
205 // snapshot taken under `network: 'deny'` into a sandbox with open egress.
206 const sandbox = await createSandbox(
207 this.createOpts({
208 template: input.snapshotId,
209 ...(input.env !== undefined ? { env: input.env } : {}),
210 ...(input.policy !== undefined ? { policy: input.policy } : {}),
211 }),
212 input.signal,
213 )
214 // The snapshot already contains the workdir; `makeDir` is idempotent.
215 return this.prepare(sandbox, input.signal)
216 }
217​
218 async resume(input: SandboxResumeInput): Promise<SandboxHandle | null> {
219 input.signal?.throwIfAborted()
220 try {
221 // `connect` resumes a paused sandbox and extends a running one's
222 // timeout when the new value is longer.
223 const sandbox = await Sandbox.connect(input.id, {
224 ...this.connection,
225 timeoutMs: this.timeoutMs,
226 ...(input.signal !== undefined ? { signal: input.signal } : {}),
227 })
228 return new E2BHandle({
229 sandbox,
230 workdir: this.workdir,
231 timeoutMs: this.timeoutMs,
232 })
233 } catch (error) {
234 // Killed or expired sandboxes are gone; anything else (auth, transport)
235 // must surface so `ensure()` does not silently create a duplicate.
236 if (error instanceof SandboxNotFoundError) return null
237 throw error
238 }
239 }
240​
241 async destroy(input: SandboxDestroyInput): Promise<void> {
242 input.signal?.throwIfAborted()
243 // Resolves `false` for a sandbox that is already gone; that is success.
244 await Sandbox.kill(input.id, {
245 ...this.connection,
246 ...(input.signal !== undefined ? { signal: input.signal } : {}),
247 })
248 }
250​
251/**
252 * E2B sandbox provider — runs harness adapters inside isolated E2B cloud
253 * sandboxes through the uniform `SandboxHandle`. Requires an E2B API key
254 * (`config.apiKey` or the `E2B_API_KEY` env var).
255 */
256export function e2bSandbox(config: E2BSandboxConfig = {}): SandboxProvider {
257 return new E2BProvider(config)