All Products
Search
Document Center

Agent Run:Upgrade AgentRun Sandbox to FC Cloud Sandbox

Last Updated:Aug 24, 2026

Background

With the thriving growth of the AI Agent ecosystem, Alibaba Cloud has launched a brand-new professional sandbox product: FC Cloud Sandbox. As a secure and trusted code execution environment built for AI Agent scenarios, FC Cloud Sandbox delivers significant advances in development experience, product features, and cost structure, and is dedicated to providing you with an industry-leading, more developer-friendly sandbox service. You are welcome to upgrade from AgentRun Sandbox to FC Cloud Sandbox.

FC Cloud Sandbox brings you the following value:

  • Embrace industry standards and connect to a broader ecosystem

    • Nearly 100% compatible with the native E2B SDK, enabling seamless access to the rich open-source Agent ecosystem and community best practices.

  • Richer product capabilities that unlock more advanced scenarios

    • On top of basic code execution, FC Cloud Sandbox newly provides Pause/Resume, Snapshots, DinD (Docker in Docker), OSWorld, and many other advanced features, covering more complex and diverse AI Agent application scenarios.

  • Substantially optimized cost structure, with overall costs reduced by more than 50%

    • Backed by resource scheduling optimizations and economies of scale in the underlying Function Compute architecture, FC Cloud Sandbox achieves substantial pricing optimization. Prices for vCPU, memory, and disk are all reduced to varying degrees, bringing overall costs down by 50% to 70%.

Upgrade Value Overview

Dimension

AgentRun Sandbox

FC Cloud Sandbox

Upgrade Benefits

Cost

High

Low (50%–70% reduction)

Significant cost reduction at equivalent usage levels

Feature Set

Basic sandbox capabilities

Advanced capabilities: 1:N Fork, DinD, OSWorld, etc.

Unlock advanced scenario capabilities

SDK

AgentRun SDK

E2B SDK (industry standard)

Integrate with mainstream Agent ecosystems, reducing integration costs

Ecosystem Compatibility

Proprietary SDK

E2B protocol compatible

Compatible with open-source community tools and frameworks

Iteration Pace

Basic capabilities

Continuous evolution

Continuously receive new features and optimizations after upgrade

Product Capability Comparison

Core Features

Feature

AgentRun Sandbox

FC Cloud Sandbox

Sandbox Lifecycle Management

Create, Delete

Create, Delete, Pause, Resume, etc.

Sandbox Templates

  • Built-in official templates (Code Interpreter / Browser / AIO, etc.)

  • Custom templates

  • Built-in official templates (Code Interpreter / Browser / AIO, etc.)

  • Custom templates

API Key

Supported

Supported

Port Exposure & HTTP Services

No port exposure / public access methods; only internal sandbox access allowed

Use get_host(port) to obtain the external mapping address for port exposure, enabling external access to HTTP services

Custom Domain

Supported

Supported

Monitoring

Only basic metrics: CPU, memory, network, etc.

Global overview (total sandbox instances, running/paused/terminated sandbox counts, startup rate, creation success rate, etc.) plus full-dimension monitoring of resource lifecycle and performance

Light/Deep Sleep

Not supported

Supported

1:N Fork

Not supported

Supported

DinD (Docker-in-Docker)

Not supported

Supported

OSWorld

Not supported

Supported

Cost Advantages

FC Cloud Sandbox offers significant pricing optimizations compared to AgentRun Sandbox, primarily reflected in the following areas:

Billing Dimension

Cost Change

Description

vCPU Costs

~70%–85% reduction

Percentage varies by subscription plan

Memory Costs

~0%–50% reduction

Percentage varies by subscription plan

Storage Costs

~89% reduction

  • Free quota increased from 10GB to 15GB

  • List price reduced from ¥0.0198/GB/hour to ¥0.0021/GB/hour

Total Cost of Ownership (e.g., 2C4G)

~50%–70% reduction

Comprehensive reduction across all dimensions; total costs significantly lower in typical customer scenarios

SDK Upgrade Guide

This is the most critical part of the upgrade process. AgentRun Sandbox uses the AgentRun SDK, while FC Cloud Sandbox uses the E2B SDK. E2B is a widely adopted open-source sandbox SDK in the industry. After upgrading to the E2B SDK, customers can seamlessly integrate with a broader range of Agent frameworks and the open-source ecosystem.

Core Concept Mapping

The AgentRun SDK and AgentRun Sandbox follow a two-stage Template + Sandbox approach: first create a template, then launch sandboxes from the template; code execution goes through the Context object; file operations have two sets of APIs—"read/write within the sandbox" and "local ↔ sandbox transfer." The correspondence after upgrade is as follows:

AgentRun SDK Concept

E2B SDK Concept

Description

Sandbox.create_template(...)

Template.build(Template().from_image(...)); or use the default template directly

FC E2B currently supports only building from an existing image or using the default template; layer-by-layer pip_install/apt_install builds are not supported

Sandbox.create(template_type=, ...)

Sandbox.create(template=..., timeout=...)

Create a sandbox instance. Note: E2B's Sandbox(...) constructor is only for connecting to existing sandboxes; creation must use Sandbox.create()

Sandbox.connect(sandbox_id=)

Sandbox.connect(sandbox_id)

Connect to an existing sandbox

sandbox.context.execute(code=)

sandbox.run_code(code)

Execute code. AgentRun uses Context to maintain cross-round state; E2B uses Jupyter Kernel

sandbox.process.cmd(command=, cwd=, timeout=)

sandbox.commands.run(command, cwd=, timeout=)

Execute shell commands. AgentRun requires cwd; E2B makes it optional and supports background=True

sandbox.file.write(path=, content=)

sandbox.files.write(path, content)

Write files within the sandbox

sandbox.file.read(path=)

sandbox.files.read(path)

Read files within the sandbox

sandbox.file_system.upload(local_file_path=, target_file_path=)

sandbox.files.write(path, open(local,'rb').read())

Upload files from local to sandbox

sandbox.file_system.download(path=, save_path=)

content = sandbox.files.read(path) then write locally

Download files from sandbox to local

sandbox.check_health()

sandbox.is_running()

Health/liveness check

sandbox.stop()

sandbox.pause() + Sandbox.connect(sandbox_id) to resume

Pause/resume. Micro-spec templates may not support pause; default specs (e.g., base) work

sandbox.delete() / Sandbox.delete_by_id(id)

sandbox.kill()

Destroy sandbox instance

Code Interpreter sandbox has no port exposure / public access API

sandbox.get_host(port)

Upgrading to E2B adds port exposure capability

Note

Regarding the two E2B Python packages: e2b (base package) provides sandbox creation, shell command execution, file operations, and port exposure; e2b-code-interpreter builds on top of it and adds run_code() (Jupyter Kernel with stateful multi-turn execution). Use e2b-code-interpreter when you need to execute code snippets; use e2b when you only need shell commands or file operations.

Python SDK Upgrade Examples

Creating a Sandbox

AgentRun SDK (Before Upgrade): AgentRun follows a two-stage "first build template, then launch sandbox" approach, using sandbox_idle_timeout_seconds to control idle reclamation when launching sandboxes.

from agentrun.sandbox import Sandbox, TemplateInput, TemplateType

# Step 1: Create a template (reusable, for batch-launching sandboxes with the same configuration)
template_name = "my-code-template"
template = Sandbox.create_template(
    input=TemplateInput(
        template_name=template_name,
        template_type=TemplateType.CODE_INTERPRETER,
        # Optional: cpu=2.0, memory=4096, disk_size=10240,
    )
)

# Step 2: Create a sandbox from the template (recommended to use the with context manager)
with Sandbox.create(
    template_type=TemplateType.CODE_INTERPRETER,
    template_name=template_name,
    sandbox_idle_timeout_seconds=600,
) as sandbox:
    print(f"Sandbox ID: {sandbox.sandbox_id}")
# Sandbox is automatically deleted when exiting the with block

# Or manage lifecycle manually
sandbox = Sandbox.create(
    template_type=TemplateType.CODE_INTERPRETER,
    template_name=template_name,
)
try:
    print(f"Sandbox ID: {sandbox.sandbox_id}")
finally:
    sandbox.delete()
# When the template is no longer needed: Sandbox.delete_template(template_name)

E2B SDK (After Upgrade): The simplest approach is to directly use the default template (e.g., base) to launch a sandbox; if custom environments are needed, FC E2B supports building templates from existing images (Template().from_image(...)).

from e2b import Sandbox

# Method 1 (Recommended): Directly use the default template to launch a sandbox without building a template
# Note: Creation must use Sandbox.create(...); the Sandbox(...) constructor is only for connecting to existing sandboxes
with Sandbox.create(
    template="base",  # FC E2B default template name (template can be omitted)
    timeout=300  # Timeout in seconds
) as sandbox:
    print(f"Sandbox ID: {sandbox.sandbox_id}")

# Or manage lifecycle manually
sandbox = Sandbox.create(template="base", timeout=300)
try:
    print(f"Sandbox ID: {sandbox.sandbox_id}")
finally:
    sandbox.kill()

If you need to pre-install dependencies/customize the environment, build a template from an existing image (FC E2B does not support layer-by-layer pip_install builds; please bake dependencies into the image):

from e2b import Sandbox, Template, default_build_logger

# Build a template from an existing image
build = Template.build(
    Template().from_image(
        "registry.cn-hangzhou.aliyuncs.com/your-namespace/your-image:tag",
        username="<registry-user>",
        password="<registry-pass>",
    ),
    name="my-python-template",
    cpu_count=2,
    memory_mb=2048,
    on_build_logs=default_build_logger(),
)

# Launch a sandbox using the built template
with Sandbox.create(template=build.template_id, timeout=300) as sandbox:
    print(f"Sandbox ID: {sandbox.sandbox_id}")
Important

AgentRun's create_template uses "select type (CODE_INTERPRETER/BROWSER/AIO) + fill in resource specs," with images built-in by the platform. E2B on FC uses "use the default template, or build a template from an already-built image"—it does not support layer-by-layer from_python_image().pip_install() builds; custom dependencies must be baked into the image first, then use from_image. For the Python synchronous SDK, it is strongly recommended to use the with context manager. When creating manually, use sandbox.delete() for AgentRun and sandbox.kill() for E2B.

Executing Code

AgentRun SDK (Before Upgrade): Code execution goes through sandbox.context. Direct execute is stateless single execution; use context.create() to get ctx for continuous execute, maintaining variables/imports across rounds.

from agentrun.sandbox import Sandbox, TemplateType
from agentrun.sandbox.model import CodeLanguage

sandbox = Sandbox.create(
    template_type=TemplateType.CODE_INTERPRETER,
    template_name="my-code-template",
)

# Method 1: Stateless single execution
result = sandbox.context.execute(code="import math\nprint(f'Pi = {math.pi:.4f}')")
print(result)

# Method 2: Stateful multi-round execution (variables, imports maintained across rounds)
with sandbox.context.create(language=CodeLanguage.PYTHON) as ctx:
    ctx.execute(code="import numpy as np")
    ctx.execute(code="arr = np.array([1, 2, 3])")
    result = ctx.execute(code="print(arr.sum())")
    print(result)

sandbox.delete()

E2B SDK (After Upgrade):

from e2b_code_interpreter import Sandbox

with Sandbox.create() as sandbox:
    execution = sandbox.run_code("import math\nprint(f'Pi = {math.pi:.4f}')")
    # Note: execution.logs.stdout is List[str] (line by line), use "".join(...) for the whole output
    print("".join(execution.logs.stdout))
    print(execution.results)  # Rich results of the last expression (charts/DataFrame, etc.)
Note

AgentRun requires explicit context.create() to maintain state; E2B's run_code maintains state by default based on Jupyter Kernel. Return structures differ: E2B's execution.logs.stdout / execution.logs.stderr are line-by-line List[str], and execution.results is a rich results list.

Executing Shell Commands

AgentRun SDK (Before Upgrade): Uses sandbox.process.cmd, where cwd is a required parameter.

from agentrun.sandbox import Sandbox, TemplateType

sandbox = Sandbox.create(
    template_type=TemplateType.CODE_INTERPRETER,
    template_name="my-code-template",
)

result = sandbox.process.cmd(
    command="ls -la /home",
    cwd="/home",     # Required
    timeout=30,
)
print(result["stdout"])
print(f"Exit code: {result['exitCode']}")

sandbox.delete()

E2B SDK (After Upgrade):

from e2b import Sandbox

with Sandbox.create() as sandbox:
    result = sandbox.commands.run(
        "ls -la /home",
        cwd="/home",   # Optional
        timeout=30,    # In seconds (the Python SDK uses timeout, not timeout_ms)
    )
    print(result.stdout)
    print(f"Exit code: {result.exit_code}")

    # Long-running background process (e.g., starting a service)
    proc = sandbox.commands.run("python3 -m http.server 8080", cwd="/tmp", background=True)
    print(f"pid: {proc.pid}")
Note

AgentRun requires cwd and has no background execution parameter; E2B makes cwd optional and supports background=True. Field naming differs: AgentRun uses result["exitCode"], E2B uses result.exit_code. Timeout units: the E2B Python SDK uses timeout (seconds), and the JS SDK uses timeoutMs (milliseconds).

File Operations

AgentRun SDK (Before Upgrade): Distinguishes two sets of APIs—sandbox.file for reading/writing file content within the sandbox; sandbox.file_system handles local ↔ sandbox upload/download and directory management.

from agentrun.sandbox import Sandbox, TemplateType

sandbox = Sandbox.create(
    template_type=TemplateType.CODE_INTERPRETER,
    template_name="my-code-template",
)

# Local → Sandbox: Upload file
sandbox.file_system.upload(
    local_file_path="./data.csv",
    target_file_path="/home/user/data.csv",
)

# Sandbox → Local: Download file
sandbox.file_system.download(
    path="/home/user/result.json",
    save_path="./result.json",
)

# Read/write file content within sandbox
sandbox.file.write(path="/tmp/note.txt", content="hello", create_dir=True)
content = sandbox.file.read(path="/tmp/note.txt")

# Directory operations
sandbox.file_system.mkdir(path="/tmp/mydir", parents=True)
sandbox.file_system.list(path="/tmp")
sandbox.file_system.move(source="/tmp/a.txt", destination="/tmp/b.txt")
sandbox.file_system.remove(path="/tmp/mydir")

sandbox.delete()

E2B SDK (After Upgrade): E2B uses a unified sandbox.files; local ↔ sandbox transfer is achieved by reading/writing bytes locally first.

from e2b import Sandbox

with Sandbox.create() as sandbox:
    # Local → Sandbox (equivalent to AgentRun file_system.upload)
    with open("./data.csv", "rb") as f:
        sandbox.files.write("/home/user/data.csv", f.read())
    
    # Sandbox → Local (equivalent to AgentRun file_system.download)
    # Pass format="bytes" to download binary content
    content = sandbox.files.read("/home/user/result.bin", format="bytes")
    with open("./result.bin", "wb") as f:
        f.write(content)
    
    # Read/write within sandbox (equivalent to AgentRun file.write / file.read)
    sandbox.files.write("/tmp/note.txt", "hello")
    text = sandbox.files.read("/tmp/note.txt")
    
    # Directory operations
    sandbox.files.make_dir("/tmp/mydir")
    sandbox.files.list("/tmp")
    sandbox.files.rename("/tmp/a.txt", "/tmp/b.txt")
    sandbox.files.remove("/tmp/mydir")

Port Exposure & HTTP Services

The AgentRun Code Interpreter sandbox SDK has no port exposure / public access methods. E2B uses get_host(port) to directly obtain the external mapping address of a port—this is a new capability added by the upgrade.

from e2b import Sandbox

with Sandbox.create() as sandbox:
    # Start HTTP service in the background
    sandbox.commands.run("cd /app && python -m http.server 8080", background=True)
    
    # Get externally accessible host
    host = sandbox.get_host(8080)
    print(f"Service address: https://{host}")

Pause & Resume

E2B uses sandbox.pause() to pause the sandbox and Sandbox.connect(sandbox_id) to resume; file/process states within the sandbox are preserved during pause. You can use lifecycle during creation to control "automatic pause after idle timeout + automatic resume on reconnection."

from e2b import Sandbox

# Declare during creation: automatically pause after idle timeout, automatically resume on reconnection
sandbox = Sandbox.create(
    template="base",
    timeout=300,
    lifecycle={"on_timeout": "pause", "auto_resume": True},
)

sandbox.files.write("/tmp/state.txt", "persist-me")
sandbox_id = sandbox.sandbox_id

# Explicitly pause
sandbox.pause()

# Later (can be in another process/machine), resume using sandbox_id; state is preserved
resumed = Sandbox.connect(sandbox_id)
assert resumed.files.read("/tmp/state.txt").strip() == "persist-me"
resumed.kill()

Specifying VPC (Accessing Internal Network Resources)

In FC E2B, VPC and other FC extension configurations are passed through the metadata parameter of Sandbox.create, using fc.sandbox.* convention keys (values as JSON strings).

import json
from e2b import Sandbox

vpc_config = {
    "vpcId": "vpc-xxxxxxxx",
    "securityGroupId": "sg-xxxxxxxx",
    "vSwitchIds": ["vsw-xxxxxxxx"],
}
metadata = {"fc.sandbox.network.vpc": json.dumps(vpc_config)}

with Sandbox.create(template="base", timeout=300, metadata=metadata) as sandbox:
    r = sandbox.commands.run(
        "python3 -c \"import socket; socket.create_connection(('nas-host', 2049), 5); print('ok')\""
    )
    print(r.stdout)

Mounting OSS

Pass OSS mount points through metadata and specify the trusted role (RAM Role ARN) using fc.sandbox.auth.role. After mounting, OSS directories appear as ordinary file system paths within the sandbox.

import json
from e2b import Sandbox

oss_config = {
    "mountPoints": [
        {
            "bucketName": "my-bucket",
            "mountDir": "/mnt/oss",
            "bucketPath": "/some/prefix",
            "endpoint": "oss-cn-hangzhou-internal.aliyuncs.com",
            "readOnly": False,
        }
    ]
}
metadata = {
    "fc.sandbox.storage.oss": json.dumps(oss_config),
    "fc.sandbox.auth.role": "acs:ram::<MainAccountID>:role/<RoleName>",
}

with Sandbox.create(template="base", timeout=300, metadata=metadata) as sandbox:
    files = sandbox.files.list("/mnt/oss")
    print(f"Number of OSS files: {len(files)}")
    sandbox.files.write("/mnt/oss/hello.txt", "written to oss\n")
Note

It is recommended to use an internal endpoint (*-internal.aliyuncs.com) to route through the internal network and avoid public network traffic fees. Mounting OSS requires the RAM role specified by fc.sandbox.auth.role to have read/write permissions on the corresponding bucket.

JavaScript / TypeScript SDK Upgrade Examples

Creating Sandboxes & Executing Code

AgentRun SDK (Before Upgrade): Also follows a "template → sandbox" two-stage approach and requires explicit waitUntilReadyOrFailed(); code execution goes through sandbox.context.create() + ctx.execute().

import { CodeInterpreterSandbox, Template, TemplateType, CodeLanguage } from '@agentrun/sdk';

// Step 1: Build template and wait until ready
const templateName = 'my-code-template';
const template = await Template.create({
    input: {
        templateName,
        templateType: TemplateType.CODE_INTERPRETER,
        sandboxIdleTimeoutInSeconds: 600,
    },
});
await template.waitUntilReadyOrFailed();

// Step 2: Launch sandbox from template and wait until running/healthy
const sandbox = await CodeInterpreterSandbox.createFromTemplate(templateName);
await sandbox.waitUntilRunning();
await sandbox.waitUntilReadyOrFailed();

// Execute code (through context)
const ctx = await sandbox.context.create({ language: CodeLanguage.PYTHON });
const result = await ctx.execute({
    code: "arr = [1,2,3,4,5]\nprint('Sum:', sum(arr))",
});
console.log(result);

await ctx.delete();
await sandbox.delete();
await template.delete();

E2B SDK (After Upgrade): E2B's JS SDK does not have run_code (Jupyter Kernel is Python-only), so it is recommended to write scripts first and then execute with commands.run.

import { Sandbox } from 'e2b';
import 'dotenv/config';

const sandbox = await Sandbox.create({
    template: 'default',
    timeoutMs: 300_000,  // Note: the E2B JS SDK uses milliseconds
});

try {
    await sandbox.files.write('/tmp/calc.js', `
        const arr = [1, 2, 3, 4, 5];
        console.log('Sum:', arr.reduce((a, b) => a + b, 0));
    `);
    const result = await sandbox.commands.run('node /tmp/calc.js');
    console.log(result.stdout);  // Sum: 15
} finally {
    await sandbox.kill();
}

File Operations

AgentRun SDK (Before Upgrade):

import { CodeInterpreterSandbox } from '@agentrun/sdk';

const sandbox = await CodeInterpreterSandbox.createFromTemplate('my-code-template');
await sandbox.waitUntilReadyOrFailed();

// Local → Sandbox
await sandbox.fileSystem.upload({
    localFilePath: './local.txt',
    targetFilePath: '/home/user/remote.txt',
});

// Sandbox → Local
await sandbox.fileSystem.download({
    path: '/home/user/result.txt',
    savePath: './result.txt',
});

// Read/write within sandbox
await sandbox.file.write({ path: '/tmp/note.txt', content: 'hello' });
const content = await sandbox.file.read({ path: '/tmp/note.txt' });

await sandbox.delete();

E2B SDK (After Upgrade):

import { Sandbox } from 'e2b';
import fs from 'fs';
import 'dotenv/config';

const sandbox = await Sandbox.create();

try {
    // Local → Sandbox
    const content = fs.readFileSync('./local.txt');
    await sandbox.files.write('/home/user/remote.txt', content);
    
    // Sandbox → Local
    const result = await sandbox.files.read('/home/user/result.txt');
    fs.writeFileSync('./result.txt', result);
} finally {
    await sandbox.kill();
}

Upgrade Implementation Plan

Recommended Upgrade Process

The entire upgrade process is recommended to proceed in four phases, with a total duration of approximately 10 days:

  1. Phase 1: Assessment & Preparation (1 day recommended) — Inventory existing capabilities, audit templates/images, confirm specification mappings, and develop an upgrade plan.

  2. Phase 2: Development & Validation (3 days recommended) — SDK upgrade development, functional regression testing, performance benchmarking, and edge-case coverage.

  3. Phase 3: Canary Rollout (3 days recommended) — Canary traffic shift, monitoring metrics observation, cost comparison validation, and rapid rollback if issues arise.

  4. Phase 4: Full Upgrade & Wrap-up (3 days recommended) — Full traffic switch, clean up old configurations, retrospective review, and documentation archival.

Phase 1: Assessment & Preparation

Objective: Comprehensively audit the current usage of AgentRun sandbox and develop a detailed upgrade plan.

Assessment Item

Details

Feature Inventory

Catalog all sandbox features currently in use (code execution, file operations, port exposure, etc.)

Templates / Images

Audit the list of custom templates and confirm whether corresponding versions exist in FC Cloud Sandbox or need to be rebuilt

Resource Specifications

Record current CPU / memory / disk specifications in use and map them to FC Cloud Sandbox specification options

Dependencies

Review all AgentRun SDK dependency references in the codebase and assess the scope of required changes

Phase 2: Development & Validation

Objective: Complete SDK upgrade development and validate functionality and performance in the FC Cloud Sandbox environment.

  • Replace code item by item following the SDK upgrade guide

  • Create sandbox templates via the E2B SDK to ensure environment configurations are consistent with the original AgentRun templates

  • Write regression test cases covering core business workflows and edge-case scenarios

  • Run performance benchmarks comparing creation latency, execution latency, and stability between the two platforms

Phase 3: Canary Rollout

Objective: Shift a small percentage of traffic to FC Cloud Sandbox, observe operational status, and validate cost and performance expectations.

  • Start with an initial canary ratio of 5%–10% and monitor for 2–3 days

  • Key metrics to monitor: sandbox creation success rate, code execution success rate, average latency, and error rate

  • Confirm that cost data aligns with expectations

  • If issues are detected, roll back to AgentRun sandbox immediately via a configuration toggle

Phase 4: Full Upgrade & Wrap-up

Objective: Complete full traffic switch to FC Cloud Sandbox.

  • Gradually increase the canary ratio to 100%

  • Confirm that all business workflows are running normally on FC Cloud Sandbox

  • Clean up AgentRun SDK-related old configurations and code