pagentv4 Sandbox
sandbox 是 agent 的伴身电脑,可跑命令、读写文件。后端可以使用独立 workspace, 也可以直接绑定项目目录。各后端统一映射到虚拟 home(默认 /home/agent)。
快捷路径:Runner.create()
给 agent 配电脑的最简方式:
from pagentv4 import DeepSeek, Runner
runner = await Runner.create(
"demo",
DeepSeek("deepseek-v4-flash"),
overrides={"backend": "local"},
)
try:
async for event in runner.run("列出 /home/agent 下的文件,然后创建 notes.md。"):
...
finally:
await runner.close()流程:
- 打开 thread,并按 thread spec 创建 sandbox
- 绑定 sandbox 工具 + 额外工具
- 构建
AgentCore,经runner.run()运行 - 用
runner.close()关闭 sandbox
后端
这四种是并列选项,不是 inplace 的四种写法。对照与选型见 怎么选沙箱后端。
backend= | 说明 |
|---|---|
"local" | 默认。thread workspace 在 ~/.pagent/threads/<thread_id>/workspaces/main/ |
"inplace" | 直接编辑绑定的项目目录,行为与本地 coding CLI 一致 |
"docker" | 容器 + bind mount |
"podman" | 同 docker,用 Podman CLI |
"ssh" | 经 asyncssh 连远端 |
让终端 agent 直接编辑当前目录:
pagent -C .绑定其他目录:
pagent -C /path/to/project-C PROJECT 等同于 --backend inplace --project PROJECT。配置文件和脚本仍可使用 完整参数。
新 thread 会把项目路径写入 thread.toml。之后从其他目录恢复该 thread,仍会编辑 原来的项目。命令和文件工具会直接修改项目内容,使用时应检查工具审批,并用版本控制 保留修改记录。
inplace 提供 run_command、read_file、write_file、str_replace 和 list_dir。项目已经是工作目录,因此不挂载 list_host_files、copy_from_host 和 copy_to_host。
安全试用 inplace
第一次使用时,可以先绑定临时目录:
mkdir -p /tmp/pagent-inplace-test
echo "alpha" > /tmp/pagent-inplace-test/hello.txt
pagent -C /tmp/pagent-inplace-test输入:
读取 hello.txt,把 alpha 改成 beta,然后运行 cat hello.txt 验证。批准工具调用,退出 pagent 后检查原文件:
cat /tmp/pagent-inplace-test/hello.txt
# beta修改会直接写入绑定目录。thread 的对话和配置仍保存在 ~/.pagent/threads/, 该模式不会创建独立 workspace。
runner = await Runner.create(
"demo",
provider,
overrides={"backend": "docker", "image": "python:3.12-slim"},
)
try:
async for event in runner.run(user_input):
...
finally:
await runner.close()SSH 示例,在 thread spec 或 overrides 里设置 ssh_host:
runner = await Runner.create(
"remote",
provider,
overrides={
"backend": "ssh",
"ssh_host": "user@example.com",
"ssh_workdir": "/tmp/agent",
},
)Workspace 布局
thread_id="demo" 时:
~/.pagent/threads/demo/workspace/local 模式的持久化 runner 从 thread 获取 workspace。inplace 模式会把 agent 看到的 /home/agent 下路径映射到绑定的项目目录。
直接使用 Sandbox API
需要更低层控制时,可以直接创建 sandbox,并自行选择 workspace_id 或 workdir:
from pagentv4 import Sandbox
sandbox = await Sandbox.create(backend="local", workspace_id="my-project")
try:
result = await sandbox.commands.run("ls -la")
await sandbox.files.write("hello.txt", "hi")
content = await sandbox.files.read_text("hello.txt")
finally:
await sandbox.close()上下文管理器写法:
async with await Sandbox.create(backend="local", workspace_id="demo") as box:
await box.files.write("hello.txt", "hi")内置 agent 工具
sandbox.tools() 返回 8 个 FunctionTool(见 工具)。 展示给模型的措辞不含 "sandbox" 等内部术语。
与 Thread 集成
Thread 在 ~/.pagent/threads/<id>/ 下保存 sandbox spec 和消息。 local 还会把 workspace 放在这里;inplace 会把绑定的项目路径写入 thread.toml。 进程重启后仍要使用同一台电脑和同一段对话时使用 thread。示例见 examples/pagentv4/runner/sandbox.py。
资源限制
sandbox.commands.run(..., timeout=...) 和 SandboxLimits 限制 stdout、 stderr、内存和 CPU 时间。默认值偏保守,可按 workload 调整。