sandbox-sdk

sandbox-sdk

热门

构建沙盒化应用程序,用于安全代码执行。在构建AI代码执行、代码解释器、CI/CD系统、交互式开发环境或执行不受信任代码时加载。涵盖Sandbox SDK生命周期、命令、文件、代码解释器和预览URL。偏向从Cloudflare文档检索而非预训练知识。

2012Star
180Fork
更新于 2026/7/1
SKILL.md
readonly只读
name
sandbox-sdk
description

构建沙盒化应用程序,用于安全代码执行。在构建AI代码执行、代码解释器、CI/CD系统、交互式开发环境或执行不受信任代码时加载。涵盖Sandbox SDK生命周期、命令、文件、代码解释器和预览URL。偏向从Cloudflare文档检索而非预训练知识。

Cloudflare Sandbox SDK

在Cloudflare Workers上构建安全、隔离的代码执行环境。

第一步:验证安装

npm install @cloudflare/sandbox
docker info  # 必须成功 - 本地开发需要Docker

检索来源

您对Sandbox SDK的了解可能已过时。对于任何Sandbox SDK任务,优先检索而非预训练知识。

资源 URL
文档 https://developers.cloudflare.com/sandbox/
API参考 https://developers.cloudflare.com/sandbox/api/
示例 https://github.com/cloudflare/sandbox-sdk/tree/main/examples
入门指南 https://developers.cloudflare.com/sandbox/get-started/

实现功能时,请先获取相关文档页面或示例。

必需配置

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 }

代码解释器(推荐用于AI)

使用 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"

支持语言pythonjavascripttypescript

状态在上下文中持久化。生产环境中请创建显式上下文。

文件操作

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

扩展Dockerfile

基础镜像(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  # 本地开发端口暴露必需

保持镜像精简——影响冷启动时间。

预览URL(端口暴露)

暴露沙盒中运行的HTTP服务:

const { url } = await sandbox.exposePort(8080);
// 返回服务的预览URL

生产环境要求:预览URL需要具有通配符DNS的自定义域名(*.yourdomain.com)。.workers.dev域名不支持预览URL子域名。

参见:https://developers.cloudflare.com/sandbox/guides/expose-services/

OpenAI Agents SDK集成

SDK在 @cloudflare/sandbox/openai 中提供了OpenAI Agents的辅助工具:

import { Shell, Editor } from '@cloudflare/sandbox/openai';

完整的集成模式请参见 examples/openai-agents

沙盒生命周期

  • getSandbox() 立即返回——容器在首次操作时延迟启动
  • 容器在10分钟无活动后休眠(可通过 sleepAfter 配置)
  • 使用 destroy() 立即释放资源
  • 相同的 sandboxId 始终返回相同的沙盒实例

反模式

  • 不要使用内部客户端CommandClientFileClient)——使用 sandbox.* 方法
  • 不要跳过Sandbox导出——没有 export { Sandbox },Worker无法部署
  • 不要为多用户硬编码沙盒ID——使用用户/会话标识符
  • 不要忘记清理——为临时沙盒调用 destroy()

详细参考