mcpField
C
cloudflare-sandbox

cloudflare-sandbox

github.com/secondsky云与 DevOps240222 次安装5 周前更新
代码仓库

关于 cloudflare-sandbox

介绍 Cloudflare Sandboxes SDK 的技能,面向在容器中执行命令和管理文件的 Workers 开发者。内容涵盖会话、生命周期与持久化行为,以及搭建和安全注意事项。

主要功能

  1. 01在容器中执行命令
  2. 02读写和管理文件
  3. 03用会话支持多步任务
  4. 04处理沙箱生命周期和冷启动
  5. 05管理 Git、代码执行与进程

适用场景

  1. 01通过 Worker 执行隔离代码
  2. 02用持久会话构建多步工作流
  3. 03为测试或构建创建干净沙箱
  4. 04规划空闲重置期间的数据存储

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/secondsky/claude-skills --skill cloudflare-sandbox

安装后在 Claude Code 中输入/cloudflare-sandbox确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

assets/
example-template.txt
references/
advanced.md
api-reference.md
common-errors.md
example-reference.md
naming-strategies.md
patterns.md
persistence-guide.md
session-management.md
scripts/
example-script.sh
setup-sandbox-binding.sh
test-sandbox.ts
templates/
basic-executor.ts
chat-agent.ts
ci-cd.ts
workspace.ts

详细介绍

Cloudflare Sandboxes SDK

状态:生产就绪(开放测试版) 最后更新:2025-12-10 依赖项:cloudflare-worker-base、cloudflare-durable-objects(建议了解) 最新版本:@cloudflare/[email protected],Docker 镜像:cloudflare/sandbox:0.6.3-python

**⚠️ 重大变更(v0.6.0):**默认镜像不再包含 Python。需要 Python 支持时,请使用 cloudflare/sandbox:<version>-python(包含数据科学包,约 1.3GB)。精简版(约 600-800MB)不包含 Python。


快速入门(15 分钟)

1. 安装 SDK 并设置 Wrangler
bun add @cloudflare/sandbox@latest  # preferred
# or: bun add @cloudflare/sandbox@latest

wrangler.jsonc:

{
  "name": "my-sandbox-worker",
  "main": "src/index.ts",
  "compatibility_flags": ["nodejs_compat"],
  "containers": [{
    "class_name": "Sandbox",
    "image": "cloudflare/sandbox:0.6.3-python",
    "instance_type": "lite"
  }],
  "durable_objects": {
    "bindings": [{
      "class_name": "Sandbox",
      "name": "Sandbox"
    }]
  },
  "migrations": [{
    "tag": "v1",
    "new_sqlite_classes": ["Sandbox"]
  }]
}

重要原因:

  • nodejs_compat 启用 SDK 所需的 Node.js API
  • containers 定义 Ubuntu 容器镜像
  • durable_objects 绑定启用持久路由
  • migrations 注册 Sandbox 类
2. 创建你的第一个 Sandbox Worker
import { getSandbox, type Sandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox';

type Env = {
  Sandbox: DurableObjectNamespace<Sandbox>;
};

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // Get sandbox instance (creates if doesn't exist)
    const sandbox = getSandbox(env.Sandbox, 'my-first-sandbox');

    // Execute Python code
    const result = await sandbox.exec('python3 -c "print(2 + 2)"');

    return Response.json({
      output: result.stdout,
      success: result.success,
      exitCode: result.exitCode
    });
  }
};

重要:

  • Worker 中必须导出来自 @cloudflare/sandbox 的 { Sandbox }
  • Sandbox ID 决定路由(相同 ID = 相同容器)
  • 第一个请求会创建容器(冷启动约需 2-3 分钟)
  • 后续请求速度很快(<1 秒)
3. 部署并测试
npm run deploy
curl https://your-worker.workers.dev

预期输出:

{
  "output": "4\n",
  "success": true,
  "exitCode": 0
}

安全安装

Sandbox SDK 包可授予容器访问权限——安装前请先验证,以防止未经授权的代码执行。请遵循供应链安全最佳实践:

  • 阻止安装后脚本——npm config set ignore-scripts true(或使用 Bun:默认禁用)
  • 冷却期——新软件包版本发布后等待 7 天,让社区进行审查
  • 安装前审计——运行 socket package score npm <pkg>,或使用 socket npm install <pkg> 检查软件包

加载 dependency-upgrade 技能,获取完整的安全配置,包括 Socket CLI 集成、冷却期设置、锁文件验证和 CI 强制执行。


架构(了解三层模型)

Sandbox 的工作原理
┌─────────────────────────────────────────┐
│  Your Worker (Layer 1)                  │
│  - Handles HTTP requests                │
│  - Calls getSandbox()                   │
│  - Uses sandbox.exec(), writeFile(), etc│
└──────────────┬──────────────────────────┘
               │ RPC via Durable Object
┌──────────────▼──────────────────────────┐
│  Durable Object (Layer 2)               │
│  - Routes by sandbox ID                 │
│  - Maintains persistent identity        │
│  - Geographic stickiness                │
└──────────────┬──────────────────────────┘
               │ Container API
┌──────────────▼──────────────────────────┐
│  Ubuntu Container (Layer 3)             │
│  - Full Linux environment               │
│  - Python 3.11, Node 20, Git, etc.      │
│  - Filesystem: /workspace, /tmp, /home  │
│  - Process isolation (VM-based)         │
└─────────────────────────────────────────┘

关键要点:Worker 处理 API 逻辑(快速),Durable Objects 路由请求(身份持久),容器执行代码(功能完整)。


重要的容器生命周期(最重要的部分!)

容器状态
┌─────────┐  First request  ┌────────┐  ~10 min idle  ┌──────┐
│ Not     │ ───────────────>│ Active │ ─────────────> │ Idle │
│ Created │                 │        │                │      │
└─────────┘                 └───┬────┘                └──┬───┘
                                │ ^                      │
                                │ │ New request          │
                                │ └──────────────────────┘
                                │                         │
                                ▼                         ▼
                            Files persist          ALL FILES DELETED
                            Processes run          ALL PROCESSES KILLED
                            State maintained       ALL STATE RESET
最大的注意事项:默认情况下是临时的

容器处于活动状态时(上次请求后约 10 分钟内):

  • ✅ /workspace、/tmp、/home 中的文件会保留
  • ✅ 后台进程会持续运行
  • ✅ Shell 环境变量会保留
  • ✅ 会话工作目录会保留

容器进入空闲状态时(不活动一段时间后):

  • ❌ 所有文件都会被删除(整个文件系统会重置)
  • ❌ 所有进程都会终止
  • ❌ 所有 Shell 状态都会丢失
  • ⚠️ 下一个请求会从头创建一个全新的容器

这与传统服务器不同。Sandbox 的设计本身就是临时性的。

处理持久化

重要数据:使用外部存储

// Save to R2 before container goes idle
await sandbox.writeFile('/workspace/data.txt', content);
const fileData = await sandbox.readFile('/workspace/data.txt');
await env.R2.put('backup/data.txt', fileData);

// Restore on next request
const restored = await env.R2.get('backup/data.txt');
if (restored) {
  await sandbox.writeFile('/workspace/data.txt', await restored.text());
}

构建产物:接受其临时性,或使用缓存

// Check if setup needed (handles cold starts)
const exists = await sandbox.readdir('/workspace/project').catch(() => null);
if (!exists) {
  await sandbox.gitCheckout(repoUrl, '/workspace/project');
  await sandbox.exec('npm install', { cwd: '/workspace/project' });
}
// Now safe to run build
await sandbox.exec('npm run build', { cwd: '/workspace/project' });

会话管理(聊天 Agent 的关键利器)

什么是会话?

会话是一个 Sandbox 内的 bash Shell 上下文。可以把它们想成终端标签页。

关键特性:

  • 每个会话都有独立的工作目录
  • 会话共享同一个文件系统
  • 同一会话中的工作目录会在不同命令间保留
  • 非常适合多步骤工作流
模式:基于聊天的编码 Agent
type ConversationState = {
  sandboxId: string;
  sessionId: string;
};

// First message: Create sandbox and session
const sandboxId = `user-${userId}`;
const sandbox = getSandbox(env.Sandbox, sandboxId);
const sessionId = await sandbox.createSession();

// Store in conversation state (database, KV, etc.)
await env.KV.put(`conversation:${conversationId}`, JSON.stringify({
  sandboxId,
  sessionId
}));

// Later messages: Reuse same session
const state = await env.KV.get(`conversation:${conversationId}`);
const { sandboxId, sessionId } = JSON.parse(state);
const sandbox = getSandbox(env.Sandbox, sandboxId);

// Commands run in same context
await sandbox.exec('cd /workspace/project', { session: sessionId });
await sandbox.exec('ls -la', { session: sessionId }); // Still in /workspace/project
await sandbox.exec('git status', { session: sessionId }); // Still in /workspace/project
不使用会话(常见错误)
// ❌ WRONG: Each command runs in separate session
await sandbox.exec('cd /workspace/project');
await sandbox.exec('ls'); // NOT in /workspace/project (different session)
模式:并行执行
const session1 = await sandbox.createSession();
const session2 = await sandbox.createSession();

// Run different tasks simultaneously
await Promise.all([
  sandbox.exec('python train_model.py', { session: session1 }),
  sandbox.exec('node generate_reports.js', { session: session2 })
]);

Sandbox 命名策略

每个用户一个 Sandbox(持久工作区)
const sandbox = getSandbox(env.Sandbox, `user-${userId}`);

优点:用户在持续使用时,工作会保留(空闲时间为 10 分钟) 缺点:受地域限制(首次请求决定位置) 适用场景:交互式笔记本、IDE、持久工作区

每个会话一个 Sandbox(每次全新创建)
const sandboxId = `session-${Date.now()}-${crypto.randomUUID()}`;
const sandbox = getSandbox(env.Sandbox, sandboxId);
// Always destroy after use
await sandbox.destroy();

优点:环境干净,不会受到状态污染 缺点:请求之间不会持久化 适用场景:一次性代码执行、CI/CD、测试

按任务创建沙箱(幂等且可追踪)
const sandbox = getSandbox(env.Sandbox, `build-${repoName}-${commitSha}`);

优点:可复现、易调试、可缓存 缺点:需要明确的清理策略 适用场景:构建系统、数据管道、自动化工作流


核心 API 参考

Sandbox SDK 提供用于命令执行、文件操作、Git 操作、代码解释(类似 Jupyter)、后台进程和清理的方法。

📖 需要详细的 API 方法签名、参数选项或实现示例时,请加载 references/api-reference.md:

  • 使用选项(cwd、超时、环境变量、会话)执行命令
  • 文件操作(read/write/mkdir/rm/readdir)
  • Git 操作(gitCheckout、git 命令)
  • 代码解释器(createCodeContext、runCode)
  • 后台进程(spawn、isProcessRunning、killProcess)
  • 沙箱清理(destroy)

关键规则

始终做到

✅ 检查退出代码 - if (!result.success) { handle error } ✅ 多步骤工作流使用会话 - 保留工作目录 ✅ 处理冷启动 - 先检查文件是否存在,不要想当然地认为它们已存在 ✅ 设置超时 - 防止长时间操作一直挂起 ✅ 销毁临时沙箱 - 清理临时或基于会话的沙箱 ✅ 使用外部存储实现持久化 - 重要数据存储在 R2/KV/D1 中 ✅ 验证用户输入 - 在 exec() 前进行清理,以防止命令注入 ✅ 导出 Sandbox 类 - export { Sandbox } from '@cloudflare/sandbox'

绝不要

❌ 假设空闲后文件仍会保留 - 容器会在约 10 分钟后重置 ❌ 忽略退出代码 - 始终检查 result.success 或 result.exitCode ❌ 不使用会话就串联命令 - 先执行 cd /dir 再执行 ls 不会生效 ❌ 执行未经清理的用户输入 - 使用代码解释器或彻底验证输入 ❌ 忘记 nodejs_compat 标志 - wrangler.jsonc 中必须设置 ❌ 跳过迁移 - Durable Objects 需要迁移条目 ❌ 将 .workers.dev 用作预览 URL - 需要自定义域名 ❌ 创建无限量沙箱 - 销毁临时沙箱以避免泄漏


已知问题防范

此技能可防范 10 个已记录的问题:

问题 #1:缺少 nodejs_compat 标志

错误:ReferenceError: fetch is not defined 或 Buffer is not defined 来源:https://developers.cloudflare.com/sandbox/get-started/ 原因:SDK 需要标准 Workers 中不可用的 Node.js API 防范措施:在 wrangler.jsonc 中添加 "compatibility_flags": ["nodejs_compat"]

问题 #2:缺少迁移

错误:Error: Class 'Sandbox' not found 来源:https://developers.cloudflare.com/durable-objects/ 原因:必须通过迁移注册 Durable Objects 防范措施:在 wrangler.jsonc 中包含 migrations 数组

问题 #3:假设文件会持久保存

错误:闲置后文件消失 来源:https://developers.cloudflare.com/sandbox/concepts/sandboxes/ 原因:容器在约 10 分钟后进入空闲状态,所有状态都会重置 防范措施:使用外部存储(R2/KV)或在每次请求时检查文件是否存在

问题 #4:会话目录混淆

错误:命令在错误的目录中执行 来源:https://developers.cloudflare.com/sandbox/concepts/sessions/ 原因:除非明确指定,否则每次 exec() 都会使用新会话 防范措施:使用 createSession() 创建会话,并将其传递给所有相关命令

问题 #5:忽略退出代码

错误:命令失败时仍认为它已成功 来源:Shell 最佳实践 原因:未检查 result.success 或 result.exitCode 防范措施:始终检查:if (!result.success) throw new Error(result.stderr)

问题 #6:未处理冷启动

错误:由于未安装依赖项,命令执行失败 来源:https://developers.cloudflare.com/sandbox/concepts/sandboxes/ 原因:容器在空闲一段时间后会重置 防范措施:运行命令前检查是否需要进行设置

问题 #7:Docker 未运行(本地开发)

错误:本地开发期间出现 Failed to build container 来源:https://developers.cloudflare.com/sandbox/get-started/ 原因:本地开发需要 Docker 守护进程 预防:运行 npm run dev 前,确保 Docker Desktop 正在运行

问题 #8:版本不匹配(软件包与 Docker 镜像)

错误:API 方法不可用或行为异常 来源:GitHub issues 原因:npm 软件包版本与 Docker 镜像版本不匹配 预防:确保 @cloudflare/sandbox 软件包与 cloudflare/sandbox 镜像版本一致

问题 #9:未清理临时 Sandbox

错误:资源耗尽、产生意外费用 来源:资源管理最佳实践 原因:创建 Sandbox 后未销毁 预防:在临时 Sandbox 的 finally 块中调用 await sandbox.destroy()

问题 #10:命令注入漏洞

错误:未清理的用户输入导致安全漏洞 来源:安全最佳实践 原因:直接将用户输入传递给 exec() 预防:使用代码解释器 API,或彻底验证和清理输入


wrangler.jsonc 示例

{
  "name": "my-sandbox-app",
  "main": "src/index.ts",
  "compatibility_date": "2025-10-29",
  "compatibility_flags": ["nodejs_compat"], // ← REQUIRED

  "containers": [{
    "class_name": "Sandbox",
    "image": "cloudflare/sandbox:0.6.3-python", // ← Use -python for Python support
    "instance_type": "lite"
  }],

  "durable_objects": {
    "bindings": [{"class_name": "Sandbox", "name": "Sandbox"}]
  },

  "migrations": [{
    "tag": "v1",
    "new_sqlite_classes": ["Sandbox"]
  }]
}

常见模式

使用 Cloudflare Sandboxes 构建应用的四种生产就绪模式:一次性代码执行、持久化用户工作区、CI/CD 流水线和 AI Agent 集成。

📖 需要完整的实现示例时,请加载 references/patterns.md:

  1. 一次性代码执行 - API 端点、代码游乐场、学习平台
  2. 持久化用户工作区 - 交互式环境、笔记本、IDE
  3. CI/CD 构建流水线 - 构建系统、测试流水线、部署自动化
  4. 使用 Claude Code 的 AI Agent - 自动重构、代码生成、AI 开发

使用捆绑资源

脚本(scripts/)
  • setup-sandbox-binding.sh - 交互式 wrangler.jsonc 配置
  • test-sandbox.ts - 用于测试 Sandbox 设置的验证脚本

用法示例:

# Setup wrangler config
./scripts/setup-sandbox-binding.sh

# Test sandbox
bunx tsx scripts/test-sandbox.ts
参考资料(references/)
  • references/persistence-guide.md - 深入了解容器生命周期和持久化
  • references/session-management.md - 高级会话模式和最佳实践
  • references/common-errors.md - 完整的错误列表及解决方案
  • references/naming-strategies.md - 为不同用例选择 Sandbox ID

Claude 应加载这些资料的时机:

  • 调试状态问题或冷启动时,加载 persistence-guide.md
  • 构建多步骤工作流或聊天 Agent 时,加载 session-management.md
  • 遇到特定错误时,加载 common-errors.md
  • 设计 Sandbox 架构时,加载 naming-strategies.md

高级主题

📖 加载 references/advanced.md,了解生产环境模式:

  • 面向全球应用的地理分布策略
  • 错误处理包装函数
  • 安全加固和输入验证

官方资源

软件包:@cloudflare/[email protected] | Docker:cloudflare/sandbox:0.6.3-python

文档:Cloudflare Sandboxes | API 参考 | GitHub SDK

评论

支持 Markdown