跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

沙箱

最后更新 查看 MarkdownAgent 设置

为 Agent 提供 Linux 沙箱,用于跨多轮对话持续保存的 shell 命令、语言运行时、包安装和项目文件。沙箱是附加到 Agent 的 Container。Agent 向模型提供一个在沙箱中运行命令的 tool。

在 Agent 需要以下能力时使用沙箱:

  • 运行 shell 命令或脚本。
  • 使用编译器和其他 Linux 工具构建或测试代码。
  • 在同一段对话的多轮之间处理同一批文件。
  • 在远离 Agent 存储和凭据的环境中运行不受信任或模型生成的代码。

工作原理

将容器附加到 Agent 的 Durable Object,即可通过 this.ctx.container 为 Agent 提供沙箱。名称不同的 Agent 获得各自独立的沙箱,发往同一 Agent 的每一轮都会到达同一个沙箱。

沙箱运行在自己的虚拟机中。它无法读取 Agent 的存储、环境变量或绑定(binding)。只有在你允许时才能访问 Internet。

基本模式

以下 Think Agent 向模型提供一个 tool:run_command。该 tool 在首次使用时启动沙箱,并用 Bash 运行每条命令。

import { Think } from "@cloudflare/think";
import { routeAgentRequest } from "agents";
import { tool } from "ai";
import { createAI } from "agents/models/ai-sdk";
import { z } from "zod";

const MAX_OUTPUT_CHARS = 10_000;
// Keep the container for 10 minutes after the agent becomes inactive.
const INACTIVITY_TIMEOUT_MS = 10 * 60 * 1000;

export class CodeAgent extends Think {
	constructor(ctx, env) {
		super(ctx, env);
		const container = ctx.container;
		// A restarted agent sets the timeout again.
		if (container?.running) {
			void ctx.blockConcurrencyWhile(() =>
				container.setInactivityTimeout(INACTIVITY_TIMEOUT_MS),
			);
		}
	}

	getModel() {
		return createAI({ binding: this.env.AI })("@cf/moonshotai/kimi-k2.6");
	}

	getSystemPrompt() {
		return "You are a coding assistant. Use run_command to work in your Debian Linux sandbox.";
	}

	// Offer only the sandbox tool, so the model does not use the workspace file tools.
	beforeTurn() {
		return { activeTools: ["run_command"] };
	}

	getTools() {
		return {
			run_command: tool({
				description:
					"Run a shell command in this agent's Debian Linux sandbox. The sandbox cannot reach the Internet.",
				inputSchema: z.object({
					command: z.string().describe("The command to run with bash -lc"),
				}),
				execute: ({ command }) => this.runCommand(command),
			}),
		};
	}

	async runCommand(command) {
		const container = this.ctx.container;
		if (!container) {
			throw new Error("No container is configured");
		}

		if (!container.running) {
			container.start({
				image: "cloudflare/debian-trixie",
				entrypoint: ["sleep", "infinity"],
				enableInternet: false,
			});
			await container.setInactivityTimeout(INACTIVITY_TIMEOUT_MS);
		}

		// `timeout` stops the command and every process it started.
		const process = await container.exec([
			"timeout",
			"--kill-after=5",
			"60",
			"bash",
			"-lc",
			command,
		]);
		const output = await process.output();
		const decoder = new TextDecoder();

		return {
			exitCode: output.exitCode,
			stdout: decoder.decode(output.stdout).slice(-MAX_OUTPUT_CHARS),
			stderr: decoder.decode(output.stderr).slice(-MAX_OUTPUT_CHARS),
		};
	}
}

export default {
	async fetch(request, env) {
		return (
			(await routeAgentRequest(request, env)) ||
			new Response("Not found", { status: 404 })
		);
	},
};
import { Think } from "@cloudflare/think";
import { routeAgentRequest } from "agents";
import { tool } from "ai";
import { createAI } from "agents/models/ai-sdk";
import { z } from "zod";

const MAX_OUTPUT_CHARS = 10_000;
// Keep the container for 10 minutes after the agent becomes inactive.
const INACTIVITY_TIMEOUT_MS = 10 * 60 * 1000;

export class CodeAgent extends Think<Env> {
    constructor(ctx: DurableObjectState, env: Env) {
        super(ctx, env);
        const container = ctx.container;
        // A restarted agent sets the timeout again.
        if (container?.running) {
            void ctx.blockConcurrencyWhile(() =>
                container.setInactivityTimeout(INACTIVITY_TIMEOUT_MS),
            );
        }
    }

    getModel() {
        return createAI({ binding: this.env.AI })(
            "@cf/moonshotai/kimi-k2.6",
        );
    }

    getSystemPrompt() {
        return "You are a coding assistant. Use run_command to work in your Debian Linux sandbox.";
    }

    // Offer only the sandbox tool, so the model does not use the workspace file tools.
    beforeTurn() {
        return { activeTools: ["run_command"] };
    }

    getTools() {
        return {
            run_command: tool({
                description:
                    "Run a shell command in this agent's Debian Linux sandbox. The sandbox cannot reach the Internet.",
                inputSchema: z.object({
                    command: z.string().describe("The command to run with bash -lc"),
                }),
                execute: ({ command }) => this.runCommand(command),
            }),
        };
    }

    private async runCommand(command: string) {
        const container = this.ctx.container;
        if (!container) {
            throw new Error("No container is configured");
        }

        if (!container.running) {
            container.start({
                image: "cloudflare/debian-trixie",
                entrypoint: ["sleep", "infinity"],
                enableInternet: false,
            });
            await container.setInactivityTimeout(INACTIVITY_TIMEOUT_MS);
        }

        // `timeout` stops the command and every process it started.
        const process = await container.exec([
            "timeout",
            "--kill-after=5",
            "60",
            "bash",
            "-lc",
            command,
        ]);
        const output = await process.output();
        const decoder = new TextDecoder();

        return {
            exitCode: output.exitCode,
            stdout: decoder.decode(output.stdout).slice(-MAX_OUTPUT_CHARS),
            stderr: decoder.decode(output.stderr).slice(-MAX_OUTPUT_CHARS),
        };
    }
}

export default {
    async fetch(request: Request, env: Env) {
        return (
            (await routeAgentRequest(request, env)) ||
            new Response("Not found", { status: 404 })
        );
    },
} satisfies ExportedHandler<Env>;

start() 启动 cloudflare/debian-trixie 镜像,这是带 Node.js 和 npm 的 Debian 系统。该镜像的默认命令会立即退出,因此 sleep infinity entrypoint 会在命令之间保持容器运行。enableInternet: false 会阻止出站请求。

setInactivityTimeout() 会在 Agent 变为非活动后将容器再保持运行 10 分钟,以便文件可供下一轮使用。tool 在 start() 之后设置该超时。重启后的 Durable Object 不会带上该超时,因此当容器已在运行时,构造函数会再次设置。更多信息请参阅 setInactivityTimeout。

timeout 会在 60 秒后停止命令及其启动的每个进程。更多信息请参阅停止命令启动的进程。

tool 只返回每个输出流的最后 10,000 个字符,避免嘈杂命令占满模型上下文。

Think 为每个 Agent 提供内置工作区工具,这些工具将文件存储在 Agent 中。沙箱中的命令看不到这些文件。beforeTurn() 中的 activeTools 将模型限制为只能使用 run_command,因此其所有文件操作都发生在沙箱中。

要添加 Python、Git、编译器或其他工具,请构建自己的镜像并将其传给 start()。更多信息请参阅 images。

配置

在 wrangler.jsonc 中将容器附加到 Agent 类。该类还需要 Durable Object 绑定(binding)和 SQLite migration,与任何 Agent 相同。容器需要 Workers 付费计划。

{
    "compatibility_flags": ["nodejs_compat"],
    "ai": {
        "binding": "AI"
    },
    "containers": [
        {
            "class_name": "CodeAgent",
            "scheduling_policy": "durable_object"
        }
    ],
    "durable_objects": {
        "bindings": [
            {
                "class_name": "CodeAgent",
                "name": "CodeAgent"
            }
        ]
    },
    "migrations": [
        {
            "tag": "v1",
            "new_sqlite_classes": ["CodeAgent"]
        }
    ]
}
compatibility_flags = [ "nodejs_compat" ]

[ai]
binding = "AI"

[[containers]]
class_name = "CodeAgent"
scheduling_policy = "durable_object"

[[durable_objects.bindings]]
class_name = "CodeAgent"
name = "CodeAgent"

[[migrations]]
tag = "v1"
new_sqlite_classes = [ "CodeAgent" ]

scheduling_policy: "durable_object" 设置 Durable Object 调度策略,使 Agent 在调用 start() 时可以选择镜像。

网络访问

沙箱启动时没有 Internet 访问,因此 npm install 等命令无法下载软件包。将 enableInternet: true 会允许所有目标。模型编写的命令随后可以把它能读取的任何内容发送到 Internet 上的任何服务器。

若要允许特定主机名,或在请求离开沙箱后添加凭据,请将沙箱发出的请求通过 Worker 中的出站 handler 路由。示例请参阅从沙箱调用已认证 API。

沙箱与 Agent 状态

沙箱中的文件在容器运行期间会保留。容器停止后,下一条命令会从镜像启动新容器,先前的文件会消失。要在容器停止后保留文件,请保存快照并在之后从快照启动。更多信息请参阅使用快照保存和恢复沙箱。

使用 Agent 状态保存用户可见的进度和少量元数据,例如最新快照的 ID。

对于长时间运行的沙箱工作,将沙箱与使用 fiber 的持久化 execution 或 Workflows 配合使用,以便工作超出单次请求时 Agent 能够恢复或报告进度。

安全考虑

模型会读取 run_command 返回的所有内容。沙箱中的文件、软件包或网页可能打印用于引导模型的文本,例如指示再运行另一条命令。在 Agent 于沙箱外根据 tool 结果采取行动之前请先检查这些结果,并对有副作用的 tool 要求审批。

与同一 Agent 实例对话的每个用户共享其沙箱。当用户文件必须隔离时,请为每个用户提供独立的 Agent 实例。

更多信息请参阅沙箱安全。

相关资源

沙箱

在 Containers 或 Dynamic Workers 中运行不受信任或生成的代码。

选择沙箱环境

判断生成的代码需要 Linux,还是只需调用你的 Worker 提供的方法。

Container API

从 Durable Object 启动容器、在其中运行命令并制作快照。

这篇文档对您有帮助吗?