sandbox-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCloudflare 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 devbash
npm install @cloudflare/sandbox
docker info # 必须执行成功 - 本地开发需要DockerRetrieval-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 exportwrangler.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
快速参考
| Task | Method |
|---|---|
| Get sandbox | |
| Run command | |
| Run code (interpreter) | |
| Write file | |
| Read file | |
| Create directory | |
| List files | |
| Expose port | |
| 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 for executing LLM-generated code with rich outputs:
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"Languages: , ,
pythonjavascripttypescriptState 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"支持语言:, ,
pythonjavascripttypescript上下文内会保留状态。生产环境中请创建显式上下文。
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
场景选择指南
| Need | Use | Why |
|---|---|---|
| Shell commands, scripts | | Direct control, streaming |
| LLM-generated code | | Rich outputs, state persistence |
| Build/test pipelines | | Exit codes, stderr capture |
| Data analysis | | Charts, tables, pandas |
| 需求 | 使用方法 | 原因 |
|---|---|---|
| Shell命令、脚本 | | 直接控制,支持流式输出 |
| 大语言模型生成的代码 | | 丰富输出格式,状态持久化 |
| 构建/测试流水线 | | 捕获退出码、标准错误输出 |
| 数据分析 | | 支持图表、表格、pandas库 |
Extending the Dockerfile
扩展Dockerfile
Base image () includes Python 3.11, Node.js 20, and common tools.
docker.io/cloudflare/sandbox:0.7.0Add dependencies by extending the Dockerfile:
dockerfile
FROM docker.io/cloudflare/sandbox:0.7.0基础镜像()包含Python 3.11、Node.js 20以及常用工具。
docker.io/cloudflare/sandbox:0.7.0通过扩展Dockerfile添加依赖:
dockerfile
FROM docker.io/cloudflare/sandbox:0.7.0Python 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 serviceProduction requirement: Preview URLs need a custom domain with wildcard DNS (). The domain does not support preview URL subdomains.
*.yourdomain.com.workers.dev暴露沙箱中运行的HTTP服务:
typescript
const { url } = await sandbox.exposePort(8080);
// 返回服务的预览URL生产环境要求:预览URL需要配置带有通配符DNS的自定义域名()。域名不支持预览URL子域名。
*.yourdomain.com.workers.devOpenAI Agents SDK Integration
OpenAI Agents SDK集成
The SDK provides helpers for OpenAI Agents at :
@cloudflare/sandbox/openaitypescript
import { Shell, Editor } from '@cloudflare/sandbox/openai';See for complete integration pattern.
examples/openai-agentsSDK在路径下提供了OpenAI Agents的辅助工具:
@cloudflare/sandbox/openaitypescript
import { Shell, Editor } from '@cloudflare/sandbox/openai';完整集成模式请查看。
examples/openai-agentsSandbox Lifecycle
沙箱生命周期
- returns immediately - container starts lazily on first operation
getSandbox() - Containers sleep after 10 minutes of inactivity (configurable via )
sleepAfter - Use to immediately free resources
destroy() - Same always returns same sandbox instance
sandboxId
- 会立即返回 - 容器会在首次操作时延迟启动
getSandbox() - 容器在闲置10分钟后进入休眠状态(可通过配置)
sleepAfter - 使用立即释放资源
destroy() - 相同的始终返回同一个沙箱实例
sandboxId
Anti-Patterns
反模式
- Don't use internal clients (,
CommandClient) - useFileClientmethodssandbox.* - 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 for temporary sandboxes
destroy()
- 不要使用内部客户端(,
CommandClient)- 请使用FileClient方法sandbox.* - 不要跳过Sandbox导出 - 不添加的话Worker无法部署
export { Sandbox } - 不要为多用户场景硬编码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 - 包含各种使用场景的示例索引