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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Capabilities

Continue reading this section for the full explanation and source context.

Section Key Components

Continue reading this section for the full explanation and source context.

Section JavaScript/TypeScript SDK

Continue reading this section for the full explanation and source context.

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

CapabilityDescription
Secure SandboxesIsolated cloud environments for safe code execution
Multi-Language SDKsOfficial JavaScript/TypeScript and Python SDKs
Template SystemCustomizable sandbox environments with Dockerfile-like syntax
Code InterpreterDedicated SDK for AI code execution use cases
MCP Server SupportIntegration with Model Context Protocol servers
Volume ManagementPersistent 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] --> C

Key Components

#### Sandboxes

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

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:

ParameterTypeDefaultDescription
templateIDstringrequiredTemplate identifier to base the sandbox on
timeoutnumber300000msMaximum execution time before auto-termination
securebooleantrueEnable security restrictions
allowInternetAccessbooleantrueControl network connectivity
metadataobject{}User-defined metadata for the sandbox
envsRecord<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:

MethodDescription
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.

SDKPackageUse Case
JS@e2b/code-interpreterAI agents, code generators
Pythone2b-code-interpreterAI 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

InstructionDescription
run_cmd() / RUNExecute shell commands during build
copy() / COPYCopy files into the sandbox
set_envs() / ENVSet 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:

FunctionImplementationUse Case
waitForURL(url, statusCode)curl + grepHTTP service health checks
waitForProcess(name)pgrepDaemon process verification
waitForFile(path)shell testFile 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

FormatReturn TypeUse Case
text (default)stringSource code, configs
bytesUint8ArrayBinary files
blobBlobWeb-compatible binary
streamReadableStreamLarge 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

PropertyTypeDescription
stdoutstringStandard output content
stderrstringStandard error content
exitCodenumberProcess exit code (0 = success)
errorstringError 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

FormatAPI MethodReturn Type
textreadFile(path, { format: 'text' })string
bytesreadFile(path, { format: 'bytes' })Uint8Array
blobreadFile(path, { format: 'blob' })Blob
streamreadFile(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

ResourceDescription
JavaScript SDK GuideDetailed JS/TS SDK documentation
Python SDK GuideDetailed Python SDK documentation
E2B CookbookExample projects with various LLMs
Official DocumentationFull platform documentation

Sources: README.md:1

Installation

Related topics: JavaScript/TypeScript SDK, Python SDK, CLI Tool

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core SDK

Continue reading this section for the full explanation and source context.

Section Code Interpreter SDK

Continue reading this section for the full explanation and source context.

Section Core SDK

Continue reading this section for the full explanation and source context.

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:

RequirementDescription
E2B AccountSign up at e2b.dev
API KeyObtain from E2B Dashboard
RuntimePython 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 PackagePurposeLanguage
e2bCore sandbox functionalityPython
e2bCore sandbox functionalityJavaScript/TypeScript
@e2b/code-interpreterCode execution sandboxPython
@e2b/code-interpreterCode execution sandboxJavaScript/TypeScript
e2b (CLI)Command-line interfaceNode.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

VariableRequiredDescription
E2B_API_KEYYesYour E2B API key for authentication

Optional Configuration

The SDKs support additional configuration options passed during client initialization:

ParameterTypeDefaultDescription
timeoutnumbervariesMaximum request timeout in seconds
verify_sslbooleantrueWhether to verify SSL certificates
follow_redirectsbooleanfalseWhether to follow HTTP redirects
base_urlstringE2B APICustom 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

IssueSolution
ModuleNotFoundErrorEnsure pip/npm is updated and try reinstalling
API key errorsVerify E2B_API_KEY environment variable is set correctly
Network timeoutsCheck firewall/proxy settings for outbound HTTPS connections
Version conflictsUse virtual environments or ensure Node.js version compatibility

Getting Help

If installation issues persist:

Source: https://github.com/e2b-dev/E2B / Human Manual

Sandbox Usage

Related topics: Sandbox Management, Filesystem and Git Operations, Network Configuration

Section Related Pages

Continue reading this section for the full explanation and source context.

Section JavaScript/TypeScript SDK

Continue reading this section for the full explanation and source context.

Section Python SDK

Continue reading this section for the full explanation and source context.

Section Configuration Parameters

Continue reading this section for the full explanation and source context.

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| C

Creating 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

ParameterTypeDefaultDescription
templatestring'base'Sandbox template name or ID. Use 'mcp-gateway' when mcp option is set
metadataRecord<string, string>{}Custom metadata for the sandbox
envsRecord<string, string>{}Custom environment variables for the sandbox
timeoutMsnumbervariesTimeout in milliseconds (max 24h for Pro, 1h for Hobby)
mcpbooleanfalseEnable MCP gateway support
onTimeout`'pause' \'kill'`'pause'Action on sandbox timeout
autoResumebooleanfalseAuto-resume paused sandbox (requires onTimeout: 'pause')
cpuCountnumber2Number of CPU cores
memoryMBnumber512Memory in MiB (must be even)
allowInternetAccessbooleantrueEnable/disable internet access
network`boolean \SandboxNetworkOpts`trueNetwork configuration
volumeMountsArray<{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:

FieldTypeDescription
sandboxIdstringUnique sandbox identifier
sandboxDomainstringDomain name for the sandbox
envdVersionstringVersion of envd running in sandbox
envdAccessTokenstringToken for envd API authentication
trafficAccessTokenstringToken for traffic authentication
templateIdstringID of the template used
namestringSandbox alias/name
startedAtDateSandbox start time
endAtDateSandbox expiration date
state`'running' \'paused'`Current sandbox state
cpuCountnumberNumber of CPUs allocated
memoryMBnumberMemory allocated in MiB
metadataRecord<string, string>Custom metadata
allowInternetAccessbooleanInternet access setting
lifecycleSandboxInfoLifecycleLifecycle configuration
volumeMountsArray<{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 terminated

Sandbox Instances

JavaScript SDK Instance

The Sandbox class provides the following APIs:

APIDescription
sandbox.filesystemFile system operations (upload, download, list, etc.)
sandbox.commandsExecute shell commands
sandbox.ptyTerminal/PTY access
sandbox.gitGit 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:

MetricTypeDescription
timestampDateTimestamp of metrics
cpuUsedPctnumberCPU usage percentage
cpuCountnumberNumber of CPU cores
memUsednumberMemory used in bytes
memTotalnumberTotal memory in bytes
diskUsednumberUsed disk space in bytes
diskTotalnumberTotal 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:

FieldLabel
sandboxIdSandbox ID
templateIdTemplate ID
nameAlias
startedAtStarted at
endAtEnd at
stateState
cpuCountvCPUs
memoryMBRAM MiB
envdVersionEnvd version
allowInternetAccessInternet access
lifecycleLifecycle
networkNetwork
sandboxDomainSandbox domain
metadataMetadata

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 TierMaximum Timeout
Pro24 hours (86,400,000 ms)
Hobby1 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

  1. Always clean up resources: Use context managers or explicitly call kill() to terminate sandboxes when done.
  1. Set appropriate timeouts: Match the timeout to your workload. Shorter timeouts are more cost-effective for quick tasks.
  1. Use metadata for tracking: Add meaningful metadata to easily identify sandboxes in listings.
  1. Handle errors gracefully: Catch exceptions for sandbox creation and command execution.
  1. Use pause lifecycle for interactive sessions: When you need to resume work later, use onTimeout: 'pause' with autoResume: true.
  1. 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Key Capabilities

Continue reading this section for the full explanation and source context.

Section Package Configuration

Continue reading this section for the full explanation and source context.

Section Core Components

Continue reading this section for the full explanation and source context.

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

ComponentFile LocationPurpose
Entry Pointsrc/index.tsExports all public APIs
Sandbox Managersrc/sandbox/index.tsManages sandbox lifecycle
Connection Configsrc/connectionConfig.tsHandles API configuration and authentication
Error Handlingsrc/errors.tsDefines SDK-specific error types
Filesystemsrc/sandbox/filesystem/index.tsFile operations within sandboxes
Commandssrc/sandbox/commands/index.tsExecute commands in sandboxes
Networksrc/sandbox/network.tsNetwork configuration and proxies
Volumesrc/volume/index.tsPersistent 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

ParameterTypeDescription
templatestringTemplate ID to use for the sandbox
timeoutnumberTimeout in milliseconds
metadataRecord<string, string>Custom metadata for filtering
aliasesstring[]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

MethodDescription
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

OptionTypeDescription
timeoutnumberCommand timeout in milliseconds
envVarsRecord<string, string>Environment variables
userstringUser 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

OptionTypeDefaultDescription
networkbooleantrueEnable/disable network access
dnsstring[]System DNSCustom 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

MethodDescription
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 TypeDescription
AuthenticationErrorInvalid or missing API key
TimeoutErrorOperation exceeded timeout
SandboxErrorSandbox creation or operation failure
RateLimitErrorAPI rate limit exceeded
ValidationErrorInvalid 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

OptionTypeDescription
apiKeystringE2B API key
baseUrlstringCustom API base URL
timeoutnumberDefault request timeout
headersRecord<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

PlatformFormatTarget
Node.jsCommonJSnode18
BrowserESMes2017

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:

PackageVersionPurpose
@connectrpc/connect2.0.0-rc.3RPC communication
@connectrpc/connect-web2.0.0-rc.3Web RPC transport
openapi-fetch0.14.1REST API client
platform1.3.6Runtime detection
chalk5.3.0Terminal styling
tar7.5.11Archive 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

For more information, refer to:

Sources: packages/js-sdk/tsup.config.js

Python SDK

Related topics: JavaScript/TypeScript SDK, CLI Tool, Sandbox Usage

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Install the SDK

Continue reading this section for the full explanation and source context.

Section Configure API Credentials

Continue reading this section for the full explanation and source context.

Section Quick Start Example

Continue reading this section for the full explanation and source context.

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

ModulePurpose
e2b.sandboxCore sandbox functionality
e2b.sandbox_asyncAsync sandbox implementation
e2b.sandbox_syncSynchronous sandbox implementation
e2b.templateTemplate builder functionality
e2b.envdEnvironment daemon API
e2b.apiHTTP API client layer
e2b.exceptionsCustom 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

MethodDescription
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.filesystemAccess 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.

FeatureSync APIAsync API
Importfrom e2b import Sandboxfrom e2b.sandbox_async import Sandbox
I/O ModelBlockingNon-blocking
Use CaseScripts, CLI toolsWeb servers, async frameworks
Connectione2b.sandbox_sync.sandbox_apie2b.sandbox_async.sandbox_api

Sources: e2b/sandbox_sync/main.pye2b/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

MethodBase 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

MethodDescription
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

ParameterTypeDefaultDescription
api_keystrE2B_API_KEY envAPI authentication key
access_tokenstrE2B_ACCESS_TOKEN envAlternative auth token
base_urlstrE2B APICustom API endpoint
timeoutint60Request 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

PropertyTypeDescription
stdoutstrStandard output
stderrstrStandard error
exit_codeintProcess exit code
stdout_linesList[str]Output as line array

Error Handling

The SDK defines custom exception types for different error scenarios.

Exception Types

ExceptionDescription
SandboxExceptionBase exception for sandbox errors
AuthenticationExceptionAPI key/authentication failures
TimeoutExceptionOperation timeout exceeded
NotFoundExceptionResource not found
RateLimitExceptionAPI 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

Sources: e2b/api/metadata.py

CLI Tool

Related topics: JavaScript/TypeScript SDK, Python SDK, Template System

Section Related Pages

Continue reading this section for the full explanation and source context.

Section System Requirements

Continue reading this section for the full explanation and source context.

Section Installation Methods

Continue reading this section for the full explanation and source context.

Section Interactive Login

Continue reading this section for the full explanation and source context.

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

RequirementVersion/Details
Node.jsv14.0.0 or higher
npmv6.0.0 or higher
Operating SystemmacOS, 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

FlagDescriptionExample
--help, -hDisplay help informatione2b --help
--version, -vDisplay CLI versione2b --version
--debugEnable debug outpute2b --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:

OptionDescriptionDefault
--alias, -aTemplate alias/nameRequired
--tagAdditional tags for the buildNone
--file, -fPath to Dockerfile./Dockerfile
--timeoutBuild timeout in seconds600

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

CommandDescription
e2b sandbox startStart a new sandbox instance
e2b sandbox stopStop a running sandbox
e2b sandbox listList all running sandboxes
e2b sandbox logsView 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

VariableDescriptionRequired
E2B_ACCESS_TOKENCLI authentication tokenYes (non-interactive)
E2B_API_KEYAPI key for SDK operationsFor 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 --> G

Template 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

IssueSolution
Authentication failedEnsure E2B_ACCESS_TOKEN is valid and not expired
Build timeoutIncrease timeout with --timeout flag or optimize Dockerfile
Dockerfile not foundVerify the file exists or specify path with --file flag
Permission deniedEnsure 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Lifecycle Configuration

Continue reading this section for the full explanation and source context.

Section JavaScript SDK

Continue reading this section for the full explanation and source context.

Section Python SDK

Continue reading this section for the full explanation and source context.

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:

LayerDescriptionComponents
Client SDKHigh-level language bindingsJavaScript SDK, Python SDK
API GatewayREST API for sandbox operationsTemplate management, sandbox lifecycle
InfrastructureContainer orchestrationDocker 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"
}
ParameterTypeDefaultDescription
on_timeoutstr"kill"Action when sandbox timeout is reached
auto_resumeboolFalseWhether 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 base or mcp-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

OptionTypeRequiredDefaultDescription
templatestringNo"base"Sandbox template name or ID
timeoutMsnumberNoVaries by planMaximum sandbox lifetime in milliseconds
metadataRecord<string, string>No{}Custom metadata for the sandbox
envsRecord<string, string>No{}Environment variables
mcpMCPConfigNo-MCP server configuration
networkbooleanNotrueNetwork isolation setting
allowInternetAccessbooleanNotrueInternet 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:

FlagDefaultDescription
--cpu-count2Number of vCPUs
--memory-mb512RAM 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"
)
FieldTypeDescription
sandbox_idstringUnique sandbox identifier
sandbox_domainstring or nullPublic domain for the sandbox
envd_versionstringVersion of the envd agent
envd_access_tokenstring or nullToken for envd authentication
traffic_access_tokenstring or nullToken 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:

FieldLabelDescription
sandboxIdSandbox IDUnique identifier
templateIdTemplate IDTemplate used
nameAliasUser-assigned name
stateStateCurrent sandbox state
startedAtStarted atCreation timestamp
endAtEnd atScheduled termination
cpuCountvCPUsCPU allocation
memoryMBRAM MiBMemory allocation
envdVersionEnvd versionAgent version
allowInternetAccessInternet accessNetwork setting
lifecycleLifecycleTimeout behavior
networkNetworkNetwork configuration
sandboxDomainSandbox domainPublic endpoint
metadataMetadataCustom 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:

OptionShortDescription
--path <path>-pTemplate directory path
--dockerfile <filename>-dCustom Dockerfile name
--cmd <start-command>-cCommand 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| D

See Also

Sources: packages/js-sdk/src/sandbox/sandboxApi.ts:1-50

Template System

Related topics: CLI Tool

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Package Structure

Continue reading this section for the full explanation and source context.

Section JavaScript SDK Usage

Continue reading this section for the full explanation and source context.

Section Python SDK Usage

Continue reading this section for the full explanation and source context.

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 --> Sandbox

Package Structure

PackageLanguagePurpose
packages/js-sdkTypeScriptJS/TS SDK with Template support
packages/python-sdkPythonPython SDK with Template support
packages/cliTypeScriptCommand-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

MethodImageDefault 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 imageRequired
// 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

TypeDockerfile EquivalentDescription
RUNRUNExecute shell commands
COPYCOPYCopy files into sandbox
ENVENVSet environment variables
WORKDIRWORKDIRSet working directory
USERUSERSet 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

FunctionUse CaseImplementation
waitForPort(port)Service listening on portnc -z localhost {port}
waitForURL(url, statusCode)HTTP endpoint availabilitycurl with status check
waitForProcess(name)Daemon process runningpgrep {name}
waitForFile(path)File exists in filesystemtest -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 deployed

Build 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:

  1. Validates the template specification
  2. Initiates Docker build with caching
  3. Monitors build status until completion
  4. Pushes the resulting image to the registry

Sources: packages/js-sdk/src/template/index.ts:250-350

Build Options

OptionTypeDescription
aliasstringTemplate alias (deprecated)
tagsstring[]Additional image tags
timeoutMsnumberBuild timeout in milliseconds
metadataRecord<string, string>Custom metadata

CLI Integration

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

Available Commands

CommandDescription
e2b template createCreate a new template from Dockerfile
e2b template buildBuild and deploy a template
e2b template publishPublish 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:

  1. Uploads local template files
  2. Initiates template creation
  3. Polls for completion
  4. 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

Sources: packages/js-sdk/src/template/index.ts:1-50

Filesystem and Git Operations

Related topics: Sandbox Usage

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Components

Continue reading this section for the full explanation and source context.

Section Reading Files

Continue reading this section for the full explanation and source context.

Section Writing Files

Continue reading this section for the full explanation and source context.

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

FormatReturn TypeDescription
textstringFile content as plain text (default)
bytesUint8Array / bytesRaw binary content
blobBlobWeb API Blob object
streamReadableStream<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

ParameterTypeDefaultDescription
format`'text' \'bytes' \'blob' \'stream'`'text'Output format
gzipbooleanfalseRequest gzip-compressed response
userstringundefinedRun as specific user
signalAbortSignalundefinedCancellation signal
requestTimeoutMsnumberundefinedRequest 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

ParameterTypeDefaultDescription
filesWriteEntry[]RequiredList of files to write
userstringundefinedRun as specific user
gzipbooleanfalseUse gzip compression
use_octet_streambooleanfalseUse octet-stream upload (requires envd 0.5.7+)
request_timeoutnumberundefinedRequest timeout

#### WriteEntry Structure

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

#### Upload Methods

The SDK supports two upload methods:

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

When use_octet_stream is enabled and the envd version supports it, the upload uses application/octet-stream content type. Otherwise, it gracefully falls back to multipart form data. 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

FieldTypeDescription
namestringName of the filesystem object
typeFileTypeType of object (file, directory, symlink)
pathstringFull path to the object

#### EntryInfo (for directory listings)

FieldTypeDescription
sizenumberSize in bytes
modenumberFile mode and permission bits
permissionsstringString representation (e.g., 'rwxr-xr-x')
ownerstringOwner username
groupstringGroup owner
modifiedTimeDateLast modification time
symlinkTargetstringTarget 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:

MethodDescriptionUse Case
SSH KeyUse predefined SSH key stored in E2BPrivate repository access
TokenPersonal Access Token or GitHub TokenCI/CD scenarios
Username/PasswordBasic authenticationLegacy 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

ParameterTypeRequiredDescription
urlstringYesRepository URL
pathstringNoDestination path (defaults to repo name)
branchstringNoSpecific branch to clone
depthnumberNoClone depth for shallow clone
recursiveboolNoClone 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

ModulePurpose
e2b/sandbox/_git/__init__.pyCore git operations and command building
e2b/sandbox/_git/args.pyArgument construction for git commands
e2b/sandbox/_git/auth.pyAuthentication 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 TypeCondition
FileNotFoundErrorFile or directory does not exist
NotFoundErrorVolume path not found
SandboxErrorGeneral sandbox communication error
CommandExitErrorCommand 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

FeatureMinimum envd Version
Basic filesystem read/write0.1.0
Default user handlingAutomatic fallback for older versions
Octet-stream upload0.5.7
Gzip compressionAll 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

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

Summary

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

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

Source: https://github.com/e2b-dev/E2B / Human Manual

Network Configuration

Related topics: Sandbox Usage, Sandbox Management

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Data Flow

Continue reading this section for the full explanation and source context.

Section NetworkConfig Interface

Continue reading this section for the full explanation and source context.

Section Usage Example

Continue reading this section for the full explanation and source context.

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:

PropertyTypeDescription
customServersstring[]List of custom DNS server IPs
blockAutoDetectbooleanWhether to block auto-detected DNS

Sources: packages/js-sdk/src/sandbox/network.ts:10-30

#### Port Configuration

Manages inbound and outbound port access:

PropertyTypeDescription
portnumberThe port number to configure
protocol`'tcp' \'udp'`Network protocol
access`'allow' \'deny'`Access rule for the port
descriptionstringOptional description

Sources: packages/js-sdk/src/sandbox/network.ts:35-45

#### VPN Configuration

Provides VPN tunnel support:

PropertyTypeDescription
enabledbooleanEnable/disable VPN tunnel
configVPNConfigVPN 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
ParameterTypeDefaultDescription
custom_serversList[str]NoneCustom DNS server IPs
block_auto_detectboolFalseBlock 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
ParameterTypeRequiredDescription
portintYesPort number
protocolstrYesNetwork protocol
accessstrYesAccess rule
descriptionstrNoRule 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:

SettingDefault Value
DNSAuto-detected system DNS
PortsAll ports allowed
VPNDisabled

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

  1. Explicit Port Rules: Always explicitly define port access rules rather than relying on defaults for production workloads.
  1. DNS Configuration: Use specific DNS servers when you need consistent resolution behavior across sandbox instances.
  1. VPN for Sensitive Workloads: Enable VPN when handling sensitive data that requires encrypted tunnel communication.
  1. Protocol Specificity: Specify both port and protocol to avoid unintended access.

Sources: packages/js-sdk/src/sandbox/network.ts:1-50

Doramagic Pitfall Log

Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.

high process was not killed when auto paused

Users may get misleading failures or incomplete behavior unless configuration is checked carefully.

medium Closed Port Error

First-time setup may fail or require extra isolation and rollback planning.

medium Please add skills to use with any ai agent to use e2b in our project

First-time setup may fail or require extra isolation and rollback planning.

medium [Bug]: Incorrect info about webhooks in docs and dashboard

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 of python collect_env.py here ` </details> ### 🐛 Describe the bug run ` vllm serve google/gemma-3n-E2B-it -tp 1 `` on torch==2.8.0:…
  • 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.

Sources 12

Count of project-level external discussion links exposed on this manual page.

Use Review before install

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.

Source: Project Pack community evidence and pitfall evidence