E2B
Run sandboxes as E2B microVMs. Pause with memory intact, snapshots, templates, a PTY terminal, native file watching, metrics, network allow lists, and a hard lifetime a reconnect can't extend.
e2b() runs each sandbox as an E2B microVM. It calls E2B’s API and the daemon inside each sandbox over HTTP, so you install no E2B package.
Install
npm install @opencoredev/sandbox-sdkpnpm add @opencoredev/sandbox-sdkyarn add @opencoredev/sandbox-sdkbun add @opencoredev/sandbox-sdkSet E2B_API_KEY on your server, and keep it out of browser bundles.
Quickstart
import { createSandbox } from "@opencoredev/sandbox-sdk";
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
await using box = await createSandbox(e2b());
const result = await box.run("python3 -c 'print(2 + 2)'");
console.log(result.stdout);
This prints 4. await using destroys the sandbox when the block ends.
What it supports
| Feature | Support | Notes |
|---|---|---|
| Commands and streaming | Yes | Live output through E2B’s command API |
| Files | Yes | |
| Background processes | Yes | |
| Preview URLs | Yes | Public https:// URL by default, no ports to declare. public: false requires a token header |
| Pause and resume | Yes | Memory and files survive |
| Snapshots | Yes | Kept until you delete them with deleteSnapshot. expiresInMs fails with unsupported |
| Templates | Yes | buildTemplate builds from an image or another template |
| File watching | Native | Events come from envd as they happen, not by polling |
| Metrics | Yes | box.usage() adds the newest CPU, memory and disk sample; box.ext.e2b.metrics() returns the history |
| Machine size | No | Fixed by the template |
| Network policy | Yes | "none" or a host allow list |
Hard lifetime (timeoutMs) |
Yes | Reconnect and resume never extend it. With autoPause, it is the running time before E2B pauses the sandbox |
Idle timeout (idleTimeoutMs) |
No | E2B measures elapsed time only |
| Keys | Best-effort | Found by metadata search |
| Terminal | Yes | A login shell on a PTY, as root |
The capability matrix compares these with every other provider.
Run commands
Await box.run for the result, or iterate it to stream output as it arrives.
import { createSandbox } from "@opencoredev/sandbox-sdk";
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
await using box = await createSandbox(e2b());
const result = await box.run("ls -la", { cwd: "/workspace", timeoutMs: 30_000 });
console.log(result.exitCode, result.stdout);
for await (const chunk of box.run("for i in 1 2 3; do echo $i; sleep 1; done")) {
process.stdout.write(chunk.text);
}
Commands run as root.
Files
Relative paths resolve against /workspace.
import { createSandbox } from "@opencoredev/sandbox-sdk";
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
await using box = await createSandbox(e2b());
await box.files.write("notes/todo.txt", "ship the docs\n");
console.log(await box.files.read("notes/todo.txt"));
console.log(await box.files.list("notes"));
await box.files.write("secrets/token", "abc123", { mode: 0o600 });
E2B’s file API has no mode, so for { mode } the SDK runs chmod right after the write.
Background processes and previews
box.preview(port) returns https:// plus E2B’s host for that port.
import { createSandbox } from "@opencoredev/sandbox-sdk";
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
await using box = await createSandbox(e2b());
await box.start("python3 -m http.server 3000", { name: "web", ready: { port: 3000 } });
const preview = await box.preview(3000);
console.log(preview.url);
Previews are public by default. With public: false, E2B rejects requests that lack the sandbox’s traffic token, and preview() returns it in headers:
import { createSandbox } from "@opencoredev/sandbox-sdk";
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
await using box = await createSandbox(e2b({ public: false }));
await box.start("python3 -m http.server 3000", { name: "web", ready: { port: 3000 } });
const { url, headers } = await box.preview(3000);
const response = await fetch(url, { headers }); // headers: { "e2b-traffic-access-token": "..." }
console.log(response.status);
Pause, resume, and snapshots
A paused sandbox keeps its memory and file system and stops using compute. snapshot() returns E2B’s snapshot ID, which from accepts.
import { createSandbox } from "@opencoredev/sandbox-sdk";
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
await using box = await createSandbox(e2b(), { key: "user:123" });
await box.pause();
await box.resume();
const { id } = await box.snapshot();
await using copy = await createSandbox(e2b(), { from: id });
E2B keeps snapshots until you delete them, so snapshot({ expiresInMs }) fails with unsupported. expiresInMs: 0 is accepted. Delete one with deleteSnapshot, which needs no sandbox and resolves false when the snapshot was already gone:
import { createSandbox, deleteSnapshot } from "@opencoredev/sandbox-sdk";
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
const provider = e2b();
await using box = await createSandbox(provider);
const { id } = await box.snapshot();
console.log(await deleteSnapshot(provider, id)); // true
With autoPause, E2B pauses the sandbox when its timeout runs out instead of killing it. timeoutMs then sets the running time before that pause, and the SDK records no hard deadline. Add autoResume to wake the sandbox when a request reaches one of its preview URLs. Otherwise, connectSandbox or box.resume() brings it back.
import { createSandbox } from "@opencoredev/sandbox-sdk";
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
const box = await createSandbox(e2b({ autoPause: true, autoResume: true }), {
key: "user:123",
timeoutMs: 10 * 60_000, // paused after 10 minutes of running, not destroyed
});
Templates
buildTemplate builds a reusable E2B template and waits until it is ready. Start sandboxes from it with from, or pass its name as the factory’s template.
import { buildTemplate, createSandbox } from "@opencoredev/sandbox-sdk";
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
const provider = e2b();
const template = await buildTemplate(
provider,
{
name: "node-dev",
image: "node:22-bookworm",
env: { NODE_ENV: "development" },
run: ["npm install -g pnpm"],
size: { cpu: 2, memoryMb: 2048 },
},
{ onLog: (line) => console.log(line), timeoutMs: 15 * 60_000 },
);
await using box = await createSandbox(provider, { from: template.id });
Each run command is one build step and runs as root. Without image, E2B’s base image is used. env and workdir apply to the build steps only, as in E2B’s own template builder: pass env to createSandbox for the sandboxes. Files a step writes under /tmp don’t survive into the template, so write to a path such as /opt instead. Beyond the portable fields, E2B accepts fromTemplate (start from another template instead of an image), startCommand and readyCommand (a process kept running in the template, and the check that must pass before E2B snapshots it), tags, and skipCache.
timeoutMs covers the whole build, 30 minutes by default. When it runs out, or the signal aborts, the error names the template and build IDs, because the build keeps running on E2B. A failed build throws provider naming the failed step; the reason is in the log lines passed to onLog.
Terminal
box.terminal() opens a login shell on a PTY. Output arrives as text through onData, with secrets redacted like command output. Output that arrives before the first onData call is kept, so the prompt is not lost.
import { createSandbox } from "@opencoredev/sandbox-sdk";
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
await using box = await createSandbox(e2b());
const terminal = await box.terminal({ cols: 120, rows: 40, cwd: "/workspace" });
terminal.onData((data) => process.stdout.write(data));
await terminal.write("ls -la\r");
await terminal.resize(100, 30);
await terminal.write("exit\r");
console.log(await terminal.wait?.()); // { exitCode: 0 }
The shell starts with the sandbox’s environment, plus TERM=xterm-256color and LANG=C.UTF-8 unless you set them in env. close() kills it.
Watch files
box.files.watch uses envd’s file events, so changes arrive as they happen. Creating a file reports added, a write or a permission change modified, and a delete or a rename away removed. One write can report both added and modified.
import { createSandbox } from "@opencoredev/sandbox-sdk";
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
await using box = await createSandbox(e2b());
const stop = box.files.watch("src", (event) => console.log(event.type, event.path), {
recursive: true,
onError: (error) => console.error(error.code),
});
await box.files.write("src/index.ts", "export {};\n");
stop();
If the watch stream breaks, onError receives the error and the watch starts again a second later. A template with an envd older than 0.1.4 can’t watch recursively, so the SDK polls instead.
Metrics
box.usage() adds E2B’s newest metric sample to the SDK’s own counters. The fields are absent until E2B has taken a sample, a few seconds after creation, and when the metrics request fails; usage() never fails because of metrics. box.ext.e2b.metrics() throws instead.
import { createSandbox } from "@opencoredev/sandbox-sdk";
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
await using box = await createSandbox(e2b());
const usage = await box.usage();
console.log(usage.cpuPercent, usage.memoryBytes, usage.memoryLimitBytes, usage.diskBytes);
const history = await box.ext.e2b.metrics({ startMs: Date.now() - 10 * 60_000 });
console.log(history.length);
box.ext.e2b holds the features only E2B has. metrics() returns every sample in the window, oldest first, with E2B’s own field names (cpuUsedPct, memUsed, memTotal, diskUsed, diskTotal).
Size, network, and lifetime
The template fixes CPU, memory, and disk, so any size fails with unsupported. Build a template with the machine you need and pass it as template.
import { createSandbox } from "@opencoredev/sandbox-sdk";
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
await using box = await createSandbox(e2b({ template: "my-node-template" }), {
network: { allow: ["registry.npmjs.org"] },
timeoutMs: 30 * 60_000,
});
Host rules match on the HTTP Host header and TLS SNI, and DNS stays allowed. See E2B internet access for what that blocks.
Configuration
| Option | Type | Default | Env var |
|---|---|---|---|
apiKey |
string |
E2B_API_KEY |
|
template |
string |
"base" |
|
domain |
string |
e2b.app |
E2B_DOMAIN |
requestTimeoutMs |
number |
60000 |
|
public |
boolean |
true |
|
autoPause |
boolean |
false |
|
autoResume |
boolean |
false, needs autoPause |
|
volumes |
Record<string, string> |
requestTimeoutMs bounds each E2B control-plane request. volumes maps absolute mount paths to E2B volume names or IDs, for example { "/data": "my-volume" }. Volumes must be enabled on your E2B team.
A custom template needs sh, bash, setsid, and git.
Call the API directly
box.native calls any E2B endpoint with the adapter’s credentials, retries, error mapping, and redaction. It has two planes:
| Plane | Base URL | Credentials | What is there |
|---|---|---|---|
"api" (default) |
https://api.{domain} |
X-API-KEY |
The E2B REST API: sandboxes, snapshots, templates |
"envd" |
The sandbox’s envd daemon | The sandbox’s access token | GET /health, GET and POST /files, and the filesystem.Filesystem and process.Process RPCs as Connect JSON |
{sandboxId} in a path fills itself from the sandbox. An envd RPC is a POST to /{service}/{method} with the request message as the JSON body.
import { createSandbox } from "@opencoredev/sandbox-sdk";
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
await using box = await createSandbox(e2b());
const info = await box.native.request<{ state: string; endAt: string }>(
"GET",
"/sandboxes/{sandboxId}",
);
console.log(info.state, info.endAt);
const { processes = [] } = await box.native.request<{ processes?: { pid: number }[] }>(
"POST",
"/process.Process/List",
{
plane: "envd",
body: {},
},
);
console.log(processes.length);
await box.files.write("/tmp/data.bin", new Uint8Array([0, 1, 2]));
const response = await box.native.fetch("GET", "/files", {
plane: "envd",
query: { path: "/tmp/data.bin", username: "root" },
});
console.log(new Uint8Array(await response.arrayBuffer()));
request resolves with the JSON body. fetch resolves with the raw Response, so read the body or cancel it.
For calls about your account rather than one sandbox, use the factory’s api. It has no sandbox and no envd plane:
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
const provider = e2b();
const templates = await provider.api.request<{ templateID: string }[]>("GET", "/templates");
console.log(templates.map((template) => template.templateID));
// A snapshot ID from box.snapshot() is a template ID.
await provider.api.request("DELETE", "/templates/{id}", { params: { id: "snapshot-id" } });
To use the official SDK for something the SDK doesn’t wrap, install e2b and pass its import to sdk. On box.native you get an e2b Sandbox for this sandbox, built from its existing connection, so no API call is made and its timeout doesn’t change. On provider.api you get an E2B client with the same API key.
import { createSandbox } from "@opencoredev/sandbox-sdk";
import { e2b } from "@opencoredev/sandbox-sdk/e2b";
await using box = await createSandbox(e2b());
const sandbox = await box.native.sdk(() => import("e2b"));
const result = await sandbox.commands.run("echo from the e2b SDK");
console.log(result.stdout);
const client = await e2b().api.sdk(() => import("e2b"));
const page = await client.Sandbox.list().nextItems();
console.log(page.length);
In earlier betas, box.native was the e2b Sandbox itself. Replace box.native.commands.run(...) with (await box.native.sdk(() => import("e2b"))).commands.run(...), or with a request call.
Limitations
- Keys are best-effort. Pass a
locatorfor exact get-or-create. sizefails withunsupported. Pick the machine in the template.idleTimeoutMsfails withunsupported. UsetimeoutMs, or Daytona for idle auto-stop.snapshot({ expiresInMs })fails withunsupported. Delete snapshots withdeleteSnapshot.- Template builds take the portable steps plus E2B’s start and ready commands. Copying local files into a template, registry credentials, and Dockerfiles need the
e2bpackage’sTemplatebuilder throughprovider.api.sdk.
How it works
- Your
labelsbecome E2B metadata.sandbox-sdk-keyandsandbox-sdk-deadlineare reserved. - The SDK stores the
timeoutMsdeadline in metadata and clamps E2B’s timeout back to it on every connect and resume. WithautoPauseit stores no deadline. - After creation the SDK reads the network settings back from E2B, including
public: false. If they don’t match, it destroys the sandbox and throwsunsupported. - Commands, files, and processes go to envd, the daemon inside the sandbox. Each command start carries a unique tag, so a start that was cancelled, or whose response was lost, can still be found and stopped.
Next steps
- Lifecycle and cleanup
- Give your agent a sandbox
- E2B self-hosted: run E2B Embed on your own machine and point
e2b()at it - E2B SDK and API in TypeScript: the
e2bpackage and REST API next toe2b() - Daytona SDK and API in TypeScript: the same task on Daytona, and moving it there from E2B