# E2B SDK Compatibility Migration Path for CubeSandbox: Seamless Integration Guide

> Leverage CubeSandbox's E2B SDK compatibility. Seamlessly migrate using environment variables and an adapter pattern without code changes. Integrate effortlessly.

- Repository: [Tencent Cloud/CubeSandbox](https://github.com/TencentCloud/CubeSandbox)
- Tags: migration-guide
- Published: 2026-07-16

---

**CubeSandbox provides a built-in compatibility layer that lets the E2B Python SDK operate against a CubeSandbox control-plane without code changes by using environment variables and an adapter pattern.**

TencentCloud/CubeSandbox offers a zero-code migration path for teams currently using the E2B Python SDK (`e2b-code-interpreter` or `e2b`). By implementing a compatibility adapter, CubeSandbox intercepts E2B SDK calls and translates them to CubeSandbox-compatible RPCs, allowing existing codebases to run against a self-hosted CubeSandbox deployment simply by updating configuration variables.

## How the E2B SDK Compatibility Layer Works

The migration relies on three core translation layers that normalize the interface between the E2B SDK and the CubeSandbox control-plane.

### Adapter Pattern Implementation

The `E2BAdapter` class in [`tests/e2e/sdk_compat/adapters/e2b_adapter.py`](https://github.com/TencentCloud/CubeSandbox/blob/main/tests/e2e/sdk_compat/adapters/e2b_adapter.py) implements the `SandboxAdapter` interface required by the unified test suite. This adapter acts as a bridge, selecting the E2B backend via the `SDK_E2E_BACKENDS` environment variable and translating E2B-style calls into CubeSandbox-compatible RPCs.

```python

# The adapter is selected via environment variable

export SDK_E2E_BACKENDS=e2b

```

The adapter handles lazy imports of the `e2b` or `e2b_code_interpreter` packages, ensuring that your existing code continues to import from the expected namespaces while the underlying implementation routes to CubeSandbox.

### Parameter Mapping and API Key Propagation

E2B expects specific parameters such as `envs` and a custom API-key header (`e2b-traffic-access-token`). The `E2BAdapter.create` method maps the generic `env_vars` option to `envs` and merges extra metadata through the `_e2b_api_params` helper function.

The adapter reads configuration from `SdkE2EConfig` environment variables including `CUBE_API_URL`, `E2B_API_KEY`, and `SDK_E2E_E2B_VALIDATE_API_KEY`, then injects these into the SDK initialization.

```python

# Configuration is read from environment variables

export E2B_API_KEY=<your-key>
export CUBE_API_URL=https://<your-cubesandbox>/v1
export SDK_E2E_E2B_VALIDATE_API_KEY=true

```

### Result Normalisation

E2B returns data in **snake_case** and sometimes as dataclasses, while CubeSandbox uses a canonical format. The adapter normalizes responses through several dedicated functions:

- **`_sandbox_info_to_raw`** – Converts `SandboxInfo` objects or dicts into a flat map, preserving both original snake_case keys and CubeSandbox-style camelCase aliases.
- **`_sandbox_entry_to_dict`** – Normalizes list entries from the SDK.
- **`_normalize_info_value`** and **`_accepts_keyword`** – Ensure compatibility across older and newer SDK versions by handling type variations gracefully.

## Step-by-Step Migration Path

Follow these five steps to migrate your E2B SDK implementation to CubeSandbox:

1. **Install the E2B SDK** – Install the required dependencies from the compatibility test requirements: `pip install -r tests/e2e/sdk_compat/requirements.txt`. The adapter lazily imports `e2b` or `e2b_code_interpreter` as needed.

2. **Export required environment variables** – Set your authentication and endpoint details:
   ```bash
   export E2B_API_KEY=<your-key>
   export CUBE_API_URL=https://<your-cubesandbox>/v1
   ```

3. **Choose the backend** – Set the `SDK_E2E_BACKENDS` variable to `e2b` (or `e2b,cubesandbox` for dual testing). The test framework automatically selects `E2BAdapter` when this variable is configured.

4. **Run existing E2B code unchanged** – Execute your existing scripts. All SDK calls (`sandbox.run`, `sandbox.files.write`, `sandbox.run_code`, etc.) are intercepted by the adapter and forwarded to CubeSandbox's control-plane.

5. **Optional: Dual-backend validation** – Run the suite with both backends (`SDK_E2E_BACKENDS=e2b,cubesandbox`) to verify parity. The adapter provides fallback mechanisms for parsing responses when switching between environments.

## Key Migration Considerations

When migrating from the native E2B SDK to CubeSandbox, account for these specific implementation details:

- **API Key validation** – The adapter validates the API key only when `SDK_E2E_E2B_VALIDATE_API_KEY=true`. By default, it passes the raw string to preserve backward compatibility with existing E2B implementations.

- **Per-host network rules** – E2B's `network.rules` dictionary shape is supported via `convertE2BPerHostRules` in [`sdk/python/cubesandbox/_policy.py`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/python/cubesandbox/_policy.py). This function expands the dictionary into CubeSandbox's list-based rule format, ensuring network policies translate correctly.

- **Error handling compatibility** – E2B raises `CommandExitException` on non-zero exits. The adapter catches this exception (imported lazily to avoid hard dependencies) and converts it into a standard `CommandResult` object containing `exit_code`, `stdout`, and `stderr`.

## Code Examples

### Creating a Sandbox

The following example demonstrates creating a sandbox using the E2B SDK pattern, which the adapter transparently routes to CubeSandbox:

```python
from e2b import Sandbox
from tests.e2e.sdk_compat.framework.config import SdkE2EConfig

cfg = SdkE2EConfig.from_env()  # Reads CUBE_API_URL, E2B_API_KEY, etc.

sandbox = Sandbox.create(
    template=cfg.cube_template_id,
    envs={"MY_VAR": "value"},  # 'env_vars' is automatically mapped to 'envs'

    metadata={"example": "demo"},
    timeout=cfg.create_timeout,
)

```

### Running Commands and File Operations

Existing E2B patterns for command execution and file manipulation work without modification:

```python

# Run a command

result = sandbox.commands.run(
    "python - <<'PY'\nprint('hello')\nPY", 
    user="root"
)
print(result.stdout)  # -> "hello\n"

# File operations

sandbox.files.write("/tmp/hello.txt", "CubeSandbox ↔ E2B")
content = sandbox.files.read("/tmp/hello.txt")
print(content)  # -> "CubeSandbox ↔ E2B"

```

### Converting Network Rules

For applications using E2B-style network security rules, use the conversion helper:

```python
from cubesandbox import _policy

# E2B-style per-host rules

rules = {
    "example.com": [
        {"type": "http", "action": "allow"},
        {"type": "tcp", "port": 443, "action": "allow"},
    ]
}

# Convert to CubeSandbox format

cube_rules = _policy.convertE2BPerHostRules(rules)

# cube_rules is now a list of Inject objects compatible with CubeSandbox

```

## Core Implementation Files

Understanding these source files helps troubleshoot migration issues:

- **[`tests/e2e/sdk_compat/adapters/e2b_adapter.py`](https://github.com/TencentCloud/CubeSandbox/blob/main/tests/e2e/sdk_compat/adapters/e2b_adapter.py)** – Contains the core `E2BAdapter` class that handles ID extraction, info normalization, and error mapping between SDKs.

- **[`sdk/python/cubesandbox/_policy.py`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/python/cubesandbox/_policy.py)** – Implements `convertE2BPerHostRules` and other compatibility helpers for network rule conversion.

- **[`sdk/python/cubesandbox/_models.py`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/python/cubesandbox/_models.py)** – Provides backward-compatible aliases for fields (`json`, `line`, `error`) used by the E2B SDK.

- **[`tests/e2e/sdk_compat/README.md`](https://github.com/TencentCloud/CubeSandbox/blob/main/tests/e2e/sdk_compat/README.md)** – Documents the compatibility test suite execution, including environment variable setup and dual-backend testing procedures.

- **[`sdk/python/cubesandbox/sandbox.py`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/python/cubesandbox/sandbox.py)** – Exposes high-level CubeSandbox SDK methods (`run`, `run_code`, `files`, etc.) that align with E2B SDK expectations.

## Summary

- CubeSandbox provides an **E2BAdapter** in [`tests/e2e/sdk_compat/adapters/e2b_adapter.py`](https://github.com/TencentCloud/CubeSandbox/blob/main/tests/e2e/sdk_compat/adapters/e2b_adapter.py) that translates E2B SDK calls to CubeSandbox RPCs without requiring code changes.
- Migration requires only environment variable configuration (`E2B_API_KEY`, `CUBE_API_URL`, `SDK_E2E_BACKENDS`) rather than source code modifications.
- The adapter handles **parameter mapping** (converting `env_vars` to `envs`), **result normalisation** (snake_case to camelCase), and **error translation** (`CommandExitException` to `CommandResult`).
- Network rules from E2B convert to CubeSandbox format via `convertE2BPerHostRules` in [`sdk/python/cubesandbox/_policy.py`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/python/cubesandbox/_policy.py).
- Dual-backend testing is supported by setting `SDK_E2E_BACKENDS=e2b,cubesandbox` to verify parity between environments.

## Frequently Asked Questions

### Do I need to modify my existing E2B code to use CubeSandbox?

No. The migration path is designed for zero-code changes. You only need to install the E2B SDK, export the required environment variables (`E2B_API_KEY`, `CUBE_API_URL`), and set `SDK_E2E_BACKENDS=e2b`. The `E2BAdapter` intercepts all SDK calls and routes them to your CubeSandbox control-plane.

### How does CubeSandbox handle E2B's network security rules?

CubeSandbox supports E2B's dictionary-based `network.rules` format through the `convertE2BPerHostRules` function in [`sdk/python/cubesandbox/_policy.py`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/python/cubesandbox/_policy.py). This helper expands per-host rule dictionaries into CubeSandbox's list-based `Inject` object format, preserving your security policies during migration.

### What happens to E2B-specific exceptions when using CubeSandbox?

The `E2BAdapter` catches `CommandExitException` (the E2B error class) and converts it into a standardized `CommandResult` object containing `exit_code`, `stdout`, and `stderr`. This ensures your error handling logic continues to function while supporting CubeSandbox's response format.

### Can I test against both E2B and CubeSandbox simultaneously?

Yes. Set `SDK_E2E_BACKENDS=e2b,cubesandbox` to enable dual-backend testing. The test framework will execute your code against both platforms, allowing you to verify behavioral parity before fully committing to the CubeSandbox migration.