Cloudflare Agents 从入门到精通
附录

§16 沙箱与代码执行:跑任意代码

16.1 什么时候要沙箱

模型生成的代码、Python 脚本、要装包的数据分析——这些不能跑在 Worker 隔离区里。要隔离容器。

16.2 getSandbox:容器里跑命令

沙箱基于 Cloudflare Containers,暴露文件系统、shell、语言运行时。

import { getSandbox } from "@cloudflare/sandbox";
export { Sandbox } from "@cloudflare/sandbox";

export class CodeAgent extends Agent {
  @callable()
  async runPython(code: string) {
    const sandbox = getSandbox(this.env.Sandbox, this.name);
    await sandbox.writeFile("/workspace/script.py", code);
    const r = await sandbox.exec("python3 /workspace/script.py");
    this.setState({ lastOutput: r.stdout });
    return { stdout: r.stdout, stderr: r.stderr, exitCode: r.exitCode };
  }
}
"containers": [{ "class_name": "Sandbox", "image": "./Dockerfile", "instance_type": "lite", "max_instances": 1 }],
"durable_objects": { "bindings": [{ "name": "Sandbox", "class_name": "Sandbox" }] },
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["Sandbox"] }]

16.3 Code Mode:让模型写可执行 TS

更高一层的玩法:模型不直接调工具,而是生成一段可执行 TypeScript,调用你的工具。这叫 Code Mode(@cloudflare/codemode)。适合"多工具编排"场景,模型自己决定怎么组合。

维度 Sandbox 容器 Code Mode 标叔的结论
用途 跑任意代码/装包 模型编排工具 看要跑啥
隔离 容器级 Worker 沙箱 都隔离
典型 数据分析、构建 复杂多步任务 各取所需
核心建议
临时文件、生成代码、日志放沙箱文件系统;用户可见进度和小元数据放 Agent 状态。别把大文件塞状态里。

沙箱讲完。下一章用 MCP 把能力接到外部世界。