@finalai/sandbox-router-e2b 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,784 @@
1
+ import {
2
+ AtEnd,
3
+ attempt,
4
+ canonicalJson,
5
+ defineProvider,
6
+ EgressMode,
7
+ ExitReason,
8
+ fail,
9
+ failFromStatus,
10
+ FileKind,
11
+ fitWithinLimits,
12
+ imageKey,
13
+ ImageStrategy,
14
+ ok,
15
+ PauseKeep,
16
+ PortAuth,
17
+ ProcessSignal,
18
+ SandboxRouterErrorCode,
19
+ SandboxState,
20
+ sha256Hex,
21
+ shellQuote,
22
+ SPECIFICATION_VERSION
23
+ } from "@finalai/sandbox-router/provider";
24
+ import {
25
+ ALL_TRAFFIC,
26
+ AuthenticationError,
27
+ CommandExitError,
28
+ FileType,
29
+ InvalidArgumentError,
30
+ NotFoundError,
31
+ RateLimitError,
32
+ Sandbox,
33
+ SandboxError,
34
+ SandboxNotRunningError,
35
+ SandboxUnreachableError,
36
+ ServiceBusyError,
37
+ Template,
38
+ TimeoutError
39
+ } from "e2b";
40
+ import * as z from "zod";
41
+ import { E2B_CAPABILITIES, E2B_REGIONS, e2bLimits } from "./limits.mjs";
42
+ import {
43
+ createProcessRegistry,
44
+ processKey
45
+ } from "./process-history.mjs";
46
+ import { DEFAULT_TEMPLATE, templateOf } from "./template.mjs";
47
+ const e2bOptionsSchema = z.object({
48
+ // Start from this E2B template (name or id) instead of the default. Its size is the
49
+ // template's own.
50
+ template: z.string().min(1).optional()
51
+ }).strict();
52
+ const PROVIDER = "e2b";
53
+ const REGION = "us-west";
54
+ const DEFAULT_TIMEOUT_S = 3600;
55
+ const TEMPLATE_SIZE = { cpu: 2, memoryMib: 512 };
56
+ const TIMEOUT_KEY = "sandbox_router_timeout_s";
57
+ const RESERVED_KEYS = /* @__PURE__ */ new Set([TIMEOUT_KEY]);
58
+ const ENVD_PORT = 49983;
59
+ const classify = (cause) => {
60
+ const message = cause instanceof Error ? cause.message : String(cause);
61
+ if (cause instanceof NotFoundError)
62
+ return fail(SandboxRouterErrorCode.NotFound, `${PROVIDER} has no such resource`, {
63
+ status: 404,
64
+ nativeError: message
65
+ });
66
+ if (cause instanceof AuthenticationError)
67
+ return fail(SandboxRouterErrorCode.Unauthorized, `${PROVIDER} rejected the credentials`, {
68
+ status: 401,
69
+ nativeError: message
70
+ });
71
+ if (cause instanceof RateLimitError || cause instanceof ServiceBusyError)
72
+ return fail(SandboxRouterErrorCode.ProviderUnavailable, `${PROVIDER} is unavailable`, {
73
+ status: cause instanceof RateLimitError ? 429 : 503,
74
+ nativeError: message,
75
+ retryable: true
76
+ });
77
+ if (cause instanceof SandboxNotRunningError)
78
+ return fail(SandboxRouterErrorCode.NotFound, `the ${PROVIDER} sandbox is not running`, {
79
+ nativeError: message
80
+ });
81
+ if (cause instanceof SandboxUnreachableError)
82
+ return fail(
83
+ SandboxRouterErrorCode.ProviderUnavailable,
84
+ `the ${PROVIDER} sandbox is unreachable`,
85
+ {
86
+ nativeError: message,
87
+ retryable: true
88
+ }
89
+ );
90
+ if (cause instanceof TimeoutError)
91
+ return fail(SandboxRouterErrorCode.Timeout, `${PROVIDER} timed out`, {
92
+ nativeError: message,
93
+ retryable: true
94
+ });
95
+ if (cause instanceof InvalidArgumentError)
96
+ return fail(SandboxRouterErrorCode.InvalidRequest, `${PROVIDER} refused the request`, {
97
+ nativeError: message
98
+ });
99
+ if (cause instanceof SandboxError && cause.statusCode != null)
100
+ return failFromStatus(PROVIDER, cause.statusCode, message);
101
+ return null;
102
+ };
103
+ const call = (run) => attempt(PROVIDER, run, classify);
104
+ const stateOf = (state) => state === "running" ? SandboxState.Running : state === "paused" ? SandboxState.Paused : SandboxState.Unknown;
105
+ const labelsOf = (metadata) => Object.fromEntries(Object.entries(metadata).filter(([key]) => !RESERVED_KEYS.has(key)));
106
+ const sandboxOf = (info) => ({
107
+ providerSandboxId: info.sandboxId,
108
+ region: REGION,
109
+ state: stateOf(info.state),
110
+ nativeState: info.state,
111
+ nativeError: null,
112
+ labels: labelsOf(info.metadata),
113
+ createdAt: info.startedAt.toISOString(),
114
+ granted: { cpu: info.cpuCount, memoryMib: info.memoryMB, diskGib: null }
115
+ });
116
+ const entryOf = (entry) => ({
117
+ name: entry.name,
118
+ path: entry.path,
119
+ kind: entry.type === FileType.DIR ? FileKind.Directory : entry.type === FileType.SYMLINK ? FileKind.Symlink : entry.type === FileType.FILE ? FileKind.File : FileKind.Other,
120
+ size: entry.size,
121
+ modifiedAt: entry.modifiedTime?.toISOString() ?? null,
122
+ mode: entry.mode & 4095
123
+ });
124
+ const networkOf = (network) => {
125
+ if (network.egress === EgressMode.AllowAll) return {};
126
+ if (network.egress === EgressMode.DenyAll) return { allowInternetAccess: false };
127
+ const allowOut = [...network.egress.allowDomains ?? [], ...network.egress.allowCidrs ?? []];
128
+ return { network: { allowOut, denyOut: [ALL_TRAFFIC] } };
129
+ };
130
+ const networkUpdateOf = (network) => {
131
+ if (network.egress === EgressMode.AllowAll) return {};
132
+ if (network.egress === EgressMode.DenyAll) return { denyOut: [ALL_TRAFFIC] };
133
+ return {
134
+ allowOut: [...network.egress.allowDomains ?? [], ...network.egress.allowCidrs ?? []],
135
+ denyOut: [ALL_TRAFFIC]
136
+ };
137
+ };
138
+ const SIGNAL_NAMES = {
139
+ killed: "SIGKILL",
140
+ terminated: "SIGTERM",
141
+ interrupt: "SIGINT",
142
+ hangup: "SIGHUP",
143
+ aborted: "SIGABRT",
144
+ "segmentation fault": "SIGSEGV",
145
+ "broken pipe": "SIGPIPE"
146
+ };
147
+ const signalOf = (error) => {
148
+ const match = /signal: ([a-z ]+)/i.exec(error ?? "");
149
+ if (match == null) return null;
150
+ const name = match[1].trim().toLowerCase();
151
+ return SIGNAL_NAMES[name] ?? `SIG${name.toUpperCase().replaceAll(" ", "")}`;
152
+ };
153
+ const encoder = new TextEncoder();
154
+ const detailSchema = z.object({
155
+ envdAccessToken: z.string().nullish(),
156
+ domain: z.string().nullish(),
157
+ envdVersion: z.string().nullish()
158
+ });
159
+ const templateName = (value) => value.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 120);
160
+ const e2b = (credentials, options = {}) => {
161
+ const domain = options.domain ?? "e2b.app";
162
+ const api = {
163
+ apiKey: credentials.apiKey,
164
+ domain: options.domain,
165
+ requestTimeoutMs: options.requestTimeoutMs ?? 6e4
166
+ };
167
+ const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
168
+ const defaultTemplate = options.template ?? DEFAULT_TEMPLATE;
169
+ const defaultTimeoutS = options.defaultTimeoutS ?? DEFAULT_TIMEOUT_S;
170
+ const processes = createProcessRegistry();
171
+ const connected = /* @__PURE__ */ new Map();
172
+ const timeouts = /* @__PURE__ */ new Map();
173
+ const pausedKeeping = /* @__PURE__ */ new Map();
174
+ const sizedTemplates = /* @__PURE__ */ new Set();
175
+ const limits = e2bLimits;
176
+ const maxOutputBytes = limits.maxOutputBytes;
177
+ const timeoutOf = (info) => timeouts.get(info.sandboxId) ?? (Number(info.metadata[TIMEOUT_KEY]) || defaultTimeoutS);
178
+ const sandboxFor = async (id) => {
179
+ const cached = connected.get(id);
180
+ if (cached != null) return ok(cached);
181
+ const info = await call(() => Sandbox.getInfo(id, api));
182
+ if (!info.ok) return info;
183
+ const sandbox = await call(
184
+ () => Sandbox.connect(id, { ...api, timeoutMs: timeoutOf(info.value) * 1e3 })
185
+ );
186
+ if (sandbox.ok) connected.set(id, sandbox.value);
187
+ return sandbox;
188
+ };
189
+ const sizedTemplate = async (source, size) => {
190
+ if (size.cpu === TEMPLATE_SIZE.cpu && size.memoryMib === TEMPLATE_SIZE.memoryMib)
191
+ return ok(source);
192
+ const name = templateName(
193
+ `${source === DEFAULT_TEMPLATE ? "sandbox-router" : source}-${size.cpu}c-${size.memoryMib}m`
194
+ );
195
+ if (sizedTemplates.has(name)) return ok(name);
196
+ const exists = await call(() => Template.exists(name, api));
197
+ if (!exists.ok) return exists;
198
+ if (!exists.value) {
199
+ const built = await call(
200
+ () => Template.build(Template().fromTemplate(source), name, {
201
+ ...api,
202
+ cpuCount: size.cpu,
203
+ memoryMB: size.memoryMib
204
+ })
205
+ );
206
+ if (!built.ok) return built;
207
+ }
208
+ sizedTemplates.add(name);
209
+ return ok(name);
210
+ };
211
+ const startProcess = (args) => {
212
+ const { record, handle, sandbox } = args;
213
+ let killed = false;
214
+ let timedOut = false;
215
+ const killNow = async () => {
216
+ await handle.kill().catch(() => false);
217
+ };
218
+ const timer = args.timeoutMs == null ? null : setTimeout(() => {
219
+ timedOut = true;
220
+ void killNow();
221
+ }, args.timeoutMs);
222
+ void (async () => {
223
+ try {
224
+ const result = await handle.wait();
225
+ record.queue.exit(result.exitCode, timedOut ? ExitReason.Timeout : ExitReason.Exited);
226
+ } catch (cause) {
227
+ if (cause instanceof CommandExitError) {
228
+ const signal = signalOf(cause.error);
229
+ const code = cause.exitCode < 0 ? null : cause.exitCode;
230
+ record.queue.exit(
231
+ code,
232
+ timedOut ? ExitReason.Timeout : killed || signal != null ? ExitReason.Killed : ExitReason.Exited,
233
+ signal
234
+ );
235
+ } else if (cause instanceof SandboxNotRunningError || cause instanceof NotFoundError)
236
+ record.queue.exit(null, ExitReason.ProviderLost);
237
+ else
238
+ record.queue.error(
239
+ SandboxRouterErrorCode.ProviderError,
240
+ cause instanceof Error ? cause.message : String(cause)
241
+ );
242
+ } finally {
243
+ if (timer != null) clearTimeout(timer);
244
+ }
245
+ })();
246
+ const controls = {
247
+ write: async (data) => args.stdin ? call(() => handle.sendStdin(data)) : fail(SandboxRouterErrorCode.InvalidRequest, "the process was started without stdin"),
248
+ closeStdin: async () => {
249
+ if (!args.stdin) return ok(void 0);
250
+ const closed = await call(() => handle.closeStdin());
251
+ return closed.ok || record.ended() ? ok(void 0) : closed;
252
+ },
253
+ kill: async (signal) => {
254
+ killed = true;
255
+ if (signal == null || signal === ProcessSignal.Kill) {
256
+ const done = await call(() => handle.kill());
257
+ return done.ok ? ok(void 0) : done;
258
+ }
259
+ const sent = await call(
260
+ () => sandbox.commands.run(`kill -s ${signal.replace(/^SIG/, "")} ${args.pid} || true`, {
261
+ user: "root"
262
+ })
263
+ );
264
+ return sent.ok ? ok(void 0) : sent;
265
+ }
266
+ };
267
+ return record.open(String(args.pid), args.afterSeq, controls);
268
+ };
269
+ const outputSink = () => {
270
+ let record = null;
271
+ const early = [];
272
+ const push = (kind, bytes) => {
273
+ if (record == null) early.push([kind, bytes]);
274
+ else record.queue[kind](bytes);
275
+ };
276
+ return {
277
+ stdout: (text) => push("stdout", encoder.encode(text)),
278
+ stderr: (text) => push("stderr", encoder.encode(text)),
279
+ data: (bytes) => push("data", bytes.slice()),
280
+ bind: (target) => {
281
+ record = target;
282
+ for (const [kind, bytes] of early.splice(0)) target.queue[kind](bytes);
283
+ }
284
+ };
285
+ };
286
+ const fit = (spec) => {
287
+ const base = fitWithinLimits({ limits, spec });
288
+ if (spec.timeouts.idleS != null)
289
+ base.ignored.push({
290
+ field: "timeouts.idleS",
291
+ reason: "E2B ends sandboxes at a fixed lifetime, not after idle time"
292
+ });
293
+ if (spec.gpu != null) base.rejected.push({ field: "gpu", reason: "E2B has no GPUs" });
294
+ return base;
295
+ };
296
+ return defineProvider({
297
+ specificationVersion: SPECIFICATION_VERSION,
298
+ name: PROVIDER,
299
+ regions: E2B_REGIONS,
300
+ capabilities: E2B_CAPABILITIES,
301
+ limits,
302
+ providerOptions: e2bOptionsSchema,
303
+ fit,
304
+ create: async (spec, context) => {
305
+ const parsed = e2bOptionsSchema.safeParse(context.providerOptions ?? {});
306
+ if (!parsed.success) return fail(SandboxRouterErrorCode.InvalidRequest, parsed.error.message);
307
+ const granted = fit(spec).granted;
308
+ let template;
309
+ let sized = false;
310
+ if (context.snapshotId != null) template = context.snapshotId;
311
+ else if (parsed.data.template != null) template = parsed.data.template;
312
+ else {
313
+ const source = context.artifact?.id ?? defaultTemplate;
314
+ const resized = await sizedTemplate(source, granted);
315
+ if (!resized.ok) return resized;
316
+ template = resized.value;
317
+ sized = source === DEFAULT_TEMPLATE || context.artifact != null;
318
+ }
319
+ const timeoutS = spec.timeouts.maxS ?? defaultTimeoutS;
320
+ const idempotencyKey = `sandbox-router-${(await sha256Hex(
321
+ canonicalJson({ name: context.name, spec, labels: context.labels, template })
322
+ )).slice(0, 48)}`;
323
+ const created = await call(
324
+ () => Sandbox.create(template, {
325
+ ...api,
326
+ signal: context.signal,
327
+ idempotencyKey,
328
+ metadata: { ...context.labels, [TIMEOUT_KEY]: String(timeoutS) },
329
+ envs: { ...spec.image?.env, ...spec.env },
330
+ timeoutMs: timeoutS * 1e3,
331
+ lifecycle: {
332
+ onTimeout: spec.atEnd === AtEnd.Pause ? "pause" : "kill",
333
+ autoResume: false
334
+ },
335
+ ...networkOf(spec.network)
336
+ })
337
+ );
338
+ if (!created.ok) return created;
339
+ const sandbox = created.value;
340
+ connected.set(sandbox.sandboxId, sandbox);
341
+ if (!sized) {
342
+ const info = await call(() => Sandbox.getInfo(sandbox.sandboxId, api));
343
+ if (!info.ok) return info;
344
+ return ok(sandboxOf(info.value));
345
+ }
346
+ return ok({
347
+ providerSandboxId: sandbox.sandboxId,
348
+ region: REGION,
349
+ state: SandboxState.Running,
350
+ nativeState: "running",
351
+ nativeError: null,
352
+ labels: context.labels,
353
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
354
+ granted: { cpu: granted.cpu, memoryMib: granted.memoryMib, diskGib: null }
355
+ });
356
+ },
357
+ get: async (id) => {
358
+ const info = await call(() => Sandbox.getInfo(id, api));
359
+ if (!info.ok)
360
+ return info.error.code === SandboxRouterErrorCode.NotFound || info.error.code === SandboxRouterErrorCode.InvalidRequest ? ok(null) : info;
361
+ return ok(sandboxOf(info.value));
362
+ },
363
+ list: async ({ labels }) => call(async () => {
364
+ const paginator = Sandbox.list({
365
+ ...api,
366
+ query: { metadata: labels, state: ["running", "paused"] },
367
+ limit: 100
368
+ });
369
+ const found = [];
370
+ while (paginator.hasNext)
371
+ for (const info of await paginator.nextItems())
372
+ if (Object.entries(labels).every(([key, value]) => info.metadata[key] === value))
373
+ found.push(sandboxOf(info));
374
+ return found;
375
+ }),
376
+ delete: async (id) => {
377
+ connected.delete(id);
378
+ timeouts.delete(id);
379
+ processes.forgetSandbox(id);
380
+ const killed = await call(() => Sandbox.kill(id, api));
381
+ return killed.ok || killed.error.code === SandboxRouterErrorCode.NotFound ? ok(void 0) : killed;
382
+ },
383
+ pause: async (id, { keep }) => {
384
+ const pause = (mode) => call(() => Sandbox.pause(id, { ...api, mode }));
385
+ let kept = keep;
386
+ let paused = await pause(keep === PauseKeep.Files ? "filesystem" : "full");
387
+ if (!paused.ok && keep === PauseKeep.Files && paused.error.status === 400) {
388
+ kept = PauseKeep.Memory;
389
+ paused = await pause("full");
390
+ }
391
+ if (!paused.ok) return paused;
392
+ connected.delete(id);
393
+ pausedKeeping.set(id, kept);
394
+ return ok({ kept });
395
+ },
396
+ resume: async (id) => {
397
+ const info = await call(() => Sandbox.getInfo(id, api));
398
+ if (!info.ok) return info;
399
+ const resumed = await call(
400
+ () => Sandbox.connect(id, { ...api, timeoutMs: timeoutOf(info.value) * 1e3 })
401
+ );
402
+ if (!resumed.ok) return resumed;
403
+ connected.set(id, resumed.value);
404
+ const coldRestart = pausedKeeping.get(id) === PauseKeep.Files;
405
+ pausedKeeping.delete(id);
406
+ return ok({ coldRestart });
407
+ },
408
+ setTimeout: async (id, { maxS }) => {
409
+ if (maxS == null)
410
+ return fail(SandboxRouterErrorCode.UnsupportedByProvider, "E2B has no idle timeout");
411
+ const set = await call(() => Sandbox.setTimeout(id, maxS * 1e3, api));
412
+ if (!set.ok) return set;
413
+ timeouts.set(id, maxS);
414
+ return ok(void 0);
415
+ },
416
+ setNetwork: async (id, network) => {
417
+ const updated = await call(() => Sandbox.updateNetwork(id, networkUpdateOf(network), api));
418
+ return updated.ok ? ok(void 0) : updated;
419
+ },
420
+ exec: async (id, command, execOptions) => {
421
+ const sandbox = await sandboxFor(id);
422
+ if (!sandbox.ok) return sandbox;
423
+ const sink = outputSink();
424
+ const stdin = execOptions.stdin === true;
425
+ const started = await call(
426
+ () => sandbox.value.commands.run(command, {
427
+ background: true,
428
+ stdin,
429
+ cwd: execOptions.cwd,
430
+ envs: execOptions.env,
431
+ user: execOptions.user,
432
+ timeoutMs: 0,
433
+ retainOutput: false,
434
+ onStdout: sink.stdout,
435
+ onStderr: sink.stderr,
436
+ signal: execOptions.signal
437
+ })
438
+ );
439
+ if (!started.ok) return started;
440
+ const handle = started.value;
441
+ const record = processes.create(processKey(id, String(handle.pid)), {
442
+ maxOutputBytes,
443
+ onOutputCap: () => void handle.kill().catch(() => false)
444
+ });
445
+ record.queue.started(String(handle.pid), handle.pid);
446
+ sink.bind(record);
447
+ return ok(
448
+ startProcess({
449
+ id,
450
+ record,
451
+ pid: handle.pid,
452
+ handle,
453
+ stdin,
454
+ timeoutMs: execOptions.timeoutMs,
455
+ sandbox: sandbox.value,
456
+ afterSeq: -1
457
+ })
458
+ );
459
+ },
460
+ attach: async (id, processId, { afterSeq }) => {
461
+ const known = processes.get(processKey(id, processId));
462
+ const pid = Number(processId);
463
+ if (known != null) {
464
+ const sandbox2 = await sandboxFor(id);
465
+ if (!sandbox2.ok) return sandbox2;
466
+ const handleFor = sandbox2.value;
467
+ return ok(
468
+ known.open(processId, afterSeq, {
469
+ write: (data) => call(() => handleFor.commands.sendStdin(pid, data)),
470
+ closeStdin: async () => {
471
+ const closed = await call(() => handleFor.commands.closeStdin(pid));
472
+ return closed.ok || known.ended() ? ok(void 0) : closed;
473
+ },
474
+ kill: async () => {
475
+ const killed = await call(() => handleFor.commands.kill(pid));
476
+ return killed.ok ? ok(void 0) : killed;
477
+ }
478
+ })
479
+ );
480
+ }
481
+ if (!Number.isInteger(pid))
482
+ return fail(SandboxRouterErrorCode.NotFound, `no process ${processId}`);
483
+ const sandbox = await sandboxFor(id);
484
+ if (!sandbox.ok) return sandbox;
485
+ const sink = outputSink();
486
+ const handle = await call(
487
+ () => sandbox.value.commands.connect(pid, {
488
+ timeoutMs: 0,
489
+ retainOutput: false,
490
+ onStdout: sink.stdout,
491
+ onStderr: sink.stderr
492
+ })
493
+ );
494
+ if (!handle.ok) return handle;
495
+ const record = processes.create(processKey(id, processId), {
496
+ firstSeq: afterSeq + 1,
497
+ maxOutputBytes,
498
+ onOutputCap: () => void handle.value.kill().catch(() => false)
499
+ });
500
+ record.queue.gap(afterSeq + 1, null);
501
+ sink.bind(record);
502
+ return ok(
503
+ startProcess({
504
+ id,
505
+ record,
506
+ pid,
507
+ handle: handle.value,
508
+ stdin: true,
509
+ timeoutMs: void 0,
510
+ sandbox: sandbox.value,
511
+ afterSeq
512
+ })
513
+ );
514
+ },
515
+ pty: async (id, ptyOptions) => {
516
+ const sandbox = await sandboxFor(id);
517
+ if (!sandbox.ok) return sandbox;
518
+ const sink = outputSink();
519
+ const started = await call(
520
+ () => sandbox.value.pty.create({
521
+ cols: ptyOptions.cols,
522
+ rows: ptyOptions.rows,
523
+ cwd: ptyOptions.cwd,
524
+ envs: ptyOptions.env,
525
+ timeoutMs: 0,
526
+ onData: sink.data
527
+ })
528
+ );
529
+ if (!started.ok) return started;
530
+ const handle = started.value;
531
+ const pid = handle.pid;
532
+ const record = processes.create(processKey(id, String(pid)), {
533
+ maxOutputBytes,
534
+ onOutputCap: () => void handle.kill().catch(() => false)
535
+ });
536
+ record.queue.started(String(pid), pid);
537
+ sink.bind(record);
538
+ const terminal = sandbox.value;
539
+ const process = startProcess({
540
+ id,
541
+ record,
542
+ pid,
543
+ handle,
544
+ stdin: false,
545
+ timeoutMs: void 0,
546
+ sandbox: terminal,
547
+ afterSeq: -1
548
+ });
549
+ if (ptyOptions.command != null) {
550
+ const sent = await call(
551
+ () => terminal.pty.sendInput(pid, encoder.encode(`exec ${ptyOptions.command}
552
+ `))
553
+ );
554
+ if (!sent.ok) return sent;
555
+ }
556
+ return ok({
557
+ ...process,
558
+ write: (data) => call(() => terminal.pty.sendInput(pid, data)),
559
+ closeStdin: async () => ok(void 0),
560
+ resize: (size) => call(() => terminal.pty.resize(pid, size))
561
+ });
562
+ },
563
+ files: {
564
+ read: async (id, path, range = {}) => {
565
+ const sandbox = await sandboxFor(id);
566
+ if (!sandbox.ok) return sandbox;
567
+ return call(async () => {
568
+ const stream = await sandbox.value.files.read(path, { format: "stream" });
569
+ const start = range.offset ?? 0;
570
+ const end = range.length == null ? Number.POSITIVE_INFINITY : start + range.length;
571
+ const parts = [];
572
+ let position = 0;
573
+ const reader = stream.getReader();
574
+ for (; ; ) {
575
+ const next = await reader.read();
576
+ if (next.done) break;
577
+ const chunk = next.value;
578
+ const from = Math.max(0, start - position);
579
+ const to = Math.min(chunk.byteLength, end - position);
580
+ if (to > from) parts.push(chunk.subarray(from, to));
581
+ position += chunk.byteLength;
582
+ if (position >= end) {
583
+ await reader.cancel().catch(() => void 0);
584
+ break;
585
+ }
586
+ }
587
+ const bytes = new Uint8Array(parts.reduce((total, part) => total + part.byteLength, 0));
588
+ let offset = 0;
589
+ for (const part of parts) {
590
+ bytes.set(part, offset);
591
+ offset += part.byteLength;
592
+ }
593
+ return bytes;
594
+ });
595
+ },
596
+ write: async (id, path, bytes, writeOptions = {}) => {
597
+ const sandbox = await sandboxFor(id);
598
+ if (!sandbox.ok) return sandbox;
599
+ const written = await call(() => sandbox.value.files.write(path, bytes.slice()));
600
+ if (!written.ok) return written;
601
+ if (writeOptions.mode == null) return ok(void 0);
602
+ const mode = (writeOptions.mode & 4095).toString(8);
603
+ const changed = await call(
604
+ () => sandbox.value.commands.run(`chmod ${mode} ${shellQuote(path)}`)
605
+ );
606
+ return changed.ok ? ok(void 0) : changed;
607
+ },
608
+ list: async (id, path) => {
609
+ const sandbox = await sandboxFor(id);
610
+ if (!sandbox.ok) return sandbox;
611
+ const entries = await call(() => sandbox.value.files.list(path, { depth: 1 }));
612
+ return entries.ok ? ok(entries.value.map(entryOf)) : entries;
613
+ },
614
+ mkdir: async (id, path) => {
615
+ const sandbox = await sandboxFor(id);
616
+ if (!sandbox.ok) return sandbox;
617
+ const made = await call(() => sandbox.value.files.makeDir(path));
618
+ return made.ok ? ok(void 0) : made;
619
+ },
620
+ remove: async (id, path, removeOptions = {}) => {
621
+ const sandbox = await sandboxFor(id);
622
+ if (!sandbox.ok) return sandbox;
623
+ if (removeOptions.recursive !== true) {
624
+ const listed = await call(() => sandbox.value.files.list(path, { depth: 1 }));
625
+ if (listed.ok && listed.value.length > 0)
626
+ return fail(SandboxRouterErrorCode.InvalidRequest, `${path} is a non-empty directory`);
627
+ }
628
+ const removed = await call(() => sandbox.value.files.remove(path));
629
+ return removed.ok || removed.error.code === SandboxRouterErrorCode.NotFound ? ok(void 0) : removed;
630
+ },
631
+ stat: async (id, path) => {
632
+ const sandbox = await sandboxFor(id);
633
+ if (!sandbox.ok) return sandbox;
634
+ const info = await call(() => sandbox.value.files.getInfo(path));
635
+ if (!info.ok) return info.error.code === SandboxRouterErrorCode.NotFound ? ok(null) : info;
636
+ return ok(entryOf(info.value));
637
+ }
638
+ },
639
+ ports: {
640
+ url: async (id, port) => {
641
+ const info = await call(() => Sandbox.getInfo(id, api));
642
+ if (!info.ok) return info;
643
+ if (info.value.network?.allowPublicTraffic === false)
644
+ return fail(
645
+ SandboxRouterErrorCode.UnsupportedByProvider,
646
+ "the sandbox serves ports only with a traffic access token header"
647
+ );
648
+ return ok({
649
+ url: `https://${port}-${id}.${info.value.sandboxDomain ?? domain}`,
650
+ auth: PortAuth.Public,
651
+ token: null,
652
+ expiresAt: null
653
+ });
654
+ }
655
+ },
656
+ snapshot: async (id) => {
657
+ const taken = await call(() => Sandbox.createSnapshot(id, api));
658
+ return taken.ok ? ok({ snapshotId: taken.value.snapshotId }) : taken;
659
+ },
660
+ deleteSnapshot: async (snapshotId) => {
661
+ const deleted = await call(() => Sandbox.deleteSnapshot(snapshotId, api));
662
+ return deleted.ok || deleted.error.code === SandboxRouterErrorCode.NotFound ? ok(void 0) : deleted;
663
+ },
664
+ image: {
665
+ strategy: () => ImageStrategy.Build,
666
+ build: async (spec, buildContext) => {
667
+ const key = await call(() => imageKey(spec));
668
+ if (!key.ok) return key;
669
+ const base = spec.base;
670
+ if (base.kind === "oci" && base.registryCredential != null)
671
+ return fail(
672
+ SandboxRouterErrorCode.UnsupportedByProvider,
673
+ "private registry bases need their credential resolved before building"
674
+ );
675
+ const name = templateName(`sandbox-router-${key.value}`);
676
+ const copies = spec.steps.some((step) => step.kind === "copy");
677
+ const fs = copies ? await import("node:fs/promises") : null;
678
+ const contextPath = fs == null ? null : await fs.mkdtemp(`${(await import("node:os")).tmpdir()}/sandbox-router-e2b-`);
679
+ try {
680
+ const template = await call(
681
+ () => templateOf({
682
+ spec,
683
+ context: buildContext,
684
+ contextPath,
685
+ writeFile: async (path, bytes, mode) => {
686
+ if (fs == null) throw new Error("no build context");
687
+ await fs.mkdir(path.slice(0, path.lastIndexOf("/")), { recursive: true });
688
+ await fs.writeFile(path, bytes, { mode });
689
+ }
690
+ })
691
+ );
692
+ if (!template.ok) return template;
693
+ const built = await call(
694
+ () => Template.build(template.value, name, {
695
+ ...api,
696
+ signal: buildContext.signal,
697
+ cpuCount: TEMPLATE_SIZE.cpu,
698
+ memoryMB: TEMPLATE_SIZE.memoryMib,
699
+ onBuildLogs: (entry) => buildContext.onLog?.(entry.toString())
700
+ })
701
+ );
702
+ if (!built.ok) return built;
703
+ return ok({ kind: "template", id: name, startsOnBoot: spec.start != null });
704
+ } finally {
705
+ if (fs != null && contextPath != null)
706
+ await fs.rm(contextPath, { recursive: true, force: true }).catch(() => void 0);
707
+ }
708
+ },
709
+ // Removes the template and the sized templates derived from it.
710
+ remove: async (artifact) => call(async () => {
711
+ const derived = new RegExp(`^${artifact.id}-\\d+c-\\d+m$`);
712
+ const paginator = Template.list({ ...api, limit: 100 });
713
+ const names = [];
714
+ while (paginator.hasNext)
715
+ for (const template of await paginator.nextItems())
716
+ names.push(
717
+ ...template.names.filter(
718
+ (name) => derived.test((name.split("/").at(-1) ?? "").split(":")[0] ?? "")
719
+ )
720
+ );
721
+ for (const name of [...names, artifact.id]) {
722
+ sizedTemplates.delete(name);
723
+ await Template.delete(name, api);
724
+ }
725
+ })
726
+ },
727
+ connect: async (id) => {
728
+ let response;
729
+ try {
730
+ response = await doFetch(`https://api.${domain}/sandboxes/${encodeURIComponent(id)}`, {
731
+ headers: { "X-API-KEY": credentials.apiKey },
732
+ signal: AbortSignal.timeout(api.requestTimeoutMs)
733
+ });
734
+ } catch (cause) {
735
+ return fail(SandboxRouterErrorCode.NetworkError, `${PROVIDER} could not be reached`, {
736
+ retryable: true,
737
+ nativeError: cause instanceof Error ? cause.message : String(cause)
738
+ });
739
+ }
740
+ const text = await response.text();
741
+ if (!response.ok) return failFromStatus(PROVIDER, response.status, text);
742
+ let body;
743
+ try {
744
+ body = JSON.parse(text);
745
+ } catch {
746
+ body = null;
747
+ }
748
+ const detail = detailSchema.safeParse(body);
749
+ if (!detail.success)
750
+ return fail(
751
+ SandboxRouterErrorCode.InvalidResponse,
752
+ `${PROVIDER} returned an unexpected sandbox`,
753
+ {
754
+ nativeError: text.slice(0, 2e3)
755
+ }
756
+ );
757
+ const token = detail.data.envdAccessToken;
758
+ if (token == null || token === "")
759
+ return fail(
760
+ SandboxRouterErrorCode.UnsupportedByProvider,
761
+ "the sandbox has no envd access token"
762
+ );
763
+ const sandboxDomain = detail.data.domain ?? domain;
764
+ return ok({
765
+ provider: PROVIDER,
766
+ providerSandboxId: id,
767
+ kind: "envd_access_token",
768
+ token,
769
+ url: `https://${ENVD_PORT}-${id}.${sandboxDomain}`,
770
+ expiresAt: null,
771
+ details: {
772
+ header: "X-Access-Token",
773
+ sandboxDomain,
774
+ envdVersion: detail.data.envdVersion ?? ""
775
+ }
776
+ });
777
+ }
778
+ });
779
+ };
780
+ export {
781
+ e2b,
782
+ e2bOptionsSchema
783
+ };
784
+ //# sourceMappingURL=e2b.mjs.map