sandbox-sdk by cloudflare/skills
npx skills add https://github.com/cloudflare/skills --skill sandbox-sdk在 Cloudflare Workers 上构建安全、隔离的代码执行环境。
npm install @cloudflare/sandbox
docker info # 必须成功 - 本地开发需要 Docker
您对 Sandbox SDK 的了解可能已过时。对于任何 Sandbox SDK 任务,请优先使用检索而非预训练知识。
实现功能时,请首先获取相关的文档页面或示例。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
wrangler.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 类:
import { getSandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox'; // 必需的导出
| 任务 | 方法 |
|---|---|
| 获取沙箱 | 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() |
const sandbox = getSandbox(env.Sandbox, 'user-123');
const result = await sandbox.exec('python --version');
// result: { stdout, stderr, exitCode, success }
使用 runCode() 来执行 LLM 生成的代码并获取丰富的输出:
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
状态在上下文内持久化。在生产环境中请创建明确的上下文。
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');
| 需求 | 使用 | 原因 |
|---|---|---|
| Shell 命令、脚本 | exec() | 直接控制、流式输出 |
| LLM 生成的代码 | runCode() | 丰富的输出、状态持久化 |
| 构建/测试流水线 | exec() | 退出码、stderr 捕获 |
| 数据分析 | runCode() | 图表、表格、pandas |
基础镜像 (docker.io/cloudflare/sandbox:0.7.0) 包含 Python 3.11、Node.js 20 和常用工具。
通过扩展 Dockerfile 来添加依赖:
FROM docker.io/cloudflare/sandbox:0.7.0
# Python 包
RUN pip install requests beautifulsoup4
# Node 包(全局)
RUN npm install -g typescript
# 系统包
RUN apt-get update && apt-get install -y ffmpeg && rm -rf /var/lib/apt/lists/*
EXPOSE 8080 # 本地开发端口暴露所必需
保持镜像精简 - 这会影响冷启动时间。
暴露在沙箱中运行的 HTTP 服务:
const { url } = await sandbox.exposePort(8080);
// 返回服务的预览 URL
生产环境要求 : 预览 URL 需要一个带有通配符 DNS (*.yourdomain.com) 的自定义域名。.workers.dev 域名不支持预览 URL 子域名。
SDK 在 @cloudflare/sandbox/openai 提供了 OpenAI Agents 的辅助工具:
import { Shell, Editor } from '@cloudflare/sandbox/openai';
完整的集成模式请参见 examples/openai-agents。
getSandbox() 立即返回 - 容器在首次操作时延迟启动sleepAfter 配置)destroy() 立即释放资源sandboxId 总是返回相同的沙箱实例CommandClient, FileClient) - 使用 sandbox.* 方法export { Sandbox } Worker 将无法部署destroy()每周安装量
938
代码仓库
GitHub 星标数
566
首次出现
2026年2月5日
安全审计
安装于
opencode859
codex856
gemini-cli845
github-copilot819
amp778
kimi-cli777
Build secure, isolated code execution environments on Cloudflare Workers.
npm install @cloudflare/sandbox
docker info # Must succeed - Docker required for local dev
Your knowledge of the Sandbox SDK may be outdated. Prefer retrieval over pre-training for any Sandbox SDK task.
When implementing features, fetch the relevant doc page or example first.
wrangler.jsonc (exact - do not modify structure):
{
"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:
import { getSandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox'; // Required export
| Task | Method |
|---|---|
| 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 |
const sandbox = getSandbox(env.Sandbox, 'user-123');
const result = await sandbox.exec('python --version');
// result: { stdout, stderr, exitCode, success }
Use runCode() for executing LLM-generated code with rich outputs:
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.
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');
| Need | Use | Why |
|---|---|---|
| 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 |
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:
FROM docker.io/cloudflare/sandbox:0.7.0
# Python packages
RUN pip install requests beautifulsoup4
# Node packages (global)
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.
Expose HTTP services running in sandboxes:
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.
See: https://developers.cloudflare.com/sandbox/guides/expose-services/
The SDK provides helpers for OpenAI Agents at @cloudflare/sandbox/openai:
import { Shell, Editor } from '@cloudflare/sandbox/openai';
See examples/openai-agents for complete integration pattern.
getSandbox() returns immediately - container starts lazily on first operationsleepAfter)destroy() to immediately free resourcessandboxId always returns same sandbox instanceCommandClient, FileClient) - use sandbox.* methodsexport { Sandbox }destroy() for temporary sandboxesWeekly Installs
938
Repository
GitHub Stars
566
First Seen
Feb 5, 2026
Security Audits
Gen Agent Trust HubPassSocketFailSnykPass
Installed on
opencode859
codex856
gemini-cli845
github-copilot819
amp778
kimi-cli777
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
102,200 周安装
await sandbox.mkdir('/workspace/src', { recursive: true })| List files | await sandbox.listFiles('/workspace') |
| Expose port | await sandbox.exposePort(8080) |
| Destroy | await sandbox.destroy() |