Doramagic Project Pack · Human Manual
E2B Sandbox Code Execution Pack
Related topics: Sandbox Usage, JavaScript/TypeScript SDK, Python SDK
Overview
Related topics: Sandbox Usage, JavaScript/TypeScript SDK, Python SDK
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Sandbox Usage, JavaScript/TypeScript SDK, Python SDK
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.
Sources: 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.
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] --> CKey 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.
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 |
Sources: 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 |
Sources: 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.
npm install e2b
Sources: packages/js-sdk/README.md:1
Installation and Quick Start:
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+.
pip install e2b
Sources: packages/python-sdk/README.md:1
Installation and Quick Start:
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 |
Sources: packages/js-sdk/README.md:1
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 |
Sources: packages/python-sdk/e2b/template/main.py:1
Template Lifecycle
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 |
Sources: 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.
Sources: 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.
Sources: 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
opts.volumeMounts = {
'/mount/path': 'volume-name'
}
Each mount maps a volume name to a path within the sandbox filesystem.
Sources: 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 |
Sources: 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.
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 | Detailed JS/TS SDK documentation |
| Python SDK Guide | Detailed Python SDK documentation |
| E2B Cookbook | Example projects with various LLMs |
| Official Documentation | Full platform documentation |
Sources: README.md:1
Installation
Related topics: JavaScript/TypeScript SDK, Python SDK, CLI Tool
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: JavaScript/TypeScript SDK, Python SDK, CLI Tool
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 |
| API Key | Obtain from E2B Dashboard |
| 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:
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:
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:
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:
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:
npm i @e2b/code-interpreter
Installing the CLI
The E2B CLI provides command-line access to template management and sandbox operations.
Installation via npm
npm i e2b
Installation via npx
For one-time usage without global installation:
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
import e2b
print(e2b.__version__)
JavaScript Verification
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
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
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)
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:
# 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
- Contact support at https://e2b.dev/docs/support
- Visit the E2B Cookbook for examples
Source: https://github.com/e2b-dev/E2B / Human Manual
Sandbox Usage
Related topics: Sandbox Management, Filesystem and Git Operations, Network Configuration
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Sandbox Management, Filesystem and Git Operations, Network Configuration
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
Sources: README.md:1-20
Architecture
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| CCreating a Sandbox
JavaScript/TypeScript SDK
#### Create with default template
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!
Sources: packages/js-sdk/src/sandbox/index.ts:80-100
#### Create with specific template
const sandbox = await Sandbox.create('my-custom-template')
#### Create with options
const sandbox = await Sandbox.create({
template: 'my-template',
metadata: { user: 'alice', app: 'production' },
envs: { NODE_ENV: 'production' },
timeoutMs: 60000,
})
Sources: packages/js-sdk/src/sandbox/index.ts:95-130
Python SDK
#### Async usage
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
from e2b import Sandbox
with Sandbox.create() as sandbox:
result = sandbox.commands.run('echo "Hello from E2B!"')
print(result.stdout) # Hello from E2B!
Sources: README.md:30-50
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 |
Sources: packages/js-sdk/src/sandbox/sandboxApi.ts:50-120 Sources: packages/python-sdk/e2b/sandbox_async/sandbox_api.py:1-50
Network Configuration
const sandbox = await Sandbox.create({
network: true, // Full network access (default)
// Or with custom configuration:
network: {
timeoutMs: 30000,
}
})
Resource Configuration
const sandbox = await Sandbox.create({
cpuCount: 4, // Number of CPUs (default: 2)
memoryMB: 1024, // Memory in MiB (default: 512, must be even)
})
Lifecycle Configuration
const sandbox = await Sandbox.create({
timeoutMs: 3600000, // 1 hour max
lifecycle: {
onTimeout: 'pause', // Pause instead of kill
autoResume: true, // Auto-resume when accessed
}
})
Sources: packages/js-sdk/src/sandbox/sandboxApi.ts:40-70
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 |
Sources: packages/js-sdk/src/api/schema.gen.ts:1-80 Sources: packages/js-sdk/src/sandbox/sandboxApi.ts:200-280
Sandbox State Machine
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 terminatedSandbox 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 |
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' })
Sources: packages/js-sdk/src/sandbox/index.ts:130-180
Python SDK Instance
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:
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 |
Sources: packages/js-sdk/src/sandbox/sandboxApi.ts:250-300
CLI Commands
List Sandboxes
e2b sandbox list
Get Sandbox Info
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 |
Sources: packages/cli/src/commands/sandbox/info.ts:1-60
Create Sandbox Template
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
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
Sources: packages/cli/src/commands/template/create.ts:1-100 Sources: packages/cli/src/commands/template/build.ts:1-100
Beta Features
MCP Gateway
Enable MCP (Model Context Protocol) gateway support:
const sandbox = await Sandbox.betaCreate({
mcp: true,
// Uses 'mcp-gateway' template by default
})
Dev Container Support
Templates can use devcontainer configuration:
template
.gitClone('https://myrepo.com/project.git', '/my-devcontainer')
.betaDevContainerPrebuild('/my-devcontainer')
.betaSetDevContainerStart('/my-devcontainer')
Sources: packages/js-sdk/src/sandbox/index.ts:40-80 Sources: packages/js-sdk/src/template/types.ts:1-50
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
// 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).
Sources: packages/js-sdk/src/sandbox/sandboxApi.ts:20-60
Best Practices
- Always clean up resources: Use context managers or explicitly call
kill()to terminate sandboxes when done.
- Set appropriate timeouts: Match the timeout to your workload. Shorter timeouts are more cost-effective for quick tasks.
- Use metadata for tracking: Add meaningful metadata to easily identify sandboxes in listings.
- Handle errors gracefully: Catch exceptions for sandbox creation and command execution.
- Use pause lifecycle for interactive sessions: When you need to resume work later, use
onTimeout: 'pause'withautoResume: true.
- Configure resources appropriately: Allocate CPU and memory based on your actual workload requirements.
Sources: README.md:1-20
JavaScript/TypeScript SDK
Related topics: Python SDK, CLI Tool, Sandbox Usage
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Python SDK, CLI Tool, Sandbox Usage
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. Sources: 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. Sources: packages/js-sdk/src/api/metadata.ts Sources: 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. Sources: packages/js-sdk/README.md
{
"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. Sources: packages/js-sdk/src/index.ts
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
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. Sources: packages/js-sdk/src/api/metadata.ts
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. Sources: packages/js-sdk/src/api/metadata.ts
// 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. Sources: packages/js-sdk/src/sandbox/index.ts
Creating a Sandbox
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
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:
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. Sources: 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
const content = await sandbox.filesystem.read('/app/data.json')
console.log('File content:', content)
Writing Files
await sandbox.filesystem.write('/app/output.txt', 'Hello, E2B!')
Listing Directory Contents
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. Sources: packages/js-sdk/src/sandbox/commands/index.ts
Running Commands
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:
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. Sources: packages/js-sdk/src/sandbox/network.ts
Network Settings
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. Sources: packages/js-sdk/src/volume/index.ts
Creating and Mounting Volumes
// 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. Sources: 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
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. Sources: 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
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. Sources: packages/js-sdk/tsup.config.js
Build Output Configuration
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
class E2B {
constructor(config?: ConnectionConfig)
// Sandboxes
sandboxes: Sandboxes
// Volumes
volumes: Volumes
// Templates
templates: Templates
// Close the client
close(): void
}
Sandbox Instance
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:
// 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:
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:
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. Sources: packages/cli/src/commands/template/build.ts Sources: packages/cli/src/commands/template/init.ts
Related Documentation
For more information, refer to:
- Python SDK - Python client library
- CLI Documentation - Command-line interface
- API Reference - REST API documentation
- Template Development - Creating custom templates
Sources: packages/js-sdk/tsup.config.js
Python SDK
Related topics: JavaScript/TypeScript SDK, CLI Tool, Sandbox Usage
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: JavaScript/TypeScript SDK, CLI Tool, Sandbox Usage
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:
# 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(),
}
Sources: e2b/api/metadata.py
Installation and Setup
Install the SDK
pip install e2b
Configure API Credentials
Obtain your API key from the E2B Dashboard and set it as an environment variable:
export E2B_API_KEY=e2b_***
Quick Start Example
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.
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
from e2b import Sandbox
# Using context manager (recommended)
with Sandbox.create() as sandbox:
result = sandbox.commands.run('echo "Hello"')
print(result.stdout)
Sandbox Lifecycle
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 |
Sources: e2b/sandbox/main.py
Synchronous vs Asynchronous APIs
The Python SDK provides both synchronous and asynchronous interfaces to accommodate different programming patterns.
Synchronous API
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
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 |
Sources: e2b/sandbox_sync/main.py,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
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 |
Sources: e2b/template/main.py
Async Template Operations
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
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
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
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()
Sources: 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
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)
Sources: e2b/envd/api.py
API Client Layer
The HTTP API client handles low-level communication with the E2B backend.
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
from e2b.api.client.client import APIClient
client = APIClient(
base_url="https://api.e2b.dev",
timeout=60,
headers={
"X-Custom-Header": "value"
}
)
Sources: e2b/api/client/client.py
Complete Usage Example
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 - TypeScript/JavaScript implementation
- CLI - Command-line interface
- Code Interpreter - Code execution SDK
- E2B Documentation - Official documentation
- Cookbook - Usage examples
Sources: e2b/api/metadata.py
CLI Tool
Related topics: JavaScript/TypeScript SDK, Python SDK, Template System
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: JavaScript/TypeScript SDK, Python SDK, Template System
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
Sources: 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)
brew install e2b
#### Using NPM
npm install -g @e2b/cli
Sources: 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
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:
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.
Sources: packages/cli/README.md:22-32
Command Structure
The CLI organizes commands hierarchically under the e2b namespace:
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.
e2b template create <template-name>
Example workflow:
# 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.
Sources: packages/cli/src/commands/template/create.ts:1-20
Template Build
Builds a sandbox template and uploads it to E2B infrastructure.
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:
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:
# 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
Sources: 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
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:
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:
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 }
}
}
Sources: 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!"')
Sources: 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.
Sources: 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
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]Sources: 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:
[env]
NODE_ENV = "production"
PORT = "8080"
DATABASE_URL = "postgres://..."
Sources: 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:
// 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:
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, 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
// packages/cli/tsup.config.js
// Configures CLI bundling for distribution
Integration with SDKs
The CLI works in conjunction with the JavaScript and Python SDKs:
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 --> GTemplate Usage with SDKs
After building a template with the CLI, use it with the SDKs:
Python SDK:
from e2b import Sandbox
sandbox = Sandbox.create(template="my-template")
result = sandbox.commands.run('echo "Hello from E2B!"')
print(result.stdout)
JavaScript SDK:
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)
Sources: 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:
e2b --debug template build --alias my-template
Getting Help
# General help
e2b --help
# Command-specific help
e2b template --help
e2b template build --help
e2b sandbox --help
See Also
Sources: packages/cli/README.md:1-20
Sandbox Management
Related topics: Sandbox Usage, Network Configuration
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Sandbox Usage, Network Configuration
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.
Sources: packages/js-sdk/src/sandbox/sandboxApi.ts:1-50
Architecture Overview
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 |
Sources: packages/js-sdk/src/sandbox/index.ts:1-60
Sandbox Lifecycle
Sandboxes follow a well-defined state machine with transitions controlled by the platform.
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:
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 |
Sources: 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:
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):
const sandbox = await Sandbox.betaCreate('my-template', {
mcp: { servers: ['exa', 'firecrawl'] }
})
The SDK automatically handles:
- Template resolution (defaults to
baseormcp-gateway) - Connection configuration
- Debug mode fallback
Sources: packages/js-sdk/src/sandbox/index.ts:60-120
Python SDK
Async Sandbox:
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:
from e2b import Sandbox
with Sandbox.create(
template='my-template',
timeout=60_000
) as sandbox:
result = sandbox.commands.run('echo "Hello"')
Sources: packages/python-sdk/e2b/sandbox_async/main.py:1-80 Sources: 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
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) |
Sources: packages/js-sdk/src/sandbox/sandboxApi.ts:80-150 Sources: packages/cli/src/commands/template/create.ts:40-80
Volume Mounts
Sandboxes support attaching persistent volumes for data storage across sessions.
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:
transformed_mounts = [
SandboxVolumeMountAPI(
name=vol.name if isinstance(vol, AsyncVolume) else vol,
path=path,
)
for path, vol in volume_mounts.items()
]
Sources: 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:
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:
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`"
)
Sources: packages/python-sdk/e2b/sandbox_async/sandbox_api.py:50-80
CLI Sandbox Management
Viewing Sandbox Information
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 |
# JSON output
e2b sandbox info <sandboxID> --format json
# Pretty output (default)
e2b sandbox info <sandboxID> --format pretty
Sources: 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
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 |
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:
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.`
)
}
Sources: packages/cli/src/commands/template/create.ts:50-90 Sources: packages/cli/src/commands/template/build.ts:1-50
Debug Mode
The SDK supports a debug mode for local development:
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.
Sources: packages/js-sdk/src/sandbox/index.ts:80-100
Error Handling
Template Exceptions
When a template is incompatible with the current SDK version:
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
if res.status_code >= 300:
raise handle_api_exception(res)
if isinstance(res.parsed, Error):
raise SandboxException(f"{res.parsed.message}: Request failed")
Sources: packages/python-sdk/e2b/sandbox_async/sandbox_api.py:40-60
Complete Workflow Diagram
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| DSee Also
Template System
Related topics: CLI Tool
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: CLI Tool
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.
Sources: packages/js-sdk/src/template/index.ts:1-50
Architecture
The Template System is organized across multiple layers:
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 --> SandboxPackage 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:
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
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')
Sources: packages/js-sdk/src/template/index.ts:200-280
Python SDK Usage
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")
Sources: 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 |
// JavaScript SDK base image examples
Template().fromPythonImage('3.12')
Template().fromNodeImage('20')
Template().fromBunImage('1.3')
# Python SDK base image examples
Template().from_python_image("3.12")
Template().from_node_image("20")
Template().from_bun_image("1.3")
Sources: packages/js-sdk/src/template/types.ts:100-180
Custom Registries
For private images, configure registry authentication:
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
template.setEnvs({ NODE_ENV: 'production', PORT: '8080' })
template.set_envs({"NODE_ENV": "production", "PORT": "8080"})
Sources: packages/js-sdk/src/template/types.ts:200-230
#### File Operations
template.copy('./local/path', '/remote/path')
template.copy('./config', '/app/config')
#### Shell Commands
template.runCmd('apt-get update && apt-get install -y vim')
#### Skip Cache
Force rebuild of subsequent layers:
template.skipCache().runCmd('apt-get update')
Sources: 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} |
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))
Sources: packages/js-sdk/src/template/readycmd.ts:1-80
Build Process
Build Flow
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 deployedBuild API Integration
The JavaScript SDK normalizes build arguments for different calling patterns:
// 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:
- Validates the template specification
- Initiates Docker build with caching
- Monitors build status until completion
- Pushes the resulting image to the registry
Sources: 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
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
Sources: packages/cli/src/commands/template/build.ts:1-100
Create Command
e2b template create my-template
The create command:
- Uploads local template files
- Initiates template creation
- Polls for completion
- Displays example usage code
Sources: 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
classDiagram
class TemplateBuilder {
+fromImage(image)
+runCmd(cmd)
+copy(src, dest)
+setEnvs(envs)
+setStartCmd(start, ready)
}
class TemplateFinal {
<<interface>>
}
TemplateBuilder --|> TemplateFinal : after setStartCmd()TypeScript Interfaces
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().
Sources: packages/js-sdk/src/template/types.ts:50-150
Dockerfile Generation
Templates internally generate equivalent Dockerfile instructions:
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
}
Sources: packages/js-sdk/src/template/index.ts:350-400
Error Handling
Build errors are caught and reported with actionable guidance:
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:
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
Sources: 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
Filesystem and Git Operations
Related topics: Sandbox Usage
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Sandbox Usage
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. Sources: packages/js-sdk/src/sandbox/filesystem/index.ts:1-100
Architecture Overview
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. Sources: 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. Sources: 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. Sources: 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
// 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
# 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. Sources: 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
interface WriteEntry {
path: string // Destination path in sandbox
data: string | Uint8Array // File content
}
#### Upload Methods
The SDK supports two upload methods:
- multipart/form-data (default, universally supported)
- 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. Sources: packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py:60-85
#### Write Example
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. Sources: packages/js-sdk/src/sandbox/filesystem/watchHandle.ts:30-50
#### WatchHandle Class
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
interface FilesystemEvent {
name: string // Name of the changed file/directory
type: FilesystemEventType // 'created' | 'modified' | 'deleted'
}
#### Watch Flow
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
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. Sources: 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
# 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
# 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:
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:
// 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('[email protected]: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
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
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:
// Automatic version check in read operation
if (user == undefined && compareVersions(envdVersion, ENVD_DEFAULT_USER) < 0) {
user = defaultUsername
}
Best Practices
- Use Appropriate Formats: Choose
streamfor large files to avoid memory issues - Enable Compression: Use gzip for text-based files larger than 1KB
- Use Octet-Stream: Enable for faster uploads when targeting envd 0.5.7+
- Handle Errors: Always catch specific error types for better error handling
- Set Timeouts: Configure appropriate request timeouts for network operations
- 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
Source: https://github.com/e2b-dev/E2B / Human Manual
Network Configuration
Related topics: Sandbox Usage, Sandbox Management
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Sandbox Usage, Sandbox Management
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.
Sources: 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:
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.
Sources: 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:
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 |
Sources: 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 |
Sources: 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 |
Sources: packages/js-sdk/src/sandbox/network.ts:50-60
Usage Example
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
})
Sources: 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:
class NetworkConfig:
def __init__(self) -> None:
self._dns: Optional[DNSConfig] = None
self._ports: List[PortRule] = []
self._vpn: Optional[VPNConfig] = None
#### DNS Configuration
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 |
Sources: packages/python-sdk/e2b/sandbox/network.py:1-80
#### Port Rules
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 |
Sources: 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
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
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
def enable_vpn(self) -> "NetworkConfig":
"""Enable VPN tunnel for the sandbox."""
self._vpn = VPNConfig(enabled=True)
return self
Sources: packages/python-sdk/e2b/sandbox/network.py:150-250
Python Usage Example
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
)
Sources: packages/python-sdk/e2b/sandbox_async/main.py:1-80
API Model
The backend API uses a standardized SandboxNetworkConfig model defined in OpenAPI format:
class SandboxNetworkConfig:
dns: Optional[DNSConfig] = None
ports: Optional[List[PortRule]] = None
vpn: Optional[VPNConfig] = None
Sources: 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:
{
"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}
}
Sources: packages/js-sdk/src/sandbox/sandboxApi.ts:50-70
Sandbox Creation Integration
Network configuration is passed during sandbox creation through the network option:
JavaScript
const sandboxInfo = await SandboxApi.createSandbox(
template,
timeoutMs,
{
network: networkConfig,
// ... other options
}
)
Python
sandbox = await cls._create(
template=template,
timeout=timeout,
network=network,
# ... other options
)
Sources: packages/js-sdk/src/sandbox/sandboxApi.ts:1-50 Sources: 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.
Sources: packages/js-sdk/src/sandbox/sandboxApi.ts:20-40
Best Practices
- Explicit Port Rules: Always explicitly define port access rules rather than relying on defaults for production workloads.
- DNS Configuration: Use specific DNS servers when you need consistent resolution behavior across sandbox instances.
- VPN for Sensitive Workloads: Enable VPN when handling sensitive data that requires encrypted tunnel communication.
- Protocol Specificity: Specify both port and protocol to avoid unintended access.
Related Documentation
Doramagic Pitfall Log
Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.
Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
First-time setup may fail or require extra isolation and rollback planning.
First-time setup may fail or require extra isolation and rollback planning.
First-time setup may fail or require extra isolation and rollback planning.
Doramagic Pitfall Log
Doramagic extracted 16 source-linked risk signals. Review them before installing or handing real data to the project.
1. Configuration risk: process was not killed when auto paused
- Severity: high
- Finding: Configuration risk is backed by a source signal: process was not killed when auto paused. Treat it as a review item until the current version is checked.
- User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: Source-linked evidence: https://github.com/e2b-dev/E2B/issues/1031
2. Installation risk: Closed Port Error
- Severity: medium
- Finding: Installation risk is backed by a source signal: Closed Port Error. Treat it as a review item until the current version is checked.
- User impact: First-time setup may fail or require extra isolation and rollback planning.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: Source-linked evidence: https://github.com/e2b-dev/E2B/issues/907
3. Installation risk: Please add skills to use with any ai agent to use e2b in our project
- Severity: medium
- Finding: Installation risk is backed by a source signal: Please add skills to use with any ai agent to use e2b in our project. Treat it as a review item until the current version is checked.
- User impact: First-time setup may fail or require extra isolation and rollback planning.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: Source-linked evidence: https://github.com/e2b-dev/E2B/issues/1138
4. Installation risk: [Bug]: Incorrect info about webhooks in docs and dashboard
- Severity: medium
- Finding: Installation risk is backed by a source signal: [Bug]: Incorrect info about webhooks in docs and dashboard. Treat it as a review item until the current version is checked.
- User impact: First-time setup may fail or require extra isolation and rollback planning.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: Source-linked evidence: https://github.com/e2b-dev/E2B/issues/1103
5. Installation risk: [Bug]: Sandbox create fails from template, but succeeds without template
- Severity: medium
- Finding: Installation risk is backed by a source signal: [Bug]: Sandbox create fails from template, but succeeds without template. Treat it as a review item until the current version is checked.
- User impact: First-time setup may fail or require extra isolation and rollback planning.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: Source-linked evidence: https://github.com/e2b-dev/E2B/issues/1130
6. Installation risk: build status polling timed out
- Severity: medium
- Finding: Installation risk is backed by a source signal: build status polling timed out. Treat it as a review item until the current version is checked.
- User impact: First-time setup may fail or require extra isolation and rollback planning.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: Source-linked evidence: https://github.com/e2b-dev/E2B/issues/1009
7. Configuration risk: Paused sandbox is not persisting the file changes / addition after second time resumed and onward
- Severity: medium
- Finding: Configuration risk is backed by a source signal: Paused sandbox is not persisting the file changes / addition after second time resumed and onward. Treat it as a review item until the current version is checked.
- User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: Source-linked evidence: https://github.com/e2b-dev/E2B/issues/884
8. Configuration risk: [Bug]: torch.compile fails for Gemma3n on pytorch 2.8
- Severity: medium
- Finding: [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 ofpython collect_env.pyhere`</details> ### 🐛 Describe the bug run`vllm serve google/gemma-3n-E2B-it -tp 1`` on torch==2.8.0:… - User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: social_signal:github | ssig_3c3209f718cd4d108c88e3bf9d35db24 | https://github.com/vllm-project/vllm/issues/24547 | [Bug]: torch.compile fails for Gemma3n on pytorch 2.8
9. Capability assumption: README/documentation is current enough for a first validation pass.
- Severity: medium
- Finding: README/documentation is current enough for a first validation pass.
- User impact: The project should not be treated as fully validated until this signal is reviewed.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: capability.assumptions | github_repo:609539715 | https://github.com/e2b-dev/E2B | README/documentation is current enough for a first validation pass.
10. Maintenance risk: When using autoPause in sandbox creation, connect overrides this when resuming the sandbox again
- Severity: medium
- Finding: Maintenance risk is backed by a source signal: When using autoPause in sandbox creation, connect overrides this when resuming the sandbox again. Treat it as a review item until the current version is checked.
- User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: Source-linked evidence: https://github.com/e2b-dev/E2B/issues/875
11. Maintenance risk: Maintainer activity is unknown
- Severity: medium
- Finding: Maintenance risk is backed by a source signal: Maintainer activity is unknown. Treat it as a review item until the current version is checked.
- User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: evidence.maintainer_signals | github_repo:609539715 | https://github.com/e2b-dev/E2B | last_activity_observed missing
12. Security or permission risk: no_demo
- Severity: medium
- Finding: no_demo
- User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: downstream_validation.risk_items | github_repo:609539715 | https://github.com/e2b-dev/E2B | no_demo; severity=medium
Source: Doramagic discovery, validation, and Project Pack records
Community Discussion Evidence
These external discussion links are review inputs, not standalone proof that the project is production-ready.
Count of project-level external discussion links exposed on this manual page.
Open the linked issues or discussions before treating the pack as ready for your environment.
Community Discussion Evidence
Doramagic exposes project-level community discussion separately from official documentation. Review these links before using E2B Sandbox Code Execution Pack with real data or production workflows.
- Paused sandbox is not persisting the file changes / addition after secon - github / github_issue
- (feature request) Run-scoped messaging for multi-sandbox agent workflows - github / github_issue
- process was not killed when auto paused - github / github_issue
- Docker Build Secrets Support - github / github_issue
- When using autoPause in sandbox creation, connect overrides this when re - github / github_issue
- Closed Port Error - github / github_issue
- AuthenticationError: Unauthorized, please check your credentials. - Inva - github / github_issue
- Template Build Fails with "syncing took too long" Error - github / github_issue
- build status polling timed out - github / github_issue
- [[Bug]: Incorrect info about webhooks in docs and dashboard](https://github.com/e2b-dev/E2B/issues/1103) - github / github_issue
- How to use the file that I uploaded when I create template - github / github_issue
- [[Bug]: Sandbox create fails from template, but succeeds without template](https://github.com/e2b-dev/E2B/issues/1130) - github / github_issue
Source: Project Pack community evidence and pitfall evidence