# https://github.com/e2b-dev/E2B 项目说明书

生成时间：2026-05-18 03:19:07 UTC

## 目录

- [Overview](#overview)
- [Installation](#installation)
- [Sandbox Usage](#sandbox-usage)
- [JavaScript/TypeScript SDK](#js-sdk)
- [Python SDK](#python-sdk)
- [CLI Tool](#cli-tool)
- [Sandbox Management](#sandbox-management)
- [Template System](#template-system)
- [Filesystem and Git Operations](#filesystem-git)
- [Network Configuration](#network-config)

<a id='overview'></a>

## Overview

### 相关页面

相关主题：[Sandbox Usage](#sandbox-usage), [JavaScript/TypeScript SDK](#js-sdk), [Python SDK](#python-sdk)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/e2b-dev/E2B/blob/main/README.md)
- [packages/js-sdk/README.md](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/README.md)
- [packages/python-sdk/README.md](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/README.md)
- [packages/js-sdk/src/index.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/index.ts)
- [packages/python-sdk/e2b/__init__.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/__init__.py)
- [packages/js-sdk/src/template/types.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/template/types.ts)
- [packages/js-sdk/src/sandbox/sandboxApi.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/sandboxApi.ts)
- [packages/js-sdk/src/template/readycmd.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/template/readycmd.ts)
</details>

# Overview

E2B is an open-source infrastructure platform that enables developers to run AI-generated code in secure, isolated cloud-based sandboxes. It provides a unified API layer across multiple programming languages, allowing seamless integration of sandboxed code execution into AI applications, agents, and workflows.

## What is E2B?

E2B addresses the fundamental challenge of safely executing code generated by Large Language Models (LLMs) and AI agents. When AI systems produce code, executing that code directly in production environments poses significant security risks. E2B creates isolated execution environments where AI-generated code can be run safely without affecting the host system.

资料来源：[README.md:1]()

### Core Capabilities

| Capability | Description |
|------------|-------------|
| **Secure Sandboxes** | Isolated cloud environments for safe code execution |
| **Multi-Language SDKs** | Official JavaScript/TypeScript and Python SDKs |
| **Template System** | Customizable sandbox environments with Dockerfile-like syntax |
| **Code Interpreter** | Dedicated SDK for AI code execution use cases |
| **MCP Server Support** | Integration with Model Context Protocol servers |
| **Volume Management** | Persistent storage and file system operations |

## Architecture Overview

E2B's architecture consists of several interconnected components that work together to provide secure code execution.

```mermaid
graph TD
    A[Client Application] --> B[E2B SDK]
    B --> C[API Gateway]
    C --> D[Sandbox Manager]
    D --> E[Isolated Sandbox]
    D --> F[Template Registry]
    E --> G[envd Runtime]
    F --> H[Docker Images]
    
    I[Volume Storage] <--> E
    J[MCP Gateway] --> C
```

### Key Components

#### Sandboxes

Sandboxes are the core execution units in E2B. Each sandbox is an isolated environment based on a template that defines the base image, installed packages, environment variables, and startup commands.

```mermaid
graph LR
    A[Sandbox Instance] --> B[Filesystem]
    A --> C[Process Execution]
    A --> D[Network Access]
    A --> E[Volume Mounts]
```

Sandbox configuration options control the execution environment behavior:

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `templateID` | string | required | Template identifier to base the sandbox on |
| `timeout` | number | 300000ms | Maximum execution time before auto-termination |
| `secure` | boolean | `true` | Enable security restrictions |
| `allowInternetAccess` | boolean | `true` | Control network connectivity |
| `metadata` | object | `{}` | User-defined metadata for the sandbox |
| `envs` | Record<string, string> | `{}` | Environment variables to inject |

资料来源：[packages/js-sdk/src/sandbox/sandboxApi.ts:1]()

#### Templates

Templates define the configuration for sandbox environments. They use a fluent builder pattern to construct sandbox definitions that are then built and deployed to E2B infrastructure.

Supported base images include:

| Method | Description |
|--------|-------------|
| `fromBaseImage()` | E2B's default base image (e2bdev/base:latest) |
| `fromDebianImage(variant?)` | Debian-based image |
| `fromUbuntuImage(variant?)` | Ubuntu-based image |
| `fromPythonImage(version?)` | Python runtime image |
| `fromNodeImage(variant?)` | Node.js runtime image |
| `fromBunImage(variant?)` | Bun runtime image |

资料来源：[packages/js-sdk/src/template/types.ts:1]()

## SDKs Overview

E2B provides official SDKs for two major programming languages, both offering equivalent functionality through idiomatic API designs.

### JavaScript/TypeScript SDK

The JavaScript SDK is available on npm and supports both CommonJS and ES modules.

```bash
npm install e2b
```

资料来源：[packages/js-sdk/README.md:1]()

**Installation and Quick Start:**

```typescript
import Sandbox from 'e2b'

const sandbox = await Sandbox.create()
const result = await sandbox.commands.run('echo "Hello from E2B!"')
console.log(result.stdout) // Hello from E2B!
```

### Python SDK

The Python SDK is available on PyPI and supports Python 3.8+.

```bash
pip install e2b
```

资料来源：[packages/python-sdk/README.md:1]()

**Installation and Quick Start:**

```python
from e2b import Sandbox

with Sandbox.create() as sandbox:
    result = sandbox.commands.run('echo "Hello from E2B!"')
    print(result.stdout)  # Hello from E2B!
```

### Code Interpreter SDK

For AI applications requiring code execution capabilities (like REPLs or code agents), E2B provides a specialized Code Interpreter SDK.

| SDK | Package | Use Case |
|-----|---------|----------|
| JS | `@e2b/code-interpreter` | AI agents, code generators |
| Python | `e2b-code-interpreter` | AI agents, code generators |

资料来源：[packages/js-sdk/README.md:1]()

```typescript
import { Sandbox } from '@e2b/code-interpreter'

const sandbox = await Sandbox.create()
const execution = await sandbox.runCode('x = 1; x += 1; x')
console.log(execution.text)  // outputs 2
```

## Template Builder System

Templates in E2B use a fluent builder pattern that generates Dockerfile-like instructions. This approach provides flexibility while maintaining simplicity.

### Instruction Types

| Instruction | Description |
|-------------|-------------|
| `run_cmd()` / `RUN` | Execute shell commands during build |
| `copy()` / `COPY` | Copy files into the sandbox |
| `set_envs()` / `ENV` | Set environment variables |
| `add_mcp_server()` | Install MCP servers via mcp-gateway |
| `apt_install()` | Install APT packages |

资料来源：[packages/python-sdk/e2b/template/main.py:1]()

### Template Lifecycle

```mermaid
stateDiagram-v2
    [*] --> TemplateBuilder: Create Template
    TemplateBuilder --> TemplateBuilder: Add Instructions
    TemplateBuilder --> TemplateBuilder: Configure Start Command
    TemplateBuilder --> TemplateFinal: set_start_cmd()
    TemplateFinal --> Building: Template.build()
    Building --> BuildInfo: Success
    Building --> Error: Failure
    BuildInfo --> [*]
    Error --> [*]
```

### Ready Commands

Ready commands determine when a sandbox is considered fully initialized and ready to accept requests:

| Function | Implementation | Use Case |
|----------|---------------|----------|
| `waitForURL(url, statusCode)` | `curl` + `grep` | HTTP service health checks |
| `waitForProcess(name)` | `pgrep` | Daemon process verification |
| `waitForFile(path)` | shell test | File system readiness |

资料来源：[packages/js-sdk/src/template/readycmd.ts:1]()

## File System Operations

E2B provides comprehensive file system operations within sandboxes through the `Filesystem` API.

### Supported Read Formats

| Format | Return Type | Use Case |
|--------|-------------|----------|
| `text` (default) | `string` | Source code, configs |
| `bytes` | `Uint8Array` | Binary files |
| `blob` | `Blob` | Web-compatible binary |
| `stream` | `ReadableStream` | Large file handling |

Filesystem operations support gzip compression via the `gzip` option to reduce network transfer for large files.

资料来源：[packages/js-sdk/src/sandbox/filesystem/index.ts:1]()

## Command Execution

Commands executed within sandboxes return structured results containing stdout, stderr, and exit codes.

### Command Result Properties

| Property | Type | Description |
|----------|------|-------------|
| `stdout` | string | Standard output content |
| `stderr` | string | Standard error content |
| `exitCode` | number | Process exit code (0 = success) |
| `error` | string | Error message if execution failed |

The `CommandHandle.wait()` method throws a `CommandExitError` when the exit code is non-zero, enabling automatic error propagation in async workflows.

资料来源：[packages/js-sdk/src/sandbox/commands/commandHandle.ts:1]()

## Volume System

Volumes provide persistent storage that can be mounted into sandboxes. They are managed through the Volume API which supports CRUD operations on files and directories.

### Volume Mount Configuration

```typescript
opts.volumeMounts = {
  '/mount/path': 'volume-name'
}
```

Each mount maps a volume name to a path within the sandbox filesystem.

资料来源：[packages/js-sdk/src/sandbox/sandboxApi.ts:1]()

### Volume Read Operations

| Format | API Method | Return Type |
|--------|------------|-------------|
| text | `readFile(path, { format: 'text' })` | `string` |
| bytes | `readFile(path, { format: 'bytes' })` | `Uint8Array` |
| blob | `readFile(path, { format: 'blob' })` | `Blob` |
| stream | `readFile(path, { format: 'stream' })` | `ReadableStream` |

资料来源：[packages/js-sdk/src/volume/index.ts:1]()

## Authentication

All E2B SDKs require API key authentication. The API key should be set as an environment variable before initializing SDK clients.

```bash
export E2B_API_KEY=e2b_your_api_key_here
```

API keys can be obtained from the E2B dashboard at https://e2b.dev/dashboard?tab=keys.

## Next Steps

| Resource | Description |
|----------|-------------|
| [JavaScript SDK Guide](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/README.md) | Detailed JS/TS SDK documentation |
| [Python SDK Guide](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/README.md) | Detailed Python SDK documentation |
| [E2B Cookbook](https://github.com/e2b-dev/e2b-cookbook) | Example projects with various LLMs |
| [Official Documentation](https://www.e2b.dev/docs) | Full platform documentation |

---

<a id='installation'></a>

## Installation

### 相关页面

相关主题：[JavaScript/TypeScript SDK](#js-sdk), [Python SDK](#python-sdk), [CLI Tool](#cli-tool)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/js-sdk/package.json](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/package.json)
- [packages/python-sdk/pyproject.toml](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/pyproject.toml)
- [packages/cli/package.json](https://github.com/e2b-dev/E2B/blob/main/packages/cli/package.json)
- [packages/python-sdk/README.md](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/README.md)
- [packages/js-sdk/README.md](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/README.md)
</details>

# Installation

This guide covers how to install and configure the E2B SDKs for different programming languages. E2B provides two official SDKs: a Python SDK and a JavaScript/TypeScript SDK, both enabling developers to run AI-generated code in secure isolated sandboxes in the cloud.

## Prerequisites

Before installing any E2B SDK, ensure you have:

| Requirement | Description |
|-------------|-------------|
| **E2B Account** | Sign up at [e2b.dev](https://www.e2b.dev) |
| **API Key** | Obtain from [E2B Dashboard](https://www.e2b.dev/dashboard?tab=keys) |
| **Runtime** | Python 3.x or Node.js 18+ depending on SDK |

You must set the `E2B_API_KEY` environment variable with your API key before using the SDK:

```bash
export E2B_API_KEY=e2b_***
```

## SDK Overview

E2B provides multiple SDK packages depending on your use case:

| SDK Package | Purpose | Language |
|-------------|---------|----------|
| `e2b` | Core sandbox functionality | Python |
| `e2b` | Core sandbox functionality | JavaScript/TypeScript |
| `@e2b/code-interpreter` | Code execution sandbox | Python |
| `@e2b/code-interpreter` | Code execution sandbox | JavaScript/TypeScript |
| `e2b` (CLI) | Command-line interface | Node.js |

## Installing the Python SDK

### Core SDK

Install the core E2B Python SDK using pip:

```bash
pip install e2b
```

The SDK is published to PyPI and can be installed in any Python environment with pip support. The package includes all necessary dependencies for sandbox management, command execution, and file operations.

### Code Interpreter SDK

For running AI-generated code in a sandboxed environment:

```bash
pip install e2b-code-interpreter
```

This specialized SDK provides enhanced code execution capabilities with support for multiple programming languages and automatic dependency resolution.

## Installing the JavaScript/TypeScript SDK

### Core SDK

Install the E2B JavaScript SDK using npm:

```bash
npm i e2b
```

The JavaScript SDK supports both CommonJS and ESM module formats. It is written in TypeScript and includes full type definitions out of the box.

### Code Interpreter SDK

For JavaScript-based code execution:

```bash
npm i @e2b/code-interpreter
```

## Installing the CLI

The E2B CLI provides command-line access to template management and sandbox operations.

### Installation via npm

```bash
npm i e2b
```

### Installation via npx

For one-time usage without global installation:

```bash
npx e2b <command>
```

## Package Dependencies

### Python SDK Dependencies

The Python SDK requires the following runtime dependencies:

- `httpx` - HTTP client for API communication
- Python 3.8+ compatible

### JavaScript SDK Dependencies

The JavaScript SDK requires:

- Node.js 18 or higher
- Browser environment support (for client-side usage)

## Verifying Installation

After installation, verify that the SDK is correctly installed by checking the version or importing the package:

### Python Verification

```python
import e2b
print(e2b.__version__)
```

### JavaScript Verification

```javascript
import Sandbox from 'e2b'
console.log(Sandbox)
```

## Environment Configuration

### Required Environment Variables

| Variable | Required | Description |
|----------|----------|-------------|
| `E2B_API_KEY` | Yes | Your E2B API key for authentication |

### Optional Configuration

The SDKs support additional configuration options passed during client initialization:

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `timeout` | number | varies | Maximum request timeout in seconds |
| `verify_ssl` | boolean | true | Whether to verify SSL certificates |
| `follow_redirects` | boolean | false | Whether to follow HTTP redirects |
| `base_url` | string | E2B API | Custom API endpoint URL |

## Quick Start After Installation

Once installed, you can create and use sandboxes:

### Python Example

```python
from e2b import Sandbox

with Sandbox.create() as sandbox:
    result = sandbox.commands.run('echo "Hello from E2B!"')
    print(result.stdout)  # Hello from E2B!
```

### JavaScript/TypeScript Example

```typescript
import Sandbox from 'e2b'

const sandbox = await Sandbox.create()
const result = await sandbox.commands.run('echo "Hello from E2B!"')
console.log(result.stdout) // Hello from E2B!
```

### Code Interpreter Example (Python)

```python
from e2b_code_interpreter import Sandbox

with Sandbox.create() as sandbox:
    execution = sandbox.run_code("x = 1; x += 1; x")
    print(execution.text)  # outputs 2
```

## Installation from Source

For development or custom builds, you can install from source:

```bash
# Clone the repository
git clone https://github.com/e2b-dev/E2B.git
cd E2B

# Install Python SDK from source
cd packages/python-sdk
pip install -e .

# Install JavaScript SDK from source
cd ../js-sdk
npm install
```

## Troubleshooting

### Common Installation Issues

| Issue | Solution |
|-------|----------|
| `ModuleNotFoundError` | Ensure pip/npm is updated and try reinstalling |
| API key errors | Verify `E2B_API_KEY` environment variable is set correctly |
| Network timeouts | Check firewall/proxy settings for outbound HTTPS connections |
| Version conflicts | Use virtual environments or ensure Node.js version compatibility |

### Getting Help

If installation issues persist:

- Check [E2B Documentation](https://e2b.dev/docs)
- Contact support at [https://e2b.dev/docs/support](https://e2b.dev/docs/support)
- Visit the [E2B Cookbook](https://github.com/e2b-dev/e2b-cookbook) for examples

---

<a id='sandbox-usage'></a>

## Sandbox Usage

### 相关页面

相关主题：[Sandbox Management](#sandbox-management), [Filesystem and Git Operations](#filesystem-git), [Network Configuration](#network-config)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/js-sdk/src/sandbox/index.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/index.ts)
- [packages/js-sdk/src/sandbox/sandboxApi.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/sandboxApi.ts)
- [packages/js-sdk/src/api/schema.gen.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/api/schema.gen.ts)
- [packages/python-sdk/e2b/sandbox_async/sandbox_api.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_async/sandbox_api.py)
- [packages/python-sdk/e2b/sandbox_async/main.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_async/main.py)
- [packages/python-sdk/e2b/sandbox_sync/main.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_sync/main.py)
- [packages/python-sdk/e2b/template/main.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/template/main.py)
- [packages/cli/src/commands/sandbox/info.ts](https://github.com/e2b-dev/E2B/blob/main/packages/cli/src/commands/sandbox/info.ts)
- [README.md](https://github.com/e2b-dev/E2B/blob/main/README.md)
</details>

# Sandbox Usage

## Overview

A **Sandbox** in E2B is a secure, isolated cloud environment that allows you to execute AI-generated code safely. Sandboxes provide a controlled runtime environment with configurable resources, network settings, and lifecycle management. They are created from **sandbox templates** that define the base configuration, installed dependencies, and startup behavior of the environment.

Sandboxes are the core execution unit in E2B, providing:
- Isolated execution of untrusted code
- Configurable CPU and memory resources
- Network access control
- File system operations
- Terminal/PTY access
- Git operations

资料来源：[README.md:1-20](https://github.com/e2b-dev/E2B/blob/main/README.md)

## Architecture

```mermaid
graph TD
    A[Developer/AI Agent] -->|Creates Sandbox| B[E2B API]
    B -->|Template Config| C[Sandbox Instance]
    C -->|Provides| D[Filesystem API]
    C -->|Provides| E[Commands API]
    C -->|Provides| F[PTY/Terminal API]
    C -->|Provides| G[Git API]
    C -->|Manages| H[Lifecycle & Timeout]
    
    I[Template Definition] -->|Defines base image| C
    J[Resource Config] -->|CPU/Memory| C
    K[Network Config] -->|Internet access| C
```

## Creating a Sandbox

### JavaScript/TypeScript SDK

#### Create with default template

```typescript
import Sandbox from 'e2b'

const sandbox = await Sandbox.create()
const result = await sandbox.commands.run('echo "Hello from E2B!"')
console.log(result.stdout) // Hello from E2B!
```

资料来源：[packages/js-sdk/src/sandbox/index.ts:80-100](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/index.ts)

#### Create with specific template

```typescript
const sandbox = await Sandbox.create('my-custom-template')
```

#### Create with options

```typescript
const sandbox = await Sandbox.create({
  template: 'my-template',
  metadata: { user: 'alice', app: 'production' },
  envs: { NODE_ENV: 'production' },
  timeoutMs: 60000,
})
```

资料来源：[packages/js-sdk/src/sandbox/index.ts:95-130](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/index.ts)

### Python SDK

#### Async usage

```python
import asyncio
from e2b import Sandbox

async def main():
    sandbox = await Sandbox.create()
    result = sandbox.commands.run('echo "Hello from E2B!"')
    print(result.stdout)  # Hello from E2B!

asyncio.run(main())
```

#### Sync usage

```python
from e2b import Sandbox

with Sandbox.create() as sandbox:
    result = sandbox.commands.run('echo "Hello from E2B!"')
    print(result.stdout)  # Hello from E2B!
```

资料来源：[README.md:30-50](https://github.com/e2b-dev/E2B/blob/main/README.md)

## Sandbox Options

### Configuration Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `template` | `string` | `'base'` | Sandbox template name or ID. Use `'mcp-gateway'` when `mcp` option is set |
| `metadata` | `Record<string, string>` | `{}` | Custom metadata for the sandbox |
| `envs` | `Record<string, string>` | `{}` | Custom environment variables for the sandbox |
| `timeoutMs` | `number` | varies | Timeout in milliseconds (max 24h for Pro, 1h for Hobby) |
| `mcp` | `boolean` | `false` | Enable MCP gateway support |
| `onTimeout` | `'pause' \| 'kill'` | `'pause'` | Action on sandbox timeout |
| `autoResume` | `boolean` | `false` | Auto-resume paused sandbox (requires `onTimeout: 'pause'`) |
| `cpuCount` | `number` | `2` | Number of CPU cores |
| `memoryMB` | `number` | `512` | Memory in MiB (must be even) |
| `allowInternetAccess` | `boolean` | `true` | Enable/disable internet access |
| `network` | `boolean \| SandboxNetworkOpts` | `true` | Network configuration |
| `volumeMounts` | `Array<{name, path}>` | `[]` | Volume mounts |

资料来源：[packages/js-sdk/src/sandbox/sandboxApi.ts:50-120](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/sandboxApi.ts)
资料来源：[packages/python-sdk/e2b/sandbox_async/sandbox_api.py:1-50](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_async/sandbox_api.py)

### Network Configuration

```typescript
const sandbox = await Sandbox.create({
  network: true,  // Full network access (default)
  // Or with custom configuration:
  network: {
    timeoutMs: 30000,
  }
})
```

### Resource Configuration

```typescript
const sandbox = await Sandbox.create({
  cpuCount: 4,     // Number of CPUs (default: 2)
  memoryMB: 1024,  // Memory in MiB (default: 512, must be even)
})
```

### Lifecycle Configuration

```typescript
const sandbox = await Sandbox.create({
  timeoutMs: 3600000,  // 1 hour max
  lifecycle: {
    onTimeout: 'pause',  // Pause instead of kill
    autoResume: true,    // Auto-resume when accessed
  }
})
```

资料来源：[packages/js-sdk/src/sandbox/sandboxApi.ts:40-70](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/sandboxApi.ts)

## Sandbox API Response

When a sandbox is created, the API returns a `SandboxInfo` object containing:

| Field | Type | Description |
|-------|------|-------------|
| `sandboxId` | `string` | Unique sandbox identifier |
| `sandboxDomain` | `string` | Domain name for the sandbox |
| `envdVersion` | `string` | Version of envd running in sandbox |
| `envdAccessToken` | `string` | Token for envd API authentication |
| `trafficAccessToken` | `string` | Token for traffic authentication |
| `templateId` | `string` | ID of the template used |
| `name` | `string` | Sandbox alias/name |
| `startedAt` | `Date` | Sandbox start time |
| `endAt` | `Date` | Sandbox expiration date |
| `state` | `'running' \| 'paused'` | Current sandbox state |
| `cpuCount` | `number` | Number of CPUs allocated |
| `memoryMB` | `number` | Memory allocated in MiB |
| `metadata` | `Record<string, string>` | Custom metadata |
| `allowInternetAccess` | `boolean` | Internet access setting |
| `lifecycle` | `SandboxInfoLifecycle` | Lifecycle configuration |
| `volumeMounts` | `Array<{name, path}>` | Mounted volumes |

资料来源：[packages/js-sdk/src/api/schema.gen.ts:1-80](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/api/schema.gen.ts)
资料来源：[packages/js-sdk/src/sandbox/sandboxApi.ts:200-280](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/sandboxApi.ts)

## Sandbox State Machine

```mermaid
stateDiagram-v2
    [*] --> Creating: Sandbox.create()
    Creating --> Running: Sandbox ready
    Running --> Paused: Timeout reached (if onTimeout: pause)
    Running --> Killed: Timeout reached (if onTimeout: kill)
    Paused --> Running: Sandbox accessed
    Paused --> Killed: Timeout reached
    Running --> [*]: sandbox.kill()
    Paused --> [*]: sandbox.kill()
    Killed --> [*]: Sandbox terminated
```

## Sandbox Instances

### JavaScript SDK Instance

The `Sandbox` class provides the following APIs:

| API | Description |
|-----|-------------|
| `sandbox.filesystem` | File system operations (upload, download, list, etc.) |
| `sandbox.commands` | Execute shell commands |
| `sandbox.pty` | Terminal/PTY access |
| `sandbox.git` | Git operations |

```typescript
const sandbox = await Sandbox.create()

// File operations
await sandbox.filesystem.write('/app/main.py', 'print("hello")')
const content = await sandbox.filesystem.read('/app/main.py')

// Run commands
const result = await sandbox.commands.run('python /app/main.py')

// Terminal access
const pty = await sandbox.pty.start({ cmd: 'bash' })
```

资料来源：[packages/js-sdk/src/sandbox/index.ts:130-180](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/index.ts)

### Python SDK Instance

```python
sandbox = await Sandbox.create()

# File operations
await sandbox.filesystem.write('/app/main.py', 'print("hello")')

# Run commands
result = sandbox.commands.run('python /app/main.py')

# Cleanup
await sandbox.kill()
```

Or with sync context manager:

```python
with Sandbox.create() as sandbox:
    result = sandbox.commands.run('echo "Hello"')
```

## Sandbox Metrics

Sandbox resource usage can be monitored through the metrics API:

| Metric | Type | Description |
|--------|------|-------------|
| `timestamp` | `Date` | Timestamp of metrics |
| `cpuUsedPct` | `number` | CPU usage percentage |
| `cpuCount` | `number` | Number of CPU cores |
| `memUsed` | `number` | Memory used in bytes |
| `memTotal` | `number` | Total memory in bytes |
| `diskUsed` | `number` | Used disk space in bytes |
| `diskTotal` | `number` | Total disk space in bytes |

资料来源：[packages/js-sdk/src/sandbox/sandboxApi.ts:250-300](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/sandboxApi.ts)

## CLI Commands

### List Sandboxes

```bash
e2b sandbox list
```

### Get Sandbox Info

```bash
e2b sandbox info <sandboxID>
# or
e2b sandbox in <sandboxID>
```

Options:
- `-f, --format <format>` - Output format (json, pretty)

The info command displays:

| Field | Label |
|-------|-------|
| `sandboxId` | Sandbox ID |
| `templateId` | Template ID |
| `name` | Alias |
| `startedAt` | Started at |
| `endAt` | End at |
| `state` | State |
| `cpuCount` | vCPUs |
| `memoryMB` | RAM MiB |
| `envdVersion` | Envd version |
| `allowInternetAccess` | Internet access |
| `lifecycle` | Lifecycle |
| `network` | Network |
| `sandboxDomain` | Sandbox domain |
| `metadata` | Metadata |

资料来源：[packages/cli/src/commands/sandbox/info.ts:1-60](https://github.com/e2b-dev/E2B/blob/main/packages/cli/src/commands/sandbox/info.ts)

### Create Sandbox Template

```bash
e2b template create <template-name>
```

Options:
- `-p, --path <path>` - Path to template directory
- `-d, --dockerfile <file>` - Custom Dockerfile name
- `-c, --cmd <start-command>` - Command executed when sandbox starts
- `--ready-cmd <ready-command>` - Command that must exit 0 for sandbox to be ready
- `--cpu-count <count>` - Number of CPUs (default: 2)
- `--memory-mb <mb>` - Memory in MB (default: 512, must be even)
- `--no-cache` - Skip cache when building

### Build Sandbox Template

```bash
e2b template build [template-id]
# or
e2b template bd [template-id]
```

Options:
- `-p, --path <path>` - Path to template directory
- `-d, --dockerfile <file>` - Custom Dockerfile name
- `-n, --name <name>` - Template name
- `-c, --cmd <start-command>` - Command executed when sandbox starts
- `--ready-cmd <ready-command>` - Command that must exit 0
- `--cpu-count <count>` - Number of CPUs
- `--memory-mb <mb>` - Memory in MB
- `--build-arg <args...>` - Build arguments
- `--no-cache` - Skip cache when building

资料来源：[packages/cli/src/commands/template/create.ts:1-100](https://github.com/e2b-dev/E2B/blob/main/packages/cli/src/commands/template/create.ts)
资料来源：[packages/cli/src/commands/template/build.ts:1-100](https://github.com/e2b-dev/E2B/blob/main/packages/cli/src/commands/template/build.ts)

## Beta Features

### MCP Gateway

Enable MCP (Model Context Protocol) gateway support:

```typescript
const sandbox = await Sandbox.betaCreate({
  mcp: true,
  // Uses 'mcp-gateway' template by default
})
```

### Dev Container Support

Templates can use devcontainer configuration:

```typescript
template
  .gitClone('https://myrepo.com/project.git', '/my-devcontainer')
  .betaDevContainerPrebuild('/my-devcontainer')
  .betaSetDevContainerStart('/my-devcontainer')
```

资料来源：[packages/js-sdk/src/sandbox/index.ts:40-80](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/index.ts)
资料来源：[packages/js-sdk/src/template/types.ts:1-50](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/template/types.ts)

## Timeout and Lifecycle Management

### Maximum Timeout Limits

| User Tier | Maximum Timeout |
|-----------|-----------------|
| Pro | 24 hours (86,400,000 ms) |
| Hobby | 1 hour (3,600,000 ms) |

### Lifecycle Options

```typescript
// Option 1: Pause sandbox on timeout
const sandbox = await Sandbox.create({
  timeoutMs: 3600000,
  lifecycle: {
    onTimeout: 'pause',
    autoResume: true,  // Can auto-resume when accessed
  }
})

// Option 2: Kill sandbox on timeout
const sandbox = await Sandbox.create({
  timeoutMs: 3600000,
  lifecycle: {
    onTimeout: 'kill',  // Sandbox is terminated
  }
})
```

When a sandbox is paused, accessing it again will automatically resume it, allowing you to continue where you left off (with some limitations based on the template).

资料来源：[packages/js-sdk/src/sandbox/sandboxApi.ts:20-60](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/sandboxApi.ts)

## Best Practices

1. **Always clean up resources**: Use context managers or explicitly call `kill()` to terminate sandboxes when done.

2. **Set appropriate timeouts**: Match the timeout to your workload. Shorter timeouts are more cost-effective for quick tasks.

3. **Use metadata for tracking**: Add meaningful metadata to easily identify sandboxes in listings.

4. **Handle errors gracefully**: Catch exceptions for sandbox creation and command execution.

5. **Use pause lifecycle for interactive sessions**: When you need to resume work later, use `onTimeout: 'pause'` with `autoResume: true`.

6. **Configure resources appropriately**: Allocate CPU and memory based on your actual workload requirements.

---

<a id='js-sdk'></a>

## JavaScript/TypeScript SDK

### 相关页面

相关主题：[Python SDK](#python-sdk), [CLI Tool](#cli-tool), [Sandbox Usage](#sandbox-usage)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this documentation:

- [packages/js-sdk/src/index.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/index.ts)
- [packages/js-sdk/src/sandbox/index.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/index.ts)
- [packages/js-sdk/src/connectionConfig.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/connectionConfig.ts)
- [packages/js-sdk/src/errors.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/errors.ts)
- [packages/js-sdk/src/sandbox/commands/index.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/commands/index.ts)
- [packages/js-sdk/src/sandbox/filesystem/index.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/filesystem/index.ts)
- [packages/js-sdk/src/sandbox/network.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/network.ts)
- [packages/js-sdk/src/volume/index.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/volume/index.ts)
- [packages/js-sdk/tsup.config.js](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/tsup.config.js)
</details>

# JavaScript/TypeScript SDK

## Overview

The E2B JavaScript/TypeScript SDK (`e2b`) is an official client library that enables developers to interact with E2B's cloud-based sandbox infrastructure for running AI-generated code in secure, isolated environments. The SDK provides a programmatic interface to create, manage, and communicate with sandboxes, as well as to work with templates and volumes. 资料来源：[packages/js-sdk/README.md]()

### Key Capabilities

The SDK supports multiple runtime environments including Node.js and browser applications, offering a unified API for sandbox operations. Developers can spawn isolated sandboxes, execute commands, manage files, handle network communications, and mount persistent storage volumes through a well-structured TypeScript interface. 资料来源：[packages/js-sdk/src/api/metadata.ts]()
资料来源：[packages/js-sdk/tsup.config.js]()

### Package Configuration

The SDK is published to npm under the package name `e2b` and includes both ESM and CommonJS formats for maximum compatibility. 资料来源：[packages/js-sdk/README.md]()

```json
{
  "name": "e2b",
  "version": "^2.19.3",
  "main": "./dist/index.js",
  "module": "./dist/index.mjs",
  "types": "./dist/index.d.ts"
}
```

## Architecture Overview

The SDK architecture follows a modular design pattern with distinct layers for API communication, sandbox management, and utility functions. 资料来源：[packages/js-sdk/src/index.ts]()

```mermaid
graph TD
    A[Client Application] --> B[SDK Entry Point<br/>packages/js-sdk/src/index.ts]
    B --> C[Sandbox Manager<br/>sandbox/index.ts]
    B --> D[Connection Config<br/>connectionConfig.ts]
    B --> E[Error Handling<br/>errors.ts]
    C --> F[Filesystem API<br/>filesystem/index.ts]
    C --> G[Commands API<br/>commands/index.ts]
    C --> H[Network API<br/>network.ts]
    C --> I[Volume API<br/>volume/index.ts]
    D --> J[E2B API Server]
    J --> K[Sandbox Instances]
```

### Core Components

| Component | File Location | Purpose |
|-----------|---------------|---------|
| Entry Point | `src/index.ts` | Exports all public APIs |
| Sandbox Manager | `src/sandbox/index.ts` | Manages sandbox lifecycle |
| Connection Config | `src/connectionConfig.ts` | Handles API configuration and authentication |
| Error Handling | `src/errors.ts` | Defines SDK-specific error types |
| Filesystem | `src/sandbox/filesystem/index.ts` | File operations within sandboxes |
| Commands | `src/sandbox/commands/index.ts` | Execute commands in sandboxes |
| Network | `src/sandbox/network.ts` | Network configuration and proxies |
| Volume | `src/volume/index.ts` | Persistent storage management |

## Installation and Setup

### Prerequisites

- Node.js 18 or higher
- An E2B API key

### Installation

```bash
npm install e2b
```

### Environment Configuration

The SDK automatically reads the `E2B_API_KEY` environment variable for authentication. You can also configure the API key programmatically through the connection configuration. 资料来源：[packages/js-sdk/src/api/metadata.ts]()

```typescript
import { E2B } from 'e2b'

// SDK automatically reads E2B_API_KEY from environment
const client = new E2B()
```

### Runtime Detection

The SDK detects the runtime environment and sets appropriate headers for API requests. It supports Node.js, Deno, and browser environments. 资料来源：[packages/js-sdk/src/api/metadata.ts]()

```typescript
// Runtime detection in metadata.ts
export const defaultHeaders = {
  browser: (typeof window !== 'undefined' && platform.name) || 'unknown',
  lang: 'js',
  lang_version: runtimeVersion,
  package_version: version,
  publisher: 'e2b',
  sdk_runtime: runtime,
  system: platform.os?.family || 'unknown',
}
```

## Sandbox Management

The Sandbox class is the primary interface for interacting with E2B sandboxes. It provides methods for lifecycle management, file operations, command execution, and network configuration. 资料来源：[packages/js-sdk/src/sandbox/index.ts]()

### Creating a Sandbox

```typescript
import { E2B } from 'e2b'

const client = new E2B()

// Create a sandbox from a template
const sandbox = await client.createSandbox({
  template: 'base',
  metadata: { userId: '12345' }
})

console.log('Sandbox ID:', sandbox.id)
console.log('Sandbox URL:', sandbox.url)
```

### Sandbox Configuration

| Parameter | Type | Description |
|-----------|------|-------------|
| `template` | `string` | Template ID to use for the sandbox |
| `timeout` | `number` | Timeout in milliseconds |
| `metadata` | `Record<string, string>` | Custom metadata for filtering |
| `aliases` | `string[]` | Alternative names for the sandbox |

### Sandbox Lifecycle

```mermaid
stateDiagram-v2
    [*] --> Created: client.createSandbox()
    Created --> Starting: sandbox.start()
    Starting --> Running: sandbox ready
    Running --> Stopping: sandbox.kill() or timeout
    Stopping --> Stopped: cleanup complete
    Stopped --> [*]
    
    Running --> Error: exception
    Error --> [*]
```

### Stopping a Sandbox

Always ensure proper cleanup by stopping sandboxes when they are no longer needed:

```typescript
try {
  const sandbox = await client.createSandbox({ template: 'base' })
  
  // Perform operations...
  
  await sandbox.kill()
} finally {
  // Sandbox is now terminated
}
```

## Filesystem Operations

The SDK provides comprehensive filesystem operations through the filesystem module, enabling reading, writing, and managing files within sandboxes. 资料来源：[packages/js-sdk/src/sandbox/filesystem/index.ts]()

### File Operations

| Method | Description |
|--------|-------------|
| `write(path, content)` | Write content to a file |
| `read(path)` | Read file content |
| `list(path)` | List directory contents |
| `mkdir(path)` | Create a directory |
| `remove(path)` | Remove a file or directory |
| `exists(path)` | Check if path exists |

### Reading Files

```typescript
const content = await sandbox.filesystem.read('/app/data.json')
console.log('File content:', content)
```

### Writing Files

```typescript
await sandbox.filesystem.write('/app/output.txt', 'Hello, E2B!')
```

### Listing Directory Contents

```typescript
const files = await sandbox.filesystem.list('/app')
console.log('Files:', files)
```

## Command Execution

Execute shell commands within the sandbox environment using the commands API. This is essential for running build scripts, installing packages, and performing system operations. 资料来源：[packages/js-sdk/src/sandbox/commands/index.ts]()

### Running Commands

```typescript
const result = await sandbox.commands.run('ls -la /app')

console.log('Exit code:', result.exitCode)
console.log('Stdout:', result.stdout)
console.log('Stderr:', result.stderr)
```

### Command Options

| Option | Type | Description |
|--------|------|-------------|
| `timeout` | `number` | Command timeout in milliseconds |
| `envVars` | `Record<string, string>` | Environment variables |
| `user` | `string` | User to run command as |

### Streaming Command Output

For long-running commands, you can stream output:

```typescript
const process = sandbox.commands.runStreaming('npm install')

process.stdout.on('data', (data) => {
  console.log('Output:', data.toString())
})

const exitCode = await process.exitCode
```

## Network Configuration

The network module provides configuration for network proxies, DNS settings, and sandbox connectivity options. 资料来源：[packages/js-sdk/src/sandbox/network.ts]()

### Network Settings

```typescript
const sandbox = await client.createSandbox({
  template: 'base',
  network: true // Enable networking
})
```

### Available Network Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `network` | `boolean` | `true` | Enable/disable network access |
| `dns` | `string[]` | System DNS | Custom DNS servers |

## Volume Management

Volumes provide persistent storage that survives sandbox restarts. They are useful for maintaining state across sandbox sessions. 资料来源：[packages/js-sdk/src/volume/index.ts]()

### Creating and Mounting Volumes

```typescript
// Create a volume
const volume = await client.volumes.create({
  name: 'my-data-volume'
})

// Mount volume to sandbox
const sandbox = await client.createSandbox({
  template: 'base',
  volumes: [
    { volumeId: volume.id, mountPath: '/data' }
  ]
})
```

### Volume Operations

| Method | Description |
|--------|-------------|
| `create(config)` | Create a new volume |
| `delete(volumeId)` | Delete a volume |
| `list()` | List all volumes |

## Error Handling

The SDK defines custom error types for different failure scenarios, making it easier to handle errors appropriately in your application. 资料来源：[packages/js-sdk/src/errors.ts]()

### Error Types

| Error Type | Description |
|------------|-------------|
| `AuthenticationError` | Invalid or missing API key |
| `TimeoutError` | Operation exceeded timeout |
| `SandboxError` | Sandbox creation or operation failure |
| `RateLimitError` | API rate limit exceeded |
| `ValidationError` | Invalid parameters or configuration |

### Error Handling Pattern

```typescript
import { E2B, AuthenticationError, TimeoutError } from 'e2b'

try {
  const sandbox = await client.createSandbox({ template: 'base' })
  await sandbox.filesystem.read('/app/data.json')
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Please check your API key')
  } else if (error instanceof TimeoutError) {
    console.error('Operation timed out')
  } else {
    throw error
  }
}
```

## API Client Configuration

The connection configuration allows customization of the API client behavior, including custom base URLs, headers, and authentication. 资料来源：[packages/js-sdk/src/connectionConfig.ts]()

### Configuration Options

| Option | Type | Description |
|--------|------|-------------|
| `apiKey` | `string` | E2B API key |
| `baseUrl` | `string` | Custom API base URL |
| `timeout` | `number` | Default request timeout |
| `headers` | `Record<string, string>` | Custom HTTP headers |

### Custom Configuration Example

```typescript
import { E2B } from 'e2b'

const client = new E2B({
  apiKey: process.env.E2B_API_KEY,
  baseUrl: 'https://api.e2b.dev/v1',
  timeout: 30000
})
```

## Build Configuration

The SDK is built using tsup, a TypeScript bundler that produces optimized output for both ESM and CommonJS formats. 资料来源：[packages/js-sdk/tsup.config.js]()

### Build Output Configuration

```javascript
export default defineConfig({
  minify: false,
  target: ['es2017'],
  sourcemap: true,
  dts: true,
  format: ['esm', 'cjs'],
  clean: true,
  entry: {
    index: './src/index.ts',
  },
  esbuildOptions: (options) => {
    options.legalComments = 'none'
    return options
  },
})
```

### Supported Platforms

| Platform | Format | Target |
|----------|--------|--------|
| Node.js | CommonJS | `node18` |
| Browser | ESM | `es2017` |

## API Reference

### E2B Client

```typescript
class E2B {
  constructor(config?: ConnectionConfig)
  
  // Sandboxes
  sandboxes: Sandboxes
  
  // Volumes
  volumes: Volumes
  
  // Templates
  templates: Templates
  
  // Close the client
  close(): void
}
```

### Sandbox Instance

```typescript
class Sandbox {
  id: string
  url: string
  startedAt: Date
  
  // Properties
  filesystem: Filesystem
  commands: Commands
  network: Network
  
  // Methods
  kill(): Promise<void>
  restart(): Promise<void>
}
```

## Best Practices

### Resource Management

Always properly terminate sandboxes when they are no longer needed to avoid unnecessary resource consumption and costs:

```typescript
// Recommended pattern with try/finally
const sandbox = await client.createSandbox({ template: 'base' })
try {
  // Perform operations
} finally {
  await sandbox.kill()
}
```

### Error Handling

Implement comprehensive error handling to gracefully manage API failures, timeouts, and sandbox errors:

```typescript
async function withSandbox<T>(
  fn: (sandbox: Sandbox) => Promise<T>
): Promise<T> {
  const sandbox = await client.createSandbox({ template: 'base' })
  try {
    return await fn(sandbox)
  } catch (error) {
    if (error instanceof RateLimitError) {
      await new Promise(r => setTimeout(r, 1000))
      return withSandbox(fn)
    }
    throw error
  } finally {
    await sandbox.kill()
  }
}
```

### Timeout Configuration

Set appropriate timeouts for long-running operations:

```typescript
const sandbox = await client.createSandbox({
  template: 'base',
  timeout: 60000 // 60 seconds
})
```

## Dependencies

The SDK relies on several key dependencies for its functionality:

| Package | Version | Purpose |
|---------|---------|---------|
| `@connectrpc/connect` | `2.0.0-rc.3` | RPC communication |
| `@connectrpc/connect-web` | `2.0.0-rc.3` | Web RPC transport |
| `openapi-fetch` | `0.14.1` | REST API client |
| `platform` | `1.3.6` | Runtime detection |
| `chalk` | `5.3.0` | Terminal styling |
| `tar` | `7.5.11` | Archive handling |

## CLI Integration

The SDK also integrates with the E2B CLI for template management. Template commands allow building, creating, and migrating sandbox templates across different languages. 资料来源：[packages/cli/src/commands/template/build.ts]()
资料来源：[packages/cli/src/commands/template/init.ts]()

## Related Documentation

For more information, refer to:

- [Python SDK](../python-sdk/README.md) - Python client library
- [CLI Documentation](./cli) - Command-line interface
- [API Reference](./api) - REST API documentation
- [Template Development](./templates) - Creating custom templates

---

<a id='python-sdk'></a>

## Python SDK

### 相关页面

相关主题：[JavaScript/TypeScript SDK](#js-sdk), [CLI Tool](#cli-tool), [Sandbox Usage](#sandbox-usage)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/python-sdk/e2b/__init__.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/__init__.py)
- [packages/python-sdk/e2b/sandbox/main.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox/main.py)
- [packages/python-sdk/e2b/sandbox_async/main.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_async/main.py)
- [packages/python-sdk/e2b/sandbox_sync/main.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_sync/main.py)
- [packages/python-sdk/e2b/sandbox/sandbox_api.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox/sandbox_api.py)
- [packages/python-sdk/e2b/sandbox_async/sandbox_api.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_async/sandbox_api.py)
- [packages/python-sdk/e2b/sandbox_sync/sandbox_api.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py)
- [packages/python-sdk/e2b/envd/api.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/envd/api.py)
- [packages/python-sdk/e2b/exceptions.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/exceptions.py)
- [packages/python-sdk/e2b/api/client/client.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/api/client/client.py)
</details>

# Python SDK

The E2B Python SDK provides a programmatic interface for creating and managing secure cloud sandboxes that execute AI-generated code in isolated environments. The SDK enables developers to spawn sandbox instances, execute shell commands, manage filesystem operations, and build reusable sandbox templates.

## Overview

E2B (Execution-to-Brain) is an open-source infrastructure platform that allows developers to run AI-generated code in secure, isolated sandboxes hosted in the cloud. The Python SDK serves as the primary client library for Python developers to interact with the E2B infrastructure.

**Key capabilities:**

- Create and manage sandboxed execution environments
- Execute arbitrary shell commands within sandboxes
- Build and deploy custom sandbox templates
- Access filesystem operations (upload, download, file management)
- Configure sandbox resources (CPU, memory)
- Support for both synchronous and asynchronous programming patterns

**Package information:**

```python
# SDK metadata captured from package
package_version = metadata.version("e2b")

default_headers = {
    "lang": "python",
    "lang_version": platform.python_version(),
    "package_version": metadata.version("e2b"),
    "publisher": "e2b",
    "sdk_runtime": "python",
    "system": platform.system(),
}
```

资料来源：[e2b/api/metadata.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/api/metadata.py)

## Installation and Setup

### Install the SDK

```bash
pip install e2b
```

### Configure API Credentials

Obtain your API key from the [E2B Dashboard](https://e2b.dev/dashboard?tab=keys) and set it as an environment variable:

```bash
export E2B_API_KEY=e2b_***
```

### Quick Start Example

```python
from e2b import Sandbox

with Sandbox.create() as sandbox:
    result = sandbox.commands.run('echo "Hello from E2B!"')
    print(result.stdout)  # Hello from E2B!
```

## Architecture

The Python SDK is structured around several key modules that provide different functionality layers.

```mermaid
graph TD
    A[User Code] --> B[Python SDK]
    B --> C[Sandbox API Client]
    B --> D[Template API Client]
    C --> E[E2B Backend API]
    D --> E
    E --> F[Sandbox Instances]
    E --> G[Template Registry]
    F --> H[envd Runtime]
    H --> I[Isolated Execution Environment]
```

### Module Structure

| Module | Purpose |
|--------|---------|
| `e2b.sandbox` | Core sandbox functionality |
| `e2b.sandbox_async` | Async sandbox implementation |
| `e2b.sandbox_sync` | Synchronous sandbox implementation |
| `e2b.template` | Template builder functionality |
| `e2b.envd` | Environment daemon API |
| `e2b.api` | HTTP API client layer |
| `e2b.exceptions` | Custom exception types |

## Sandbox Class

The `Sandbox` class is the primary entry point for creating and interacting with sandboxed execution environments. The SDK provides both context manager support and manual lifecycle management.

### Creating a Sandbox

```python
from e2b import Sandbox

# Using context manager (recommended)
with Sandbox.create() as sandbox:
    result = sandbox.commands.run('echo "Hello"')
    print(result.stdout)
```

### Sandbox Lifecycle

```mermaid
stateDiagram-v2
    [*] --> Created: Sandbox.create()
    Created --> Running: __enter__()
    Running --> Stopped: __exit__() / close()
    Stopped --> [*]
    Created --> Stopped: close()
```

### Key Sandbox Methods

| Method | Description |
|--------|-------------|
| `Sandbox.create()` | Static factory method to create a new sandbox instance |
| `sandbox.close()` | Manually terminate the sandbox |
| `sandbox.commands.run(cmd)` | Execute a shell command |
| `sandbox.filesystem` | Access filesystem operations |
| `sandbox.upload(src, dest)` | Upload files to sandbox |
| `sandbox.download(src, dest)` | Download files from sandbox |

资料来源：[e2b/sandbox/main.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox/main.py)

## Synchronous vs Asynchronous APIs

The Python SDK provides both synchronous and asynchronous interfaces to accommodate different programming patterns.

### Synchronous API

```python
from e2b.sandbox_sync import Sandbox

sandbox = Sandbox.create()
result = sandbox.commands.run('echo "sync"')
sandbox.close()
```

The synchronous API uses blocking I/O operations and is suitable for scripts and applications where concurrency is not a primary concern.

### Asynchronous API

```python
import asyncio
from e2b.sandbox_async import Sandbox

async def main():
    async with Sandbox.create() as sandbox:
        result = await sandbox.commands.run('echo "async"')
        print(result.stdout)

asyncio.run(main())
```

The async API is designed for web applications, async frameworks, and scenarios requiring concurrent sandbox operations.

| Feature | Sync API | Async API |
|---------|----------|-----------|
| Import | `from e2b import Sandbox` | `from e2b.sandbox_async import Sandbox` |
| I/O Model | Blocking | Non-blocking |
| Use Case | Scripts, CLI tools | Web servers, async frameworks |
| Connection | `e2b.sandbox_sync.sandbox_api` | `e2b.sandbox_async.sandbox_api` |

资料来源：[e2b/sandbox_sync/main.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_sync/main.py)，[e2b/sandbox_async/main.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_async/main.py)

## Template Builder

Templates define the base image and configuration for sandbox environments. The Template Builder API allows programmatic creation of custom sandbox templates.

### Creating a Template

```python
from e2b import Template

template = (
    Template()
    .from_python_image('3')
    .copy('requirements.txt', '/home/user/')
    .run_cmd('pip install -r /home/user/requirements.txt')
)

# Build and deploy
Template.build(template, 'my-python-env:v1.0')
```

### Available Base Images

| Method | Base Image |
|--------|------------|
| `fromPythonImage(version)` | Python Docker image |
| `fromNodeImage(variant)` | Node.js Docker image |
| `fromBunImage(variant)` | Bun Docker image |
| `fromDebianImage(variant)` | Debian Docker image |
| `fromUbuntuImage(variant)` | Ubuntu Docker image |
| `fromTemplate(name)` | E2B template |
| `fromDockerfile(content)` | Custom Dockerfile |

### Template Builder Methods

| Method | Description |
|--------|-------------|
| `run_cmd(cmd, user)` | Execute a shell command during build |
| `copy(src, dest)` | Copy files into the template |
| `apt_install(packages)` | Install system packages |
| `bun_install(packages)` | Install npm/bun packages |
| `set_envs(envs)` | Set environment variables |
| `set_start_cmd(cmd, ready_cmd)` | Configure startup command |
| `skip_cache()` | Force rebuild ignoring cache |

资料来源：[e2b/template/main.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/template/main.py)

### Async Template Operations

```python
from e2b import AsyncTemplate

template = (
    AsyncTemplate()
    .from_python_image('3')
    .run_cmd('pip install numpy')
)

# Build with progress callback
async def on_logs(log):
    print(log.message)

await AsyncTemplate.build(
    template, 
    'my-template:v1.0',
    on_build_logs=on_logs
)
```

## Connection Configuration

The SDK uses `ConnectionConfig` to manage API connection parameters including authentication, endpoints, and timeouts.

### Configuration Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `api_key` | str | `E2B_API_KEY` env | API authentication key |
| `access_token` | str | `E2B_ACCESS_TOKEN` env | Alternative auth token |
| `base_url` | str | E2B API | Custom API endpoint |
| `timeout` | int | 60 | Request timeout in seconds |

### Custom Configuration

```python
from e2b import Sandbox
from e2b.constants import ConnectionConfig

config = ConnectionConfig(
    api_key='e2b_***',
    timeout=120
)

with Sandbox.create(**config) as sandbox:
    result = sandbox.commands.run('echo "configured"')
```

## Command Execution

### Running Commands

```python
sandbox = Sandbox.create()

# Basic command
result = sandbox.commands.run('ls -la')

# With working directory
result = sandbox.commands.run('pwd', cwd='/home/user')

# With timeout
result = sandbox.commands.run('sleep 10', timeout=5)
```

### Command Result Properties

| Property | Type | Description |
|----------|------|-------------|
| `stdout` | str | Standard output |
| `stderr` | str | Standard error |
| `exit_code` | int | Process exit code |
| `stdout_lines` | List[str] | Output as line array |

## Error Handling

The SDK defines custom exception types for different error scenarios.

### Exception Types

| Exception | Description |
|-----------|-------------|
| `SandboxException` | Base exception for sandbox errors |
| `AuthenticationException` | API key/authentication failures |
| `TimeoutException` | Operation timeout exceeded |
| `NotFoundException` | Resource not found |
| `RateLimitException` | API rate limit exceeded |

### Handling Errors

```python
from e2b import Sandbox
from e2b.exceptions import TimeoutException, SandboxException

try:
    sandbox = Sandbox.create(timeout=30)
    result = sandbox.commands.run('long-running-command', timeout=5)
except TimeoutException:
    print("Command timed out")
except SandboxException as e:
    print(f"Sandbox error: {e}")
finally:
    sandbox.close()
```

资料来源：[e2b/exceptions.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/exceptions.py)

## envd API

The `envd` module provides access to the environment daemon running inside each sandbox, enabling advanced operations and introspection.

### Available Operations

```python
sandbox = Sandbox.create()

# Get environment info
info = sandbox.envd.info()

# Check service status
status = sandbox.envd.is_process_running('nginx')

# Wait for port to be ready
sandbox.envd.wait_for_port(3000)
```

资料来源：[e2b/envd/api.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/envd/api.py)

## API Client Layer

The HTTP API client handles low-level communication with the E2B backend.

```mermaid
graph LR
    A[SDK Classes] --> B[SandboxAPI Client]
    B --> C[HTTP Requests]
    C --> D[E2B REST API]
    D --> E[Response Handling]
    E --> F[SDK Data Models]
```

### Client Configuration

```python
from e2b.api.client.client import APIClient

client = APIClient(
    base_url="https://api.e2b.dev",
    timeout=60,
    headers={
        "X-Custom-Header": "value"
    }
)
```

资料来源：[e2b/api/client/client.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/api/client/client.py)

## Complete Usage Example

```python
from e2b import Sandbox, Template

# Create and configure a template
template = (
    Template()
    .from_python_image('3.11')
    .apt_install(['git', 'curl'])
    .run_cmd('pip install fastapi uvicorn')
    .set_envs({'APP_ENV': 'production'})
    .set_start_cmd('uvicorn main:app', 'curl http://localhost:8000/health')
)

# Build template (run once)
Template.build(template, 'my-fastapi:v1.0')

# Use the template in sandboxes
with Sandbox.create(template='my-fastapi:v1.0') as sandbox:
    # Upload application code
    sandbox.upload('./app', '/home/user/app')
    
    # Run a command
    result = sandbox.commands.run('cd /home/user/app && python main.py')
    print(result.stdout)
```

## See Also

- [JavaScript SDK](../js-sdk) - TypeScript/JavaScript implementation
- [CLI](../cli) - Command-line interface
- [Code Interpreter](https://github.com/e2b-dev/code-interpreter) - Code execution SDK
- [E2B Documentation](https://e2b.dev/docs) - Official documentation
- [Cookbook](https://github.com/e2b-dev/e2b-cookbook) - Usage examples

---

<a id='cli-tool'></a>

## CLI Tool

### 相关页面

相关主题：[JavaScript/TypeScript SDK](#js-sdk), [Python SDK](#python-sdk), [Template System](#template-system)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/cli/README.md](https://github.com/e2b-dev/E2B/blob/main/packages/cli/README.md)
- [packages/cli/src/index.ts](https://github.com/e2b-dev/E2B/blob/main/packages/cli/src/index.ts)
- [packages/cli/src/commands/index.ts](https://github.com/e2b-dev/E2B/blob/main/packages/cli/src/commands/index.ts)
- [packages/cli/src/commands/auth/index.ts](https://github.com/e2b-dev/E2B/blob/main/packages/cli/src/commands/auth/index.ts)
- [packages/cli/src/commands/sandbox/index.ts](https://github.com/e2b-dev/E2B/blob/main/packages/cli/src/commands/sandbox/index.ts)
- [packages/cli/src/commands/template/index.ts](https://github.com/e2b-dev/E2B/blob/main/packages/cli/src/commands/template/index.ts)
- [packages/cli/src/commands/template/create.ts](https://github.com/e2b-dev/E2B/blob/main/packages/cli/src/commands/template/create.ts)
- [packages/cli/src/commands/template/build.ts](https://github.com/e2b-dev/E2B/blob/main/packages/cli/src/commands/template/build.ts)
</details>

# CLI Tool

The E2B CLI (Command Line Interface) is a Node.js-based command-line tool that enables developers to build, manage, and interact with E2B sandbox templates and running sandboxes directly from the terminal. It provides a unified interface for authentication, template management, and sandbox operations without requiring direct API integration.

## Overview

The E2B CLI serves as the primary management interface for E2B infrastructure. It allows users to authenticate with the E2B platform, create and build sandbox templates, manage running sandboxes, and configure their development environment for AI-generated code execution.

**Key capabilities include:**

- User authentication and token management
- Sandbox template creation and building
- Running sandbox lifecycle management
- Support for multiple package managers and base images
- Environment variable configuration during build
- Dockerfile integration for custom sandbox definitions

资料来源：[packages/cli/README.md:1-20]()

## Installation

### System Requirements

| Requirement | Version/Details |
|------------|-----------------|
| Node.js | v14.0.0 or higher |
| npm | v6.0.0 or higher |
| Operating System | macOS, Linux, Windows |

### Installation Methods

#### Using Homebrew (macOS/Linux)

```bash
brew install e2b
```

#### Using NPM

```bash
npm install -g @e2b/cli
```

资料来源：[packages/cli/README.md:13-20]()

## Authentication

Before using the CLI, you must authenticate with your E2B account. The CLI supports two authentication methods.

### Interactive Login

```bash
e2b auth login
```

This command opens a browser window for the user to complete the OAuth authentication flow.

### Token-Based Authentication

For non-interactive environments (CI/CD pipelines, remote servers), provide the access token directly:

```bash
E2B_ACCESS_TOKEN=sk_e2b_... e2b template build
```

**Important:** Note the distinction between `E2B_ACCESS_TOKEN` and `E2B_API_KEY`. The CLI uses `E2B_ACCESS_TOKEN`, which can be found in Account Settings under the Team selector at [e2b.dev/dashboard](https://e2b.dev/dashboard).

资料来源：[packages/cli/README.md:22-32]()

## Command Structure

The CLI organizes commands hierarchically under the `e2b` namespace:

```mermaid
graph TD
    A[e2b] --> B[auth]
    A --> C[template]
    A --> D[sandbox]
    
    B --> B1[login]
    
    C --> C1[create]
    C --> C2[build]
    C --> C3[list]
    C --> C4[delete]
    
    D --> D1[start]
    D --> D2[stop]
    D --> D3[list]
    D --> D4[logs]
```

### Global Flags

| Flag | Description | Example |
|------|-------------|---------|
| `--help, -h` | Display help information | `e2b --help` |
| `--version, -v` | Display CLI version | `e2b --version` |
| `--debug` | Enable debug output | `e2b --debug template build` |

## Template Commands

Templates define the sandbox environment including base images, installed packages, environment variables, and startup commands.

### Template Create

Creates a new sandbox template from a directory containing a `e2b.toml` configuration file or a Dockerfile.

```bash
e2b template create <template-name>
```

**Example workflow:**

```bash
# Navigate to your template directory
cd my-sandbox-template

# Create the template
e2b template create my-python-env
```

The command reads the template configuration, builds the Docker image, and uploads it to E2B infrastructure.

资料来源：[packages/cli/src/commands/template/create.ts:1-20]()

### Template Build

Builds a sandbox template and uploads it to E2B infrastructure.

```bash
e2b template build <template-name> [options]
```

**Options:**

| Option | Description | Default |
|--------|-------------|---------|
| `--alias, -a` | Template alias/name | Required |
| `--tag` | Additional tags for the build | None |
| `--file, -f` | Path to Dockerfile | `./Dockerfile` |
| `--timeout` | Build timeout in seconds | 600 |

**Build Process Flow:**

```mermaid
graph LR
    A[Start Build] --> B{Config File?}
    B -->|Dockerfile| C[Load Dockerfile]
    B -->|e2b.toml| D[Parse Configuration]
    C --> E[Build Docker Image]
    D --> F[Generate Dockerfile]
    E --> G[Upload to Registry]
    F --> E
    G --> H[Create Template]
    H --> I[Build Complete]
```

**Example usage:**

```bash
# Build with auto-generated name
e2b template build --alias my-template

# Build with custom Dockerfile
e2b template build --alias my-template --file ./custom.Dockerfile

# Build with tags
e2b template build --alias my-template --tag v1.0 --tag stable
```

资料来源：[packages/cli/src/commands/template/build.ts:1-50]()

### Template Configuration

Templates can be configured using either a `e2b.toml` file or a `Dockerfile`.

#### Using e2b.toml

```toml
name = "my-template"
runtime = "dockerfile"

[env]
NODE_ENV = "production"

[start]
command = "npm start"
ready = "curl http://localhost:3000/health"
```

#### Using Dockerfile

The CLI automatically detects and uses a `Dockerfile` in the template directory:

```dockerfile
FROM python:3.11-slim

RUN pip install numpy pandas flask

ENV PORT=8080

ENTRYPOINT ["python", "app.py"]
```

The CLI loads the Dockerfile content using the `getDockerfile()` function:

```typescript
function getDockerfile(root: string, file?: string) {
  // Check if user specified custom Dockerfile exists
  if (file) {
    const dockerfilePath = path.join(root, file)
    const dockerfileContent = loadFile(dockerfilePath)
    const dockerfileRelativePath = path.relative(root, dockerfilePath)
    
    // Returns { dockerfilePath, dockerfileContent, dockerfileRelativePath }
  }
}
```

资料来源：[packages/cli/src/commands/template/build.ts:80-100]()

### Template Build Output

Upon successful build completion, the CLI displays:

```
✅ Building sandbox template <template-name> finished.

Example usage:

Python SDK
  from e2b import Sandbox
  sandbox = Sandbox.create(template="<template-name>")
  result = sandbox.commands.run('echo "Hello from E2B!"')

JS SDK
  import Sandbox from 'e2b'
  const sandbox = await Sandbox.create({ template: '<template-name>' })
  const result = await sandbox.commands.run('echo "Hello from E2B!"')
```

资料来源：[packages/cli/src/commands/template/build.ts:35-45]()

### Error Handling

Build errors are reported with detailed context:

```
❌ Building sandbox template <template-name> failed.
Check the logs above for more details or contact us (https://e2b.dev/docs/support) to get help.
```

资料来源：[packages/cli/src/commands/template/build.ts:50-58]()

## Sandbox Commands

Sandbox commands allow you to manage running sandbox instances.

### Available Sandbox Operations

| Command | Description |
|---------|-------------|
| `e2b sandbox start` | Start a new sandbox instance |
| `e2b sandbox stop` | Stop a running sandbox |
| `e2b sandbox list` | List all running sandboxes |
| `e2b sandbox logs` | View sandbox logs |

### Sandbox Lifecycle

```mermaid
graph TD
    A[Create Sandbox] --> B[Initialize]
    B --> C[Run Ready Command]
    C --> D{Ready?}
    D -->|Yes| E[Sandbox Active]
    D -->|No| F[Retry/Timeout]
    E --> G[Execute Commands]
    G --> H[Stop Sandbox]
    H --> I[Cleanup]
```

资料来源：[packages/cli/src/commands/sandbox/index.ts:1-30]()

## Environment Variables

### CLI Environment Variables

| Variable | Description | Required |
|----------|-------------|----------|
| `E2B_ACCESS_TOKEN` | CLI authentication token | Yes (non-interactive) |
| `E2B_API_KEY` | API key for SDK operations | For SDK usage |

### Template Environment Variables

During template build, environment variables can be set in the configuration:

```toml
[env]
NODE_ENV = "production"
PORT = "8080"
DATABASE_URL = "postgres://..."
```

资料来源：[packages/cli/README.md:28-30]()

## Architecture

### CLI Entry Point

The CLI entry point at `packages/cli/src/index.ts` initializes the command infrastructure and registers all available commands:

```typescript
// Main CLI entry point
// Registers: auth, template, sandbox commands
// Handles global flags and configuration
```

### Command Registration

Commands are registered in `packages/cli/src/commands/index.ts` which serves as the command router:

```mermaid
graph TD
    A[index.ts] --> B[commands/index.ts]
    B --> C[auth/index.ts]
    B --> D[template/index.ts]
    B --> E[sandbox/index.ts]
    
    D --> D1[create.ts]
    D --> D2[build.ts]
    
    C --> C1[login.ts]
    C --> C2[logout.ts]
```

### Build System

The CLI is built using [tsup](https://github.com/egoist/tsup), a TypeScript bundler built on top of esbuild. The build configuration in `tsup.config.js` handles:

- TypeScript compilation
- Module resolution
- Output format (CJS/ESM)
- External dependencies

```javascript
// packages/cli/tsup.config.js
// Configures CLI bundling for distribution
```

## Integration with SDKs

The CLI works in conjunction with the JavaScript and Python SDKs:

```mermaid
graph LR
    A[CLI] --> B[Manage Templates]
    A --> C[Authenticate]
    
    D[JS SDK/Python SDK] --> E[Sandbox Runtime]
    E --> F[Execute Code]
    
    B --> G[E2B Cloud]
    C --> G
```

### Template Usage with SDKs

After building a template with the CLI, use it with the SDKs:

**Python SDK:**

```python
from e2b import Sandbox

sandbox = Sandbox.create(template="my-template")
result = sandbox.commands.run('echo "Hello from E2B!"')
print(result.stdout)
```

**JavaScript SDK:**

```typescript
import Sandbox from 'e2b'

const sandbox = await Sandbox.create({ template: 'my-template' })
const result = await sandbox.commands.run('echo "Hello from E2B!"')
console.log(result.stdout)
```

资料来源：[packages/cli/src/commands/template/create.ts:5-15]()

## Troubleshooting

### Common Issues

| Issue | Solution |
|-------|----------|
| Authentication failed | Ensure `E2B_ACCESS_TOKEN` is valid and not expired |
| Build timeout | Increase timeout with `--timeout` flag or optimize Dockerfile |
| Dockerfile not found | Verify the file exists or specify path with `--file` flag |
| Permission denied | Ensure npm global install permissions are correct |

### Debug Mode

Enable debug output for detailed logging:

```bash
e2b --debug template build --alias my-template
```

### Getting Help

```bash
# General help
e2b --help

# Command-specific help
e2b template --help
e2b template build --help
e2b sandbox --help
```

## See Also

- [E2B Documentation](https://e2b.dev/docs)
- [JavaScript SDK](../js-sdk/README.md)
- [Python SDK](../python-sdk/README.md)
- [E2B Cookbook](https://github.com/e2b-dev/e2b-cookbook)

---

<a id='sandbox-management'></a>

## Sandbox Management

### 相关页面

相关主题：[Sandbox Usage](#sandbox-usage), [Network Configuration](#network-config)

<details>
<summary>Relevant Source Files</summary>

The following source files were used to generate this documentation page:

- [packages/js-sdk/src/sandbox/sandboxApi.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/sandboxApi.ts)
- [packages/js-sdk/src/sandbox/index.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/index.ts)
- [packages/python-sdk/e2b/sandbox_async/main.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_async/main.py)
- [packages/python-sdk/e2b/sandbox_sync/main.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_sync/main.py)
- [packages/python-sdk/e2b/sandbox_async/sandbox_api.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_async/sandbox_api.py)
- [packages/cli/src/commands/sandbox/info.ts](https://github.com/e2b-dev/E2B/blob/main/packages/cli/src/commands/sandbox/info.ts)
- [packages/cli/src/commands/template/create.ts](https://github.com/e2b-dev/E2B/blob/main/packages/cli/src/commands/template/create.ts)
- [packages/cli/src/commands/template/build.ts](https://github.com/e2b-dev/E2B/blob/main/packages/cli/src/commands/template/build.ts)
</details>

# Sandbox Management

## Overview

Sandbox Management is the core system in E2B that enables the creation, control, and lifecycle management of secure, isolated cloud environments for running AI-generated code. Sandboxes provide ephemeral compute instances that can be spawned on-demand, configured with specific templates, and terminated when no longer needed.

The sandbox system abstracts away infrastructure complexity, allowing developers to work with a simple high-level API while E2B handles container orchestration, network isolation, and resource allocation behind the scenes.

资料来源：[packages/js-sdk/src/sandbox/sandboxApi.ts:1-50]()

## Architecture Overview

```mermaid
graph TD
    A[Developer Application] --> B[SDK Client]
    B --> C[Sandbox API]
    C --> D[E2B Infrastructure]
    D --> E[Isolated Sandbox Container]
    
    F[Template Definition] --> C
    G[CLI Commands] --> C
    
    H[Sandbox Instance] --> I[Commands Execution]
    H --> J[File System Access]
    H --> K[Network Resources]
```

The architecture consists of three primary layers:

| Layer | Description | Components |
|-------|-------------|------------|
| **Client SDK** | High-level language bindings | JavaScript SDK, Python SDK |
| **API Gateway** | REST API for sandbox operations | Template management, sandbox lifecycle |
| **Infrastructure** | Container orchestration | Docker containers, isolated networking |

资料来源：[packages/js-sdk/src/sandbox/index.ts:1-60]()

## Sandbox Lifecycle

Sandboxes follow a well-defined state machine with transitions controlled by the platform.

```mermaid
stateDiagram-v2
    [*] --> Starting
    Starting --> Running : API returns sandbox info
    Running --> Paused : Pause request
    Running --> Stopped : Timeout or kill
    Paused --> Running : Resume request
    Paused --> Stopped : Kill
    Stopped --> [*]
    
    Running --> Error : Infrastructure failure
    Error --> [*]
```

### Lifecycle Configuration

The sandbox lifecycle behavior can be configured at creation time:

```python
lifecycle = {
    "on_timeout": "pause",     # "kill" (default) or "pause"
    "auto_resume": True        # Only when on_timeout="pause"
}
```

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `on_timeout` | `str` | `"kill"` | Action when sandbox timeout is reached |
| `auto_resume` | `bool` | `False` | Whether to auto-resume paused sandbox |

资料来源：[packages/js-sdk/src/sandbox/sandboxApi.ts:60-80]()

## Creating a Sandbox

### JavaScript SDK

The JavaScript SDK provides both stable and beta creation methods.

**Stable Creation:**

```typescript
import Sandbox from 'e2b'

const sandbox = await Sandbox.create('my-template', {
  timeoutMs: 60000,
  metadata: { userId: '123' },
  envs: { NODE_ENV: 'production' }
})
```

**Beta Creation (with MCP support):**

```typescript
const sandbox = await Sandbox.betaCreate('my-template', {
  mcp: { servers: ['exa', 'firecrawl'] }
})
```

The SDK automatically handles:
- Template resolution (defaults to `base` or `mcp-gateway`)
- Connection configuration
- Debug mode fallback

资料来源：[packages/js-sdk/src/sandbox/index.ts:60-120]()

### Python SDK

**Async Sandbox:**

```python
from e2b import AsyncSandbox

async with await AsyncSandbox.create(
    template='my-template',
    timeout=60_000,
    metadata={'userId': '123'},
    envs={'PYTHON_ENV': 'production'}
) as sandbox:
    result = await sandbox.commands.run('echo "Hello"')
```

**Sync Sandbox:**

```python
from e2b import Sandbox

with Sandbox.create(
    template='my-template',
    timeout=60_000
) as sandbox:
    result = sandbox.commands.run('echo "Hello"')
```

资料来源：[packages/python-sdk/e2b/sandbox_async/main.py:1-80]()
资料来源：[packages/python-sdk/e2b/sandbox_sync/main.py:1-70]()

## Sandbox Options and Configuration

### Core Options

| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| `template` | `string` | No | `"base"` | Sandbox template name or ID |
| `timeoutMs` | `number` | No | Varies by plan | Maximum sandbox lifetime in milliseconds |
| `metadata` | `Record<string, string>` | No | `{}` | Custom metadata for the sandbox |
| `envs` | `Record<string, string>` | No | `{}` | Environment variables |
| `mcp` | `MCPConfig` | No | - | MCP server configuration |
| `network` | `boolean` | No | `true` | Network isolation setting |
| `allowInternetAccess` | `boolean` | No | `true` | Internet access in sandbox |

### Resource Configuration

```typescript
const sandbox = await Sandbox.create('my-template', {
  // CPU and memory can be specified via CLI
  // SDK uses template defaults
})
```

**CLI Resource Options:**

| Flag | Default | Description |
|------|---------|-------------|
| `--cpu-count` | `2` | Number of vCPUs |
| `--memory-mb` | `512` | RAM in megabytes (must be even) |

资料来源：[packages/js-sdk/src/sandbox/sandboxApi.ts:80-150]()
资料来源：[packages/cli/src/commands/template/create.ts:40-80]()

## Volume Mounts

Sandboxes support attaching persistent volumes for data storage across sessions.

```python
from e2b import AsyncSandbox, AsyncVolume

volume = await AsyncVolume.create('my-data-volume')

async with AsyncSandbox.create(
    volume_mounts={
        '/data': volume
    }
) as sandbox:
    # Files in /data persist across sandbox instances
    await sandbox.commands.run('echo "data" > /data/file.txt')
```

Volume mount transformation:

```python
transformed_mounts = [
    SandboxVolumeMountAPI(
        name=vol.name if isinstance(vol, AsyncVolume) else vol,
        path=path,
    )
    for path, vol in volume_mounts.items()
]
```

资料来源：[packages/python-sdk/e2b/sandbox_async/main.py:30-60]()

## Sandbox API Methods

### Creation Response

When a sandbox is created, the API returns a response containing connection details:

```python
SandboxCreateResponse(
    sandbox_id="sbox_xxxxx",
    sandbox_domain="sbox-xxxxx.e2b.dev",
    envd_version="0.1.0",
    envd_access_token="token_xxxxx",
    traffic_access_token="traffic_xxxxx"
)
```

| Field | Type | Description |
|-------|------|-------------|
| `sandbox_id` | `string` | Unique sandbox identifier |
| `sandbox_domain` | `string` or `null` | Public domain for the sandbox |
| `envd_version` | `string` | Version of the envd agent |
| `envd_access_token` | `string` or `null` | Token for envd authentication |
| `traffic_access_token` | `string` or `null` | Token for traffic encryption |

### Version Compatibility Check

The SDK validates that the template's envd version meets minimum requirements:

```python
if Version(res.parsed.envd_version) < Version("0.1.0"):
    await SandboxApi._cls_kill(res.parsed.sandbox_id)
    raise TemplateException(
        "You need to update the template to use the new SDK. "
        "You can do this by running `e2b template build`"
    )
```

资料来源：[packages/python-sdk/e2b/sandbox_async/sandbox_api.py:50-80]()

## CLI Sandbox Management

### Viewing Sandbox Information

```bash
e2b sandbox info <sandboxID>
```

**Output Fields:**

| Field | Label | Description |
|-------|-------|-------------|
| `sandboxId` | Sandbox ID | Unique identifier |
| `templateId` | Template ID | Template used |
| `name` | Alias | User-assigned name |
| `state` | State | Current sandbox state |
| `startedAt` | Started at | Creation timestamp |
| `endAt` | End at | Scheduled termination |
| `cpuCount` | vCPUs | CPU allocation |
| `memoryMB` | RAM MiB | Memory allocation |
| `envdVersion` | Envd version | Agent version |
| `allowInternetAccess` | Internet access | Network setting |
| `lifecycle` | Lifecycle | Timeout behavior |
| `network` | Network | Network configuration |
| `sandboxDomain` | Sandbox domain | Public endpoint |
| `metadata` | Metadata | Custom metadata |

```bash
# JSON output
e2b sandbox info <sandboxID> --format json

# Pretty output (default)
e2b sandbox info <sandboxID> --format pretty
```

资料来源：[packages/cli/src/commands/sandbox/info.ts:1-60]()

## Template-Based Sandbox Creation

Templates define the base environment for sandboxes. They can be built and managed via CLI.

### Building Templates

```bash
e2b template build <template-name>
```

**Options:**

| Option | Short | Description |
|--------|-------|-------------|
| `--path <path>` | `-p` | Template directory path |
| `--dockerfile <filename>` | `-d` | Custom Dockerfile name |
| `--cmd <start-command>` | `-c` | Command executed on sandbox start |
| `--ready-cmd <ready-command>` | - | Command that must exit 0 for ready state |
| `--cpu-count <count>` | - | vCPUs (default: 2) |
| `--memory-mb <mb>` | - | RAM in MB, even number (default: 512) |
| `--no-cache` | - | Skip build cache |

```bash
e2b template build my-template \
  --path ./templates/my-app \
  --cmd "python app.py" \
  --ready-cmd "curl -f http://localhost:3000/health" \
  --cpu-count 4 \
  --memory-mb 1024
```

### Template Validation

Template names must follow strict naming conventions:

```typescript
if (!/^[a-z0-9-_]+$/.test(templateName)) {
  console.error(
    `Template name ${templateName} is not valid. ` +
    `Template name can only contain lowercase letters, numbers, dashes and underscores.`
  )
}
```

资料来源：[packages/cli/src/commands/template/create.ts:50-90]()
资料来源：[packages/cli/src/commands/template/build.ts:1-50]()

## Debug Mode

The SDK supports a debug mode for local development:

```typescript
const config = new ConnectionConfig(sandboxOpts)
if (config.debug) {
  return new this({
    sandboxId: 'debug_sandbox_id',
    envdVersion: ENVD_DEBUG_FALLBACK,
    ...config,
  })
}
```

In debug mode, the sandbox uses a fallback environment instead of connecting to real infrastructure, enabling local testing of sandbox code without cloud resources.

资料来源：[packages/js-sdk/src/sandbox/index.ts:80-100]()

## Error Handling

### Template Exceptions

When a template is incompatible with the current SDK version:

```python
raise TemplateException(
    "You need to update the template to use the new SDK. "
    "You can do this by running `e2b template build` in the directory with the template."
)
```

### API Error Handling

```python
if res.status_code >= 300:
    raise handle_api_exception(res)

if isinstance(res.parsed, Error):
    raise SandboxException(f"{res.parsed.message}: Request failed")
```

资料来源：[packages/python-sdk/e2b/sandbox_async/sandbox_api.py:40-60]()

## Complete Workflow Diagram

```mermaid
graph LR
    A[Define Template] --> B[Build Template]
    B --> C[Create Sandbox]
    C --> D[Execute Commands]
    D --> E{More Work?}
    E -->|Yes| D
    E -->|No| F[Terminate Sandbox]
    F --> G[Clean Up]
    
    H[CLI Commands] -.->|Manage| C
    I[SDK API] -.->|Programmatic| D
```

## See Also

- [Template Building Guide](./template-building.md)
- [JavaScript SDK Reference](../js-sdk/README.md)
- [Python SDK Reference](../python-sdk/README.md)
- [MCP Server Integration](./mcp-integration.md)

---

<a id='template-system'></a>

## Template System

### 相关页面

相关主题：[CLI Tool](#cli-tool)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/js-sdk/src/template/index.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/template/index.ts)
- [packages/js-sdk/src/template/types.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/template/types.ts)
- [packages/js-sdk/src/template/readycmd.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/template/readycmd.ts)
- [packages/python-sdk/e2b/template/main.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/template/main.py)
- [packages/python-sdk/e2b/template/types.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/template/types.py)
- [packages/python-sdk/e2b/template_async/build_api.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/template_async/build_api.py)
- [packages/python-sdk/e2b/template_sync/build_api.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/template_sync/build_api.py)
- [packages/cli/src/commands/template/build.ts](https://github.com/e2b-dev/E2B/blob/main/packages/cli/src/commands/template/build.ts)
- [packages/cli/src/commands/template/create.ts](https://github.com/e2b-dev/E2B/blob/main/packages/cli/src/commands/template/create.ts)
</details>

# Template System

## Overview

The Template System is a core component of the E2B infrastructure that enables developers to create reproducible, pre-configured sandbox environments for running AI-generated code. Templates define the base image, system packages, environment variables, files, and startup commands needed for a sandbox instance.

Templates follow a **fluent builder pattern** where developers chain method calls to configure the environment, then invoke `build()` to compile the template into a deployable sandbox image. The system supports both synchronous and asynchronous operations, with full SDK coverage for JavaScript/TypeScript and Python.

资料来源：[packages/js-sdk/src/template/index.ts:1-50]()

## Architecture

The Template System is organized across multiple layers:

```mermaid
graph TD
    subgraph "User Layer"
        User[Developer]
    end
    
    subgraph "SDK Layer"
        JS_SDK[JS/TS SDK<br/>TemplateBuilder]
        PY_SDK[Python SDK<br/>TemplateBuilder]
    end
    
    subgraph "API Layer"
        BuildAPI[Build API]
        SandboxAPI[Sandbox API]
    end
    
    subgraph "Infrastructure Layer"
        Docker[Docker Build]
        Registry[Container Registry]
        Sandbox[Sandbox Runtime]
    end
    
    User -->|define template| JS_SDK
    User -->|define template| PY_SDK
    JS_SDK --> BuildAPI
    PY_SDK --> BuildAPI
    BuildAPI --> Docker
    Docker --> Registry
    Registry --> Sandbox
```

### Package Structure

| Package | Language | Purpose |
|---------|----------|---------|
| `packages/js-sdk` | TypeScript | JS/TS SDK with Template support |
| `packages/python-sdk` | Python | Python SDK with Template support |
| `packages/cli` | TypeScript | Command-line template management |

## Template Builder Pattern

Templates use a fluent builder API that enforces a valid state machine. The builder progresses through distinct states:

```mermaid
stateDiagram-v2
    [*] --> TemplateBuilder: instantiate Template()
    TemplateBuilder --> TemplateBuilder: add instructions
    TemplateBuilder --> TemplateBuilder: set env vars
    TemplateBuilder --> TemplateBuilder: copy files
    TemplateBuilder --> TemplateFinal: setStartCmd()
    TemplateFinal --> [*]: build()
```

### JavaScript SDK Usage

```typescript
import { Template } from 'e2b'

const template = Template()
  .fromPythonImage('3')
  .runCmd('pip install flask')
  .copy('./app', '/app')
  .setEnvs({ FLASK_ENV: 'production' })
  .setStartCmd(
    'python /app/main.py',
    'curl -s http://localhost:8000/health'
  )

const buildInfo = await Template.build(template, 'my-flask-app:v1.0')
```

资料来源：[packages/js-sdk/src/template/index.ts:200-280]()

### Python SDK Usage

```python
from e2b import Template

template = (
    Template()
    .from_python_image("3")
    .run_cmd("pip install flask")
    .copy("./app", "/app")
    .set_envs({"FLASK_ENV": "production"})
    .set_start_cmd("python /app/main.py", "curl -s http://localhost:8000/health")
)

build_info = template.build("my-flask-app:v1.0")
```

资料来源：[packages/python-sdk/e2b/template/main.py:1-100]()

## Base Images

The Template System provides convenience methods for common base images, along with support for custom images and registries.

### Supported Base Images

| Method | Image | Default Variant |
|--------|-------|-----------------|
| `fromBaseImage()` | `e2bdev/base:latest` | - |
| `fromPythonImage()` | `python:{version}` | `3` |
| `fromNodeImage()` | `node:{variant}` | `lts` |
| `fromBunImage()` | `oven/bun:{variant}` | `latest` |
| `fromDebianImage()` | `debian:{variant}` | `stable` |
| `fromUbuntuImage()` | `ubuntu:{variant}` | `latest` |
| `fromImage()` | Custom image | Required |

```typescript
// JavaScript SDK base image examples
Template().fromPythonImage('3.12')
Template().fromNodeImage('20')
Template().fromBunImage('1.3')
```

```python
# Python SDK base image examples
Template().from_python_image("3.12")
Template().from_node_image("20")
Template().from_bun_image("1.3")
```

资料来源：[packages/js-sdk/src/template/types.ts:100-180]()

### Custom Registries

For private images, configure registry authentication:

```typescript
import { Template, GenericDockerRegistry } from 'e2b'

const registry: GenericDockerRegistry = {
  type: 'registry',
  username: 'myuser',
  password: 'mypassword'
}

const template = Template()
  .fromImage('my-private-registry.com/my-image:latest', {
    registries: [registry]
  })
```

## Build Instructions

Templates support multiple instruction types that translate directly to Dockerfile commands.

### Instruction Types

| Type | Dockerfile Equivalent | Description |
|------|----------------------|-------------|
| `RUN` | `RUN` | Execute shell commands |
| `COPY` | `COPY` | Copy files into sandbox |
| `ENV` | `ENV` | Set environment variables |
| `WORKDIR` | `WORKDIR` | Set working directory |
| `USER` | `USER` | Set current user |

### Common Instructions

#### Environment Variables

```typescript
template.setEnvs({ NODE_ENV: 'production', PORT: '8080' })
```

```python
template.set_envs({"NODE_ENV": "production", "PORT": "8080"})
```

资料来源：[packages/js-sdk/src/template/types.ts:200-230]()

#### File Operations

```typescript
template.copy('./local/path', '/remote/path')
template.copy('./config', '/app/config')
```

#### Shell Commands

```typescript
template.runCmd('apt-get update && apt-get install -y vim')
```

#### Skip Cache

Force rebuild of subsequent layers:

```typescript
template.skipCache().runCmd('apt-get update')
```

资料来源：[packages/python-sdk/e2b/template/main.py:150-200]()

## Ready Commands

Ready commands verify that the sandbox is fully initialized before accepting connections.

### ReadyCmd Helpers

| Function | Use Case | Implementation |
|----------|----------|----------------|
| `waitForPort(port)` | Service listening on port | `nc -z localhost {port}` |
| `waitForURL(url, statusCode)` | HTTP endpoint availability | `curl` with status check |
| `waitForProcess(name)` | Daemon process running | `pgrep {name}` |
| `waitForFile(path)` | File exists in filesystem | `test -f {path}` |

```typescript
import { Template, waitForPort, waitForURL, waitForProcess, waitForFile } from 'e2b'

const template = Template()
  .fromNodeImage()
  .runCmd('npm start')
  .setStartCmd('npm start', waitForPort(3000))

const template2 = Template()
  .fromPythonImage()
  .setStartCmd('python server.py', waitForURL('http://localhost:8000/health', 200))
```

资料来源：[packages/js-sdk/src/template/readycmd.ts:1-80]()

## Build Process

### Build Flow

```mermaid
sequenceDiagram
    participant User
    participant TemplateBuilder
    participant BuildAPI
    participant DockerBuild
    participant Registry
    
    User->>TemplateBuilder: Define template
    User->>TemplateBuilder: build(name, options)
    TemplateBuilder->>BuildAPI: POST /templates/build
    BuildAPI->>DockerBuild: Start build
    DockerBuild->>DockerBuild: Build layers
    DockerBuild->>Registry: Push image
    Registry-->>BuildAPI: Build complete
    BuildAPI-->>TemplateBuilder: BuildInfo
    TemplateBuilder-->>User: Template deployed
```

### Build API Integration

The JavaScript SDK normalizes build arguments for different calling patterns:

```typescript
// New pattern - name as parameter
await Template.build(template, 'my-template:v1.0')

// Legacy pattern - alias in options
await Template.build(template, { alias: 'my-template' })
```

The SDK internally calls the E2B Build API which:
1. Validates the template specification
2. Initiates Docker build with caching
3. Monitors build status until completion
4. Pushes the resulting image to the registry

资料来源：[packages/js-sdk/src/template/index.ts:250-350]()

### Build Options

| Option | Type | Description |
|--------|------|-------------|
| `alias` | `string` | Template alias (deprecated) |
| `tags` | `string[]` | Additional image tags |
| `timeoutMs` | `number` | Build timeout in milliseconds |
| `metadata` | `Record<string, string>` | Custom metadata |

## CLI Integration

The E2B CLI provides command-line access to template operations.

### Available Commands

| Command | Description |
|---------|-------------|
| `e2b template create` | Create a new template from Dockerfile |
| `e2b template build` | Build and deploy a template |
| `e2b template publish` | Publish template to registry |

### Build Command

```bash
e2b template build --name my-template:v1.0
```

The CLI reads Dockerfile content and handles:
- Custom Dockerfile paths
- Template validation
- Build polling and status display
- Error reporting with support links

资料来源：[packages/cli/src/commands/template/build.ts:1-100]()

### Create Command

```bash
e2b template create my-template
```

The create command:
1. Uploads local template files
2. Initiates template creation
3. Polls for completion
4. Displays example usage code

资料来源：[packages/cli/src/commands/template/create.ts:1-50]()

## State Management

The template builder enforces valid state transitions through the `TemplateBuilder` and `TemplateFinal` interfaces.

### State Interface Hierarchy

```mermaid
classDiagram
    class TemplateBuilder {
        +fromImage(image)
        +runCmd(cmd)
        +copy(src, dest)
        +setEnvs(envs)
        +setStartCmd(start, ready)
    }
    
    class TemplateFinal {
        <<interface>>
    }
    
    TemplateBuilder --|> TemplateFinal : after setStartCmd()
```

### TypeScript Interfaces

```typescript
export interface TemplateBuilder {
  fromImage(image: string, options?: FromImageOptions): TemplateBuilder
  runCmd(cmd: string, user?: string): TemplateBuilder
  copy(src: string, dest: string): TemplateBuilder
  setEnvs(envs: Record<string, string>): TemplateBuilder
  skipCache(): this
  setStartCmd(startCommand: string, readyCommand: string): TemplateFinal
}
```

The `TemplateFinal` interface is an empty marker type that signals the builder is complete and ready for `build()`.

资料来源：[packages/js-sdk/src/template/types.ts:50-150]()

## Dockerfile Generation

Templates internally generate equivalent Dockerfile instructions:

```typescript
generateDockerfile(): string {
  let dockerfile = `FROM ${this.baseImage}\n`
  
  for (const instruction of this.instructions) {
    switch (instruction.type) {
      case InstructionType.RUN:
        dockerfile += `RUN ${instruction.args[0]}\n`
      case InstructionType.COPY:
        dockerfile += `COPY ${instruction.args[0]} ${instruction.args[1]}\n`
      case InstructionType.ENV:
        const values = instruction.args.map((v, i) => 
          i % 2 === 0 ? `${instruction.args[i]}=${instruction.args[i+1]}` : null
        ).filter(Boolean)
        dockerfile += `ENV ${values.join(' ')}\n`
    }
  }
  
  if (this.startCmd) {
    dockerfile += `ENTRYPOINT ${this.startCmd}\n`
  }
  
  return dockerfile
}
```

资料来源：[packages/js-sdk/src/template/index.ts:350-400]()

## Error Handling

Build errors are caught and reported with actionable guidance:

```typescript
case 'error':
  throw new Error(
    `❌ Building sandbox template ${templateName} failed.
Check the logs above for more details or contact us (https://e2b.dev/docs/support) to get help.`
  )
```

## SDK Configuration

Templates inherit connection configuration for API communication:

```typescript
const config = new ConnectionConfig(sandboxOpts)
const client = new ApiClient(config)
```

Configuration includes:
- API key authentication
- Request timeouts
- Debug mode for local development
- Signal handling for cancellation

资料来源：[packages/js-sdk/src/sandbox/index.ts:100-150]()

## Summary

The E2B Template System provides a unified, fluent API for defining sandbox environments across JavaScript and Python SDKs. Key capabilities include:

- **Base image selection** with convenience methods for common runtimes
- **Instruction composition** using familiar Dockerfile semantics
- **Ready command validation** ensuring sandboxes are fully initialized
- **Build API integration** for remote Docker builds and registry deployment
- **CLI tooling** for command-line workflow integration
- **State machine enforcement** preventing invalid template configurations

---

<a id='filesystem-git'></a>

## Filesystem and Git Operations

### 相关页面

相关主题：[Sandbox Usage](#sandbox-usage)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/js-sdk/src/sandbox/filesystem/index.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/filesystem/index.ts)
- [packages/js-sdk/src/sandbox/filesystem/watchHandle.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts)
- [packages/js-sdk/src/sandbox/git/index.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/git/index.ts)
- [packages/python-sdk/e2b/sandbox/filesystem/filesystem.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py)
- [packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py)
- [packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py)
- [packages/python-sdk/e2b/sandbox/git.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox/git.py)
- [packages/python-sdk/e2b/sandbox_async/git.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_async/git.py)
- [packages/python-sdk/e2b/sandbox_sync/git.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox_sync/git.py)
- [packages/python-sdk/e2b/sandbox/_git/__init__.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox/_git/__init__.py)
- [packages/python-sdk/e2b/sandbox/_git/args.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox/_git/args.py)
- [packages/python-sdk/e2b/sandbox/_git/auth.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox/_git/auth.py)
</details>

# Filesystem and Git Operations

## Overview

The E2B SDK provides comprehensive filesystem and Git operations for interacting with sandbox environments. These operations allow developers to read, write, and watch files within isolated sandboxes, as well as perform Git operations including repository cloning with various authentication methods.

Filesystem operations are available through dedicated filesystem classes that handle file I/O with support for multiple data formats (text, bytes, blob, stream), compression, and user-specific permissions. Git operations provide a fluent API for cloning repositories using SSH keys, tokens, or username/password authentication. 资料来源：[packages/js-sdk/src/sandbox/filesystem/index.ts:1-100]()

## Architecture Overview

```mermaid
graph TD
    A[Sandbox Instance] --> B[Filesystem API]
    A --> C[Git API]
    
    B --> D[envd API - /files endpoint]
    B --> E[Volume API - /volumecontent endpoint]
    
    C --> F[envd API - git operations]
    C --> G[SSH Key Management]
    C --> H[Token Auth]
    C --> I[Username/Password Auth]
    
    J[Read Operations] --> K[text | bytes | blob | stream]
    L[Write Operations] --> M[multipart/form-data | application/octet-stream]
    N[Watch Operations] --> O[FilesystemEvent stream]
```

## Filesystem Operations

### Core Components

The filesystem module is implemented separately in both JavaScript and Python SDKs with consistent functionality across both platforms.

#### JavaScript SDK

The JavaScript SDK exposes filesystem operations through the `Sandbox.filesystem` property, providing type-safe methods for file operations. 资料来源：[packages/js-sdk/src/sandbox/filesystem/index.ts:1-50]()

#### Python SDK

The Python SDK provides filesystem access through both synchronous (`sandbox_sync`) and asynchronous (`sandbox_async`) implementations, allowing developers to choose the appropriate model for their application. 资料来源：[packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py:1-50]()

### Reading Files

#### Supported Formats

| Format | Return Type | Description |
|--------|-------------|-------------|
| `text` | `string` | File content as plain text (default) |
| `bytes` | `Uint8Array` / `bytes` | Raw binary content |
| `blob` | `Blob` | Web API Blob object |
| `stream` | `ReadableStream<Uint8Array>` | Streaming response |

The `read` method automatically handles user version compatibility by checking the envd API version. If the sandbox's envd version is below the default user version threshold, it falls back to a default username for authentication. 资料来源：[packages/js-sdk/src/sandbox/filesystem/index.ts:60-80]()

#### Read Options

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `format` | `'text' \| 'bytes' \| 'blob' \| 'stream'` | `'text'` | Output format |
| `gzip` | `boolean` | `false` | Request gzip-compressed response |
| `user` | `string` | `undefined` | Run as specific user |
| `signal` | `AbortSignal` | `undefined` | Cancellation signal |
| `requestTimeoutMs` | `number` | `undefined` | Request timeout |

#### JavaScript SDK Example

```typescript
// Read as text
const content = await sandbox.filesystem.read('/path/to/file.txt')

// Read as bytes
const bytes = await sandbox.filesystem.read('/path/to/file.bin', { format: 'bytes' })

// Read with gzip compression
const compressed = await sandbox.filesystem.read('/path/to/large.txt', { gzip: true })
```

#### Python SDK Example

```python
# Read as text
content = sandbox.filesystem.read('/path/to/file.txt')

# Read as bytes
bytes_data = sandbox.filesystem.read('/path/to/file.bin', format='bytes')

# Async version
content = await sandbox.filesystem.read('/path/to/file.txt')
```

### Writing Files

The write operation supports multiple files in a single call and creates necessary parent directories automatically. 资料来源：[packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py:40-70]()

#### Write Options

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `files` | `WriteEntry[]` | Required | List of files to write |
| `user` | `string` | `undefined` | Run as specific user |
| `gzip` | `boolean` | `false` | Use gzip compression |
| `use_octet_stream` | `boolean` | `false` | Use octet-stream upload (requires envd 0.5.7+) |
| `request_timeout` | `number` | `undefined` | Request timeout |

#### WriteEntry Structure

```typescript
interface WriteEntry {
  path: string   // Destination path in sandbox
  data: string | Uint8Array  // File content
}
```

#### Upload Methods

The SDK supports two upload methods:

1. **multipart/form-data** (default, universally supported)
2. **application/octet-stream** (faster, requires envd 0.5.7+)

When `use_octet_stream` is enabled and the envd version supports it, the upload uses `application/octet-stream` content type. Otherwise, it gracefully falls back to multipart form data. 资料来源：[packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py:60-85]()

#### Write Example

```typescript
await sandbox.filesystem.write([
  { path: '/app/config.json', data: JSON.stringify(config) },
  { path: '/app/data.bin', data: binaryBuffer }
])
```

### Directory Watching

The filesystem module provides directory watching capabilities through the `WatchHandle` class, allowing applications to monitor filesystem changes in real-time. 资料来源：[packages/js-sdk/src/sandbox/filesystem/watchHandle.ts:30-50]()

#### WatchHandle Class

```typescript
class WatchHandle {
  // Stop watching the directory
  async stop(): void
  
  // Event callback
  onEvent?: (event: FilesystemEvent) => void | Promise<void>
  
  // Exit callback with optional error
  onExit?: (err?: Error) => void | Promise<void>
}
```

#### FilesystemEvent Structure

```typescript
interface FilesystemEvent {
  name: string           // Name of the changed file/directory
  type: FilesystemEventType  // 'created' | 'modified' | 'deleted'
}
```

#### Watch Flow

```mermaid
sequenceDiagram
    participant App as Application
    participant WH as WatchHandle
    participant API as envd API
    participant FS as Sandbox FS
    
    App->>WH: watch('/path')
    WH->>API: Subscribe to filesystem events
    FS->>API: File change detected
    API->>WH: Event stream
    WH->>App: onEvent callback
    App->>WH: stop()
    WH->>API: Unsubscribe
```

#### Watch Example

```typescript
const handle = await sandbox.filesystem.watch('/app', {
  onEvent: (event) => {
    console.log(`File ${event.type}: ${event.name}`)
  },
  onExit: (err) => {
    if (err) console.error('Watch error:', err)
  }
})

// Later: stop watching
await handle.stop()
```

### File Information

When writing files, the operation returns `WriteInfo` objects containing metadata about the created/modified files.

#### WriteInfo Structure

| Field | Type | Description |
|-------|------|-------------|
| `name` | `string` | Name of the filesystem object |
| `type` | `FileType` | Type of object (file, directory, symlink) |
| `path` | `string` | Full path to the object |

#### EntryInfo (for directory listings)

| Field | Type | Description |
|-------|------|-------------|
| `size` | `number` | Size in bytes |
| `mode` | `number` | File mode and permission bits |
| `permissions` | `string` | String representation (e.g., 'rwxr-xr-x') |
| `owner` | `string` | Owner username |
| `group` | `string` | Group owner |
| `modifiedTime` | `Date` | Last modification time |
| `symlinkTarget` | `string` | Target if symlink |

## Git Operations

Git operations provide a fluent API for cloning and managing Git repositories within sandboxes. The implementation supports multiple authentication methods and comprehensive git functionality. 资料来源：[packages/python-sdk/e2b/sandbox/git.py:1-80]()

### Authentication Methods

The SDK supports three authentication methods for Git operations:

| Method | Description | Use Case |
|--------|-------------|----------|
| SSH Key | Use predefined SSH key stored in E2B | Private repository access |
| Token | Personal Access Token or GitHub Token | CI/CD scenarios |
| Username/Password | Basic authentication | Legacy systems |

#### Authentication Configuration

```python
# SSH Key authentication (most common)
git.auth.ssh_key('my-ssh-key-name')

# Token authentication
git.auth.token('ghp_xxxxxxxxxxxx')

# Username/Password
git.auth.username_password('user', 'password')
```

### Git Clone Operations

#### Clone Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `url` | `string` | Yes | Repository URL |
| `path` | `string` | No | Destination path (defaults to repo name) |
| `branch` | `string` | No | Specific branch to clone |
| `depth` | `number` | No | Clone depth for shallow clone |
| `recursive` | `bool` | No | Clone submodules (default: true) |

#### Clone Example

```python
# Basic clone
sandbox.git.clone('https://github.com/user/repo.git')

# Clone to specific path
sandbox.git.clone('https://github.com/user/repo.git', '/workspace/project')

# Clone specific branch
sandbox.git.clone('https://github.com/user/repo.git', branch='develop')

# Shallow clone
sandbox.git.clone('https://github.com/user/repo.git', depth=1)

# With authentication
sandbox.git.auth.token('ghp_xxx').clone('https://github.com/user/private.git')
```

### Git Module Structure

The Python SDK organizes Git functionality across multiple modules:

```mermaid
classDiagram
    class GitCore {
        +clone()
        +auth: GitAuth
    }
    class GitAuth {
        +ssh_key(name)
        +token(token)
        +username_password(user, pass)
    }
    class GitArgs {
        +build_clone_args()
    }
    
    GitCore --> GitAuth
    GitCore --> GitArgs
```

#### Module Responsibilities

| Module | Purpose |
|--------|---------|
| `e2b/sandbox/_git/__init__.py` | Core git operations and command building |
| `e2b/sandbox/_git/args.py` | Argument construction for git commands |
| `e2b/sandbox/_git/auth.py` | Authentication configuration management |

### JavaScript SDK Git Operations

The JavaScript SDK provides similar git functionality with a fluent builder pattern:

```typescript
// Clone repository
await sandbox.git.clone('https://github.com/user/repo.git')

// Clone with options
await sandbox.git.clone('https://github.com/user/repo.git', {
  path: '/workspace/project',
  branch: 'main',
  depth: 1
})

// With authentication
await sandbox.git.auth.sshKey('my-key')
await sandbox.git.clone('git@github.com:user/private.git')
```

## Error Handling

### Filesystem Errors

The SDK provides specific error types for filesystem operations:

| Error Type | Condition |
|------------|-----------|
| `FileNotFoundError` | File or directory does not exist |
| `NotFoundError` | Volume path not found |
| `SandboxError` | General sandbox communication error |
| `CommandExitError` | Command execution failed |

#### Error Mapping

```mermaid
graph LR
    A[HTTP/RPC Error] --> B{Error Code}
    B -->|404| C[FileNotFoundError]
    B -->|Default| D[SandboxError]
    
    E[API Response] --> F{Status Code}
    F -->|404| G[NotFoundError]
    F -->|Default| H[Generic Error]
```

### Error Handling Example

```typescript
try {
  const content = await sandbox.filesystem.read('/path/to/file')
} catch (error) {
  if (error instanceof FileNotFoundError) {
    console.log('File does not exist')
  } else if (error instanceof SandboxError) {
    console.log('Sandbox communication error:', error.message)
  }
}
```

## Version Compatibility

### envd Version Requirements

| Feature | Minimum envd Version |
|---------|---------------------|
| Basic filesystem read/write | 0.1.0 |
| Default user handling | Automatic fallback for older versions |
| Octet-stream upload | 0.5.7 |
| Gzip compression | All versions |

### Version Checking

The SDK automatically checks the envd version during sandbox initialization and adjusts behavior accordingly:

```typescript
// Automatic version check in read operation
if (user == undefined && compareVersions(envdVersion, ENVD_DEFAULT_USER) < 0) {
  user = defaultUsername
}
```

## Best Practices

1. **Use Appropriate Formats**: Choose `stream` for large files to avoid memory issues
2. **Enable Compression**: Use gzip for text-based files larger than 1KB
3. **Use Octet-Stream**: Enable for faster uploads when targeting envd 0.5.7+
4. **Handle Errors**: Always catch specific error types for better error handling
5. **Set Timeouts**: Configure appropriate request timeouts for network operations
6. **Watch Cleanup**: Always call `stop()` on WatchHandle when done

## Summary

The Filesystem and Git Operations in E2B provide comprehensive tools for:

- **Reading files** in multiple formats (text, bytes, blob, stream) with optional compression
- **Writing files** with automatic directory creation and multiple upload methods
- **Watching directories** for real-time filesystem event monitoring
- **Git operations** with flexible authentication (SSH keys, tokens, username/password)
- **Robust error handling** with specific error types and version compatibility

---

<a id='network-config'></a>

## Network Configuration

### 相关页面

相关主题：[Sandbox Usage](#sandbox-usage), [Sandbox Management](#sandbox-management)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/js-sdk/src/sandbox/network.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/sandbox/network.ts)
- [packages/python-sdk/e2b/sandbox/network.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/sandbox/network.py)
- [packages/python-sdk/e2b/api/client/models/sandbox_network_config.py](https://github.com/e2b-dev/E2B/blob/main/packages/python-sdk/e2b/api/client/models/sandbox_network_config.py)
- [packages/js-sdk/src/connectionConfig.ts](https://github.com/e2b-dev/E2B/blob/main/packages/js-sdk/src/connectionConfig.ts)
</details>

# Network Configuration

E2B provides comprehensive network configuration capabilities for sandboxes, allowing users to control DNS resolution, port access rules, and VPN connectivity. This document describes the network configuration system across the JavaScript and Python SDKs.

## Overview

Network Configuration in E2B enables fine-grained control over how sandboxes communicate with external networks and how network traffic is managed. Each sandbox can be configured with custom DNS settings, port access policies, and optional VPN tunnel support.

资料来源：[packages/js-sdk/src/sandbox/network.ts:1-50]()

## Architecture

The network configuration system consists of three main components that work together to manage sandbox networking:

```mermaid
graph TD
    A[Sandbox Creation] --> B[NetworkConfig]
    B --> C[DNS Configuration]
    B --> D[Port Rules]
    B --> E[VPN Settings]
    C --> F[Sandbox DNS Resolution]
    D --> G[Port Access Control]
    E --> H[VPN Tunnel]
```

### Data Flow

When creating a sandbox, the network configuration is serialized and sent to the E2B API as part of the sandbox creation request. The API validates and stores the configuration, which is then applied when the sandbox environment initializes.

资料来源：[packages/python-sdk/e2b/api/client/models/sandbox_network_config.py:1-100]()

## JavaScript SDK Implementation

### NetworkConfig Interface

The JavaScript SDK provides a `NetworkConfig` interface located in `packages/js-sdk/src/sandbox/network.ts`:

```typescript
interface NetworkConfig {
  dns?: DNSConfig
  ports?: PortConfig[]
  vpn?: VPNConfig
}
```

#### DNS Configuration

Controls how the sandbox resolves domain names:

| Property | Type | Description |
|----------|------|-------------|
| `customServers` | `string[]` | List of custom DNS server IPs |
| `blockAutoDetect` | `boolean` | Whether to block auto-detected DNS |

资料来源：[packages/js-sdk/src/sandbox/network.ts:10-30]()

#### Port Configuration

Manages inbound and outbound port access:

| Property | Type | Description |
|----------|------|-------------|
| `port` | `number` | The port number to configure |
| `protocol` | `'tcp' \| 'udp'` | Network protocol |
| `access` | `'allow' \| 'deny'` | Access rule for the port |
| `description` | `string` | Optional description |

资料来源：[packages/js-sdk/src/sandbox/network.ts:35-45]()

#### VPN Configuration

Provides VPN tunnel support:

| Property | Type | Description |
|----------|------|-------------|
| `enabled` | `boolean` | Enable/disable VPN tunnel |
| `config` | `VPNConfig` | VPN configuration object |

资料来源：[packages/js-sdk/src/sandbox/network.ts:50-60]()

### Usage Example

```typescript
import { Sandbox, NetworkConfig } from 'e2b'

const networkConfig: NetworkConfig = {
  dns: {
    customServers: ['8.8.8.8', '1.1.1.1'],
    blockAutoDetect: true
  },
  ports: [
    { port: 80, protocol: 'tcp', access: 'allow', description: 'HTTP' },
    { port: 443, protocol: 'tcp', access: 'allow', description: 'HTTPS' },
    { port: 22, protocol: 'tcp', access: 'deny', description: 'SSH disabled' }
  ],
  vpn: {
    enabled: true
  }
}

const sandbox = await Sandbox.create('my-template', {
  network: networkConfig
})
```

资料来源：[packages/js-sdk/src/sandbox/sandboxApi.ts:1-50]()

## Python SDK Implementation

### NetworkConfig Class

The Python SDK provides a fluent API for network configuration in `packages/python-sdk/e2b/sandbox/network.py`:

```python
class NetworkConfig:
    def __init__(self) -> None:
        self._dns: Optional[DNSConfig] = None
        self._ports: List[PortRule] = []
        self._vpn: Optional[VPNConfig] = None
```

#### DNS Configuration

```python
class DNSConfig:
    custom_servers: Optional[List[str]] = None
    block_auto_detect: bool = False
```

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `custom_servers` | `List[str]` | `None` | Custom DNS server IPs |
| `block_auto_detect` | `bool` | `False` | Block auto-detected DNS |

资料来源：[packages/python-sdk/e2b/sandbox/network.py:1-80]()

#### Port Rules

```python
class PortRule:
    port: int
    protocol: str  # 'tcp' or 'udp'
    access: str    # 'allow' or 'deny'
    description: Optional[str] = None
```

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `port` | `int` | Yes | Port number |
| `protocol` | `str` | Yes | Network protocol |
| `access` | `str` | Yes | Access rule |
| `description` | `str` | No | Rule description |

资料来源：[packages/python-sdk/e2b/sandbox/network.py:80-150]()

### Fluent API Methods

The Python SDK provides a fluent interface for building network configurations:

#### DNS Configuration

```python
def dns(self, servers: List[str], block_auto_detect: bool = False) -> "NetworkConfig":
    """Configure custom DNS servers."""
    self._dns = DNSConfig(
        custom_servers=servers,
        block_auto_detect=block_auto_detect
    )
    return self
```

#### Port Management

```python
def allow_port(self, port: int, protocol: str = "tcp", description: str = None) -> "NetworkConfig":
    """Allow traffic on specified port."""
    self._ports.append(PortRule(
        port=port,
        protocol=protocol,
        access="allow",
        description=description
    ))
    return self

def deny_port(self, port: int, protocol: str = "tcp", description: str = None) -> "NetworkConfig":
    """Deny traffic on specified port."""
    self._ports.append(PortRule(
        port=port,
        protocol=protocol,
        access="deny",
        description=description
    ))
    return self
```

#### VPN Configuration

```python
def enable_vpn(self) -> "NetworkConfig":
    """Enable VPN tunnel for the sandbox."""
    self._vpn = VPNConfig(enabled=True)
    return self
```

资料来源：[packages/python-sdk/e2b/sandbox/network.py:150-250]()

### Python Usage Example

```python
from e2b import Sandbox, NetworkConfig

network = (
    NetworkConfig()
    .dns(servers=['8.8.8.8', '1.1.1.1'], block_auto_detect=True)
    .allow_port(80, protocol='tcp', description='HTTP traffic')
    .allow_port(443, protocol='tcp', description='HTTPS traffic')
    .allow_port(5432, protocol='tcp', description='PostgreSQL')
    .deny_port(22, protocol='tcp', description='SSH disabled')
    .enable_vpn()
)

sandbox = await Sandbox.create(
    template='my-template',
    network=network
)
```

资料来源：[packages/python-sdk/e2b/sandbox_async/main.py:1-80]()

## API Model

The backend API uses a standardized `SandboxNetworkConfig` model defined in OpenAPI format:

```python
class SandboxNetworkConfig:
    dns: Optional[DNSConfig] = None
    ports: Optional[List[PortRule]] = None
    vpn: Optional[VPNConfig] = None
```

资料来源：[packages/python-sdk/e2b/api/client/models/sandbox_network_config.py:1-100]()

### Serialization

The configuration is serialized to JSON when sent to the API:

```json
{
  "dns": {
    "customServers": ["8.8.8.8", "1.1.1.1"],
    "blockAutoDetect": true
  },
  "ports": [
    {"port": 80, "protocol": "tcp", "access": "allow"},
    {"port": 443, "protocol": "tcp", "access": "allow"}
  ],
  "vpn": {"enabled": true}
}
```

资料来源：[packages/js-sdk/src/sandbox/sandboxApi.ts:50-70]()

## Sandbox Creation Integration

Network configuration is passed during sandbox creation through the `network` option:

### JavaScript

```typescript
const sandboxInfo = await SandboxApi.createSandbox(
  template,
  timeoutMs,
  {
    network: networkConfig,
    // ... other options
  }
)
```

### Python

```python
sandbox = await cls._create(
    template=template,
    timeout=timeout,
    network=network,
    # ... other options
)
```

资料来源：[packages/js-sdk/src/sandbox/sandboxApi.ts:1-50]()
资料来源：[packages/python-sdk/e2b/sandbox_async/main.py:1-60]()

## Default Behavior

When no network configuration is provided, the sandbox uses default network settings:

| Setting | Default Value |
|---------|---------------|
| DNS | Auto-detected system DNS |
| Ports | All ports allowed |
| VPN | Disabled |

Internet access is enabled by default unless explicitly disabled via `allow_internet_access: false`.

资料来源：[packages/js-sdk/src/sandbox/sandboxApi.ts:20-40]()

## Best Practices

1. **Explicit Port Rules**: Always explicitly define port access rules rather than relying on defaults for production workloads.

2. **DNS Configuration**: Use specific DNS servers when you need consistent resolution behavior across sandbox instances.

3. **VPN for Sensitive Workloads**: Enable VPN when handling sensitive data that requires encrypted tunnel communication.

4. **Protocol Specificity**: Specify both port and protocol to avoid unintended access.

## Related Documentation

- [Sandbox API Reference](packages/js-sdk/src/sandbox/sandboxApi.ts)
- [Connection Configuration](packages/js-sdk/src/connectionConfig.ts)
- [Template Building](packages/cli/src/commands/template/build.ts)

---

---

## Doramagic 踩坑日志

项目：e2b-dev/E2B

摘要：发现 20 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：配置坑 - 来源证据：process was not killed when auto paused。

## 1. 配置坑 · 来源证据：process was not killed when auto paused

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：process was not killed when auto paused
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_66994844a2ec44a784ad5b80307d82e9 | https://github.com/e2b-dev/E2B/issues/1031 | 来源类型 github_issue 暴露的待验证使用条件。

## 2. 安装坑 · 来源证据：Closed Port Error

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Closed Port Error
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_33133a8885a44301a7f98b23844205cc | https://github.com/e2b-dev/E2B/issues/907 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 3. 安装坑 · 来源证据：Please add skills to use with any ai agent to use e2b in our project

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Please add skills to use with any ai agent to use e2b in our project
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_8cebd572dbd2485ab6cdbc13733fdee0 | https://github.com/e2b-dev/E2B/issues/1138 | 来源类型 github_issue 暴露的待验证使用条件。

## 4. 安装坑 · 来源证据：[Bug]: Incorrect info about webhooks in docs and dashboard

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Bug]: Incorrect info about webhooks in docs and dashboard
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_8b25841679fd4eaea5d759a33dfad3b1 | https://github.com/e2b-dev/E2B/issues/1103 | 来源类型 github_issue 暴露的待验证使用条件。

## 5. 安装坑 · 来源证据：[Bug]: Sandbox create fails from template, but succeeds without template

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Bug]: Sandbox create fails from template, but succeeds without template
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_3ae274a17e7e420ca9f2cd6e7c6105bd | https://github.com/e2b-dev/E2B/issues/1130 | 来源类型 github_issue 暴露的待验证使用条件。

## 6. 安装坑 · 来源证据：build status polling timed out

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：build status polling timed out
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_88fc7403d6a44edb8b8d4c9deaff0279 | https://github.com/e2b-dev/E2B/issues/1009 | 来源类型 github_issue 暴露的待验证使用条件。

## 7. 配置坑 · 来源证据：Paused sandbox is not persisting the file changes / addition after second time resumed and onward

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Paused sandbox is not persisting the file changes / addition after second time resumed and onward
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_2fc5340254c94ae2931673fede53e25b | https://github.com/e2b-dev/E2B/issues/884 | 来源类型 github_issue 暴露的待验证使用条件。

## 8. 配置坑 · 社区讨论暴露的待验证问题：[Bug]: torch.compile fails for Gemma3n on pytorch 2.8

- 严重度：medium
- 证据强度：source_linked
- 发现：[Bug]: torch.compile fails for Gemma3n on pytorch 2.8 ### Your current environment <details> <summary>The output of <code>python collect_env.py</code></summary> ```text Your output of `python collect_env.py` here ``` </details> ### 🐛 Describe the bug run ``` vllm serve google/gemma-3n-E2B-it -tp 1 ``` on torch==2.8.0:…
- 对用户的影响：这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。
- 建议检查：Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。
- 证据：social_signal:github | ssig_3c3209f718cd4d108c88e3bf9d35db24 | https://github.com/vllm-project/vllm/issues/24547 | [Bug]: torch.compile fails for Gemma3n on pytorch 2.8

## 9. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:609539715 | https://github.com/e2b-dev/E2B | README/documentation is current enough for a first validation pass.

## 10. 维护坑 · 来源证据：When using autoPause in sandbox creation, connect overrides this when resuming the sandbox again

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：When using autoPause in sandbox creation, connect overrides this when resuming the sandbox again
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_3002fb1e72dd4aa2ab6baed80425d7b2 | https://github.com/e2b-dev/E2B/issues/875 | 来源类型 github_issue 暴露的待验证使用条件。

## 11. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:609539715 | https://github.com/e2b-dev/E2B | last_activity_observed missing

## 12. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:609539715 | https://github.com/e2b-dev/E2B | no_demo; severity=medium

## 13. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:609539715 | https://github.com/e2b-dev/E2B | no_demo; severity=medium

## 14. 安全/权限坑 · 来源证据：(feature request) Run-scoped messaging for multi-sandbox agent workflows

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：(feature request) Run-scoped messaging for multi-sandbox agent workflows
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_a6ad64f1b6d54498906e63b880471ac4 | https://github.com/e2b-dev/E2B/issues/1330 | 来源类型 github_issue 暴露的待验证使用条件。

## 15. 安全/权限坑 · 来源证据：AuthenticationError: Unauthorized, please check your credentials. - Invalid API key

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：AuthenticationError: Unauthorized, please check your credentials. - Invalid API key
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_c6225e71e02943b7a367a36c86c96b65 | https://github.com/e2b-dev/E2B/issues/980 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 16. 安全/权限坑 · 来源证据：Docker Build Secrets Support

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Docker Build Secrets Support
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_6d5e325b8d00480b8ac7acf0b5b01379 | https://github.com/e2b-dev/E2B/issues/815 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。

## 17. 安全/权限坑 · 来源证据：How to use the file that I uploaded when I create template

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：How to use the file that I uploaded when I create template
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_57466d7f984143c1bb2ae3fb20b9b4f0 | https://github.com/e2b-dev/E2B/issues/1049 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 18. 安全/权限坑 · 来源证据：Template Build Fails with "syncing took too long" Error

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Template Build Fails with "syncing took too long" Error
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_4c757d3a005b45989cf3f2e3a6f4433b | https://github.com/e2b-dev/E2B/issues/996 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 19. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:609539715 | https://github.com/e2b-dev/E2B | issue_or_pr_quality=unknown

## 20. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:609539715 | https://github.com/e2b-dev/E2B | release_recency=unknown

<!-- canonical_name: e2b-dev/E2B; human_manual_source: deepwiki_human_wiki -->
