sandbox-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cloudflare Sandbox SDK

Cloudflare Sandbox SDK

Build secure, isolated code execution environments on Cloudflare Workers.
在Cloudflare Workers上构建安全、隔离的代码执行环境。

FIRST: Verify Installation

第一步:验证安装

bash
npm install @cloudflare/sandbox
docker info  # Must succeed - Docker required for local dev
bash
npm install @cloudflare/sandbox
docker info  # 必须执行成功 - 本地开发需要Docker

Retrieval-Led Development

检索优先开发

IMPORTANT: Prefer retrieval from docs and examples over pre-training for Sandbox SDK tasks.
When implementing features, fetch the relevant doc page or example first.
重要提示:在处理Sandbox SDK相关任务时,优先从文档和示例中检索信息,而非依赖预训练内容。
在实现功能时,请先获取相关的文档页面或示例。

Required Configuration

必要配置

wrangler.jsonc (exact - do not modify structure):
jsonc
{
  "containers": [{
    "class_name": "Sandbox",
    "image": "./Dockerfile",
    "instance_type": "lite",
    "max_instances": 1
  }],
  "durable_objects": {
    "bindings": [{ "class_name": "Sandbox", "name": "Sandbox" }]
  },
  "migrations": [{ "new_sqlite_classes": ["Sandbox"], "tag": "v1" }]
}
Worker entry - must re-export Sandbox class:
typescript
import { getSandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox';  // Required export
wrangler.jsonc(严格遵循此结构,请勿修改):
jsonc
{
  "containers": [{
    "class_name": "Sandbox",
    "image": "./Dockerfile",
    "instance_type": "lite",
    "max_instances": 1
  }],
  "durable_objects": {
    "bindings": [{ "class_name": "Sandbox", "name": "Sandbox" }]
  },
  "migrations": [{ "new_sqlite_classes": ["Sandbox"], "tag": "v1" }]
}
Worker入口文件 - 必须重新导出Sandbox类:
typescript
import { getSandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox';  // 必须导出

Quick Reference

快速参考

TaskMethod
Get sandbox
getSandbox(env.Sandbox, 'user-123')
Run command
await sandbox.exec('python script.py')
Run code (interpreter)
await sandbox.runCode(code, { language: 'python' })
Write file
await sandbox.writeFile('/workspace/app.py', content)
Read file
await sandbox.readFile('/workspace/app.py')
Create directory
await sandbox.mkdir('/workspace/src', { recursive: true })
List files
await sandbox.listFiles('/workspace')
Expose port
await sandbox.exposePort(8080)
Destroy
await sandbox.destroy()
任务方法
获取沙箱
getSandbox(env.Sandbox, 'user-123')
运行命令
await sandbox.exec('python script.py')
运行代码(解释器)
await sandbox.runCode(code, { language: 'python' })
写入文件
await sandbox.writeFile('/workspace/app.py', content)
读取文件
await sandbox.readFile('/workspace/app.py')
创建目录
await sandbox.mkdir('/workspace/src', { recursive: true })
列出文件
await sandbox.listFiles('/workspace')
暴露端口
await sandbox.exposePort(8080)
销毁沙箱
await sandbox.destroy()

Core Patterns

核心模式

Execute Commands

执行命令

typescript
const sandbox = getSandbox(env.Sandbox, 'user-123');
const result = await sandbox.exec('python --version');
// result: { stdout, stderr, exitCode, success }
typescript
const sandbox = getSandbox(env.Sandbox, 'user-123');
const result = await sandbox.exec('python --version');
// result: { stdout, stderr, exitCode, success }

Code Interpreter (Recommended for AI)

代码解释器(AI场景推荐)

Use
runCode()
for executing LLM-generated code with rich outputs:
typescript
const ctx = await sandbox.createCodeContext({ language: 'python' });

await sandbox.runCode('import pandas as pd; data = [1,2,3]', { context: ctx });
const result = await sandbox.runCode('sum(data)', { context: ctx });
// result.results[0].text = "6"
Languages:
python
,
javascript
,
typescript
State persists within context. Create explicit contexts for production.
使用
runCode()
执行大语言模型生成的代码,支持丰富输出:
typescript
const ctx = await sandbox.createCodeContext({ language: 'python' });

await sandbox.runCode('import pandas as pd; data = [1,2,3]', { context: ctx });
const result = await sandbox.runCode('sum(data)', { context: ctx });
// result.results[0].text = "6"
支持语言
python
,
javascript
,
typescript
上下文内会保留状态。生产环境中请创建显式上下文。

File Operations

文件操作

typescript
await sandbox.mkdir('/workspace/project', { recursive: true });
await sandbox.writeFile('/workspace/project/main.py', code);
const file = await sandbox.readFile('/workspace/project/main.py');
const files = await sandbox.listFiles('/workspace/project');
typescript
await sandbox.mkdir('/workspace/project', { recursive: true });
await sandbox.writeFile('/workspace/project/main.py', code);
const file = await sandbox.readFile('/workspace/project/main.py');
const files = await sandbox.listFiles('/workspace/project');

When to Use What

场景选择指南

NeedUseWhy
Shell commands, scripts
exec()
Direct control, streaming
LLM-generated code
runCode()
Rich outputs, state persistence
Build/test pipelines
exec()
Exit codes, stderr capture
Data analysis
runCode()
Charts, tables, pandas
需求使用方法原因
Shell命令、脚本
exec()
直接控制,支持流式输出
大语言模型生成的代码
runCode()
丰富输出格式,状态持久化
构建/测试流水线
exec()
捕获退出码、标准错误输出
数据分析
runCode()
支持图表、表格、pandas库

Extending the Dockerfile

扩展Dockerfile

Base image (
docker.io/cloudflare/sandbox:0.7.0
) includes Python 3.11, Node.js 20, and common tools.
Add dependencies by extending the Dockerfile:
dockerfile
FROM docker.io/cloudflare/sandbox:0.7.0
基础镜像(
docker.io/cloudflare/sandbox:0.7.0
)包含Python 3.11、Node.js 20以及常用工具。
通过扩展Dockerfile添加依赖:
dockerfile
FROM docker.io/cloudflare/sandbox:0.7.0

Python packages

Python包

RUN pip install requests beautifulsoup4
RUN pip install requests beautifulsoup4

Node packages (global)

Node包(全局)

RUN npm install -g typescript
RUN npm install -g typescript

System packages

系统包

RUN apt-get update && apt-get install -y ffmpeg && rm -rf /var/lib/apt/lists/*
EXPOSE 8080 # Required for local dev port exposure

Keep images lean - affects cold start time.
RUN apt-get update && apt-get install -y ffmpeg && rm -rf /var/lib/apt/lists/*
EXPOSE 8080 # 本地开发端口暴露所需

保持镜像轻量化 - 镜像大小会影响冷启动时间。

Preview URLs (Port Exposure)

预览URL(端口暴露)

Expose HTTP services running in sandboxes:
typescript
const { url } = await sandbox.exposePort(8080);
// Returns preview URL for the service
Production requirement: Preview URLs need a custom domain with wildcard DNS (
*.yourdomain.com
). The
.workers.dev
domain does not support preview URL subdomains.
暴露沙箱中运行的HTTP服务:
typescript
const { url } = await sandbox.exposePort(8080);
// 返回服务的预览URL
生产环境要求:预览URL需要配置带有通配符DNS的自定义域名(
*.yourdomain.com
)。
.workers.dev
域名不支持预览URL子域名。

OpenAI Agents SDK Integration

OpenAI Agents SDK集成

The SDK provides helpers for OpenAI Agents at
@cloudflare/sandbox/openai
:
typescript
import { Shell, Editor } from '@cloudflare/sandbox/openai';
See
examples/openai-agents
for complete integration pattern.
SDK在
@cloudflare/sandbox/openai
路径下提供了OpenAI Agents的辅助工具:
typescript
import { Shell, Editor } from '@cloudflare/sandbox/openai';
完整集成模式请查看
examples/openai-agents

Sandbox Lifecycle

沙箱生命周期

  • getSandbox()
    returns immediately - container starts lazily on first operation
  • Containers sleep after 10 minutes of inactivity (configurable via
    sleepAfter
    )
  • Use
    destroy()
    to immediately free resources
  • Same
    sandboxId
    always returns same sandbox instance
  • getSandbox()
    会立即返回 - 容器会在首次操作时延迟启动
  • 容器在闲置10分钟后进入休眠状态(可通过
    sleepAfter
    配置)
  • 使用
    destroy()
    立即释放资源
  • 相同的
    sandboxId
    始终返回同一个沙箱实例

Anti-Patterns

反模式

  • Don't use internal clients (
    CommandClient
    ,
    FileClient
    ) - use
    sandbox.*
    methods
  • Don't skip the Sandbox export - Worker won't deploy without
    export { Sandbox }
  • Don't hardcode sandbox IDs for multi-user - use user/session identifiers
  • Don't forget cleanup - call
    destroy()
    for temporary sandboxes
  • 不要使用内部客户端
    CommandClient
    ,
    FileClient
    )- 请使用
    sandbox.*
    方法
  • 不要跳过Sandbox导出 - 不添加
    export { Sandbox }
    的话Worker无法部署
  • 不要为多用户场景硬编码sandbox ID - 请使用用户/会话标识符
  • 不要忘记清理 - 临时沙箱请调用
    destroy()

Detailed References

详细参考

  • references/api-quick-ref.md - Full API with options and return types
  • references/examples.md - Example index with use cases
  • references/api-quick-ref.md - 包含选项和返回类型的完整API文档
  • references/examples.md - 包含各种使用场景的示例索引