Agent 可使用 Sandbox 在隔离的容器环境中运行代码。当 Agent 需要真实文件系统、shell 命令、语言运行时、包安装或不应在 Agent 自身 Worker isolate 中运行的长期项目状态时,请使用 Sandbox。
Sandbox 基于 Cloudflare Containers 构建,提供用于命令执行、文件操作、后台进程和服务预览的 TypeScript API。
在 Agent 需要以下能力时使用 Sandbox:
- 在隔离环境中运行不受信任或模型生成的代码。
- 执行 Python、Node.js、shell 命令或包管理器。
- 读取、写入和管理项目文件。
- 运行测试、linter、构建工具或数据分析脚本。
- 在多个 Agent 轮次间维护工作区。
将 Sandbox Durable Object 绑定到 Worker,然后在 Agent 方法中通过 getSandbox() 访问 sandbox。
import { Agent, callable } from "agents";
import { getSandbox } from "@cloudflare/sandbox";
export { Sandbox } from "@cloudflare/sandbox";
export class CodeAgent extends Agent {
@callable()
async runPython(code) {
const sandbox = getSandbox(this.env.Sandbox, this.name);
await sandbox.writeFile("/workspace/script.py", code);
const result = await sandbox.exec("python3 /workspace/script.py");
this.setState({ lastOutput: result.stdout });
return {
success: result.success,
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
};
}
}import { Agent, callable } from "agents";
import { getSandbox } from "@cloudflare/sandbox";
import type { Sandbox } from "@cloudflare/sandbox";
export { Sandbox } from "@cloudflare/sandbox";
type Env = {
Sandbox: DurableObjectNamespace<Sandbox>;
};
export class CodeAgent extends Agent<Env, { lastOutput?: string }> {
@callable()
async runPython(code: string) {
const sandbox = getSandbox(this.env.Sandbox, this.name);
await sandbox.writeFile("/workspace/script.py", code);
const result = await sandbox.exec("python3 /workspace/script.py");
this.setState({ lastOutput: result.stdout });
return {
success: result.success,
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
};
}
}在 wrangler.jsonc 中配置 Sandbox 容器、Durable Object binding 和 migration。
{
"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"]
}
]
}[[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" ]Agent 状态用于用户可见的进度和少量元数据。Sandbox 文件系统用于工作区文件、生成的代码、包安装、日志和产物。
对于长时间运行的 sandbox 工作,将 Sandbox 与使用 fiber 的持久化 execution 或 Workflow 配合使用,以便 Agent 在工作超出单次请求时能够恢复或报告进度。
Sandbox SDK
命令、文件、会话和部署的完整 Sandbox 文档。
执行命令
在 sandbox 环境中运行 shell 命令。
管理文件
读取、写入、上传和下载 sandbox 文件。