@e2b/ai-sdk-sandbox

中文文档
0.3.0发布于 2026/08/28MITTypeScriptES Module构建来源已验证近 30 天下载 1.9万

E2B sandbox provider for the Vercel AI SDK

原始使用文档
文档目录9 节
  1. Setup
  2. Usage
  3. Settings
  4. Mid-session network policy
  5. Request transformations and credential brokering
  6. Running an agent (Claude Code, Codex)
  7. Good to know
  8. Examples
  9. License

AI SDK - E2B Sandbox

This package is experimental and targets AI SDK 7 (now stable).

Run your agent's code inside E2B sandboxes from the AI SDK. It's the E2B counterpart to @ai-sdk/sandbox-vercel. Drop it into a HarnessAgent, or hand a session straight to your AI SDK tools.

For how the harness itself works, see the AI SDK harness docs.

Setup

npm i @e2b/ai-sdk-sandbox

Set E2B_API_KEY (or pass apiKey in the settings). Calling createE2BSandbox() doesn't reach E2B on its own. The sandbox is created when you call createSession().

Usage

import { createE2BSandbox } from '@e2b/ai-sdk-sandbox';

const e2bSandbox = createE2BSandbox({ template: 'base' });

const sandboxSession = await e2bSandbox.createSession();
// restricted() returns the same sandbox narrowed to the tool-safe surface
// (file I/O, run, spawn) with no lifecycle or network controls — this is what
// you hand an AI SDK tool's execute().
const restrictedSandboxSession = sandboxSession.restricted();

await restrictedSandboxSession.writeTextFile({ path: 'hello.txt', content: 'hi' });

const { stdout } = await restrictedSandboxSession.run({ command: 'cat hello.txt' });
console.log(stdout); // "hi"

await sandboxSession.stop();

restricted() gives you an Experimental_SandboxSession: the same underlying sandbox, narrowed to the tool-facing surface (file I/O, run, spawn), just a view with the infra bits (ports, getPortEndpoint, setNetworkPolicy, stop) removed. That's the security boundary: code you hand the restricted view can't stop the box or change its network policy. Pass it to an AI SDK tool's execute() via experimental_sandbox; the full session stays with the harness. (See the harness docs for the restricted() contract.)

Settings

Everything goes in the object you pass to createE2BSandbox(...):

const e2bSandbox = createE2BSandbox({
  template: 'base',                                // any E2B SandboxOpts
  envs: { NODE_ENV: 'production' },
  timeoutMs: 10 * 60 * 1000,                       // optional; defaults to 30 min
  ports: [3000],                                   // provider option
  setupCommands: ['sudo npm install -g pnpm@9'],   // provider option
});

Any of E2B's [SandboxOpts](https://e2b.dev/docs) (template, envs, metadata, network, and so on) are forwarded straight through. The provider adds two more options that aren't part of E2B's SDK:

optiondefaultwhat it does
ports[]Ports to advertise on session.ports. The harness bridge binds to the first one. E2B can reach any listening port through getHost, so this is really just the list it advertises.
setupCommands[]Commands to run once on a fresh sandbox, before the harness bootstraps. For example, ['sudo npm install -g pnpm@9'] to add pnpm for the claude-code/codex adapters.

Already have a sandbox? Pass it as sandbox to reuse it (handy when you want to share one across sessions). The provider won't touch its lifecycle, so stop() and destroy() become no-ops and cleanup stays yours.

import { createE2BSandbox } from '@e2b/ai-sdk-sandbox';
import { Sandbox } from 'e2b';

const e2bSandbox = createE2BSandbox({
  sandbox: await Sandbox.create({ template: 'base' }),
});

Mid-session network policy

You can tighten or loosen outbound access on a sandbox that's already running:

await sandboxSession.setNetworkPolicy?.({
  mode: 'custom',
  allowedHosts: ['api.example.com'],
  deniedCIDRs: ['169.254.169.254/32'],
});

Request transformations and credential brokering

setRequestTransformations() replaces the managed rules, addRequestTransformations() adds without replacing. Headers in transform.headers are injected by E2B's egress proxy after the request leaves the sandbox, so real credentials never enter it — harness adapters use this automatically for their model API keys. E2B matches rules by host: a path matcher is applied host-wide, and method/queryString/headers matchers are rejected rather than silently widened. E2B allows one transform rule per host, so multiple transformations for the same host are merged into one rule (later headers override earlier ones). Rules match the host exactly (a rule for example.com does not cover www.example.com) and the egress proxy transforms HTTPS requests only. Network policies remain authoritative over which hosts can be reached. See examples/request-transformations.ts for a live end-to-end check.

Running an agent (Claude Code, Codex)

const agent = new HarnessAgent({
  harness: createClaudeCode(),
  sandbox: createE2BSandbox({
    template: 'pnpm-base', // base image + pnpm + 2GB, built via build-template.ts
    ports: [4000],
  }),
});

One thing to know about templates: the claude-code adapter installs its own pinned CLI and bridge inside the sandbox with pnpm (it doesn't use a system claude). That install pulls claude-code's ~238 MB native binary, and pnpm staging it peaks around 1.5 GB — so the sandbox needs pnpm and ~2 GB of RAM. E2B RAM is fixed at template-build time (you can't set it per sandbox), so build a 2 GB template with pnpm baked in via examples/build-template.ts and pass its name. A full, runnable version lives in examples/harness.ts.

Good to know

A few E2B-specific behaviors worth knowing:

  • stop() pauses the sandbox, so you can pick it back up later with resumeSession. destroy() kills it for good.
  • Resume works off a session-id tag in the sandbox metadata (E2B assigns the ids, so there's no name to look up), so pass a sessionId to createSession if you plan to resume.
  • run and spawn switch off E2B's 60-second per-command timeout, so long builds and background servers don't get cut off. The overall sandbox timeoutMs still applies.
  • When the harness passes identity + onFirstCreate (e.g. the claude-code/codex bootstrap), the setup runs once: it's captured as a snapshot and later sessions fork from it instead of re-running it. The snapshot is matched by name via listSnapshots, so even a cold start reuses it. For setup you control ahead of time, a prebuilt template is lighter.

Examples

  • examples/basic.ts: the session surface on its own (write, run, spawn)
  • examples/harness.ts: Claude Code working inside an E2B sandbox
  • examples/resume.ts: pause a sandbox and pick it back up
  • examples/build-template.ts: build a custom template (bakes pnpm in) to pass as template

Run any of them with npm run example:basic (they read .env).

License

MIT

版本与发布记录

@e2b/ai-sdk-sandbox 共发布 4 个版本,首次发布于 2026/08/19;过去 12 个月发布了 4 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.3.0latest2026/08/282 个月前
0.2.12026/08/192 个月前
0.2.02026/08/192 个月前
0.1.02026/08/192 个月前

关于 @e2b/ai-sdk-sandbox 的常见问题

@e2b/ai-sdk-sandbox 是什么?

E2B sandbox provider for the Vercel AI SDK

如何安装 @e2b/ai-sdk-sandbox?

在项目目录运行 npm install @e2b/ai-sdk-sandbox,或使用 pnpm add / yarn add / bun add。

@e2b/ai-sdk-sandbox 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@e2b/ai-sdk-sandbox 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@e2b/ai-sdk-sandbox 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@e2b/ai-sdk-sandbox 可以商用吗?

@e2b/ai-sdk-sandbox 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@e2b/ai-sdk-sandbox 的下载量有多少?

根据 npm 官方下载统计,@e2b/ai-sdk-sandbox 在 2026/10/13 – 2026/11/11 这 30 天内被下载 18,850 次,日均约 628 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@e2b/ai-sdk-sandbox 还在维护吗?

最新版本 0.3.0 发布于 2026/08/28(2 个月前);至今共发布 4 个版本,其中过去 12 个月发布了 4 个;首次发布于 2026/08/19。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。