Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(TUI): add /sandbox command to code agent

zhaozixuan519c4fe2f530
diff --git a/docs/en/SlashCommands.md b/docs/en/SlashCommands.md
index f8cd65fd29..6b372f777f 100644
--- a/docs/en/SlashCommands.md
+++ b/docs/en/SlashCommands.md
@@ -31,6 +31,7 @@ Executed locally in the terminal UI, not through Gateway control pipeline.
| `/evolve_list` | Show one skill's evolution records (see below) |
| `/evolve_simplify` | Simplify and consolidate one skill's evolution records (see below) |
| `/evolve_rebuild` | Rebuild `SKILL.md` from archives and evolution records (see below) |
+| `/sandbox` | Set sandbox mode (see below) |
> Note: `/mode` controlled switching logic is primarily on Gateway side, see "`/mode` and `/switch`" below.
@@ -465,6 +466,42 @@ Timestamp format: `YYYY-MM-DD-HHmmss`.
- `/export my-chat` — Save to `my-chat.txt` in workspace
- `/export 2026-05-09-debug-session.txt` — Save with explicit timestamp name
+### `/sandbox` (Sandbox Mode Management)
+
+Enter / leave jiuwenbox sandbox mode and tune its runtime policy. Calls `command.sandbox` on the agent server.
+
+#### Subcommands
+
+| Command | Description |
+|---|---|
+| `/sandbox` or `/sandbox status` | Show current runtime (`enabled`, `excluded_commands`, `files.allow_write`, `files.deny_write`) |
+| `/sandbox enable` | Enter sandbox mode (spawns jiuwenbox if needed, rebuilds agent) |
+| `/sandbox disable` | Leave sandbox mode (rebuilds agent; stops jiuwenbox only if jiuwenswarm started it) |
+| `/sandbox exclude add <pattern>` | Add a shell glob whose matches run locally instead of in the sandbox |
+| `/sandbox exclude remove <pattern>` | Remove a pattern |
+| `/sandbox exclude list` | List current `excluded_commands` |
+| `/sandbox files allow <path> [perm]` | Allow writing `<path>` inside the sandbox |
+| `/sandbox files deny <path>` | Deny writing `<path>` inside the sandbox |
+| `/sandbox files remove <path>` | Remove `<path>` from the user-configured allow & deny sets |
+| `/sandbox files list` | List effective `allow_write` / `deny_write` |
+| `/sandbox help` | Print usage |
+
+#### Concepts
+
+- **Platform support**: `/sandbox` is Linux-only (jiuwenbox depends on Linux kernel features such as bwrap, Landlock, and Linux namespaces). On a Windows or macOS agent-server, every `/sandbox` sub-command returns a `SANDBOX_BAD_REQUEST` error. If the TUI runs on Windows/macOS but the agent-server is on a Linux host, the command works — what matters is the agent-server's platform.
+- **Effective write policy**: `files.allow_write` / `files.deny_write` in the status panel show the merged view of auto-managed and user-configured entries. Auto-managed entries are server-injected (intrinsic files such as `AGENT.md`, `HEARTBEAT.md`, `IDENTITY.md`, `SOUL.md`, `USER.md`, the `memory/daily_memory/` directory, and depending on the mode, `project_dir` and `config/config.yaml`) and cannot be removed via `/sandbox files remove`.
+- **preserve_file_sharing_mode**: Controlled by jiuwenswarm config, not by `/sandbox`. Only `mount` is supported: intrinsic files and `project_dir` are bind-mounted into the sandbox and `project_dir/config/config.yaml` is explicitly added to `deny_write`. Writing any other value into config.yaml is rejected by the server.
+- **excluded_commands**: Match the full command string (not just `argv[0]`); a match makes that tool call run on the host, effectively granting the command's side effects to the local environment.
+- **Add / remove are strict**: `exclude add` rejects a pattern that is already in the list; `exclude remove` rejects a pattern that is not in the list. `files allow|deny` rejects a path that is already in the same bucket, and rejects a path that exists in the opposite bucket (allow vs deny conflict) — run `files remove` first if you want to flip it. `files remove` rejects paths that have no matching user-configured entry.
+- **enable / disable**: Triggers an agent rebuild. The response lists `rebuilt_modes` (typically `agent.*` / `code.*`) and the jiuwenbox endpoint.
+
+#### Examples
+
+- `/sandbox enable` — turn on sandbox mode
+- `/sandbox status` — see runtime + effective files
+- `/sandbox files allow ./tmp/ 0777` — let the sandbox write into `./tmp/` with mode 0777
+- `/sandbox exclude add "git *"` — let `git` run on the host instead of inside the sandbox
+
### `/status` (Show Status)
Display jiuwenswarm runtime status: overview, usage statistics, or config editor.
diff --git "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md" "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"
index 7d8f3e06a9..74e37e55f6 100644
--- "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"
+++ "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"
@@ -31,6 +31,7 @@
| `/evolve_list` | 查看某个 Skill 的演进经验库(见下文) |
| `/evolve_simplify` | 整理、合并某个 Skill 的演进经验(见下文) |
| `/evolve_rebuild` | 基于归档与演进记录重建 `SKILL.md`(见下文) |
+| `/sandbox` | 设置沙箱模式(见下文) |
> 说明:`/mode` 的受控切换逻辑以 Gateway 侧行为为主,详见下文「`/mode` 与 `/switch`」。
@@ -482,6 +483,42 @@
- `/export my-chat` — 保存到工作空间下的 `my-chat.txt`
- `/export 2026-05-09-debug-session.txt` — 使用显式时间戳文件名保存
+### `/sandbox`(沙箱模式管理)
+
+进入/离开 jiuwenbox 沙箱模式,并调整其运行时策略。通过 `command.sandbox` 与 agent-server 交互。
+
+#### 子命令
+
+| 命令 | 说明 |
+|---|---|
+| `/sandbox` 或 `/sandbox status` | 显示当前 runtime(`enabled`、`excluded_commands`、`files.allow_write`、`files.deny_write`) |
+| `/sandbox enable` | 进入沙箱模式(需要时启动 jiuwenbox,并重建 agent) |
+| `/sandbox disable` | 离开沙箱模式(重建 agent;jiuwenbox 只在 jiuwenswarm 启动时才停掉) |
+| `/sandbox exclude add <pattern>` | 加入一条 shell glob,命中后在本地而非沙箱内执行 |
+| `/sandbox exclude remove <pattern>` | 移除一条 pattern |
+| `/sandbox exclude list` | 列出当前 `excluded_commands` |
+| `/sandbox files allow <path> [perm]` | 允许沙箱内写 `<path>` |
+| `/sandbox files deny <path>` | 拒绝沙箱内写 `<path>` |
+| `/sandbox files remove <path>` | 从 user-configured allow & deny 中移除该 path |
+| `/sandbox files list` | 列出生效的 `allow_write` / `deny_write` |
+| `/sandbox help` | 打印用法 |
+
+#### 概念说明
+
+- **平台限制**:`/sandbox` 仅支持 Linux 平台(jiuwenbox 依赖 bwrap / Landlock / Linux namespace 等内核能力)。 在 Windows / macOS 上运行的 agent-server 收到任何 `/sandbox` 子命令都会返回 `SANDBOX_BAD_REQUEST` 错误;如果 TUI 在 Mac/Windows 上、agent-server 在 Linux 主机上,是支持的(看 agent-server 所在主机的平台)。
+- **生效写入策略**:状态面板里的 `files.allow_write` / `files.deny_write` 是 auto-managed 与 user-configured 合并后的视图。auto-managed 条目由服务端自动注入(intrinsic 文件 `AGENT.md`、`HEARTBEAT.md`、`IDENTITY.md`、`SOUL.md`、`USER.md`,`memory/daily_memory/` 目录,以及按 mode 决定的 `project_dir` 与 `config/config.yaml`),不能通过 `/sandbox files remove` 移除。
+- **preserve_file_sharing_mode**:由 jiuwenswarm 配置决定,不通过 `/sandbox` 切换。仅支持 `mount`:intrinsic 文件与 `project_dir` 通过 bind mount 注入沙箱,`project_dir/config/config.yaml` 会显式加进 `deny_write`;yaml 里写入其它值会被服务端拒绝。
+- **excluded_commands**:按完整命令字符串匹配(不是只看 `argv[0]`),命中后该次调用穿透到本地,相当于把对应命令的副作用授权给本地环境。
+- **add / remove 的去重与冲突**:`exclude add` 在已存在同名 pattern 时报错;`exclude remove` 在不存在该 pattern 时报错。`files allow|deny` 在同一 bucket 已有同 path 时报错,在对侧 bucket(allow vs deny)已登记同 path 时也报错,需要先 `files remove` 再 add;`files remove` 在用户配置里找不到该 path 时报错。
+- **enable / disable**:会触发 agent 重建,响应里会列出 `rebuilt_modes`(典型 `agent.*` / `code.*`)和 jiuwenbox 端点。
+
+#### 示例
+
+- `/sandbox enable` — 打开沙箱模式
+- `/sandbox status` — 查看 runtime 与生效路径
+- `/sandbox files allow ./tmp/ 0777` — 允许沙箱以 0777 写入 `./tmp/`
+- `/sandbox exclude add "git *"` — 让 `git` 命令穿透到本地执行,不进沙箱
+
### `/status`(查看运行状态)
显示 jiuwenswarm 运行状态概览、用量统计或配置编辑界面。
diff --git "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md" "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"
index 1f9431fd99..cbe4eb674a 100644
--- "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"
+++ "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"
@@ -87,6 +87,7 @@
| `/branch` | `/fork` | 从当前对话点创建分支会话 | `/branch fix-login-bug` | 全部 |
| `/rewind` | `/checkpoint` | 回退对话到指定轮次之前 | `/rewind 2` | 全部 |
| `/memory` | `/mem` | 记忆管理(状态、文件、开关、目录) | `/memory status` | 全部 |
+| `/sandbox` | - | 进出沙箱模式 / 管理 excluded_commands / files | `/sandbox enable`、`/sandbox status`、`/sandbox files allow ./tmp/` | 全部 |
#### `/resume` 与 `/continue` 在 TUI 中的特殊行为
@@ -249,6 +250,21 @@
- `open` — 显示记忆系统各目录路径。
- 示例:`/memory status`、`/memory toggle memory_enabled`、`/memory edit memory/MEMORY.md`。
+#### `/sandbox`(沙箱模式管理)
+
+- 平台限制:仅在 Linux 上的 agent-server 可用;Windows / macOS 的 agent-server 收到 `/sandbox` 命令会直接返回错误。TUI 本身跑在哪个平台不影响——只要 agent-server 在 Linux 上即可。
+- 子命令:`status`(默认)/ `enable` / `disable` / `exclude add|remove|list` / `files allow|deny|remove|list` / `help`。
+- `enable` 行为:必要时启动 jiuwenbox(已有 endpoint 则复用),随后触发 agent 重建;响应面板会显示 `rebuilt_modes` 与 jiuwenbox 端点。
+- `disable` 行为:重建 agent;只有 jiuwenswarm 自己启动的 jiuwenbox 才会被停掉,外部 endpoint 会显式保留。
+- 状态面板字段:
+ - `enabled` — 当前开关。
+ - `excluded_commands` — 命中后穿透到本地执行的 shell glob 列表。
+ - `files.allow_write` / `files.deny_write` — 生效(auto-managed ∪ user-configured,去重)的写入策略。
+- 自动配置路径:文件 `AGENT.md`、`HEARTBEAT.md`、`IDENTITY.md`、`SOUL.md`、`USER.md`,目录 `memory/daily_memory/`,以及 `project_dir`(allow_write)与 `project_dir/config/config.yaml`(deny_write)。`preserve_file_sharing_mode` 仅支持 `mount`。
+- `excluded_commands` 的匹配:按完整命令字符串匹配,不仅看 `argv[0]`;写 glob 时要把参数也覆盖进去(例如 `"git *"` 而不是 `git`)。本质等同于沙箱穿透口,不要对 `rm -rf` / `curl` 这类高风险命令使用。
+- add / remove 严格校验:`exclude add` 已存在 pattern、`exclude remove` 不存在 pattern 都会报错;`files allow|deny` 在同 bucket 已有 path 或对侧 bucket 已有 path(allow/deny 冲突)会报错,先 `files remove` 再 add;`files remove` 没匹配到也会报错。避免"看起来执行了实际什么也没改"。
+- 示例:`/sandbox enable`、`/sandbox status`、`/sandbox files allow ./tmp/ 0777`、`/sandbox exclude add "git *"`。
+
#### `/clear` 与忙状态
- 若 `session is busy`(正在处理),`/clear` 会拒绝执行,需先中断任务(**`Ctrl+C`** 第一次中断;默认构建无 `/cancel` 命令)。
diff --git a/jiuwenbox/README.md b/jiuwenbox/README.md
index 547dccf9b8..e5ba655888 100644
--- a/jiuwenbox/README.md
+++ b/jiuwenbox/README.md
@@ -432,11 +432,10 @@ sandbox:
# -- Startup & policy --
startup_mode: "internal" # internal = agent-server spawns jiuwenbox-server; external = you start it yourself
policy_file: "code-agent-policy.yaml" # bare name -> jiuwenbox/configs/<name>; otherwise an absolute / explicit path
- preserve_file_sharing_mode: "mount" # mount = bind-mount intrinsic files + project_dir; copy = upload intrinsic files after start
+ preserve_file_sharing_mode: "mount" # only `mount` is supported; any other value is rejected
# -- Runtime (also managed by the /sandbox TUI command) --
enabled: true # whether sandbox mode is on
- permission_ask: true # whether tool calls inside the sandbox go through the permission-ask flow
excluded_commands: # shell globs whose matches run locally instead of in the sandbox
- "git *"
files: # user-configured write policy; auto-managed paths are injected by the server, no need to repeat them here
@@ -452,9 +451,8 @@ Field reference:
| `sandbox.type` | string | `jiuwenbox` | Sandbox provider name. Currently jiuwenswarm only wires up `jiuwenbox`. |
| `sandbox.startup_mode` | `internal` / `external` | `internal` | `internal`: agent-server spawns `jiuwenbox-server` at boot and persists the effective `url` (auto-picks a free port if the configured one is busy). `external`: agent-server never touches jiuwenbox; you must start it yourself per the top of this README. |
| `sandbox.policy_file` | filename or path | `code-agent-policy.yaml` | Bare filename → resolved relative to `jiuwenbox/configs/`; otherwise expanded (`~`, `$VAR`) and used verbatim. **Only honored under `startup_mode=internal`**; in `external` mode the policy is chosen by whoever started jiuwenbox-server (via `JIUWENBOX_DEFAULT_POLICY_PATH`). |
-| `sandbox.preserve_file_sharing_mode` | `mount` / `copy` | `mount` | `mount`: intrinsic files and `project_dir` are bind-mounted, with `project_dir/config/config.yaml` auto-denied for write. `copy`: the provider uploads intrinsic files into the sandbox after start; `project_dir` is not mounted and `config.yaml` does not need a deny. |
+| `sandbox.preserve_file_sharing_mode` | `mount` | `mount` | Intrinsic files (`AGENT.md` etc.) and `project_dir` are bind-mounted, with `project_dir/config/config.yaml` auto-added to `deny_write`. Writing any other value is rejected. |
| `sandbox.enabled` | bool | `false` | When true, agent rebuilds route tools through the sandbox provider; toggled by `/sandbox enable`. |
-| `sandbox.permission_ask` | bool | `true` | Whether sandboxed tool calls go through the PermissionEngine ask flow. |
| `sandbox.excluded_commands` | list[str] | `[]` | Shell globs matched against the **full command string**; a match makes that single call run locally instead of in the sandbox. |
| `sandbox.files.allow` / `sandbox.files.deny` | list | `[]` | User-configured write policy. The effective set shown by `/sandbox status` is `auto_managed ∪ user_configured`; see [the `/sandbox` design doc](../../agent-core/docs/en/2.Development%20Guide/Sandbox%20and%20sandbox%20command.md). |
@@ -488,16 +486,12 @@ sandbox:
url: "http://10.0.0.5:8321" # or unix:///run/jiuwenbox/jiuwenbox.sock
type: "jiuwenbox"
startup_mode: "external"
- preserve_file_sharing_mode: "copy" # remote jiuwenbox can't see host paths, copy is the natural choice
enabled: true
```
Under this mode agent-server **does not** try to spawn jiuwenbox, and `sandbox.policy_file` has **no effect** (the policy is whatever you passed to `jiuwenbox-server` via `JIUWENBOX_DEFAULT_POLICY_PATH`). See [`Start The Server`](#start-the-server) and [`Unix Domain Socket Deployment`](#unix-domain-socket-deployment) above for how to start jiuwenbox-server in TCP or UDS mode.
-For cross-host setups:
-
-- Set `preserve_file_sharing_mode` to `copy` so jiuwenswarm uploads intrinsic files (`AGENT.md`, `HEARTBEAT.md`, `IDENTITY.md`, `SOUL.md`, `USER.md`, `memory/daily_memory/`) into the sandbox after startup, instead of relying on host paths.
-- On the jiuwenbox host, make sure the policy allows those intrinsic files to be writable inside the sandbox (the bundled `jiuwenbox/configs/code-agent-policy.yaml` already does).
+For cross-host setups, the jiuwenbox host has to be able to reach jiuwenswarm's intrinsic agent files on the same host paths: `preserve_file_sharing_mode` is now fixed to `mount`, so jiuwenswarm bind-mounts the intrinsic files (`AGENT.md`, `HEARTBEAT.md`, `IDENTITY.md`, `SOUL.md`, `USER.md`, `memory/daily_memory/`) and `project_dir` into the sandbox. Make the relevant directories visible on the jiuwenbox machine (via shared filesystem, container volume, etc.) and confirm the policy allows writes into them (the bundled `jiuwenbox/configs/code-agent-policy.yaml` already does).
## Inference Privacy Proxy
diff --git a/jiuwenbox/README_CN.md b/jiuwenbox/README_CN.md
index f47944a7a4..685464dd05 100644
--- a/jiuwenbox/README_CN.md
+++ b/jiuwenbox/README_CN.md
@@ -413,11 +413,10 @@ sandbox:
# —— 启动方式 & policy ——
startup_mode: "internal" # internal=agent-server 自动拉起 jiuwenbox-server;external=用户自行启动
policy_file: "code-agent-policy.yaml" # 仅文件名 → jiuwenbox/configs/<name>;含 / 或绝对路径 → 整路径
- preserve_file_sharing_mode: "mount" # mount=bind mount intrinsic 文件 + project_dir;copy=沙箱启动后上传 intrinsic
+ preserve_file_sharing_mode: "mount" # 仅支持 mount;写入其它值会被服务端拒绝
# —— 运行时(也可由 /sandbox 命令维护) ——
enabled: true # 是否处于沙箱模式
- permission_ask: true # 沙箱内工具调用是否走 permission ask 流程
excluded_commands: # shell glob,命中后绕过沙箱在本地执行
- "git *"
files: # 用户配置的写入策略(auto-managed 路径不需要写在这里,服务端会自动注入)
@@ -433,9 +432,8 @@ sandbox:
| `sandbox.type` | 字符串 | `jiuwenbox` | sandbox provider 名。当前 jiuwenswarm 只接通了 `jiuwenbox` |
| `sandbox.startup_mode` | `internal` / `external` | `internal` | `internal`:agent-server 启动时自动 spawn `jiuwenbox-server` 子进程并落盘最终生效的 `url`(端口被占用时自动换端口);`external`:jiuwenswarm 完全不碰 jiuwenbox 进程,要求按本 README 顶部的方式提前自己启动 |
| `sandbox.policy_file` | 文件名 / 路径 | `code-agent-policy.yaml` | 仅给文件名 → 自动定位到 `jiuwenbox/configs/<name>`;包含 `/` `\` 或 `~` 时按整路径解析。**仅在 `startup_mode=internal` 下生效**——`external` 模式下 policy 由用户自启动时的 `JIUWENBOX_DEFAULT_POLICY_PATH` 决定 |
-| `sandbox.preserve_file_sharing_mode` | `mount` / `copy` | `mount` | `mount`:intrinsic 文件 + `project_dir` 通过 bind mount 注入,`project_dir/config/config.yaml` 自动 deny_write;`copy`:沙箱启动后由 provider 把 intrinsic 文件上传进沙箱,不挂载 `project_dir`,无需 deny `config.yaml` |
+| `sandbox.preserve_file_sharing_mode` | `mount` | `mount` | intrinsic 文件(`AGENT.md` 等)与 `project_dir` 通过 bind mount 注入沙箱,`project_dir/config/config.yaml` 自动加进 `deny_write`。 写入其它值会被服务端拒绝 |
| `sandbox.enabled` | bool | `false` | 启用后 agent 在重建时会切到 sandbox provider;可用 `/sandbox enable` 触发 |
-| `sandbox.permission_ask` | bool | `true` | 沙箱内工具调用是否走 PermissionEngine 的 ask 流程 |
| `sandbox.excluded_commands` | list[str] | `[]` | shell glob 列表;按**整条命令字符串**匹配,命中后该次调用穿透到本地 |
| `sandbox.files.allow` / `sandbox.files.deny` | list | `[]` | 用户额外配置的写入策略;最终生效集合是 `auto_managed ∪ user_configured`,详见 [`/sandbox` 命令设计文档](../../agent-core/docs/zh/2.开发指南/沙箱与%20sandbox%20命令.md) |
@@ -469,16 +467,12 @@ sandbox:
url: "http://10.0.0.5:8321" # 或 unix:///run/jiuwenbox/jiuwenbox.sock
type: "jiuwenbox"
startup_mode: "external"
- preserve_file_sharing_mode: "copy" # 远端 jiuwenbox 看不到宿主目录,常用 copy 模式
enabled: true
```
此模式下 agent-server **不会**尝试拉起 jiuwenbox,`sandbox.policy_file` 也**不生效**(policy 由你启动 jiuwenbox-server 时通过 `JIUWENBOX_DEFAULT_POLICY_PATH` 指定)。jiuwenbox-server 的启动方式见前文 [`启动服务`](#启动服务) 与 [`通过 Unix Domain Socket 部署`](#通过-unix-domain-socket-部署)。
-跨机时配置:
-
-- 把 `preserve_file_sharing_mode` 设为 `copy`,让 jiuwenswarm 在沙箱启动后把 intrinsic 文件(`AGENT.md` / `HEARTBEAT.md` / `IDENTITY.md` / `SOUL.md` / `USER.md` / `memory/daily_memory/`)上传进去,避免依赖宿主路径。
-- 在 jiuwenbox 主机的 policy 里允许这些 intrinsic 文件被沙箱内写入(参考仓库内 `jiuwenbox/configs/code-agent-policy.yaml`)。
+跨机部署要求 jiuwenbox 主机能访问 jiuwenswarm 的固有 agent 文件路径——`preserve_file_sharing_mode` 现在只支持 `mount` jiuwenswarm 会把 intrinsic 文件(`AGENT.md` / `HEARTBEAT.md` / `IDENTITY.md` / `SOUL.md` / `USER.md` / `memory/daily_memory/`)和 `project_dir` 通过 bind mount 暴露给沙箱,因此目标主机必须能在同样的 host path 下看到这些文件(例如共享文件系统、容器 volume 等)。
## 推理隐私代理
@@ -561,7 +555,7 @@ inference_privacy_proxies:
代理转发: POST http://192.168.1.100:9000/v1/chat/completions -H "Authorization: Bearer sk_sandbox_managed_custom_key"
```
-#### jiuwenswarm配置示例
+#### jiuwenswarm 配置示例
| 配置项 | 旧值 | 新值 |
diff --git a/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py b/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py
index 6e64c91b3e..41f9888711 100644
--- a/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py
+++ b/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py
@@ -93,6 +93,24 @@ class BwrapConfig:
cap_add: list[str] = field(default_factory=list)
cap_drop: list[str] = field(default_factory=list)
+ # ``--die-with-parent``: arm ``PR_SET_PDEATHSIG=SIGKILL`` on every bwrap
+ # process in the sandbox chain (outer monitor, inner pid-namespace init,
+ # and the launched command). When jiuwenbox-server dies for *any* reason
+ # -- clean lifespan shutdown, crash, SIGKILL by an operator, parent
+ # jiuwenswarm being SIGKILLed before its grace window expired -- the
+ # kernel immediately SIGKILLs the bwrap monitor, which in turn cascades
+ # the kill into the pid namespace via bwrap's own ``--die-with-parent``
+ # propagation. Without this flag the sandbox-daemon.py + bwrap monitor
+ # stay alive after box-server vanishes (they were spawned with
+ # ``start_new_session=True`` so they own their own pgrp/session and
+ # nothing else kills them), showing up as long-lived ``bwrap ...
+ # --daemon /jiuwenbox/sandbox-daemon.py`` processes on the host that
+ # outlive every jiuwenbox lifecycle. The defensive layer is intentional:
+ # the normal teardown path (``runtime.stop`` -> SIGTERM/SIGKILL the
+ # daemon pgrp from lifespan) handles the cooperative case, and this
+ # flag covers every uncooperative one.
+ die_with_parent: bool = True
+
# filesystem
rootfs: str | None = None
ro_binds: list[tuple[str, str]] = field(default_factory=list)
@@ -294,6 +312,12 @@ class BwrapConfig:
if self.unshare_user and self.gid is not None:
args.extend(["--gid", str(self.gid)])
+ if self.die_with_parent:
+ # Placed after the namespace flags so it visually groups with
+ # other lifecycle controls in ``ps -ef`` output. bwrap accepts
+ # the flag at any position before the command.
+ args.append("--die-with-parent")
+
for cap in self.cap_add:
args.extend(["--cap-add", cap])
for cap in self.cap_drop:
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.ts
new file mode 100644
index 0000000000..eafa17057f
--- /dev/null
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.ts
@@ -0,0 +1,267 @@
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+type SandboxFileEntry =
+ | string
+ | { path: string; permissions?: string; kind?: "file" | "directory" };
+
+type SandboxRuntime = {
+ enabled?: boolean;
+ excluded_commands?: string[];
+ files?: { allow?: SandboxFileEntry[]; deny?: SandboxFileEntry[] };
+};
+
+type SandboxEffectiveFiles = {
+ allow_write?: SandboxFileEntry[];
+ deny_write?: SandboxFileEntry[];
+};
+
+type SandboxResponse = {
+ runtime?: SandboxRuntime;
+ excluded_commands?: string[];
+ files?: { allow?: SandboxFileEntry[]; deny?: SandboxFileEntry[] };
+ effective_files?: SandboxEffectiveFiles;
+ jiuwenbox?: { host?: string; port?: number; ready?: boolean };
+ agent_recreated?: boolean;
+ rebuilt_modes?: string[];
+ jiuwenbox_stopped?: boolean;
+};
+
+function tokenize(raw: string): string[] {
+ const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
+ const out: string[] = [];
+ let match: RegExpExecArray | null;
+ while ((match = re.exec(raw)) !== null) {
+ out.push(match[1] ?? match[2] ?? match[3] ?? "");
+ }
+ return out;
+}
+
+function formatBool(value: unknown): string {
+ return value === true ? "on" : "off";
+}
+
+function formatFileEntry(entry: SandboxFileEntry): string {
+ if (typeof entry === "string") return entry;
+ if (entry && typeof entry === "object") {
+ const path = String(entry.path ?? "");
+ const perm = entry.permissions ? ` (${entry.permissions})` : "";
+ return `${path}${perm}`;
+ }
+ return String(entry);
+}
+
+function showRuntime(
+ ctx: Parameters<SlashCommand["action"]>[0],
+ runtime: SandboxRuntime | undefined,
+ effective?: SandboxEffectiveFiles,
+): void {
+ const rt = runtime ?? {};
+ const excludes = rt.excluded_commands ?? [];
+ const allowWrite = effective?.allow_write ?? rt.files?.allow ?? [];
+ const denyWrite = effective?.deny_write ?? rt.files?.deny ?? [];
+ ctx.addItem(
+ addInfo(ctx.sessionId, "Sandbox status", "s", {
+ view: "kv",
+ title: "Sandbox Runtime",
+ items: [
+ { label: "enabled", value: formatBool(rt.enabled) },
+ {
+ label: "excluded_commands",
+ value: excludes.length ? excludes.join(", ") : "(empty)",
+ },
+ {
+ label: "files.allow_write",
+ value: allowWrite.length ? allowWrite.map(formatFileEntry).join(", ") : "(empty)",
+ },
+ {
+ label: "files.deny_write",
+ value: denyWrite.length ? denyWrite.map(formatFileEntry).join(", ") : "(empty)",
+ },
+ ],
+ }),
+ );
+}
+
+function usageText(): string {
+ return [
+ "/sandbox show current runtime status",
+ "/sandbox enable enter sandbox mode (spawns jiuwenbox + recreates agent)",
+ "/sandbox disable leave sandbox mode (recreates agent)",
+ "/sandbox exclude add <pattern> add a glob whose match runs locally instead of sandbox",
+ "/sandbox exclude remove <pattern> remove a previously added pattern",
+ "/sandbox exclude list list current excluded_commands",
+ "/sandbox files allow <path> [perm] allow accessing <path> in sandbox (trailing / => directory)",
+ "/sandbox files deny <path> deny accessing <path> in sandbox",
+ "/sandbox files remove <path> remove the path from both allow & deny",
+ "/sandbox files list list configured files",
+ ].join("\n");
+}
+
+export function createSandboxCommand(): SlashCommand {
+ return {
+ name: "sandbox",
+ description: "Manage jiuwenbox sandbox mode",
+ usage: "/sandbox <enable|disable|exclude|files> ...",
+ example: "/sandbox enable",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ const raw = (args ?? "").trim();
+ const tokens = tokenize(raw);
+ const sub = (tokens[0] ?? "").toLowerCase();
+
+ try {
+ if (!sub || sub === "status" || sub === "show") {
+ const payload = await ctx.request<SandboxResponse>("command.sandbox", { sub: "status" });
+ showRuntime(ctx, payload.runtime, payload.effective_files);
+ return;
+ }
+
+ if (sub === "help") {
+ ctx.addItem(addInfo(ctx.sessionId, usageText(), "s"));
+ return;
+ }
+
+ if (sub === "enable") {
+ const payload = await ctx.request<SandboxResponse>("command.sandbox", { sub: "enable" });
+ const jb = payload.jiuwenbox;
+ const host = jb?.host ?? "127.0.0.1";
+ const port = jb?.port ?? 8321;
+ const rebuilt = payload.rebuilt_modes ?? [];
+ const rebuiltText = rebuilt.length ? ` (rebuilt: ${rebuilt.join(", ")})` : "";
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ `Sandbox enabled (jiuwenbox @ ${host}:${port}); agent rebuilt${rebuiltText}.`,
+ "s",
+ ),
+ );
+ showRuntime(ctx, payload.runtime, payload.effective_files);
+ return;
+ }
+
+ if (sub === "disable") {
+ const payload = await ctx.request<SandboxResponse>("command.sandbox", { sub: "disable" });
+ const rebuilt = payload.rebuilt_modes ?? [];
+ const rebuiltText = rebuilt.length ? ` (rebuilt: ${rebuilt.join(", ")})` : "";
+ const jb = payload.jiuwenbox;
+ let jbText = "";
+ if (payload.jiuwenbox_stopped) {
+ const host = jb?.host ?? "127.0.0.1";
+ const port = jb?.port ?? 8321;
+ jbText = `; jiuwenbox stopped @ ${host}:${port}`;
+ } else if (jb?.host && jb?.port) {
+ jbText = `; jiuwenbox @ ${jb.host}:${jb.port} left running (external)`;
+ }
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ `Sandbox disabled; agent rebuilt${rebuiltText}${jbText}.`,
+ "s",
+ ),
+ );
+ showRuntime(ctx, payload.runtime, payload.effective_files);
+ return;
+ }
+
+ if (sub === "exclude") {
+ const op = (tokens[1] ?? "list").toLowerCase();
+ if (op === "list") {
+ const payload = await ctx.request<SandboxResponse>("command.sandbox", { sub: "exclude.list" });
+ const patterns = payload.excluded_commands ?? [];
+ ctx.addItem(
+ addInfo(ctx.sessionId, `excluded_commands (${patterns.length})`, "s", {
+ view: "list",
+ title: "Sandbox Exclude Patterns",
+ items: patterns.length
+ ? patterns.map((p, i) => ({ label: String(i + 1), value: p }))
+ : [{ label: "—", value: "(empty)" }],
+ }),
+ );
+ return;
+ }
+ if (op === "add" || op === "remove") {
+ const pattern = tokens.slice(2).join(" ").trim();
+ if (!pattern) {
+ ctx.addItem(addError(ctx.sessionId, `Missing pattern. Usage: /sandbox exclude ${op} <pattern>`));
+ return;
+ }
+ const payload = await ctx.request<SandboxResponse>("command.sandbox", {
+ sub: op === "add" ? "exclude.add" : "exclude.remove",
+ pattern,
+ });
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ `${op === "add" ? "Added" : "Removed"} exclude pattern: ${pattern}`,
+ "s",
+ ),
+ );
+ showRuntime(ctx, payload.runtime, payload.effective_files);
+ return;
+ }
+ ctx.addItem(addError(ctx.sessionId, "Usage: /sandbox exclude <add|remove|list> [pattern]"));
+ return;
+ }
+
+ if (sub === "files") {
+ const op = (tokens[1] ?? "list").toLowerCase();
+ if (op === "list") {
+ const payload = await ctx.request<SandboxResponse>("command.sandbox", { sub: "files.list" });
+ const effective = payload.effective_files ?? {};
+ const files = payload.files ?? {};
+ const allowWrite = effective.allow_write ?? files.allow ?? [];
+ const denyWrite = effective.deny_write ?? files.deny ?? [];
+ ctx.addItem(
+ addInfo(ctx.sessionId, "Sandbox files", "s", {
+ view: "kv",
+ title: "Sandbox Files",
+ items: [
+ {
+ label: "allow_write",
+ value: allowWrite.length ? allowWrite.map(formatFileEntry).join(", ") : "(empty)",
+ },
+ {
+ label: "deny_write",
+ value: denyWrite.length ? denyWrite.map(formatFileEntry).join(", ") : "(empty)",
+ },
+ ],
+ }),
+ );
+ return;
+ }
+ if (op === "allow" || op === "deny" || op === "remove") {
+ const path = tokens[2];
+ const perm = tokens[3];
+ if (!path) {
+ ctx.addItem(addError(ctx.sessionId, `Missing path. Usage: /sandbox files ${op} <path> [permissions]`));
+ return;
+ }
+ const subAction =
+ op === "allow" ? "files.allow" : op === "deny" ? "files.deny" : "files.remove";
+ const params: Record<string, unknown> = { sub: subAction, path };
+ if (perm) params.permissions = perm;
+ const payload = await ctx.request<SandboxResponse>("command.sandbox", params);
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ `${op === "allow" ? "Allowed" : op === "deny" ? "Denied" : "Removed"}: ${path}`,
+ "s",
+ ),
+ );
+ showRuntime(ctx, payload.runtime, payload.effective_files);
+ return;
+ }
+ ctx.addItem(addError(ctx.sessionId, "Usage: /sandbox files <allow|deny|remove|list> [path]"));
+ return;
+ }
+
+ ctx.addItem(addError(ctx.sessionId, `Unknown sub-command: ${sub}\n${usageText()}`));
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `sandbox failed: ${message}`));
+ }
+ },
+ };
+}
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
index c6e06129e8..cf2b44c20f 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
@@ -30,6 +30,7 @@ import { createPlanCommand } from "./builtins/plan.js";
import { createResumeCommand } from "./builtins/resume.js";
import { createRenameCommand } from "./builtins/rename.js";
import { createRewindCommand } from "./builtins/rewind.js";
+import { createSandboxCommand } from "./builtins/sandbox.js";
import { createSessionCommand } from "./builtins/session.js";
import { createStatusCommand } from "./builtins/status.js";
import { createStatusLineCommand } from "./builtins/statusline.js";
@@ -67,6 +68,7 @@ export function createBuiltinCommands(): SlashCommand[] {
createResumeCommand(),
createRenameCommand(),
createRewindCommand(),
+ createSandboxCommand(),
createSessionCommand(),
createSkillsCommand(),
createStatusCommand(),
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.py
index cd528d4e78..f3b0003a30 100644
--- a/jiuwenswarm/common/config.py
+++ b/jiuwenswarm/common/config.py
@@ -1305,3 +1305,432 @@ def get_model_config(name: str, index: int | None = None) -> dict[str, Any] | No
return entry
return matches[0][1]
return models.get(name) if name in models else None
+
+
+# =====================================================================
+# Sandbox runtime config
+#
+# 字段挂在 ``sandbox`` 顶层 (与 ``url`` / ``type`` / ``startup_mode`` /
+# ``policy_file`` / ``preserve_file_sharing_mode`` 并列):
+#
+# sandbox:
+# url: ...
+# enabled: true
+# excluded_commands: [...]
+# files: { allow: [...], deny: [...] }
+#
+# ``get_sandbox_runtime`` 把这些 key 读出来填默认值;
+# ``update_sandbox_runtime`` 写回时也只动这几个 key, 不动 endpoint 字段。
+# =====================================================================
+
+_SANDBOX_RUNTIME_DEFAULTS: dict[str, Any] = {
+ "enabled": False,
+ "excluded_commands": [],
+ "files": {"allow": [], "deny": []},
+}
+
+# 受 ``get_sandbox_runtime`` / ``update_sandbox_runtime`` 管辖的 sandbox 字段。
+_SANDBOX_RUNTIME_KEYS: tuple[str, ...] = tuple(_SANDBOX_RUNTIME_DEFAULTS.keys())
+
+
+def _ensure_sandbox_runtime_shape(runtime: Any) -> dict[str, Any]:
+ """填充 sandbox runtime 缺省字段,返回归一化后的 dict(不写盘)。"""
+ base = {k: (list(v) if isinstance(v, list) else dict(v) if isinstance(v, dict) else v)
+ for k, v in _SANDBOX_RUNTIME_DEFAULTS.items()}
+ if not isinstance(runtime, dict):
+ return base
+ out = dict(base)
+ if "enabled" in runtime:
+ out["enabled"] = bool(runtime["enabled"])
+ raw_excluded = runtime.get("excluded_commands")
+ if isinstance(raw_excluded, list):
+ out["excluded_commands"] = [
+ str(p) for p in raw_excluded if str(p).strip()
+ ]
+ files = runtime.get("files")
+ if isinstance(files, dict):
+ allow = files.get("allow")
+ deny = files.get("deny")
+ out["files"] = {
+ "allow": list(allow) if isinstance(allow, list) else [],
+ "deny": list(deny) if isinstance(deny, list) else [],
+ }
+ return out
+
+
+def get_sandbox_runtime() -> dict[str, Any]:
+ """返回 sandbox runtime 当前内容 (含缺省字段填充)。
+
+ 直接从 ``sandbox.<key>`` 扁平字段读; 字段缺失时用 ``_SANDBOX_RUNTIME_DEFAULTS``。
+ """
+ cfg = get_config() or {}
+ sandbox = cfg.get("sandbox")
+ if not isinstance(sandbox, dict):
+ return _ensure_sandbox_runtime_shape(None)
+ raw = {key: sandbox[key] for key in _SANDBOX_RUNTIME_KEYS if key in sandbox}
+ return _ensure_sandbox_runtime_shape(raw)
+
+
+# ``preserve_file_sharing_mode`` 当前合法取值集合 = ``{"mount"}``; 空值表示
+# "未配置, 按默认走"。
+_VALID_PRESERVE_FILE_SHARING_MODES = ("mount",)
+_DEFAULT_PRESERVE_FILE_SHARING_MODE = "mount"
+
+
+def _normalize_preserve_file_sharing_mode(value: Any) -> str | None:
+ """归一化 ``sandbox.preserve_file_sharing_mode``.
+
+ - ``None`` / 空字符串 → 返回 ``None`` (表示 "未配置", 调用方按默认值处理).
+ - ``"mount"`` (大小写不敏感, 前后空格) → 返回 ``"mount"``.
+ - 其它任何取值 → 抛 ``ValueError``, 让调用方拒绝该 yaml / API 输入。
+ """
+ if value is None:
+ return None
+ text = str(value).strip().lower()
+ if not text:
+ return None
+ if text not in _VALID_PRESERVE_FILE_SHARING_MODES:
+ raise ValueError(
+ f"sandbox.preserve_file_sharing_mode must be one of "
+ f"{_VALID_PRESERVE_FILE_SHARING_MODES}, got {value!r}"
+ )
+ return text
+
+
+_VALID_SANDBOX_STARTUP_MODES = ("internal", "external")
+_DEFAULT_SANDBOX_STARTUP_MODE = "internal"
+_DEFAULT_SANDBOX_POLICY_FILE = "code-agent-policy.yaml"
+
+# Public re-exports for callers that need to fall back to / advertise defaults
+# (e.g. agent_ws_server 把缺省值持久化到 config.yaml, 让重启后 get_sandbox_endpoint
+# 能直接读到, 而不必每次再走一遍 fallback 逻辑)。
+DEFAULT_SANDBOX_STARTUP_MODE = _DEFAULT_SANDBOX_STARTUP_MODE
+DEFAULT_SANDBOX_POLICY_FILE = _DEFAULT_SANDBOX_POLICY_FILE
+
+
+def _normalize_sandbox_startup_mode(value: Any) -> str:
+ """归一化 ``sandbox.startup_mode``; 非法或空值回落到默认 ``internal``."""
+ text = str(value or "").strip().lower()
+ if text not in _VALID_SANDBOX_STARTUP_MODES:
+ return _DEFAULT_SANDBOX_STARTUP_MODE
+ return text
+
+
+def get_sandbox_startup_mode() -> str:
+ """返回 ``sandbox.startup_mode``: ``internal`` (agent-server 拉起 jiuwenbox)
+ 或 ``external`` (用户自己启动 jiuwenbox)。
+
+ 未配置时默认 ``internal`` (当前 code-agent 模式预期行为)。
+ """
+ cfg = get_config() or {}
+ sandbox = cfg.get("sandbox") or {}
+ return _normalize_sandbox_startup_mode(sandbox.get("startup_mode"))
+
+
+def get_sandbox_startup_mode_explicit() -> str | None:
+ """同 :func:`get_sandbox_startup_mode`, 但仅返回 ``config.yaml`` 里**显式**
+ 写出的合法值 (``internal`` / ``external``); 未配置 / 空串 / 非法值都返回
+ ``None``。
+
+ 用途: agent-server boot 时判断要不要自动拉起 jiuwenbox 子进程。
+ ``get_sandbox_startup_mode`` 默认归一会把缺失字段变成 ``internal``, 那样
+ 会让从来没碰过沙箱的用户在升级到带 bootstrap 逻辑的版本后, 突然多出一个
+ jiuwenbox 进程。靠这个 ``_explicit`` 变体可以严格区分 "用户主动选了 internal"
+ 和 "字段不存在, 走的默认"。
+ """
+ cfg = get_config() or {}
+ sandbox = cfg.get("sandbox") or {}
+ raw = sandbox.get("startup_mode")
+ if not isinstance(raw, str):
+ return None
+ text = raw.strip().lower()
+ if text not in _VALID_SANDBOX_STARTUP_MODES:
+ return None
+ return text
+
+
+def update_sandbox_startup_mode(mode: str) -> str:
+ """写入 ``sandbox.startup_mode`` 到 config.yaml; 返回归一化后的值。"""
+ normalized = _normalize_sandbox_startup_mode(mode)
+ if str(mode or "").strip().lower() not in _VALID_SANDBOX_STARTUP_MODES:
+ raise ValueError(
+ f"startup_mode must be one of {_VALID_SANDBOX_STARTUP_MODES}, got {mode!r}",
+ )
+ data = _load_yaml_round_trip(_CONFIG_YAML_PATH)
+ if "sandbox" not in data or not isinstance(data.get("sandbox"), dict):
+ data["sandbox"] = {}
+ data["sandbox"]["startup_mode"] = normalized
+ _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)
+ return normalized
+
+
+def _looks_like_bare_filename(value: str) -> bool:
+ """``True`` 表示参数应该被解释为 ``jiuwenbox/configs/`` 下的文件名。
+
+ 判据: 不含任何路径分隔符 (``/`` 或 ``os.sep``); 含分隔符或绝对路径一律按整路径处理。
+ """
+ if not value:
+ return False
+ return "/" not in value and "\\" not in value and not Path(value).is_absolute()
+
+
+def _jiuwenbox_configs_dir() -> Path | None:
+ """探测仓库或安装位置上的 ``jiuwenbox/configs/`` 目录。
+
+ 优先在仓库目录树里寻找 (开发场景, ``code_agent/jiuwenbox/configs``);
+ 失败再尝试已 ``pip install`` 的 jiuwenbox 包同级 ``configs/``。
+ """
+ here = Path(__file__).resolve()
+
+ for ancestor in here.parents[1:7]:
+ candidate = ancestor / "jiuwenbox" / "configs"
+ if candidate.is_dir():
+ return candidate
+ try:
+ import jiuwenbox # type: ignore[import-not-found]
+ except ImportError:
+ return None
+ try:
+ pkg_dir = Path(jiuwenbox.__file__).resolve().parent
+ except Exception: # noqa: BLE001
+ return None
+ # wheel 安装版: ``scripts/build.sh`` 把 ``jiuwenbox/configs/`` 临时 stage 到
+ # ``jiuwenbox/src/jiuwenbox/configs/`` 后再打包, 安装后表现为
+ # ``<site-packages>/jiuwenbox/configs/``。优先按这个布局找。
+ direct = pkg_dir / "configs"
+ if direct.is_dir():
+ return direct
+
+ for steps_up in (2, 3):
+ candidate = pkg_dir
+ for _ in range(steps_up):
+ candidate = candidate.parent
+ candidate = candidate / "configs"
+ if candidate.is_dir():
+ return candidate
+ return None
+
+
+def resolve_sandbox_policy_path(value: str | None) -> Path | None:
+ """把 ``sandbox.policy_file`` 的取值解析为宿主机绝对路径。
+
+ - ``None`` / 空字符串 → 返回 None, 由调用方决定是否落到 jiuwenbox 自身默认 policy;
+ - 仅文件名 (不含路径分隔符) → 在 ``jiuwenbox/configs/`` 下拼接;
+ ``configs/`` 探测不到时返回 None (调用方应当报错并提示给绝对路径);
+ - 含 ``/`` ``\`` 或绝对路径 → 展开 ``~`` / ``$VAR`` 后按整路径返回 (不强校验是否存在,
+ 留给上游 ``_load_policy_file`` / jiuwenbox 自己做存在性检查并给出明确错误)。
+ """
+ if not value:
+ return None
+ text = str(value).strip()
+ if not text:
+ return None
+ expanded = os.path.expandvars(os.path.expanduser(text))
+ if _looks_like_bare_filename(expanded):
+ configs_dir = _jiuwenbox_configs_dir()
+ if configs_dir is None:
+ return None
+ return (configs_dir / expanded).resolve()
+ return Path(expanded).resolve()
+
+
+def get_sandbox_policy_file() -> str:
+ """返回 ``sandbox.policy_file`` 原始字符串 (空表示未配置, 由调用方走默认)。"""
+ cfg = get_config() or {}
+ sandbox = cfg.get("sandbox") or {}
+ return str(sandbox.get("policy_file") or "").strip()
+
+
+def get_sandbox_policy_path() -> Path | None:
+ """返回 ``sandbox.policy_file`` 解析后的绝对路径。
+
+ 未配置时回落到 ``_DEFAULT_SANDBOX_POLICY_FILE`` (即 ``code-agent-policy.yaml``);
+ 解析失败 (例如仅给文件名但 ``configs/`` 不可达) 返回 None。
+ """
+ raw = get_sandbox_policy_file() or _DEFAULT_SANDBOX_POLICY_FILE
+ return resolve_sandbox_policy_path(raw)
+
+
+def update_sandbox_policy_file(value: str) -> str:
+ """写入 ``sandbox.policy_file`` (仅文件名或绝对路径) 到 config.yaml; 返回归一化后的字符串。"""
+ text = str(value or "").strip()
+ if not text:
+ raise ValueError("policy_file must be non-empty")
+ data = _load_yaml_round_trip(_CONFIG_YAML_PATH)
+ if "sandbox" not in data or not isinstance(data.get("sandbox"), dict):
+ data["sandbox"] = {}
+ data["sandbox"]["policy_file"] = text
+ _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)
+ return text
+
+
+def get_sandbox_endpoint() -> dict[str, Any]:
+ """返回 ``sandbox.url`` / ``sandbox.type`` / ``sandbox.preserve_file_sharing_mode``
+ / ``sandbox.startup_mode`` / ``sandbox.policy_file``.
+
+ ``preserve_file_sharing_mode`` 缺省或为空时返回空串, 由调用方决定默认值
+ (当前只有 ``"mount"``)。 ``startup_mode`` 未配置时回落到 ``internal``;
+ ``policy_file`` 未配置时返回空串 (由调用方决定默认 policy)。
+
+ Raises:
+ ValueError: yaml 里 ``preserve_file_sharing_mode`` 写了非法值时, 直接
+ 把 :func:`_normalize_preserve_file_sharing_mode` 的异常向上抛, 由
+ 调用方决定要不要兜底 (例如 TUI 命令层会回执给用户看明确错误)。
+ """
+ cfg = get_config() or {}
+ sandbox = cfg.get("sandbox") or {}
+ mode = _normalize_preserve_file_sharing_mode(sandbox.get("preserve_file_sharing_mode"))
+ return {
+ "url": str(sandbox.get("url") or "").strip(),
+ "type": str(sandbox.get("type") or "").strip(),
+ "preserve_file_sharing_mode": mode or "",
+ "startup_mode": _normalize_sandbox_startup_mode(sandbox.get("startup_mode")),
+ "policy_file": str(sandbox.get("policy_file") or "").strip(),
+ }
+
+
+def update_sandbox_endpoint(
+ url: str,
+ sandbox_type: str,
+ *,
+ preserve_file_sharing_mode: str | None = None,
+ startup_mode: str | None = None,
+ policy_file: str | None = None,
+) -> dict[str, Any]:
+ """写入 ``sandbox.url`` / ``sandbox.type`` 以及可选的
+ ``preserve_file_sharing_mode`` / ``startup_mode`` / ``policy_file``
+ 到 config.yaml; 返回实际写入的字段集合 (没有改动的字段不在返回里)。
+
+ 所有 ``None`` 入参表示"本次不修改该字段, 保留 config.yaml 中既有值",
+ 以方便 ``_handle_sandbox_enable`` 在不同阶段分批落盘。
+ """
+ url_value = str(url or "").strip()
+ type_value = str(sandbox_type or "").strip()
+ if not url_value or not type_value:
+ raise ValueError("sandbox url and type must be non-empty")
+ mode_value = _normalize_preserve_file_sharing_mode(preserve_file_sharing_mode)
+
+ startup_value: str | None = None
+ if startup_mode is not None:
+ raw_startup = str(startup_mode).strip().lower()
+ if raw_startup not in _VALID_SANDBOX_STARTUP_MODES:
+ raise ValueError(
+ f"startup_mode must be one of {_VALID_SANDBOX_STARTUP_MODES}, "
+ f"got {startup_mode!r}",
+ )
+ startup_value = raw_startup
+
+ policy_value: str | None = None
+ if policy_file is not None:
+ policy_text = str(policy_file).strip()
+ if not policy_text:
+ raise ValueError("policy_file must be non-empty when provided")
+ policy_value = policy_text
+
+ data = _load_yaml_round_trip(_CONFIG_YAML_PATH)
+ if "sandbox" not in data or not isinstance(data.get("sandbox"), dict):
+ data["sandbox"] = {}
+ data["sandbox"]["url"] = url_value
+ data["sandbox"]["type"] = type_value
+ if mode_value is not None:
+ data["sandbox"]["preserve_file_sharing_mode"] = mode_value
+ if startup_value is not None:
+ data["sandbox"]["startup_mode"] = startup_value
+ if policy_value is not None:
+ data["sandbox"]["policy_file"] = policy_value
+ _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)
+ result: dict[str, Any] = {"url": url_value, "type": type_value}
+ if mode_value is not None:
+ result["preserve_file_sharing_mode"] = mode_value
+ if startup_value is not None:
+ result["startup_mode"] = startup_value
+ if policy_value is not None:
+ result["policy_file"] = policy_value
+ return result
+
+
+def get_sandbox_preserve_file_sharing_mode() -> str | None:
+ """返回 ``sandbox.preserve_file_sharing_mode`` (当前仅 ``"mount"``).
+
+ 未配置返回 ``None`` (调用方按默认走)。 非法取值不在这里兜底, 直接由
+ :func:`_normalize_preserve_file_sharing_mode` 抛 ``ValueError``。
+ """
+ cfg = get_config() or {}
+ sandbox = cfg.get("sandbox") or {}
+ return _normalize_preserve_file_sharing_mode(sandbox.get("preserve_file_sharing_mode"))
+
+
+def resolve_preserve_file_sharing_mode_default() -> str:
+ """返回当前可用的 ``preserve_file_sharing_mode``.
+
+ 优先取 yaml 已配置的值, 否则用默认 (``"mount"``)。 当前合法值只有
+ ``"mount"`` 一个, 函数保留是为了将来若引入新模式时调用点不必再改一遍。
+ """
+ configured = get_sandbox_preserve_file_sharing_mode()
+ return configured or _DEFAULT_PRESERVE_FILE_SHARING_MODE
+
+
+def update_sandbox_preserve_file_sharing_mode(mode: str) -> str:
+ """写入 ``sandbox.preserve_file_sharing_mode``; 返回归一化后的值.
+
+ 空值与非法值都会抛 ``ValueError``——写入路径不允许 "保留旧值" 语义, 必须
+ 给出明确的合法 mode (当前仅 ``"mount"``)。
+ """
+ normalized = _normalize_preserve_file_sharing_mode(mode)
+ if normalized is None:
+ raise ValueError(
+ f"preserve_file_sharing_mode must be one of {_VALID_PRESERVE_FILE_SHARING_MODES}"
+ )
+ data = _load_yaml_round_trip(_CONFIG_YAML_PATH)
+ if "sandbox" not in data or not isinstance(data.get("sandbox"), dict):
+ data["sandbox"] = {}
+ data["sandbox"]["preserve_file_sharing_mode"] = normalized
+ _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)
+ return normalized
+
+
+def update_sandbox_runtime(patch: dict[str, Any]) -> dict[str, Any]:
+ """合并 patch 到 sandbox runtime 字段, 写回 YAML, 返回合并后的完整 runtime.
+
+ 持久化位置: ``sandbox`` 顶层 (扁平形式), 与 ``url`` / ``type`` /
+ ``startup_mode`` / ``policy_file`` / ``preserve_file_sharing_mode`` 并列。
+
+ Args:
+ patch: 部分字段更新;支持顶层键 ``enabled`` / ``excluded_commands``
+ / ``files``。 ``files`` 字典若提供则整体替换;其余键按值合并。
+ """
+ if not isinstance(patch, dict):
+ raise ValueError("patch must be an object")
+
+ current = get_sandbox_runtime()
+ merged = dict(current)
+
+ if "enabled" in patch:
+ merged["enabled"] = bool(patch["enabled"])
+ if "excluded_commands" in patch:
+ value = patch["excluded_commands"]
+ if not isinstance(value, list):
+ raise ValueError("excluded_commands must be a list")
+ merged["excluded_commands"] = [
+ str(p) for p in value if str(p).strip()
+ ]
+ if "files" in patch:
+ files = patch["files"] or {}
+ if not isinstance(files, dict):
+ raise ValueError("files must be an object")
+ allow = files.get("allow")
+ deny = files.get("deny")
+ merged["files"] = {
+ "allow": list(allow) if isinstance(allow, list) else merged["files"]["allow"],
+ "deny": list(deny) if isinstance(deny, list) else merged["files"]["deny"],
+ }
+
+ data = _load_yaml_round_trip(_CONFIG_YAML_PATH)
+ if "sandbox" not in data or not isinstance(data.get("sandbox"), dict):
+ data["sandbox"] = {}
+ sandbox_block = data["sandbox"]
+ # 写入扁平 runtime 字段, 每次 update 都把全集刷一遍, 保证 yaml 形状稳定。
+ for key in _SANDBOX_RUNTIME_KEYS:
+ sandbox_block[key] = merged[key]
+ _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)
+ return merged
diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.py
index b77f01aecd..0d31657622 100644
--- a/jiuwenswarm/common/schema/message.py
+++ b/jiuwenswarm/common/schema/message.py
@@ -25,6 +25,7 @@ class ReqMethod(Enum):
COMMAND_MCP = "command.mcp"
COMMAND_MODEL = "command.model"
COMMAND_RESUME = "command.resume"
+ COMMAND_SANDBOX = "command.sandbox"
COMMAND_SESSION = "command.session"
COMMAND_STATUS = "command.status"
diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
index 2c0427294c..a832224043 100644
--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
@@ -165,6 +165,7 @@ CLI_FORWARD_REQ_METHODS = frozenset(
"command.diff",
"command.mcp",
"command.resume",
+ "command.sandbox",
"command.session",
"command.status",
"chat.send",
@@ -235,6 +236,7 @@ CLI_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset(
"command.diff",
"command.mcp",
"command.resume",
+ "command.sandbox",
"command.session",
"command.status",
"browser.start",
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 412d0359ce..8726a8ebd8 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -11,6 +11,7 @@ import logging
import math
import os
import shutil
+import sys
from pathlib import Path
from typing import Any, ClassVar, Optional
@@ -38,19 +39,34 @@ from jiuwenswarm.agents.harness.common.rails.permissions.permissions_persist imp
from jiuwenswarm.extensions.hooks_context import AgentServerChatHookContext
from jiuwenswarm.server.runtime.agent_manager import AgentManager, ACP_DEFAULT_CAPABILITIES
from jiuwenswarm.server.runtime.session.session_metadata import get_all_sessions_metadata, remove_session_metadata_cache
+from jiuwenswarm.server.runtime.agent_adapter.sysop_builder import (
+ build_filesystem_policy,
+ find_auto_managed_match,
+ list_effective_sandbox_files,
+)
from jiuwenswarm.server.utils.utils import is_team_params
from jiuwenswarm.agents.harness.common.rails.permissions.permissions_config_rpc import (
get_permissions_config_req_methods,
)
from jiuwenswarm.common.config import (
+ DEFAULT_SANDBOX_POLICY_FILE,
+ DEFAULT_SANDBOX_STARTUP_MODE,
get_config,
get_default_models,
get_mcp_server_config,
get_mcp_servers,
+ get_sandbox_endpoint,
+ get_sandbox_runtime,
+ get_sandbox_startup_mode_explicit,
remove_mcp_server_in_config,
+ resolve_preserve_file_sharing_mode_default,
+ resolve_sandbox_policy_path,
set_mcp_server_enabled_in_config,
+ update_sandbox_endpoint,
+ update_sandbox_runtime,
upsert_mcp_server_in_config,
)
+from jiuwenswarm.server.sandbox.jiuwenbox_runner import JiuwenBoxRunner
from jiuwenswarm.common.security.ws_origin import (
extract_handshake_request,
forbidden_origin_response,
@@ -146,6 +162,89 @@ def _payload_to_request(data: dict[str, Any]) -> AgentRequest:
)
+def _require_sandbox_supported() -> None:
+ """Reject ``/sandbox`` commands on non-Linux hosts.
+
+ jiuwenbox 底层依赖 Linux 专属能力 (bwrap / Landlock / Linux namespaces /
+ ``PR_SET_CHILD_SUBREAPER`` 等), Windows / macOS 上无法实际拉起沙箱;
+ ``jiuwenbox-server`` 自检也会在非 Linux 平台直接退出。 因此在 WS 命令
+ 入口前置拒绝, 让用户看到清晰 ``SANDBOX_BAD_REQUEST`` 错误, 而不是被
+ "拉起子进程失败 / 端口连接超时" 之类的下游报错搪塞。
+
+ Raises:
+ ValueError: 当 ``sys.platform`` 不是以 ``"linux"`` 开头时。
+ """
+ if not sys.platform.startswith("linux"):
+ raise ValueError(
+ f"/sandbox is only supported on Linux (current platform: {sys.platform!r}); "
+ "jiuwenbox depends on Linux-only kernel features (bwrap / Landlock / "
+ "namespaces) and cannot run on Windows or macOS."
+ )
+
+
+def _file_entry_matches_path(entry: Any, path: str) -> bool:
+ """判断 ``sandbox.files.{allow,deny}`` 中的一项是否指向给定 ``path``.
+
+ 支持两种存储格式 (历史兼容):
+ - ``dict``: ``{"path": "/foo", "permissions": "ro"}``;
+ - ``str``: 直接路径字符串 ``"/foo"``。
+
+ 抽离出来主要是给 ``_handle_sandbox_files_set`` /
+ ``_handle_sandbox_files_remove`` 的列表推导式简化条件 (G.EXP.04: 推导式
+ 不应同时使用多个子句或跨多行的复杂条件)。
+
+ 比较时两端都先 canonicalize 一次 (见 :func:`_canonicalize_sandbox_files
+ _path`), 保证历史 yaml 里残留的 ``~/...`` / 相对路径 / 含 ``..`` / 含
+ 尾斜杠 之类写法仍能跟新 canonical 化后的输入命中, 让 ``/sandbox files
+ remove`` 不会因为「字面写法不同」失效。
+ """
+ if isinstance(entry, dict):
+ entry_path = str(entry.get("path") or "")
+ elif isinstance(entry, str):
+ entry_path = entry
+ else:
+ return False
+ if entry_path == path:
+ return True
+ return (
+ _canonicalize_sandbox_files_path(entry_path)
+ == _canonicalize_sandbox_files_path(path)
+ )
+
+
+def _canonicalize_sandbox_files_path(path: str) -> str:
+ """把 TUI 传来的 ``path`` 展开成 absolute resolved 形式 (绝对、去 ``..``、
+ 展开 ``~``、按需展开 symlink) 后作为 ``sandbox.files.{allow,deny}`` 的
+ canonical key.
+
+ 历史上这个函数只做「按宿主文件类型自动补尾斜杠」, 因为 ``sysop_builder``
+ 旧版本靠尾斜杠区分文件/目录; 现在 ``build_filesystem_policy`` 已经统一
+ 用 ``Path.is_file()`` / ``is_dir()`` 实际 stat 磁盘判断, 尾斜杠的语义
+ 彻底失效, 那套补斜杠逻辑就没意义了。
+
+ 保留并扩成「绝对化 + resolve」是因为:
+ - 用户在 TUI 输 ``./mydir`` / ``~/data`` / ``foo/bar`` 这类非绝对
+ 写法时, jiuwenswarm server 直接拿去 stat / 入库 / 比较, 行为依赖
+ server 当前 cwd 与运行用户 home, 不同次重启之间会静默漂移;
+ - ``_file_entry_matches_path`` 走字符串相等比较, 同一文件如果一次以
+ ``~/foo`` 形式入库、下一次 ``remove /home/<user>/foo`` 就匹配不到,
+ 用户视角"删不掉";
+ - ``sysop_builder`` 拿到非绝对路径后 ``Path(path).exists()`` 又会基于
+ cwd 解析, 跟 server 视角再错位一次。
+
+ 一次 ``expanduser().resolve()`` 把所有这些不一致摊平在入口, 下游全部
+ 看到稳定的 absolute path。 解析失败 (例如非法字符) 时静默 fallback 到
+ 原字面值, 不阻塞命令; 真正"路径不存在"由 ``build_filesystem_policy``
+ 的 dry-run 在写盘前拦截, 见 :meth:`_dry_run_files_policy`。
+ """
+ if not path:
+ return path
+ try:
+ return str(Path(path).expanduser().resolve())
+ except (OSError, RuntimeError):
+ return path
+
+
class AgentWebSocketServer:
"""Gateway 与 AgentServer 之间的 WebSocket 服务端(单例).
@@ -186,6 +285,8 @@ class AgentWebSocketServer:
# Model cache for scheduled task execution (same approach as interface_deep)
self._model_cache: dict[str, Any] = {}
self._default_model: Optional[Any] = None
+ # 本地 jiuwenbox 子进程管理器 (lazy 启动, 在 /sandbox enable 时 ensure_running)
+ self._jiuwenbox_runner = JiuwenBoxRunner.instance()
get_acp_output_manager().set_send_push_callback(
lambda msg: asyncio.create_task(self.send_push(msg))
)
@@ -282,6 +383,159 @@ class AgentWebSocketServer:
logger.info(
"[AgentWebSocketServer] 已启动: ws://%s:%s", self._host, self._port
)
+ # WS 监听已经开放, 现在按 config.yaml::sandbox 的 runtime.enabled +
+ # startup_mode 决定要不要自动把 jiuwenbox 子进程也拉起来。失败不阻塞
+ # 启动 (用户依然可以在 TUI 里跑 /sandbox enable 重试)。
+ await self._bootstrap_internal_jiuwenbox()
+
+ async def _bootstrap_internal_jiuwenbox(self) -> None:
+ """启动时按 ``config.yaml::sandbox`` 自动拉起 jiuwenbox 子进程。
+
+ 触发条件: ``config.yaml::sandbox.startup_mode`` **显式**写为 ``internal``。
+ 这里刻意走 :func:`get_sandbox_startup_mode_explicit` 而不是
+ :func:`get_sandbox_startup_mode` —— 后者在字段缺失时默认回落到
+ ``internal``, 会让没在用沙箱的用户升级版本后突然多出 jiuwenbox 进程;
+ boot 阶段必须严格区分 "用户写过 internal" 和 "走默认值"。
+
+ 不再单独依赖 ``sandbox.enabled``:
+ - 老逻辑要 ``enabled=True`` AND ``startup_mode=internal`` 才拉, 但
+ ``enabled`` 是 ``/sandbox`` 命令的产物, 用户手改 yaml 设了 ``internal``
+ 的话很容易漏配 ``enabled`` → boot 时一声不吭跳过, 体验差。
+ - 现在: 只要 ``startup_mode=internal`` 就拉; 成功后顺手把
+ ``sandbox.enabled`` 同步成 ``True``, ``/sandbox status`` 显示与实际
+ 运行的 jiuwenbox 一致。
+ - ``/sandbox disable`` 仍然会停 jiuwenbox 并把 ``enabled`` 置 ``False``,
+ 但**重启后会被本方法重新拉起** (因为 ``startup_mode`` 没改)。要让
+ disable 跨重启生效, 把 ``startup_mode`` 改为 ``external`` 或从 yaml
+ 里删掉该字段即可。
+
+ 与 :meth:`_handle_sandbox_enable` 的其余差别:
+ - 不调用 ``agent_manager.recreate_agent``: 启动阶段还没有任何会话/agent
+ 实例, 没东西需要重建; 后续会话首次进入时按现有 ``sandbox.url`` 直接装载。
+ - 严格 best-effort: 任何失败 (policy 缺失 / 端口/spawn 失败) 一律记
+ warning, 绝不让 agent-server 自身启动失败 (否则运维误配 yaml 会让整
+ 产品起不来, 也无从修复)。
+ """
+ try:
+ # 非 Linux 平台直接跳过 auto-start: jiuwenbox 依赖 bwrap / Landlock /
+ # 命名空间, Windows / macOS 起不来; 即便 spawn 成功后续 /sandbox 命
+ # 令也会被 :func:`_require_sandbox_supported` 拒掉, 留着只会浪费一
+ # 次失败的子进程启动。
+ if not sys.platform.startswith("linux"):
+ logger.info(
+ "[AgentWebSocketServer] skipping jiuwenbox auto-start: "
+ "/sandbox is only supported on Linux (current platform: %r)",
+ sys.platform,
+ )
+ return
+ explicit_mode = get_sandbox_startup_mode_explicit()
+ if explicit_mode is None:
+ logger.info(
+ "[AgentWebSocketServer] sandbox.startup_mode 未在 config.yaml "
+ "中显式配置, skipping jiuwenbox auto-start (走默认 host 模式; "
+ "如需 agent-server 自动拉起 jiuwenbox 子进程, 设置 "
+ "sandbox.startup_mode: internal)"
+ )
+ return
+ if explicit_mode != "internal":
+ logger.info(
+ "[AgentWebSocketServer] sandbox.startup_mode=%r, skipping "
+ "jiuwenbox auto-start (external 模式由用户自行拉起 "
+ "jiuwenbox-server)",
+ explicit_mode,
+ )
+ return
+
+ # startup_mode=internal 已经定下来; 其余字段从归一后的 endpoint
+ # 取, 缺啥用默认。
+ endpoint = get_sandbox_endpoint()
+ url = endpoint.get("url") or "http://127.0.0.1:8321"
+ sandbox_type = endpoint.get("type") or "jiuwenbox"
+ raw_policy = endpoint.get("policy_file") or ""
+ effective_policy_file = raw_policy or DEFAULT_SANDBOX_POLICY_FILE
+ policy_path = resolve_sandbox_policy_path(effective_policy_file)
+ if policy_path is None or not policy_path.is_file():
+ logger.warning(
+ "[AgentWebSocketServer] sandbox auto-start skipped: "
+ "policy_file=%r 无法解析到一个存在的文件 "
+ "(resolved=%s). 进 TUI 跑 /sandbox enable 重试或修复 "
+ "config.yaml::sandbox.policy_file。",
+ effective_policy_file,
+ policy_path,
+ )
+ return
+
+ host, preferred_port = self._parse_sandbox_host_port(url)
+ port = self._allocate_internal_jiuwenbox_port(host, preferred_port)
+ if port != preferred_port:
+ url = f"http://{host}:{port}"
+ logger.info(
+ "[AgentWebSocketServer] jiuwenbox auto-start: "
+ "preferred port %d busy, using %d",
+ preferred_port,
+ port,
+ )
+
+ ok = await self._jiuwenbox_runner.ensure_running(
+ host=host,
+ port=port,
+ startup_mode="internal",
+ policy_path=policy_path,
+ )
+ if not ok:
+ stderr_tail = self._jiuwenbox_runner.get_stderr_tail(10)
+ logger.warning(
+ "[AgentWebSocketServer] jiuwenbox auto-start failed at "
+ "%s:%d (policy=%s); 进 TUI 跑 /sandbox enable 重试。"
+ " stderr tail:\n%s",
+ host,
+ port,
+ policy_path,
+ stderr_tail or "(empty)",
+ )
+ return
+
+ # 端口可能在 _allocate_internal_jiuwenbox_port 里换过, 把最终生效
+ # 的 url 落盘, 这样 (a) 后续会话/agent 重建直接读到正确端点,
+ # (b) /sandbox status 显示也是真实值, 不再是 config 里旧的 8321。
+ try:
+ update_sandbox_endpoint(
+ url,
+ sandbox_type,
+ startup_mode="internal",
+ policy_file=effective_policy_file,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[AgentWebSocketServer] persist sandbox endpoint failed "
+ "after auto-start: %s",
+ exc,
+ )
+
+ # auto-start 成功 → ``runtime.enabled`` 同步为 True, 这样 /sandbox
+ # status / TUI 显示的状态跟真实运行的 jiuwenbox 对齐。如果用户上次
+ # /sandbox disable 留下了 False, 这里会被覆盖 —— 这是已知的、属于
+ # 上面 docstring 提到的 "disable 不跨重启" 语义的一部分。
+ try:
+ update_sandbox_runtime({"enabled": True})
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[AgentWebSocketServer] persist sandbox.enabled=True "
+ "failed after auto-start: %s",
+ exc,
+ )
+
+ logger.info(
+ "[AgentWebSocketServer] jiuwenbox auto-started at %s "
+ "(policy=%s)",
+ url,
+ policy_path,
+ )
+ except Exception: # noqa: BLE001
+ logger.exception(
+ "[AgentWebSocketServer] jiuwenbox auto-start raised an "
+ "unexpected error; skipping (用户可在 TUI 里 /sandbox enable 重试)"
+ )
async def _stop_scheduler(self) -> None:
"""Stop the auto_harness scheduler."""
@@ -333,6 +587,10 @@ class AgentWebSocketServer:
self._server.close()
await self._server.wait_closed()
self._server = None
+ try:
+ await self._jiuwenbox_runner.stop()
+ except Exception as exc: # noqa: BLE001
+ logger.warning("[AgentWebSocketServer] jiuwenbox_runner.stop failed: %s", exc)
logger.info("[AgentWebSocketServer] 已停止")
# ---------- 连接处理 ----------
@@ -518,6 +776,9 @@ class AgentWebSocketServer:
if request.req_method == ReqMethod.COMMAND_MCP:
await self._handle_command_mcp(ws, request, send_lock)
return
+ if request.req_method == ReqMethod.COMMAND_SANDBOX:
+ await self._handle_command_sandbox(ws, request, send_lock)
+ return
if request.req_method == ReqMethod.COMMAND_RESUME:
await self._handle_command_resume(ws, request, send_lock)
return
@@ -2061,6 +2322,626 @@ class AgentWebSocketServer:
async with send_lock:
await ws.send(json.dumps(wire, ensure_ascii=False))
+ async def _handle_command_sandbox(
+ self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock
+ ) -> None:
+ """处理 ``/sandbox`` 命令.
+
+ 子命令通过 ``params["sub"]`` 路由:
+ - ``status`` / ``enable`` / ``disable``
+ - ``exclude.add`` / ``exclude.remove`` / ``exclude.list``
+ - ``files.allow`` / ``files.deny`` / ``files.list``
+
+ ``enable``/``disable`` 走 ``agent_manager.recreate_agent`` (重建 sys_operation 类型);
+ 其他写动作通过 ``adapter.apply_sandbox_runtime_patch()`` 立即热更,
+ 不重建 agent.
+ """
+ params = request.params or {}
+ sub = str(params.get("sub", "status")).strip().lower()
+ channel_id = request.channel_id or "default"
+ try:
+ # 平台守卫: ``/sandbox`` 全家桶仅在 Linux 上可用。 放在 try 内部是
+ # 故意的, 让 ValueError 命中下方 ``except ValueError`` 分支转成
+ # ``SANDBOX_BAD_REQUEST`` 回执, 跟其它入参校验失败的处理一致。
+ _require_sandbox_supported()
+ if sub == "status":
+ payload = {"runtime": get_sandbox_runtime()}
+ elif sub == "enable":
+ payload = await self._handle_sandbox_enable(channel_id)
+ elif sub == "disable":
+ payload = await self._handle_sandbox_disable(channel_id)
+ elif sub == "exclude.add":
+ payload = await self._handle_sandbox_exclude_add(channel_id, params)
+ elif sub == "exclude.remove":
+ payload = await self._handle_sandbox_exclude_remove(channel_id, params)
+ elif sub == "exclude.list":
+ payload = {"excluded_commands": list(get_sandbox_runtime().get("excluded_commands") or [])}
+ elif sub == "files.allow":
+ payload = await self._handle_sandbox_files_set(channel_id, params, bucket="allow")
+ elif sub == "files.deny":
+ payload = await self._handle_sandbox_files_set(channel_id, params, bucket="deny")
+ elif sub == "files.remove":
+ payload = await self._handle_sandbox_files_remove(channel_id, params)
+ elif sub == "files.list":
+ payload = {"files": dict(get_sandbox_runtime().get("files") or {})}
+ else:
+ raise ValueError(f"unknown sub: {sub!r}")
+ self._attach_effective_sandbox_files(payload, channel_id, params)
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=True,
+ payload=payload,
+ )
+ except ValueError as exc:
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={"error": str(exc), "code": "SANDBOX_BAD_REQUEST"},
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.exception("[AgentWebSocketServer] command.sandbox failed: %s", exc)
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={"error": str(exc), "code": "SANDBOX_INTERNAL"},
+ )
+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
+ async with send_lock:
+ await ws.send(json.dumps(wire, ensure_ascii=False))
+
+ async def _handle_sandbox_enable(self, channel_id: str) -> dict[str, Any]:
+ # 1. 解析 sandbox endpoint: 优先 config.yaml::sandbox.url/type, 缺省走本地 jiuwenbox.
+ # ``get_sandbox_endpoint`` 已经把 startup_mode / policy_file 的归一化值一并返回:
+ # - startup_mode 缺省/非法 → "internal"
+ # - policy_file 缺省 → "" (此处再回落到 DEFAULT_SANDBOX_POLICY_FILE)
+ endpoint = get_sandbox_endpoint()
+ url = endpoint.get("url") or "http://127.0.0.1:8321"
+ sandbox_type = endpoint.get("type") or "jiuwenbox"
+
+ # startup_mode:
+ # - internal: agent-server 通过 JiuwenBoxRunner 拉起 jiuwenbox (默认行为);
+ # - external: 用户自己启动 jiuwenbox (例如需要 sudo + network.mode: isolated),
+ # 本侧只做健康检查, 不可达直接报错并提示如何手动启动。
+ startup_mode = endpoint.get("startup_mode") or DEFAULT_SANDBOX_STARTUP_MODE
+
+ # policy_file:
+ # - 仅文件名 → 在 jiuwenbox/configs 下查找; 含路径 / 绝对路径 → 整路径使用;
+ # - 未配置 → 回落到 DEFAULT_SANDBOX_POLICY_FILE (即 code-agent-policy.yaml),
+ # 并在下方与 url/type 一起写回 config.yaml, 让重启后无需再走 fallback 路径。
+ raw_policy = endpoint.get("policy_file") or ""
+ effective_policy_file = raw_policy or DEFAULT_SANDBOX_POLICY_FILE
+ policy_path = resolve_sandbox_policy_path(effective_policy_file)
+ if policy_path is None:
+ raise RuntimeError(
+ f"sandbox.policy_file={effective_policy_file!r} 无法解析: "
+ f"仅给出文件名时需能定位到 jiuwenbox/configs 目录, "
+ f"否则请在 config.yaml::sandbox.policy_file 里配置绝对路径。",
+ )
+ if not policy_path.is_file():
+ raise RuntimeError(
+ f"sandbox policy 文件不存在: {policy_path} "
+ f"(原始配置 sandbox.policy_file="
+ f"{raw_policy or f'<default:{DEFAULT_SANDBOX_POLICY_FILE}>'!r})",
+ )
+
+ # 2. 解析 host:port 并 (internal 模式下) 完成端口分配。
+ # external 模式: 直接用配置里的 url, 由用户保证 jiuwenbox 监听在此处。
+ # internal 模式: 期望端口被占就换一个随机空闲端口, 不去探测占用方是谁。
+ host, preferred_port = self._parse_sandbox_host_port(url)
+ if startup_mode == "internal":
+ port = self._allocate_internal_jiuwenbox_port(host, preferred_port)
+ if port != preferred_port:
+ # 端口换过, 同步刷新 url 以便后续落盘 / 透传给前端
+ url = f"http://{host}:{port}"
+ logger.info(
+ "[command.sandbox] jiuwenbox effective url changed to %s "
+ "(preferred port %d was busy)",
+ url,
+ preferred_port,
+ )
+ else:
+ port = preferred_port
+
+ # 3. 启动 / 健康检查本地 jiuwenbox; 失败直接报错
+ ok = await self._jiuwenbox_runner.ensure_running(
+ host=host,
+ port=port,
+ startup_mode=startup_mode,
+ policy_path=policy_path,
+ )
+ if not ok:
+ if startup_mode == "external":
+ raise RuntimeError(
+ f"jiuwenbox 未在 {host}:{port} 监听 (sandbox.startup_mode=external); "
+ f"请在另一终端先启动 jiuwenbox-server, 例如:\n"
+ f" sudo -E .venv/bin/python -m uvicorn jiuwenbox.server.app:app "
+ f"--host {host} --port {port}\n"
+ f" (JIUWENBOX_POLICY_PATH={policy_path})"
+ )
+ stderr_tail = self._jiuwenbox_runner.get_stderr_tail(20)
+ hint = "\n--- jiuwenbox stderr (tail) ---\n" + stderr_tail if stderr_tail else (
+ " (no stderr captured; jiuwenbox / uvicorn 可能未安装)"
+ )
+ raise RuntimeError(
+ f"jiuwenbox 启动或健康检查失败 ({host}:{port}){hint}"
+ )
+
+ # 4. 把 endpoint 写回 config.yaml, 保证 agent 重建 / agent-server 重启后能直接读到。
+ # url 此时已是端口分配后的最终值; startup_mode / policy_file / preserve_file_sharing_mode 一并落盘。
+ preserve_mode = resolve_preserve_file_sharing_mode_default()
+ try:
+ update_sandbox_endpoint(
+ url,
+ sandbox_type,
+ startup_mode=startup_mode,
+ policy_file=effective_policy_file,
+ preserve_file_sharing_mode=preserve_mode,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning("[command.sandbox] persist sandbox endpoint failed: %s", exc)
+
+ runtime = update_sandbox_runtime({"enabled": True})
+ rebuilt_modes = await self._agent_manager.recreate_agent(channel_id, immediate=True)
+
+ return {
+ "runtime": runtime,
+ "endpoint": {
+ "url": url,
+ "type": sandbox_type,
+ "preserve_file_sharing_mode": preserve_mode,
+ "startup_mode": startup_mode,
+ "policy_file": effective_policy_file,
+ },
+ "jiuwenbox": {
+ "host": host,
+ "port": port,
+ "ready": True,
+ "startup_mode": startup_mode,
+ "policy_path": str(policy_path),
+ },
+ "agent_recreated": True,
+ "rebuilt_modes": rebuilt_modes,
+ }
+
+ async def _handle_sandbox_disable(self, channel_id: str) -> dict[str, Any]:
+ runtime = update_sandbox_runtime({"enabled": False})
+ # 先重建 agent: 新 agent 在 enabled=False 下不再装载 jiuwenbox provider,
+ # 不会有新请求打到将要关闭的子进程; 老 agent 上的 in-flight 调用也由
+ # recreate_agent 内部完成切换。然后再关 jiuwenbox 子进程, 避免出现
+ # "老 agent 还活着 + jiuwenbox 已死" 的中间窗口导致 tool call 报连接错误。
+ rebuilt_modes = await self._agent_manager.recreate_agent(channel_id, immediate=True)
+
+ # 记录关闭前的端点用于回执 (external 模式下 runner 没拥有进程, 会是 None)。
+ owned_endpoint = self._jiuwenbox_runner.get_owned_endpoint()
+ jiuwenbox_stopped = False
+ if owned_endpoint is not None:
+ try:
+ await self._jiuwenbox_runner.stop()
+ jiuwenbox_stopped = True
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[AgentWebSocketServer] /sandbox disable: jiuwenbox stop failed: %s",
+ exc,
+ )
+ else:
+ logger.debug(
+ "[AgentWebSocketServer] /sandbox disable: no owned jiuwenbox to stop "
+ "(external startup_mode or never started)"
+ )
+
+ payload: dict[str, Any] = {
+ "runtime": runtime,
+ "agent_recreated": True,
+ "rebuilt_modes": rebuilt_modes,
+ "jiuwenbox_stopped": jiuwenbox_stopped,
+ }
+ if owned_endpoint is not None:
+ host, port = owned_endpoint
+ payload["jiuwenbox"] = {"host": host, "port": port, "ready": False}
+ return payload
+
+ async def _handle_sandbox_exclude_add(
+ self, channel_id: str, params: dict[str, Any]
+ ) -> dict[str, Any]:
+ pattern = str(params.get("pattern") or "").strip()
+ if not pattern:
+ raise ValueError("pattern is required")
+ current = get_sandbox_runtime()
+ patterns = list(current.get("excluded_commands") or [])
+ if pattern in patterns:
+ raise ValueError(
+ f"excluded_commands already contains {pattern!r}; "
+ "use a different pattern or remove it first"
+ )
+ patterns.append(pattern)
+ runtime = update_sandbox_runtime({"excluded_commands": patterns})
+ await self._apply_sandbox_runtime_patch(channel_id, runtime, files_changed=False)
+ return {"runtime": runtime}
+
+ async def _handle_sandbox_exclude_remove(
+ self, channel_id: str, params: dict[str, Any]
+ ) -> dict[str, Any]:
+ pattern = str(params.get("pattern") or "").strip()
+ if not pattern:
+ raise ValueError("pattern is required")
+ current = get_sandbox_runtime()
+ existing = list(current.get("excluded_commands") or [])
+ if pattern not in existing:
+ raise ValueError(
+ f"excluded_commands does not contain {pattern!r}; "
+ "nothing to remove"
+ )
+ patterns = [p for p in existing if p != pattern]
+ runtime = update_sandbox_runtime({"excluded_commands": patterns})
+ await self._apply_sandbox_runtime_patch(channel_id, runtime, files_changed=False)
+ return {"runtime": runtime}
+
+ def _dry_run_files_policy(
+ self,
+ channel_id: str,
+ params: dict[str, Any],
+ files: dict[str, Any],
+ ) -> None:
+ """在 ``update_sandbox_runtime`` 之前用候选 ``files`` 跑一次
+ :func:`build_filesystem_policy` 试压, 失败立刻抛 ``ValueError`` 给 TUI.
+
+ 没有这层 dry-run 时, ``/sandbox files allow|deny|remove`` 的处理顺序是
+ "先 ``update_sandbox_runtime`` 写盘 → 再 ``_apply_sandbox_runtime_patch``
+ 调 adapter 触发 ``build_filesystem_policy``"; 一旦 build 抛
+ ``FileNotFoundError`` (典型场景: ``allow /no/such/path``——files.allow /
+ files.deny 都要求 path 在 host 上真实存在),
+ :meth:`_apply_sandbox_runtime_patch` 的 ``except Exception`` 会把异常
+ 吞成 warning, 但 yaml 已经写了 ——用户视角是"runtime 看着更新, 沙箱却
+ 没重建, 而且 TUI 上没任何报错". 本函数就是消除这个不可见的中间态:
+ 校验失败时直接拒绝命令, 不让 yaml 进入"build 不出 policy"的死局。
+ """
+ project_dir = self._resolve_active_project_dir(channel_id, params)
+ try:
+ build_filesystem_policy(
+ files,
+ project_dir=project_dir,
+ )
+ except FileNotFoundError as exc:
+ raise ValueError(str(exc)) from exc
+
+ async def _handle_sandbox_files_set(
+ self, channel_id: str, params: dict[str, Any], *, bucket: str
+ ) -> dict[str, Any]:
+ path = str(params.get("path") or "").strip()
+ if not path:
+ raise ValueError("path is required")
+ # 把 path 展开成 absolute resolved 形式, 让 ``./foo`` / ``~/data`` /
+ # 含 ``..`` 之类写法在入口就被归一化到稳定路径, 避免后续 stat / 入库
+ # / 比较行为依赖 jiuwenswarm server 当前 cwd; 见
+ # :func:`_canonicalize_sandbox_files_path` 的文档说明。
+ canonical = _canonicalize_sandbox_files_path(path)
+ if canonical != path:
+ logger.info(
+ "[sandbox] files %s: canonicalize path %r -> %r",
+ bucket, path, canonical,
+ )
+ path = canonical
+ # 拒绝把"自动配置且不可变"的路径 (intrinsic AGENT.md / HEARTBEAT.md /...
+ # / daily_memory / 项目目录 / jiuwenswarm config.yaml) 再次写进
+ # config.yaml::sandbox.files。 它们由 sysop_builder 在每次
+ # build_filesystem_policy 时按需重建; 让用户能 add 只会污染配置, 而且
+ # 若一个路径同时在 auto-allow 和用户-deny 里 (反之亦然), 实际行为难以
+ # 预期, 不如直接在入口阻断。``params`` 透传给 ``_resolve_active_
+ # project_dir`` 以便 TUI 通过 ``trusted_dirs`` / ``cwd`` 显式声明的
+ # 项目目录也参与 auto 路径的判定。
+ project_dir = self._resolve_active_project_dir(channel_id, params)
+ match = find_auto_managed_match(
+ path,
+ project_dir=project_dir,
+ )
+ if match is not None:
+ matched_bucket, canonical = match
+ raise ValueError(
+ f"path is auto-managed (always in {matched_bucket}): {canonical}; "
+ f"cannot add via /sandbox files {bucket}"
+ )
+ permissions = params.get("permissions")
+ current = get_sandbox_runtime()
+ files = dict(current.get("files") or {})
+ files.setdefault("allow", [])
+ files.setdefault("deny", [])
+ # 1) 同 bucket 内已经存在等价条目 → 直接报错, 不做 "先删后加" 的隐式覆盖。
+ # permissions 的差异也算冲突: 让用户先 ``files remove`` 再重新 add,
+ # 确保 yaml 落盘前后 TUI 看到的差异与他实际打的命令一一对应。
+ target_list: list[Any] = list(files.get(bucket) or [])
+ for existing in target_list:
+ if _file_entry_matches_path(existing, path):
+ raise ValueError(
+ f"sandbox.files.{bucket} already contains {path!r}; "
+ f"use `/sandbox files remove {path}` first if you want to change it"
+ )
+ # 2) 反方向 bucket 已经登记了同一条 → allow / deny 在 Landlock 层语义直接
+ # 冲突, 拒绝。 用户得先把它从对侧 ``remove`` 掉再加, 显式表达 "我要
+ # 切换权限方向" 的意图。
+ opposite_bucket = "deny" if bucket == "allow" else "allow"
+ for existing in files.get(opposite_bucket) or []:
+ if _file_entry_matches_path(existing, path):
+ raise ValueError(
+ f"sandbox.files.{opposite_bucket} already contains {path!r}; "
+ f"cannot add the same path to {bucket}. "
+ f"`/sandbox files remove {path}` first if you want to flip it"
+ )
+ entry: dict[str, Any] = {"path": path}
+ if isinstance(permissions, str) and permissions.strip():
+ entry["permissions"] = permissions.strip()
+ target_list.append(entry)
+ files[bucket] = target_list
+ # 在写盘前做一次 dry-run, 防止后续 build_filesystem_policy 抛错时,
+ # yaml 已经被更新成一份永远 build 不出 policy 的中间态 (见
+ # :meth:`_dry_run_files_policy` 的文档说明)。
+ self._dry_run_files_policy(channel_id, params, files)
+ runtime = update_sandbox_runtime({"files": files})
+ await self._apply_sandbox_runtime_patch(channel_id, runtime, files_changed=True)
+ return {"runtime": runtime}
+
+ async def _handle_sandbox_files_remove(
+ self, channel_id: str, params: dict[str, Any]
+ ) -> dict[str, Any]:
+ path = str(params.get("path") or "").strip()
+ if not path:
+ raise ValueError("path is required")
+ # 与 _handle_sandbox_files_set 保持同一份 canonicalize, 让 ``remove
+ # ./foo`` 能命中以 absolute 形式入库的 entry; 兼容旧 yaml 残留写法的
+ # 兜底由 :func:`_file_entry_matches_path` 双侧 canonicalize 比较负责。
+ canonical = _canonicalize_sandbox_files_path(path)
+ if canonical != path:
+ logger.info(
+ "[sandbox] files remove: canonicalize path %r -> %r",
+ path, canonical,
+ )
+ path = canonical
+ # 同 _handle_sandbox_files_set: auto-managed 条目由 sysop_builder 在
+ # 每次 build_filesystem_policy 时重建, 用户不能也不必通过 /sandbox 删除
+ # 它们。如果旧版本 config.yaml 里残留了这些路径, 提示用户直接改 yaml,
+ # 而不是让 /sandbox 默默地把同一个 auto-managed 名字从用户配置里抹掉
+ # ——后者会让用户误以为他/她真的把 sandbox 自动条目摘掉了。
+ project_dir = self._resolve_active_project_dir(channel_id, params)
+ match = find_auto_managed_match(
+ path,
+ project_dir=project_dir,
+ )
+ if match is not None:
+ matched_bucket, canonical = match
+ raise ValueError(
+ f"path is auto-managed (always in {matched_bucket}): {canonical}; "
+ f"cannot remove via /sandbox files remove"
+ )
+ current = get_sandbox_runtime()
+ files = dict(current.get("files") or {})
+ files.setdefault("allow", [])
+ files.setdefault("deny", [])
+ matched_buckets: list[str] = []
+ for bucket in ("allow", "deny"):
+ kept: list[Any] = []
+ removed = False
+ for entry in files.get(bucket) or []:
+ if _file_entry_matches_path(entry, path):
+ removed = True
+ continue
+ kept.append(entry)
+ if removed:
+ matched_buckets.append(bucket)
+ files[bucket] = kept
+ if not matched_buckets:
+ raise ValueError(
+ f"sandbox.files has no entry for {path!r}; nothing to remove"
+ )
+ # 与 _handle_sandbox_files_set 对齐: 在写盘前 dry-run, 避免 build 失败
+ # 时 yaml 已被写成 build 不出 policy 的死局 (见 :meth:`_dry_run_files
+ # _policy` 的文档说明)。
+ self._dry_run_files_policy(channel_id, params, files)
+ runtime = update_sandbox_runtime({"files": files})
+ await self._apply_sandbox_runtime_patch(channel_id, runtime, files_changed=True)
+ return {"runtime": runtime}
+
+ def _resolve_active_project_dir(
+ self, channel_id: str, params: dict[str, Any] | None = None
+ ) -> str | None:
+ """Resolve the user project dir for the current ``/sandbox`` view.
+
+ Lookup order, falling through on empty/missing:
+
+ 1. ``params["trusted_dirs"][0]`` -- freshest, includes any
+ ``/workspace add`` the user did *after* the agent was created.
+ 2. ``params["cwd"]`` -- TUI's own ``process.cwd()``, sent on every
+ request. This is the user's launch directory and matches what
+ they mean by "current directory" when ``trusted_dirs`` is empty.
+ 3. ``adapter._project_dir``.
+ 4. ``adapter._instance_overrides["project_dir"]`` (populated from
+ ``trusted_dirs[0]`` when :meth:`AgentManager.get_agent` created
+ the agent).
+
+ Returns ``None`` only when none of the above yield a usable path; we
+ deliberately do NOT fall back to ``Path.cwd()`` of the agent-server
+ process because that's typically ``~/.jiuwenswarm`` and would
+ mislabel the displayed ``files.allow_write`` entry.
+ """
+ if isinstance(params, dict):
+ trusted_dirs = params.get("trusted_dirs")
+ if isinstance(trusted_dirs, (list, tuple)) and trusted_dirs:
+ first = str(trusted_dirs[0]).strip()
+ if first:
+ return first
+ cwd_value = params.get("cwd")
+ if isinstance(cwd_value, str) and cwd_value.strip():
+ return cwd_value.strip()
+ try:
+ agent = self._agent_manager.get_agent_nowait(channel_id)
+ except Exception as exc: # noqa: BLE001
+ logger.debug("[command.sandbox] get_agent_nowait failed: %s", exc)
+ return None
+ adapter = self._resolve_adapter(agent)
+ if adapter is None:
+ return None
+ direct = getattr(adapter, "_project_dir", None)
+ if direct:
+ return str(direct)
+ overrides = getattr(adapter, "_instance_overrides", None)
+ if isinstance(overrides, dict):
+ value = overrides.get("project_dir")
+ if value:
+ return str(value)
+ return None
+
+ def _attach_effective_sandbox_files(
+ self,
+ payload: dict[str, Any],
+ channel_id: str,
+ params: dict[str, Any] | None = None,
+ ) -> None:
+ """Inject ``effective_files`` into the ``/sandbox`` response payload.
+
+ ``effective_files`` summarises what the sandbox will actually grant
+ write access to (and what it will always deny) -- the union of
+ intrinsic agent files / ``daily_memory`` / current project dir plus
+ the user-configured allow list, and jiuwenswarm's own ``config.yaml``
+ plus the user-configured deny list. The TUI ``/sandbox status`` and
+ ``/sandbox files list`` panels render this directly under
+ ``files.allow_write`` / ``files.deny_write`` so the user sees the
+ same set the policy builder would compute at sandbox-start time.
+
+ The project dir reported in ``allow_write`` is sourced from the live
+ adapter (see :meth:`_resolve_active_project_dir`) so the panel
+ matches the user's trusted directory rather than the agent-server's
+ cwd, which is usually ``~/.jiuwenswarm`` and not what the user means
+ by "project".
+
+ Best-effort: failures are logged and swallowed so the underlying
+ sub-command response still goes back to the client.
+ """
+ try:
+ files_runtime: dict[str, Any] | None = None
+ runtime = payload.get("runtime")
+ if isinstance(runtime, dict):
+ rt_files = runtime.get("files")
+ if isinstance(rt_files, dict):
+ files_runtime = rt_files
+ if files_runtime is None:
+ files_in_payload = payload.get("files")
+ if isinstance(files_in_payload, dict):
+ files_runtime = files_in_payload
+ if files_runtime is None:
+ files_runtime = get_sandbox_runtime().get("files") or {}
+ project_dir = self._resolve_active_project_dir(channel_id, params)
+ payload["effective_files"] = list_effective_sandbox_files(
+ files_runtime,
+ project_dir=project_dir,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning("[command.sandbox] attach effective_files failed: %s", exc)
+
+ async def _apply_sandbox_runtime_patch(
+ self, channel_id: str, runtime: dict[str, Any], *, files_changed: bool
+ ) -> None:
+ agent = self._agent_manager.get_agent_nowait(channel_id)
+ adapter = self._resolve_adapter(agent)
+ if adapter is None or not hasattr(adapter, "apply_sandbox_runtime_patch"):
+ return
+ try:
+ await adapter.apply_sandbox_runtime_patch(runtime, files_changed=files_changed)
+ except (FileNotFoundError, ValueError) as exc:
+ # User-facing 配置冲突 (典型: ``/sandbox files allow|deny`` path 在
+ # host 上不存在) 必须直接抛到 TUI——上层 _handle_command_sandbox 的
+ # 大 try/except 会把 ValueError 路由成 ``SANDBOX_BAD_REQUEST`` 回执,
+ # 用户能立刻看到错误原因; 而不是被 ``except Exception`` 吞成一行
+ # 后台 warning, runtime config 已经写盘但沙箱悄悄没重建。
+ raise ValueError(str(exc)) from exc
+ except Exception as exc: # noqa: BLE001
+ logger.warning("[command.sandbox] apply_sandbox_runtime_patch failed: %s", exc)
+
+ @staticmethod
+ def _resolve_adapter(agent: Any) -> Any:
+ """从 JiuwenSwarm 中提取底层 Deep/Code Adapter (持 _sys_operation_card 的实例)."""
+ if agent is None:
+ return None
+ for attr in ("_adapter", "adapter", "_active_adapter"):
+ inner = getattr(agent, attr, None)
+ if inner is not None and hasattr(inner, "apply_sandbox_runtime_patch"):
+ return inner
+ # 兜底: agent 本身有相关方法
+ if hasattr(agent, "apply_sandbox_runtime_patch"):
+ return agent
+ return None
+
+ @staticmethod
+ def _parse_sandbox_host_port(url: str) -> tuple[str, int]:
+ """从 sandbox url 解析 host:port; 默认 127.0.0.1:8321."""
+ from urllib.parse import urlparse
+
+ try:
+ parsed = urlparse(url)
+ host = parsed.hostname or "127.0.0.1"
+ port = parsed.port or 8321
+ except Exception:
+ host, port = "127.0.0.1", 8321
+ return host, int(port)
+
+ @staticmethod
+ def _is_tcp_port_bindable(host: str, port: int) -> bool:
+ """``True`` 表示当前能在 ``host:port`` 上 ``bind`` 成功 (即没有被占用)。
+
+ 不去探测 ``/health`` 之类应用层信息——只看四层占用情况, 谁占着、占着的
+ 是不是 jiuwenbox 都不关心。
+ """
+ import socket
+
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ try:
+ try:
+ sock.bind((host, port))
+ except OSError:
+ return False
+ return True
+ finally:
+ sock.close()
+
+ @staticmethod
+ def _pick_free_tcp_port(host: str) -> int:
+ """让内核挑一个空闲端口 (``bind`` 到 0); 仅用于绑定测试, 不会真正监听。
+
+ 存在 TOCTOU 风险 (返回后端口可能立即被别人抢), 但接下来 uvicorn 起来
+ 通常足够快; 即便撞上, uvicorn 自己会因 EADDRINUSE 失败, 上游再报错。
+ """
+ import socket
+
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
+ sock.bind((host, 0))
+ return int(sock.getsockname()[1])
+
+ def _allocate_internal_jiuwenbox_port(
+ self,
+ host: str,
+ preferred_port: int,
+ ) -> int:
+ """internal 模式下确定 jiuwenbox 实际监听端口。
+
+ - 若本 runner 已经在 ``host:preferred_port`` 上拥有一个仍在跑的 jiuwenbox,
+ 直接复用 (避免重复 spawn);
+ - 否则若 ``preferred_port`` 当前无人占用, 用之;
+ - 再否则让内核挑一个空闲端口返回。
+ """
+ if self._jiuwenbox_runner.is_owned_listener(host, preferred_port):
+ return preferred_port
+ if self._is_tcp_port_bindable(host, preferred_port):
+ return preferred_port
+ new_port = self._pick_free_tcp_port(host)
+ logger.warning(
+ "[command.sandbox] preferred port %s:%d is busy; "
+ "allocating fresh port %d for new jiuwenbox instance",
+ host,
+ preferred_port,
+ new_port,
+ )
+ return new_port
+
async def _handle_command_resume(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
try:
params = request.params or {}
@@ -2200,7 +3081,7 @@ class AgentWebSocketServer:
settings_sources.append(f"env:JIUWENSWARM_CONFIG_DIR={config_dir}")
settings_sources.append(config_path)
- # Memory diagnostics — use the actual workspace dir (trusted_dir or cwd),
+ # Memory diagnostics — use the actual workspace dir (trusted_dir or cwd),
# same as ProjectMemoryRail, so we detect JIUWENCLAW.md where /init creates it.
params = request.params or {}
workspace_dir = str(params.get("cwd", "") or os.getcwd())
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 7c9a7e82f0..58f3e17eaf 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -35,13 +35,6 @@ from openjiuwen.core.sys_operation import (
SysOperation,
SysOperationCard,
OperationMode,
- LocalWorkConfig,
- SandboxGatewayConfig,
-)
-from openjiuwen.core.sys_operation.config import (
- SandboxIsolationConfig,
- PreDeployLauncherConfig,
- ContainerScope,
)
from openjiuwen.core.sys_operation.cwd import set_cwd
from openjiuwen.harness import (
@@ -194,7 +187,12 @@ from jiuwenswarm.agents.harness.common.tools.xiaoyi_phone_tools import (
xiaoyi_gui_agent,
image_reading,
)
-from jiuwenswarm.common.config import get_config, get_default_models, resolve_env_vars
+from jiuwenswarm.common.config import get_config, get_default_models, get_sandbox_runtime, resolve_env_vars
+from jiuwenswarm.server.runtime.agent_adapter.sysop_builder import (
+ build_filesystem_policy,
+ create_local_sysop_card,
+ create_sandbox_sysop_card,
+)
from jiuwenswarm.agents.harness.common.plugins.rail_manager import get_rail_manager
from jiuwenswarm.gateway.cron import CronTargetChannel
from jiuwenswarm.common.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk
@@ -219,7 +217,6 @@ TodoModifyTool = CompatibleTodoModifyTool
install_todo_modify_compat_patch()
_react_config = get_config().get("react", {})
-_sandbox_config = get_config().get("sandbox", {})
_CRON_TOOL_CHANNEL_ID: ContextVar[str] = ContextVar(
"cron_tool_channel_id",
@@ -477,6 +474,7 @@ class JiuWenClawDeepAdapter:
self._tool_cards = None
self._evolution_watcher_tasks: set[asyncio.Task] = set()
self._sys_operation = None
+ self._sys_operation_card: SysOperationCard | None = None
self._vision_model_config: VisionModelConfig | None = None
self._audio_model_config: AudioModelConfig | None = None
self._video_model_config: bool = False
@@ -1528,53 +1526,56 @@ class JiuWenClawDeepAdapter:
return rail
@staticmethod
- def _create_sandbox_sys_operation(sandbox_url, sandbox_type) -> SysOperationCard | None:
- """Create a sandbox sys operation."""
- import openjiuwen.extensions.sys_operation.sandbox.providers
- try:
- file_funcs = [
- get_deepagent_agent_md_path,
- get_deepagent_heartbeat_path,
- get_deepagent_identity_md_path,
- get_deepagent_soul_md_path,
- get_deepagent_user_md_path
- ]
- sandbox_policy = {
- "policy": {
- 'filesystem_policy': {
- 'files': [],
- 'directories': []
- }
- },
- "policy_mode": "append",
- }
- for func in file_funcs:
- path = func()
- if path is not None:
- sandbox_policy["policy"]["filesystem_policy"]["files"].append(
- {"path": str(path), "permissions": "0666"}
- )
- sandbox_policy["policy"]["filesystem_policy"]["directories"].append(
- {"path": str(get_agent_memory_dir() / "daily_memory"), "permissions": "0777"}
- )
- gateway_config = SandboxGatewayConfig(
- isolation=SandboxIsolationConfig(container_scope=ContainerScope.SYSTEM),
- launcher_config=PreDeployLauncherConfig(
- base_url=sandbox_url,
- sandbox_type=sandbox_type,
- idle_ttl_seconds=600,
- extra_params=sandbox_policy,
- ),
- )
- sysop_card = SysOperationCard(
- mode=OperationMode.SANDBOX,
- work_config=LocalWorkConfig(shell_allowlist=None),
- gateway_config=gateway_config,
- )
- return sysop_card
- except Exception as exc:
- logger.warning("[JiuWenClawDeepAdapter] create sandbox sys operation failed: %s", exc)
- return None
+ def _create_sandbox_sys_operation(
+ sandbox_url: str,
+ sandbox_type: str,
+ *,
+ runtime: dict[str, Any] | None = None,
+ project_dir: str | None = None,
+ ) -> SysOperationCard | None:
+ """Create a sandbox SysOperationCard.
+
+ Delegates the actual construction to ``sysop_builder.py`` so that both
+ ``interface_deep.py`` and ``interface_code.py`` share one implementation.
+
+ Args:
+ sandbox_url: jiuwenbox HTTP base url.
+ sandbox_type: provider 名 (jiuwenbox).
+ runtime: ``sandbox`` 字段字典 (含 enabled / files / excluded_commands),
+ 来自 ``get_sandbox_runtime``.
+ project_dir: 用户项目目录 (一般是 ``trusted_dirs[0]``); 透传给
+ :func:`create_sandbox_sysop_card` 让其作为 rw bind mount。``None``
+ 时由下游 :func:`build_filesystem_policy` 回落到 cwd / env。
+ """
+ runtime = runtime or {}
+ return create_sandbox_sysop_card(
+ sandbox_url,
+ sandbox_type,
+ files_runtime=runtime.get("files"),
+ excluded_commands=runtime.get("excluded_commands"),
+ project_dir=project_dir,
+ )
+
+ def _resolve_project_dir_for_sandbox(self) -> str | None:
+ """Best-effort lookup of the user project directory for sandbox builds.
+
+ Prefers ``self._project_dir``,
+ then falls back to ``self._instance_overrides["project_dir"]`` which
+ :meth:`AgentManager.get_agent` populates from ``trusted_dirs[0]``.
+ Returning ``None`` lets :func:`build_filesystem_policy` use its own
+ fallback chain, but the agent-server cwd usually isn't what we want
+ so callers should treat ``None`` as "policy will mount cwd, which
+ may shadow secrets" and at minimum log it.
+ """
+ direct = getattr(self, "_project_dir", None)
+ if direct:
+ return str(direct)
+ overrides = getattr(self, "_instance_overrides", None)
+ if isinstance(overrides, dict):
+ value = overrides.get("project_dir")
+ if value:
+ return str(value)
+ return None
@staticmethod
def _sys_operation_isolation_key(sysop_card: SysOperationCard) -> str | None:
@@ -1612,22 +1613,39 @@ class JiuWenClawDeepAdapter:
)
return None
- @staticmethod
- def _create_sys_operation() -> SysOperation | None:
- """Create a sys operation."""
+ def _create_sys_operation(self) -> SysOperation | None:
+ """Create a sys operation.
+
+ 是否走沙箱由 ``config.yaml::sandbox.enabled`` 决定(同时要求
+ ``sandbox.url`` / ``sandbox.type`` 已配置)。其他 sandbox 字段
+ (``excluded_commands`` / ``files``) 透传给 ``create_sandbox_sysop_card``
+ 写入 ``launcher_config.extra_params``。
+
+ 注意: 每次都从 ``get_config()`` 读最新 sandbox.url/type, 因为
+ ``/sandbox enable`` 会动态写入这两个字段。
+
+ 副作用: 在 ``self._sys_operation_card`` 保存生成或复用的 SysOperationCard,
+ 供 ``apply_sandbox_runtime_patch`` 等运行时热更使用。
+ """
try:
- sandbox_url = _sandbox_config.get("url", None)
- sandbox_type = _sandbox_config.get("type", None)
- if sandbox_url and sandbox_type:
- sysop_card = JiuWenClawDeepAdapter._create_sandbox_sys_operation(sandbox_url, sandbox_type)
- else:
- sysop_card = SysOperationCard(
- mode=OperationMode.LOCAL,
- work_config=LocalWorkConfig(shell_allowlist=None),
+ sandbox_cfg = (get_config() or {}).get("sandbox") or {}
+ sandbox_url = sandbox_cfg.get("url", None)
+ sandbox_type = sandbox_cfg.get("type", None)
+ runtime = get_sandbox_runtime()
+ sysop_card: SysOperationCard | None
+ if runtime.get("enabled") and sandbox_url and sandbox_type:
+ sysop_card = JiuWenClawDeepAdapter._create_sandbox_sys_operation(
+ sandbox_url,
+ sandbox_type,
+ runtime=runtime,
+ project_dir=self._resolve_project_dir_for_sandbox(),
)
+ else:
+ sysop_card = create_local_sysop_card()
if sysop_card is None:
logger.warning("[JiuWenClawDeepAdapter] add sys_operation failed: sysop_card is None")
return None
+ self._sys_operation_card = sysop_card
isolation_key_template = JiuWenClawDeepAdapter._sys_operation_isolation_key(sysop_card)
registered_sys_operation = (
JiuWenClawDeepAdapter._get_registered_sys_operation_by_isolation_key(
@@ -1661,6 +1679,88 @@ class JiuWenClawDeepAdapter:
logger.warning("[JiuWenClawDeepAdapter] add sys_operation failed: %s", exc)
return None
+ async def apply_sandbox_runtime_patch(
+ self, runtime: dict[str, Any], *, files_changed: bool
+ ) -> None:
+ """轻量级热更新沙箱 runtime 参数(无需重建 agent).
+
+ - 通过 mutate 已构建 SysOperationCard 的 ``launcher_config.extra_params``
+ 字典让 provider 下次 exec 时读到新值(provider 持 dict 引用)。
+ - ``files_changed=True`` 时额外调用 ``force_recreate_jiuwenbox_sandbox``,
+ 清除共享 sandbox_id 缓存并立即在 jiuwenbox 服务端新建 sandbox 实例,
+ 把新 ID 写回 ``extra_params["sandbox_id"]``。
+
+ Args:
+ runtime: ``get_sandbox_runtime()`` 当前完整 runtime。
+ files_changed: 是否触发文件 policy 变更; 仅 files.* 子命令需要 True。
+ """
+ card = self._sys_operation_card
+ if card is None or card.mode != OperationMode.SANDBOX:
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] apply_sandbox_runtime_patch skipped: "
+ "no active sandbox sys_operation"
+ )
+ return
+
+ launcher = card.gateway_config.launcher_config if card.gateway_config else None
+ if launcher is None:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] apply_sandbox_runtime_patch: missing launcher_config"
+ )
+ return
+
+ extra = launcher.extra_params or {}
+ extra["excluded_commands"] = list(runtime.get("excluded_commands") or [])
+ new_policy, upload_list = build_filesystem_policy(
+ runtime.get("files") or {},
+ project_dir=self._resolve_project_dir_for_sandbox(),
+ )
+ extra["policy"] = new_policy
+ # provider 侧契约: 沙箱 sysop 永远带这两个 key, mode 固定 ``mount``,
+ # upload_list 当前一定是空 list。
+ extra["preserve_files_upload"] = upload_list
+ extra["preserve_file_sharing_mode"] = "mount"
+ extra.setdefault("policy_mode", "append")
+ launcher.extra_params = extra
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] sandbox runtime patched "
+ "(exclude=%d, files_changed=%s, uploads=%d)",
+ len(extra["excluded_commands"]),
+ files_changed,
+ len(upload_list),
+ )
+
+ if files_changed:
+ try:
+ from openjiuwen.extensions.sys_operation.sandbox.providers.jiuwenbox import (
+ force_recreate_jiuwenbox_sandbox,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] force_recreate_jiuwenbox_sandbox import "
+ "failed: %s",
+ exc,
+ )
+ return
+ try:
+ new_sandbox_id = await force_recreate_jiuwenbox_sandbox(
+ launcher.base_url,
+ policy=new_policy,
+ policy_mode=extra.get("policy_mode", "append"),
+ preserve_files_upload=upload_list,
+ )
+ extra["sandbox_id"] = new_sandbox_id
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] sandbox instance recreated: %s",
+ new_sandbox_id,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] force_recreate_jiuwenbox_sandbox "
+ "failed: %s",
+ exc,
+ )
+
@staticmethod
def _build_filesystem_rail() -> SysOperationRail | None:
"""Build SysOperationRail."""
diff --git a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
new file mode 100644
index 0000000000..f984d89d2e
--- /dev/null
+++ b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
@@ -0,0 +1,854 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""SysOperationCard 构建工具 — 抽离自 interface_deep.py。
+
+`interface_deep.py` 和 `interface_code.py` 都依赖此模块构造 sys_operation 卡片,
+不再通过类继承调用,避免静态方法依赖耦合。
+
+公开 API:
+- ``create_sandbox_sysop_card``: 构造 jiuwenbox 沙箱模式 SysOperationCard
+- ``create_local_sysop_card``: 构造本地模式 SysOperationCard
+- ``build_filesystem_policy``: 组装沙箱 filesystem policy(固有目录 + 用户自定义)
+
+关于固有文件共享 (``preserve_file_sharing_mode``):
+
+当前只支持 ``mount``: 把固有 agent 文件 (AGENT.md / HEARTBEAT.md /
+IDENTITY.md / SOUL.md / USER.md) 与 ``daily_memory`` 目录通过 ``bind_mounts``
+直接挂载进沙箱 (``host_path == sandbox_path``, mode=rw), 沙箱内外实时同步,
+无需上传。 类型别名 :data:`PreserveFileSharingMode` 收窄为 ``Literal["mount"]``,
+将来若引入新模式 (例如 overlay) 时再扩成 union。
+
+关于 "project_dir":
+
+- ``build_filesystem_policy`` 默认会把当前进程 cwd (代码 agent 运行起来时通常就是
+ 用户的工程根目录) 以 rw 模式 bind 进沙箱, 同名同路径; 同时把该目录登记进
+ allow 列表方便用户/前端展示。
+- 同时, jiuwenswarm 自己的 ``config.yaml`` (含模型 API key 等敏感凭据) 永远会
+ 作为 auto-deny (``bind_mount rw`` + ``read_only`` patch, 末尾 bwrap
+ ``--remount-ro``) 加入策略, 防止 sandbox 内的 agent 写改它; 读不被屏蔽
+ (这是 ``files.deny`` 的 deny_write 语义)。
+
+关于 ``files.allow`` / ``files.deny`` 的对称设计:
+
+- 两者共用同一套"检查 path → 翻译成 bind_mount + (read_write|read_only) patch"
+ 流程, 只是 patch 字段不同。
+- path 在 host 上必须存在, 否则抛 ``FileNotFoundError`` 让上层
+ (``_handle_sandbox_files_set`` / ``_handle_sandbox_files_remove`` 的 dry-run)
+ 转成 ``ValueError`` 回 TUI。 不存在的 path 既无意义又会让 bwrap 启动失败,
+ 早 fail 早提示。
+- file / dir 一律用 ``Path.is_file()`` / ``is_dir()`` 实际 stat 磁盘判断, 不
+ 再依赖路径尾斜杠。
+- allow 翻成 ``bind_mount mode=rw`` + 把 path 写进 patch ``read_write`` (防
+ base policy 的 ``read_only`` 在 bwrap 末尾把 mount 推回 ro); deny 翻成
+ ``bind_mount mode=rw`` + 把 path 写进 patch ``read_only`` (让 bwrap 末尾
+ ``--remount-ro`` 把这条 bind 翻成 ro)。 deny 故意用 ``mode=rw`` 而非
+ ``mode=ro``: bwrap 输出顺序是 ro_binds 在 rw_binds 之前, 子 deny 若用
+ mode=ro 会被父 allow 的 mode=rw 后到覆盖, deny 失效; 子 deny 用 mode=rw
+ 跟父挂同处于 rw_binds 阶段, 按 list 顺序在父后, 再靠 ``--remount-ro``
+ 兜底翻 ro, 才能在 "父 rw + 子 deny" 拓扑下让 deny 真生效。
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+from pathlib import Path
+from typing import Any, Literal
+
+from openjiuwen.core.sys_operation import (
+ LocalWorkConfig,
+ OperationMode,
+ SandboxGatewayConfig,
+ SysOperationCard,
+)
+from openjiuwen.core.sys_operation.config import (
+ ContainerScope,
+ PreDeployLauncherConfig,
+ SandboxIsolationConfig,
+)
+
+from jiuwenswarm.common.utils import (
+ get_agent_memory_dir,
+ get_config_file,
+ get_deepagent_agent_md_path,
+ get_deepagent_heartbeat_path,
+ get_deepagent_identity_md_path,
+ get_deepagent_soul_md_path,
+ get_deepagent_user_md_path,
+)
+
+logger = logging.getLogger(__name__)
+
+
+PreserveFileSharingMode = Literal["mount"]
+_PRESERVE_FILE_SHARING_MODE: PreserveFileSharingMode = "mount"
+
+
+_INTRINSIC_FILE_PATH_FUNCS = (
+ get_deepagent_agent_md_path,
+ get_deepagent_heartbeat_path,
+ get_deepagent_identity_md_path,
+ get_deepagent_soul_md_path,
+ get_deepagent_user_md_path,
+)
+
+
+def _normalize_fs_entry(entry: Any, default_permissions: str) -> dict[str, Any] | None:
+ """归一化 {path, permissions} 项;接受 str/dict,过滤空值。"""
+ if entry is None:
+ return None
+ if isinstance(entry, str):
+ path = entry.strip()
+ if not path:
+ return None
+ return {"path": path, "permissions": default_permissions}
+ if isinstance(entry, dict):
+ path = str(entry.get("path") or "").strip()
+ if not path:
+ return None
+ permissions = str(entry.get("permissions") or default_permissions)
+ return {"path": path, "permissions": permissions}
+ return None
+
+
+def _ensure_intrinsic_file(path: Path) -> bool:
+ """确保固有文件存在; 不存在则建空文件 (含父目录)。返回是否就绪可用。
+
+ 创建失败 (例如父目录不可写) 时记录 warning 并返回 ``False``, 让调用方
+ 把该条目从 sandbox 的 bind-mount / upload 列表里剔出去——bwrap 在 mount
+ 时要求 ``host_path`` 必须存在, 提前剔掉避免后续沙箱启动直接 fail。
+ """
+ try:
+ if path.exists():
+ return True
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.touch(exist_ok=True)
+ logger.info("[sysop_builder] created empty intrinsic file: %s", path)
+ return True
+ except OSError as exc:
+ logger.warning(
+ "[sysop_builder] could not ensure intrinsic file %s: %s; "
+ "skipping from sandbox bind/upload list",
+ path,
+ exc,
+ )
+ return False
+
+
+def _ensure_intrinsic_dir(path: Path) -> bool:
+ """确保固有目录存在; 不存在则 ``mkdir -p``。返回是否就绪可用。"""
+ try:
+ path.mkdir(parents=True, exist_ok=True)
+ if not path.is_dir():
+ logger.warning(
+ "[sysop_builder] intrinsic path %s exists but is not a directory; "
+ "skipping from sandbox bind/upload list",
+ path,
+ )
+ return False
+ return True
+ except OSError as exc:
+ logger.warning(
+ "[sysop_builder] could not ensure intrinsic dir %s: %s; "
+ "skipping from sandbox bind/upload list",
+ path,
+ exc,
+ )
+ return False
+
+
+def _collect_intrinsic_targets() -> tuple[list[str], list[str]]:
+ """收集 deep agent 固有文件路径与目录路径 (host 上的绝对路径).
+
+ 会对每个解析到的路径做存在性检查; 不存在则创建空文件 / 空目录,
+ 保证下游 bind_mount 时 host_path 一定存在。 创建失败的条目会被静默剔除,
+ 避免污染 sandbox 启动路径。
+
+ Returns:
+ ``(file_paths, dir_paths)``; 解析或创建失败的条目均跳过。
+ """
+ file_paths: list[str] = []
+ dir_paths: list[str] = []
+
+ for func in _INTRINSIC_FILE_PATH_FUNCS:
+ try:
+ raw = func()
+ except Exception as exc: # noqa: BLE001
+ logger.debug("[sysop_builder] intrinsic file path func failed: %s", exc)
+ continue
+ if raw is None:
+ continue
+ path = Path(raw)
+ if _ensure_intrinsic_file(path):
+ file_paths.append(str(path))
+
+ try:
+ daily_memory = Path(get_agent_memory_dir()) / "daily_memory"
+ except Exception as exc: # noqa: BLE001
+ logger.debug("[sysop_builder] daily_memory dir resolve failed: %s", exc)
+ else:
+ if _ensure_intrinsic_dir(daily_memory):
+ dir_paths.append(str(daily_memory))
+
+ return file_paths, dir_paths
+
+
+def _resolve_project_dir(override: str | Path | None) -> Path | None:
+ """Resolve the host directory to bind into the sandbox as ``rw``.
+
+ Priority:
+ 1. ``override`` argument (caller-supplied; useful for tests / explicit
+ project pinning when ``cwd`` is not what we want).
+ 2. ``JIUSWARM_SANDBOX_PROJECT_DIR`` env (allows operations to pin a
+ project dir without code changes).
+ 3. ``Path.cwd()``: the process working directory at the time
+ ``build_filesystem_policy`` is called.
+
+ Returns ``None`` when the resolved path doesn't exist, isn't a directory,
+ or is the filesystem root (we refuse to ``rw``-bind ``/``; that would
+ expose every other host file the user didn't intend to share).
+ """
+ candidates: list[Path] = []
+ if override is not None:
+ candidates.append(Path(override))
+ env_override = os.getenv("JIUSWARM_SANDBOX_PROJECT_DIR")
+ if env_override:
+ candidates.append(Path(env_override))
+ candidates.append(Path.cwd())
+
+ for cand in candidates:
+ try:
+ resolved = cand.expanduser().resolve()
+ except OSError as exc:
+ logger.debug(
+ "[sysop_builder] project_dir candidate %s could not be resolved: %s",
+ cand, exc,
+ )
+ continue
+ if not resolved.is_dir():
+ logger.debug(
+ "[sysop_builder] project_dir candidate %s is not a directory; skipping",
+ resolved,
+ )
+ continue
+ if resolved == Path(resolved.anchor):
+ # Filesystem root (``/`` on POSIX, ``C:\`` on Windows). Refusing
+ # to rw-bind root is non-negotiable: it would shadow every other
+ # ro mount the policy carefully set up, plus expose host secrets
+ # that the user never intended the sandbox to see.
+ logger.warning(
+ "[sysop_builder] refusing to mount filesystem root %s as rw "
+ "project directory; pick a more specific cwd or set "
+ "JIUSWARM_SANDBOX_PROJECT_DIR",
+ resolved,
+ )
+ return None
+ return resolved
+ return None
+
+
+def build_filesystem_policy(
+ files_runtime: dict[str, Any] | None,
+ *,
+ project_dir: str | Path | None = None,
+) -> tuple[dict[str, Any], list[dict[str, str]]]:
+ """组装 jiuwenbox 沙箱的 filesystem policy.
+
+ Args:
+ files_runtime: ``config.yaml::sandbox.files`` 的字典,可能包含
+ ``allow`` / ``deny`` 列表(项支持 str 或 {path, permissions} 形式)
+ project_dir: 当前工程目录的覆盖值, 缺省时回落到 :func:`_resolve_project_dir`
+ (优先级 override -> 环境变量 -> ``cwd``). 解析成功时会作为 ``rw``
+ bind mount 进沙箱, 并同步登记到 allow 列表; 解析失败 (例如指向
+ ``/``) 时静默跳过。
+
+ Returns:
+ ``(policy_dict, upload_list)``:
+ - ``policy_dict``: ``{"filesystem_policy": {"files": [...], "directories":
+ [...], "bind_mounts": [...], "read_write": [...], "read_only": [...]}}``;
+ - ``upload_list``: 当前一律返回 ``[]``。 该字段是 jiuwenbox provider
+ 的 ``preserve_files_upload`` 字段约定 (元素形如
+ ``{host_path, sandbox_path, kind}``); ``mount`` 模式下所有 intrinsic
+ 路径都走 ``bind_mounts``, 不需要 upload, 该列表始终为空。
+
+ Raises:
+ FileNotFoundError: 当 ``files.allow`` / ``files.deny`` 中任何一条 path
+ 在 host 上不存在时抛出。``/sandbox files allow|deny`` 的语义是
+ 「把已经存在于 host 的路径以可写/只读形式带进沙箱」, 对一个不存在
+ 的 path 操作既无意义 (沙箱里也无东西可挂) 又会让 bwrap 启动失败
+ (``--bind <host_src>`` 要求 ``host_src`` 真实存在), 因此前置直接
+ 拒绝。``_handle_sandbox_files_set`` / ``_handle_sandbox_files_remove``
+ 的 dry-run 会把它捕获成 ``ValueError`` 回 TUI 让用户看到。
+ """
+ files_runtime = files_runtime or {}
+
+ allow_files: list[dict[str, Any]] = []
+ allow_dirs: list[dict[str, Any]] = []
+ bind_mounts: list[dict[str, Any]] = []
+ upload_list: list[dict[str, str]] = []
+ # 沙箱里 mode=="rw" 的 bind mount 列表 (用 sandbox_path 记账)。曾用于
+ # ``_validate_deny_not_under_writable`` 的冲突自检; 现在 deny 用
+ # ``mode=rw bind + 末尾 --remount-ro`` 实现, 「父 rw + 子 deny」是合法
+ # 配置 (恰好就是用户想要的 "整目录可写、单子项禁写" 语义), 不再有冲突。
+ # 该 list 留作其他诊断信息源, 不再驱动校验路径。
+ writable_paths: list[str] = []
+ # 需要写进 patch 顶层 ``read_write`` 的 sandbox 路径。 当用户通过
+ # ``/sandbox files allow <path>`` 要求把一个**也出现在 base policy
+ # ``read_only`` 白名单里**的路径 (例如 ``code-agent-policy.yaml`` 默认
+ # 给 ``/tmp`` 配的 ro) 升级成可写时, 仅仅追加一条 rw ``bind_mount`` 还
+ # 不够: bwrap 在所有 bind 完成后会按 ``read_only - read_write`` 差集
+ # 执行 ``--remount-ro``, 把我们刚加的 rw bind 推回只读 (见
+ # ``BwrapConfig._apply_filesystem`` 第 139-142 行)。把同一个 sandbox 路
+ # 径也写进 patch ``read_write``, ``policy_engine.merge_policy`` 会把它
+ # 并入 base 的 ``read_write`` (list dedupe append), bwrap 端的差集就把这
+ # 条 remount-ro 抠掉, rw bind 才真正生效。Landlock 那边由 ``landlock.py``
+ # 直接根据 ``bind_mounts.mode`` 推导, 不依赖这里。
+ read_write_promote: list[str] = []
+ # 需要写进 patch 顶层 ``read_only`` 的 sandbox 路径——给 ``files.deny``
+ # (``deny_write`` 语义) 用。 deny 的实现路径是:
+ #
+ # 1. ``bind_mounts: {host: path, sandbox: path, mode: rw}`` 先把 path
+ # 作为独立 bind_mount 挂上去, 让它进入 ``BwrapConfig.created_paths``
+ # (``bwrap.py::to_args`` 的 created_paths 集合, ``--remount-ro`` 仅
+ # 对集合内 path 生效);
+ # 2. ``read_only: [path]`` 通过 ``policy_engine.merge_policy`` 并入 base
+ # ``read_only``, ``BwrapConfig._apply_filesystem`` 把它推进 ``cfg
+ # .remount_ro``;
+ # 3. bwrap to_args 末尾 ``--remount-ro <path>`` 把这条 mount 翻成 ro,
+ # 实现"父挂 rw + 子项 deny_write"语义。
+ #
+ # 为什么 step 1 的 bind_mount 用 ``mode=rw`` 而不是 ``mode=ro``: bwrap
+ # 输出顺序是 ``--ro-bind`` (line 381) 在 ``--bind`` (line 385) 之前;
+ # 如果 deny 用 ``mode=ro``, 而父 allow 用 ``mode=rw``, 父挂后到达会覆盖
+ # 子挂回到 rw, deny 失效。统一让 deny 的 bind_mount 跟父挂同处于
+ # ``rw_binds`` 阶段 (按 list 顺序子在父后), 再靠 ``--remount-ro`` 兜底
+ # 翻 ro 是唯一能在 bwrap 现有 mount-stage 框架下做出来的可靠方案。
+ read_only_promote: list[str] = []
+
+ def _record_rw_bind(
+ host_path: str,
+ sandbox_path: str,
+ *,
+ is_dir: bool,
+ permissions: str,
+ ) -> None:
+ """Register an rw bind mount (used by intrinsic / project-dir paths).
+
+ We deliberately do NOT also append the path to ``allow_files`` /
+ ``allow_dirs``: jiuwenbox's policy validator rejects any
+ ``bind_mount.sandbox_path`` that also appears in ``filesystem_policy
+ .files`` (or ``.directories``) with
+ ``"Filesystem file path '<x>' conflicts with a bind mount"``. Earlier
+ revisions duplicated bind-mounted paths into the allow lists so that
+ ``/sandbox status`` could read "what's writable" from a single
+ place, but that view is now computed independently by
+ :func:`list_effective_sandbox_files`, so the redundancy serves no
+ purpose and actively breaks sandbox creation in mount mode.
+
+ ``permissions`` is intentionally unused for the same reason -- bind
+ mounts carry their own mode; the previous ``permissions`` value is
+ kept in the signature so the callers (intrinsic / intrinsic-dir /
+ project-dir) stay symmetric and self-documenting at the call site.
+ """
+ del permissions # retained on the signature for caller-side symmetry
+ bind_mounts.append({
+ "host_path": host_path,
+ "sandbox_path": sandbox_path,
+ "mode": "rw",
+ })
+ if sandbox_path not in writable_paths:
+ writable_paths.append(sandbox_path)
+
+ def _record_user_deny_bind(host_path: str, sandbox_path: str) -> None:
+ """Register a deny_write bind: ``bind_mount mode=rw`` + ``read_only`` patch.
+
+ 见模块顶部 ``read_only_promote`` 注释关于为什么必须 ``mode=rw`` 而非
+ ``mode=ro``。这两条记录配合 bwrap 的 ``--bind`` + 末尾 ``--remount-ro``
+ 实现「先把 path bind 上去拿到 ``created_paths`` 通行证, 再 remount 成
+ ro」, 在「父 rw + 子 deny」拓扑下也能让 deny 子项真生效。
+ """
+ bind_mounts.append({
+ "host_path": host_path,
+ "sandbox_path": sandbox_path,
+ "mode": "rw",
+ })
+ if sandbox_path not in read_only_promote:
+ read_only_promote.append(sandbox_path)
+
+ intrinsic_files, intrinsic_dirs = _collect_intrinsic_targets()
+
+ for path in intrinsic_files:
+ _record_rw_bind(path, path, is_dir=False, permissions="0666")
+
+ for path in intrinsic_dirs:
+ _record_rw_bind(path, path, is_dir=True, permissions="0777")
+
+ # 当前工程目录 (cwd) 走 rw bind, 让 sandbox 内的 agent 能读写用户的代码
+ # 仓库。 解析失败 / 指向 ``/`` 一律跳过 (由 _resolve_project_dir 内部 warn)。
+ resolved_project = _resolve_project_dir(project_dir)
+ if resolved_project is not None:
+ project_str = str(resolved_project)
+ _record_rw_bind(project_str, project_str, is_dir=True, permissions="0777")
+
+ # ``files.allow`` 与 ``files.deny`` 走完全对称的处理流程:
+ #
+ # 1. ``_normalize_fs_entry`` 拿到 ``{path, permissions}`` (permissions
+ # 在新方案里不再被 bind_mount 消费, 但保留以兼容 effective_files
+ # view 的展示逻辑);
+ # 2. 路径剥掉尾斜杠—— file/dir 不再用斜杠区分, 也不再走 lifecycle 空
+ # 文件/空目录的兜底; 一律用磁盘 stat 判断, 不存在直接抛错;
+ # 3. 存在 → ``_record_rw_bind`` (allow) 或 ``_record_user_deny_bind``
+ # (deny) 翻成 ``bind_mount`` 一条 + ``read_write`` / ``read_only``
+ # patch 字段。
+ #
+ # 为什么 host 上不存在的路径要拒绝, 而不是默默放过 / 走 lifecycle:
+ # - bwrap 启动时 ``--bind <host_src> <sandbox_dst>`` 要求 ``host_src``
+ # 存在, 否则 bwrap 直接退出 sandbox 创建失败;
+ # - lifecycle ``directories`` / ``files`` 字段 (jiuwenbox 在沙箱内
+ # ``mkdir`` / ``touch`` 空占位) 会被父挂 (``bind_root_entries``
+ # 展开 / 用户其他 allow) 覆盖回原内容, 既无法 "凭空多一个可写目录",
+ # 又会在用户视角制造 "config 看似生效, 沙箱里却不见"的迷惑;
+ # - 用户语义是 "把 host 已有 path 带进沙箱", 不存在的 path 操作
+ # 本身就是 no-op, 报错让用户立刻知道 path 拼错或文件还没建。
+ for entry in files_runtime.get("allow") or []:
+ normalized = _normalize_fs_entry(entry, default_permissions="0666")
+ if normalized is None:
+ continue
+ path = normalized["path"].rstrip("/") or "/"
+ normalized["path"] = path
+ host = Path(path)
+ if not host.exists():
+ raise FileNotFoundError(
+ f"sandbox files.allow path does not exist on host: {path!r}"
+ )
+ _record_rw_bind(
+ path,
+ path,
+ is_dir=host.is_dir(),
+ permissions=str(normalized.get("permissions") or "0666"),
+ )
+ if path not in read_write_promote:
+ read_write_promote.append(path)
+
+ # jiuwenswarm 自己的 config.yaml 永远 deny_write: 文件里有模型 API key /
+ # OAuth secret 之类的凭据。 即便 ``/`` 被 ro-bind 进沙箱 (code-agent-
+ # policy.yaml 默认行为) 或 project_dir 把整个 ``~/.jiuwenswarm/`` 暴露
+ # 进来, 沙箱内还能读到这份 config.yaml; 我们这条 auto-deny 通过
+ # ``_record_user_deny_bind`` 把它翻成 ``bind_mount rw`` + ``read_only``
+ # patch, 末尾 ``--remount-ro`` 把它从用户 ``allow`` 升出来的 rw 区域里
+ # 挑出来禁写。 读权限不变 (符合 deny_write 语义), 但 agent 已无法把任何
+ # 修改写回 host config.yaml.
+ try:
+ config_yaml_path = str(Path(get_config_file()).expanduser().resolve())
+ if config_yaml_path and Path(config_yaml_path).exists():
+ _record_user_deny_bind(config_yaml_path, config_yaml_path)
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[sysop_builder] could not resolve config.yaml for auto deny: %s",
+ exc,
+ )
+
+ for entry in files_runtime.get("deny") or []:
+ normalized = _normalize_fs_entry(entry, default_permissions="0000")
+ if normalized is None:
+ continue
+ path = normalized["path"].rstrip("/") or "/"
+ normalized["path"] = path
+ host = Path(path)
+ if not host.exists():
+ raise FileNotFoundError(
+ f"sandbox files.deny path does not exist on host: {path!r}"
+ )
+ _record_user_deny_bind(path, path)
+
+ fs_policy: dict[str, Any] = {
+ "files": allow_files,
+ "directories": allow_dirs,
+ }
+ if bind_mounts:
+ fs_policy["bind_mounts"] = bind_mounts
+ if read_write_promote:
+ # patch 顶层 ``read_write``——``policy_engine.merge_policy`` 按
+ # list-dedupe-append 并入 base, 用来把 base policy ``read_only`` 中
+ # 同名条目带来的尾段 ``--remount-ro`` 抠掉, 否则上面新增的 rw
+ # ``bind_mount`` 会被 bwrap 在所有 bind 之后再推回 ro (见
+ # ``read_write_promote`` 字段注释)。
+ fs_policy["read_write"] = read_write_promote
+ if read_only_promote:
+ # patch 顶层 ``read_only``——给 ``files.deny`` (deny_write 语义) 用,
+ # merge 进 base 后由 bwrap 末尾 ``--remount-ro`` 把对应 bind_mount
+ # 翻成 ro (见 ``read_only_promote`` 字段注释)。
+ fs_policy["read_only"] = read_only_promote
+
+ return {"filesystem_policy": fs_policy}, upload_list
+
+
+def create_sandbox_sysop_card(
+ sandbox_url: str,
+ sandbox_type: str,
+ *,
+ files_runtime: dict[str, Any] | None = None,
+ excluded_commands: list[str] | None = None,
+ idle_ttl_seconds: int = 600,
+ project_dir: str | Path | None = None,
+) -> SysOperationCard | None:
+ """构造 jiuwenbox 沙箱模式 SysOperationCard.
+
+ Args:
+ sandbox_url: jiuwenbox HTTP 服务的 base url, 例如 ``http://127.0.0.1:8321``
+ sandbox_type: jiuwenbox provider 名, 通常为 ``jiuwenbox``
+ files_runtime: ``config.yaml::sandbox.files`` 字典, 含 allow/deny
+ excluded_commands: 命令 glob 列表; 命中时 provider 直接走本地
+ idle_ttl_seconds: 沙箱空闲超时
+ project_dir: 透传给 :func:`build_filesystem_policy` 的工程目录覆盖值;
+ ``None`` 时由其内部回落到 ``cwd``.
+
+ Returns:
+ 构造成功返回 ``SysOperationCard``; 失败 (``build_filesystem_policy``
+ 抛出 ``FileNotFoundError`` / 其他 ``ValueError`` 之类) 返回 ``None``,
+ 异常被捕获记 warning。
+ """
+ # 触发 jiuwenbox provider 注册(@SandboxRegistry.provider 装饰器副作用)
+ import openjiuwen.extensions.sys_operation.sandbox.providers # noqa: F401
+
+ try:
+ policy, upload_list = build_filesystem_policy(
+ files_runtime,
+ project_dir=project_dir,
+ )
+ extra_params: dict[str, Any] = {
+ "policy": policy,
+ "policy_mode": "append",
+ "excluded_commands": list(excluded_commands or []),
+ # provider 契约: 沙箱 sysop 永远带这两个 key, mode 固定 ``mount``,
+ # upload_list 当前固定为空 list。
+ "preserve_file_sharing_mode": _PRESERVE_FILE_SHARING_MODE,
+ "preserve_files_upload": upload_list,
+ }
+
+ gateway_config = SandboxGatewayConfig(
+ isolation=SandboxIsolationConfig(container_scope=ContainerScope.SYSTEM),
+ launcher_config=PreDeployLauncherConfig(
+ base_url=sandbox_url,
+ sandbox_type=sandbox_type,
+ idle_ttl_seconds=idle_ttl_seconds,
+ extra_params=extra_params,
+ ),
+ )
+ sysop_card = SysOperationCard(
+ mode=OperationMode.SANDBOX,
+ work_config=LocalWorkConfig(shell_allowlist=None),
+ gateway_config=gateway_config,
+ )
+
+ fs_policy = policy.get("filesystem_policy", {}) if isinstance(policy, dict) else {}
+ logger.info(
+ "[sysop_builder] sandbox SysOperationCard created:\n"
+ " base_url=%s sandbox_type=%s idle_ttl=%ds\n"
+ " preserve_file_sharing_mode=%s\n"
+ " excluded_commands(%d)=%s\n"
+ " filesystem_policy.files(%d)=%s\n"
+ " filesystem_policy.directories(%d)=%s\n"
+ " filesystem_policy.bind_mounts(%d)=%s\n"
+ " filesystem_policy.read_write(%d)=%s\n"
+ " filesystem_policy.read_only(%d)=%s\n"
+ " preserve_files_upload(%d)=%s\n"
+ " policy_mode=%s",
+ sandbox_url,
+ sandbox_type,
+ idle_ttl_seconds,
+ _PRESERVE_FILE_SHARING_MODE,
+ len(extra_params["excluded_commands"]),
+ extra_params["excluded_commands"] or "[]",
+ len(fs_policy.get("files") or []),
+ fs_policy.get("files") or [],
+ len(fs_policy.get("directories") or []),
+ fs_policy.get("directories") or [],
+ len(fs_policy.get("bind_mounts") or []),
+ fs_policy.get("bind_mounts") or [],
+ len(fs_policy.get("read_write") or []),
+ fs_policy.get("read_write") or [],
+ len(fs_policy.get("read_only") or []),
+ fs_policy.get("read_only") or [],
+ len(upload_list),
+ upload_list or [],
+ extra_params["policy_mode"],
+ )
+ return sysop_card
+ except Exception as exc: # noqa: BLE001
+ logger.warning("[sysop_builder] create sandbox sysop card failed: %s", exc)
+ return None
+
+
+def create_local_sysop_card() -> SysOperationCard:
+ """构造本地模式 SysOperationCard."""
+ logger.info("[sysop_builder] local SysOperationCard created (mode=LOCAL)")
+ return SysOperationCard(
+ mode=OperationMode.LOCAL,
+ work_config=LocalWorkConfig(shell_allowlist=None),
+ )
+
+
+def _append_unique(target: list[dict[str, str]], entry: dict[str, str]) -> None:
+ """Append ``entry`` to ``target`` if no existing item shares its ``path``.
+
+ Pulled out of :func:`list_auto_managed_sandbox_paths` / :func:`list_effective_
+ sandbox_files` so both helpers (and any future caller) dedupe by path the
+ same way: first-write-wins, comparison on the literal ``path`` string.
+ Auto-managed entries always come first, so user entries cannot override
+ them just by replaying the same path.
+ """
+ if not any(item.get("path") == entry["path"] for item in target):
+ target.append(entry)
+
+
+def _classify_host_kind(path: str) -> str:
+ """以 host 文件系统 stat 判定 ``path`` 是 ``"directory"`` 还是 ``"file"``.
+
+ 给 :func:`list_effective_sandbox_files` 用来给用户配置的
+ ``sandbox.files.{allow,deny}`` 条目打 ``kind`` 字段。
+
+ yaml 里的 path 入库前已经被 :func:`_canonicalize_sandbox_files_path`
+ 展开成 absolute resolved 形式 (尾斜杠被 ``resolve()`` 吃掉了), 因此
+ 无法再用 ``endswith("/")`` 判断目录, 必须 stat。
+
+ ``Path(...).is_dir()`` 抛 ``OSError`` (权限不足之类) 或 host 上根本不
+ 存在时, fallback 到 ``"file"``: 写入侧 :func:`build_filesystem_policy`
+ 的 dry-run 已经把不存在的 path 拦在 yaml 之外, 这里跑到 fallback 一般
+ 意味着 yaml 被手工编辑得不一致, 简单兜底比拒绝展示更友好。
+ """
+ try:
+ return "directory" if Path(path).expanduser().is_dir() else "file"
+ except OSError:
+ return "file"
+
+
+def _resolve_display_path(raw: str | Path | None) -> str | None:
+ """Resolve ``raw`` into the canonical absolute path used in display/compare.
+
+ Expands ``~`` and symlinks the same way :func:`build_filesystem_policy`
+ does so that ``list_auto_managed_sandbox_paths`` and
+ :func:`find_auto_managed_match` agree on what counts as the "same" entry.
+ Returns ``None`` for blank or unresolvable inputs.
+ """
+ if raw is None:
+ return None
+ text = str(raw).strip()
+ if not text:
+ return None
+ try:
+ return str(Path(text).expanduser().resolve())
+ except OSError as exc:
+ logger.debug(
+ "[sysop_builder] path %r could not be resolved for display: %s",
+ text, exc,
+ )
+ return None
+
+
+def list_auto_managed_sandbox_paths(
+ project_dir: str | Path | None = None,
+) -> dict[str, list[dict[str, str]]]:
+ """Auto-configured sandbox entries that users cannot mutate via ``/sandbox``.
+
+ These mirror exactly what :func:`build_filesystem_policy` seeds the policy
+ with regardless of user-supplied ``files.allow`` / ``files.deny``:
+
+ - intrinsic agent files (AGENT/HEARTBEAT/IDENTITY/SOUL/USER.md) +
+ ``daily_memory`` dir + project directory are all rw bind-mounted from
+ host.
+ - jiuwenswarm's own ``config.yaml`` is auto-added to ``deny_write`` so
+ Landlock blocks writes to the api-key file even when the bind mounts
+ otherwise expose the parent directory.
+
+ Args:
+ project_dir: explicit project-root override (typically
+ ``trusted_dirs[0]`` cached on the adapter); ``None`` skips the
+ project entry rather than falling back to cwd.
+
+ Returns:
+ ``{"allow_write": [...], "deny_write": [...]}`` where each entry is
+ ``{"path": str, "permissions": str, "kind": "file" | "directory"}``.
+ Directory paths carry a trailing ``/``.
+ """
+ allow: list[dict[str, str]] = []
+ deny: list[dict[str, str]] = []
+
+ for func in _INTRINSIC_FILE_PATH_FUNCS:
+ try:
+ raw = func()
+ except Exception as exc: # noqa: BLE001
+ logger.debug(
+ "[sysop_builder] auto view: intrinsic path func failed: %s",
+ exc,
+ )
+ continue
+ if raw is None:
+ continue
+ _append_unique(
+ allow,
+ {"path": str(Path(raw)), "permissions": "0666", "kind": "file"},
+ )
+
+ try:
+ daily_memory = str(Path(get_agent_memory_dir()) / "daily_memory")
+ except Exception as exc: # noqa: BLE001
+ logger.debug(
+ "[sysop_builder] auto view: daily_memory resolve failed: %s",
+ exc,
+ )
+ else:
+ _append_unique(
+ allow,
+ {"path": daily_memory + "/", "permissions": "0777", "kind": "directory"},
+ )
+
+ if project_dir is not None:
+ try:
+ resolved_project: Path | None = Path(project_dir).expanduser().resolve()
+ except OSError as exc:
+ logger.debug(
+ "[sysop_builder] auto view: project_dir %r resolve failed: %s",
+ project_dir, exc,
+ )
+ resolved_project = None
+ # 同 _resolve_project_dir: 显示侧也拒绝把 filesystem root 当项目目录,
+ # 否则 build_filesystem_policy 会在创建沙箱时拒绝, 让 /sandbox 面板
+ # 显示的 project_dir 与最终实际生效的 rw bind 不一致。
+ if (
+ resolved_project is not None
+ and resolved_project.is_dir()
+ and resolved_project != Path(resolved_project.anchor)
+ ):
+ _append_unique(
+ allow,
+ {
+ "path": str(resolved_project) + "/",
+ "permissions": "0777",
+ "kind": "directory",
+ },
+ )
+
+ # config.yaml 一律加入 auto-deny: 注: 现在 deny 用 ``bind_mount rw + 末尾
+ # --remount-ro`` 实现 (见 ``build_filesystem_policy`` 的
+ # ``_record_user_deny_bind``), "父 rw + 子 deny" 已经是合法配置, 不再有
+ # 过去 ``_validate_deny_not_under_writable`` 那种冲突自检的负担。
+ try:
+ config_yaml_path = str(Path(get_config_file()).expanduser().resolve())
+ except Exception as exc: # noqa: BLE001
+ logger.debug(
+ "[sysop_builder] auto view: config.yaml resolve failed: %s",
+ exc,
+ )
+ else:
+ if config_yaml_path:
+ _append_unique(
+ deny,
+ {"path": config_yaml_path, "permissions": "0000", "kind": "file"},
+ )
+
+ return {"allow_write": allow, "deny_write": deny}
+
+
+def list_effective_sandbox_files(
+ files_runtime: dict[str, Any] | None,
+ *,
+ project_dir: str | Path | None = None,
+) -> dict[str, list[dict[str, str]]]:
+ """Read-only "what will the sandbox actually allow / deny writes to" view.
+
+ The result is the union of :func:`list_auto_managed_sandbox_paths` and the
+ user-configured ``files.allow`` / ``files.deny`` entries from
+ ``config.yaml::sandbox.files``. Auto entries appear first so any
+ duplicate user entry is suppressed (and stays out of the displayed list).
+
+ Mirrors the union :func:`build_filesystem_policy` would assemble, but does
+ NOT create empty files or directories on the host. Intended for display
+ by ``/sandbox status`` / ``/sandbox files list``.
+
+ Args:
+ files_runtime: ``sandbox.files`` dict from ``get_sandbox_runtime()``.
+ project_dir: explicit override for the rw bind-mount root. Callers
+ should pass the trusted-directory project root cached on the
+ adapter (i.e. ``trusted_dirs[0]``); ``None`` means "unknown",
+ which suppresses the project-dir entry instead of falling back
+ to ``cwd``.
+
+ Returns:
+ ``{"allow_write": [...], "deny_write": [...]}`` where every entry is
+ ``{"path": str, "permissions": str, "kind": "file" | "directory"}``.
+ """
+ auto = list_auto_managed_sandbox_paths(project_dir=project_dir)
+ allow = list(auto["allow_write"])
+ deny = list(auto["deny_write"])
+
+ files_runtime = files_runtime or {}
+
+ def _emit(bucket: list[dict[str, str]], entry: Any, default_permissions: str) -> None:
+ normalized = _normalize_fs_entry(entry, default_permissions=default_permissions)
+ if normalized is None:
+ return
+ stripped = str(normalized["path"]).rstrip("/") or "/"
+ kind = _classify_host_kind(stripped)
+ display = stripped + "/" if kind == "directory" and stripped != "/" else stripped
+ _append_unique(
+ bucket,
+ {
+ "path": display,
+ "permissions": str(normalized["permissions"]),
+ "kind": kind,
+ },
+ )
+
+ for entry in files_runtime.get("allow") or []:
+ _emit(allow, entry, "0666")
+ for entry in files_runtime.get("deny") or []:
+ _emit(deny, entry, "0000")
+
+ return {"allow_write": allow, "deny_write": deny}
+
+
+def find_auto_managed_match(
+ path: str,
+ *,
+ project_dir: str | Path | None = None,
+) -> tuple[str, str] | None:
+ """Return ``(bucket, canonical_path)`` if ``path`` is auto-managed; else ``None``.
+
+ Used by ``/sandbox files allow|deny`` to refuse mutations that would
+ duplicate or contradict an auto-managed entry. Comparison normalizes
+ ``~``, trailing slashes, and ``./`` segments so the user can't sneak the
+ same path in by varying its surface form.
+
+ Args:
+ path: user-supplied path (may use ``~``, trailing slash, etc.).
+ project_dir: project-root override forwarded to
+ :func:`list_auto_managed_sandbox_paths`.
+
+ Returns:
+ ``(bucket, canonical_path)`` where ``bucket`` is ``"allow_write"`` or
+ ``"deny_write"`` and ``canonical_path`` is the entry's displayed
+ path (trailing-slash for directories). ``None`` when the path is
+ not auto-managed.
+ """
+ target = _resolve_display_path(path)
+ if target is None:
+ return None
+ auto = list_auto_managed_sandbox_paths(project_dir=project_dir)
+ for bucket in ("allow_write", "deny_write"):
+ for entry in auto.get(bucket, []):
+ candidate = _resolve_display_path(entry.get("path", ""))
+ if candidate is not None and candidate == target:
+ return bucket, str(entry.get("path", ""))
+ return None
+
+
+__all__ = [
+ "PreserveFileSharingMode",
+ "build_filesystem_policy",
+ "create_sandbox_sysop_card",
+ "create_local_sysop_card",
+ "find_auto_managed_match",
+ "list_auto_managed_sandbox_paths",
+ "list_effective_sandbox_files",
+]
diff --git a/jiuwenswarm/server/runtime/agent_manager.py b/jiuwenswarm/server/runtime/agent_manager.py
index a8fb63be52..8f06e876a0 100644
--- a/jiuwenswarm/server/runtime/agent_manager.py
+++ b/jiuwenswarm/server/runtime/agent_manager.py
@@ -52,6 +52,8 @@ class AgentManager:
def __init__(self) -> None:
self.agents: dict[str, dict[str, "JiuWenClaw"]] = {}
+ # 记录每个 (channel_id, mode) 的创建参数, 便于 recreate_agent 立刻重建
+ self._agent_create_params: dict[str, dict[str, dict[str, Any]]] = {}
self._client_capabilities_by_channel: dict[str, dict[str, Any]] = {}
self._latest_env_overrides: dict[str, Any] = {}
@@ -79,6 +81,12 @@ class AgentManager:
agent = JiuWenClaw()
await agent.create_instance(config, mode=mode, sub_mode=sub_mode)
self.agents.setdefault(agent_key, {})[mode] = agent
+ # 记录创建参数, recreate_agent() 时可原样复用
+ self._agent_create_params.setdefault(agent_key, {})[mode] = {
+ "mode": mode,
+ "sub_mode": sub_mode,
+ "config": config,
+ }
logger.info("[AgentManager] %s agent created", agent_key)
return agent
@@ -235,6 +243,92 @@ class AgentManager:
)
logger.info(f"channel {channel_id} reload agent config success.")
+ async def recreate_agent(self, channel_id: str, *, immediate: bool = True) -> list[str]:
+ """重建指定 channel 的所有 agent 实例.
+
+ 用于 ``/sandbox enable/disable`` 等需要重新构建 ``SysOperationCard`` 的场景.
+ 步骤:
+ 1. 备份现有 (mode -> create_params) 映射;
+ 2. cleanup 并删除现有 agent 实例;
+ 3. 若 ``immediate=True``, 依据备份的参数立即重新调用 ``_create_agent()``,
+ 使新的 SysOperation 生效不必等到下次 ``get_agent()``;
+ ``immediate=False`` 则按原行为, 下次 ``get_agent()`` 时再重建.
+
+ Args:
+ channel_id: 通道 ID.
+ immediate: 是否立即重建 (默认 True).
+
+ Returns:
+ 被重建的 mode 列表.
+ """
+ channel_key = channel_id or "default"
+ agents = self.agents.get(channel_key)
+ if not agents:
+ logger.info(
+ "[AgentManager] recreate_agent: no active agent on channel %s",
+ channel_key,
+ )
+ return []
+
+ # 1. 备份 (mode -> create_params)
+ existing_modes = list(agents.keys())
+ backup_params: dict[str, dict[str, Any]] = {}
+ channel_params = self._agent_create_params.get(channel_key) or {}
+ for mode_key in existing_modes:
+ params = channel_params.get(mode_key)
+ if params is None:
+ # 未记录创建参数 (理论上 _create_agent 一定记录), 兜底使用 mode_key
+ params = {"mode": mode_key, "sub_mode": None, "config": None}
+ backup_params[mode_key] = dict(params)
+
+ # 2. cleanup + 删除
+ for mode_key, agent in list(agents.items()):
+ if hasattr(agent, "cleanup"):
+ try:
+ await agent.cleanup()
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[AgentManager] recreate cleanup failed (mode=%s): %s",
+ mode_key,
+ exc,
+ )
+ del self.agents[channel_key]
+ self._agent_create_params.pop(channel_key, None)
+ logger.info(
+ "[AgentManager] recreate_agent: channel %s agents dropped (modes=%s)",
+ channel_key,
+ existing_modes,
+ )
+
+ if not immediate:
+ logger.info(
+ "[AgentManager] recreate_agent: channel %s will rebuild on next get_agent()",
+ channel_key,
+ )
+ return existing_modes
+
+ # 3. 立即按原参数重建
+ for mode_key, params in backup_params.items():
+ try:
+ await self._create_agent(
+ channel_key,
+ mode=params.get("mode") or mode_key,
+ config=params.get("config"),
+ sub_mode=params.get("sub_mode"),
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.error(
+ "[AgentManager] recreate_agent: rebuild failed (mode=%s): %s",
+ mode_key,
+ exc,
+ )
+ logger.info(
+ "[AgentManager] recreate_agent: channel %s rebuilt (modes=%s)",
+ channel_key,
+ existing_modes,
+ )
+ return existing_modes
+
async def cleanup(self) -> None:
"""清理所有 agent 实例."""
for key, agents in list(self.agents.items()):
@@ -245,5 +339,6 @@ class AgentManager:
except Exception as e:
logger.warning("[AgentManager] Agent cleanup failed: %s", e)
del self.agents[key]
+ self._agent_create_params.clear()
self._client_capabilities_by_channel.clear()
logger.info("[AgentManager] All agents cleaned up")
diff --git a/jiuwenswarm/server/sandbox/__init__.py b/jiuwenswarm/server/sandbox/__init__.py
new file mode 100644
index 0000000000..fc7f53948b
--- /dev/null
+++ b/jiuwenswarm/server/sandbox/__init__.py
@@ -0,0 +1 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
diff --git a/jiuwenswarm/server/sandbox/jiuwenbox_runner.py b/jiuwenswarm/server/sandbox/jiuwenbox_runner.py
new file mode 100644
index 0000000000..460ab203e0
--- /dev/null
+++ b/jiuwenswarm/server/sandbox/jiuwenbox_runner.py
@@ -0,0 +1,478 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""管理本地 jiuwenbox uvicorn 子进程 — 由 ``/sandbox enable`` 触发启动.
+
+设计要点:
+- 默认地址 ``http://127.0.0.1:8321``; 端口是否空闲由 ``agent_ws_server`` 在
+ 调用 ``ensure_running`` *之前* 决定 (占用就换随机空闲端口, 避免与未知第三方
+ 进程冲突); 本 runner 不再尝试识别 / 接管端口上的"外部进程".
+- ``startup_mode='internal'`` 时: 若 runner 已经在该 host:port 上拥有一个
+ 与当前 ``policy_path`` 匹配的进程, 直接复用; 否则停掉旧进程并重新 spawn
+ ``uvicorn jiuwenbox.server.app:app`` (通过 ``JIUWENBOX_POLICY_PATH`` 注入
+ policy 文件路径)。
+- ``startup_mode='external'`` 时: 仅做健康检查; 不可达则直接失败, 提示用户
+ 自行 (含 ``sudo``) 启动 jiuwenbox-server, 配合 ``policy_path`` 传入相应 policy;
+- agent_ws_server 进程退出时调用 ``stop()`` 终止子进程, 避免悬挂.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import atexit
+import contextlib
+import logging
+import os
+import signal
+import sys
+import time
+from pathlib import Path
+from typing import Any, Optional
+
+import httpx
+
+logger = logging.getLogger(__name__)
+
+# Linux ``prctl`` PR_SET_PDEATHSIG 选项常量 (来自 ``<linux/prctl.h>``);
+# 模块级常量, 避免在 ``_try_set_pdeathsig`` 函数内出现 UPPER_CASE 局部变量。
+_PR_SET_PDEATHSIG = 1
+
+
+def _resolve_jiuwenbox_src_dir() -> Optional[Path]:
+ """探测仓库内 ``code_agent/jiuwenbox/src``; 若存在则供 PYTHONPATH 注入用.
+
+ 便于无需 ``pip install -e jiuwenbox/`` 也能直接运行本地源码版 jiuwenbox.
+ 返回 ``None`` 表示未找到 (则依赖 site-packages 中的安装版).
+ """
+ here = Path(__file__).resolve()
+ for ancestor in here.parents[1:7]:
+ candidate = ancestor / "jiuwenbox" / "src" / "jiuwenbox" / "__init__.py"
+ if candidate.exists():
+ return candidate.parent.parent
+ return None
+
+
+def _try_set_pdeathsig() -> None:
+ """Linux: 让子进程在父进程退出时收到 SIGTERM, 避免 SIGKILL 父进程时 jiuwenbox 残留.
+
+ 通过 ``preexec_fn`` 调用; 在非 Linux 平台是 no-op.
+ """
+ if not sys.platform.startswith("linux"):
+ return
+ try:
+ import ctypes
+
+ libc = ctypes.CDLL("libc.so.6", use_errno=True)
+ libc.prctl(_PR_SET_PDEATHSIG, signal.SIGTERM, 0, 0, 0)
+ except Exception: # noqa: BLE001
+ pass
+
+
+class JiuwenBoxRunner:
+ """单例形态管理本地 jiuwenbox 子进程."""
+
+ _INSTANCE: "JiuwenBoxRunner | None" = None
+ # stderr 滚动缓冲最大行数; 类级常量, 避免实例级 UPPER_CASE 属性。
+ _STDERR_TAIL_MAX: int = 80
+
+ def __init__(self) -> None:
+ self._process: Optional[asyncio.subprocess.Process] = None
+ self._host: str = "127.0.0.1"
+ self._port: int = 8321
+ self._lock = asyncio.Lock()
+ # 标记进程是否由本 runner 启动; 若用户在外部已起服务, 不应在 stop() 时杀掉
+ self._owns_process: bool = False
+ # 进程退出兜底: atexit 同步钩子, 即便 stop() 没被走到也尝试终止子进程
+ self._atexit_registered: bool = False
+ # 持续 drain 的后台任务以及 stderr 滚动缓冲, 便于子进程异常退出时反查原因
+ self._stdout_pump_task: Optional[asyncio.Task] = None
+ self._stderr_pump_task: Optional[asyncio.Task] = None
+ self._stderr_tail: list[str] = []
+ # 记录最近一次 ensure_running 用到的 startup_mode, 便于诊断 / 日志透出。
+ self._last_startup_mode: str = "internal"
+ # 记录本 runner 上次 spawn 子进程时实际注入的 ``JIUWENBOX_POLICY_PATH``;
+ # 下次 ``ensure_running`` 若发现期望值与之不一致, 必须停掉旧实例重启,
+ # 避免老进程继续用旧 policy (例如 default-policy.yaml) 服务新 sandbox。
+ self._spawned_policy_path: Optional[Path] = None
+
+ @classmethod
+ def instance(cls) -> "JiuwenBoxRunner":
+ if cls._INSTANCE is None:
+ cls._INSTANCE = JiuwenBoxRunner()
+ return cls._INSTANCE
+
+ @property
+ def base_url(self) -> str:
+ return f"http://{self._host}:{self._port}"
+
+ def get_stderr_tail(self, lines: int = 40) -> str:
+ """返回最近 ``lines`` 行子进程 stderr, 便于错误诊断."""
+ if not self._stderr_tail:
+ return ""
+ return "\n".join(self._stderr_tail[-lines:])
+
+ def is_owned_listener(self, host: str, port: int) -> bool:
+ """``True`` 表示当前 runner 持有一个仍在跑的子进程, 且监听在 ``host:port``.
+
+ ``agent_ws_server`` 在分配端口前用它判断"8321 是不是我自己刚才拉起的",
+ 避免误把自己的进程当成外部占用而无谓换端口。
+ """
+ proc = self._process
+ if proc is None or proc.returncode is not None:
+ return False
+ if not self._owns_process:
+ return False
+ return self._host == host and self._port == port
+
+ def get_owned_endpoint(self) -> Optional[tuple[str, int]]:
+ """返回当前由本 runner 拥有的 (host, port); 没有就返回 None."""
+ proc = self._process
+ if proc is None or proc.returncode is not None:
+ return None
+ if not self._owns_process:
+ return None
+ return (self._host, self._port)
+
+ async def health_check(self, host: str | None = None, port: int | None = None) -> bool:
+ target_host = host or self._host
+ target_port = port or self._port
+ url = f"http://{target_host}:{target_port}/health"
+ try:
+ async with httpx.AsyncClient(timeout=2.0) as client:
+ resp = await client.get(url)
+ return resp.status_code == 200
+ except Exception:
+ return False
+
+ async def ensure_running(
+ self,
+ host: str = "127.0.0.1",
+ port: int = 8321,
+ *,
+ timeout: float = 30.0,
+ startup_mode: str = "internal",
+ policy_path: Optional[Path] = None,
+ ) -> bool:
+ """确保 jiuwenbox 在 ``host:port`` 已就绪。
+
+ Args:
+ host / port: jiuwenbox 监听地址。
+ timeout: 健康检查 / 等待就绪的总超时秒数。
+ startup_mode: ``internal`` (agent-server 拉起) 或 ``external``
+ (用户自己启动 jiuwenbox); ``external`` 模式下本方法不会 spawn 子进程,
+ 仅做健康检查。
+ policy_path: jiuwenbox 启动时使用的 policy 文件路径; 仅在
+ ``startup_mode='internal'`` 下生效, 通过 ``JIUWENBOX_POLICY_PATH``
+ 环境变量传给子进程。
+
+ Returns:
+ True 表示启动 / 已运行并通过健康检查; False 表示超时未就绪。
+ """
+ async with self._lock:
+ normalized_mode = (startup_mode or "internal").strip().lower()
+ if normalized_mode not in ("internal", "external"):
+ normalized_mode = "internal"
+ self._last_startup_mode = normalized_mode
+
+ # external 模式: 只做健康检查, 不 spawn / 不 kill 任何进程。
+ # 用户负责保证 jiuwenbox-server 使用合适的 JIUWENBOX_POLICY_PATH 启动。
+ if normalized_mode == "external":
+ self._host = host
+ self._port = port
+ if await self.health_check(host, port):
+ logger.info(
+ "[JiuwenBoxRunner] external jiuwenbox alive at %s:%d "
+ "(policy_path env is user's responsibility, expected=%s)",
+ host,
+ port,
+ policy_path,
+ )
+ return True
+ logger.warning(
+ "[JiuwenBoxRunner] startup_mode=external but %s:%d unreachable; "
+ "user is expected to start jiuwenbox-server manually",
+ host,
+ port,
+ )
+ return False
+
+ # internal 模式: agent-server 自己管理 jiuwenbox 生命周期。
+ # 不再尝试识别端口上的外部进程; 上游 agent_ws_server 已经保证传进来的
+ # ``port`` 是 (a) 我们自己之前拉起的同 host:port 或 (b) 一个空闲端口。
+ #
+ # 决策矩阵:
+ # - 我们拥有的进程仍然 alive 且 host/port/policy_path 全部匹配 → 复用;
+ # - 否则: 停掉旧进程 (如有), 在新的 host:port 上 spawn 全新实例。
+ owned_match = (
+ self._process is not None
+ and self._process.returncode is None
+ and self._owns_process
+ and self._host == host
+ and self._port == port
+ and self._spawned_policy_path == policy_path
+ )
+ if owned_match:
+ if await self.health_check(host, port):
+ logger.info(
+ "[JiuwenBoxRunner] reuse owned jiuwenbox at %s:%d "
+ "(policy_path=%s)",
+ host,
+ port,
+ policy_path,
+ )
+ return True
+ # 进程在跑但还没 ready, 继续等
+ return await self._wait_until_ready(host, port, timeout=timeout)
+
+ # 任何 mismatch (端口变了 / policy 变了 / 进程已退) 都先把旧的清掉。
+ if self._process is not None and self._owns_process:
+ logger.info(
+ "[JiuwenBoxRunner] stopping owned jiuwenbox before spawning new one "
+ "(prev host=%s port=%d policy=%s -> new host=%s port=%d policy=%s)",
+ self._host,
+ self._port,
+ self._spawned_policy_path,
+ host,
+ port,
+ policy_path,
+ )
+ await self._stop_no_lock()
+
+ self._host = host
+ self._port = port
+
+ cmd = [
+ sys.executable,
+ "-m",
+ "uvicorn",
+ "jiuwenbox.server.app:app",
+ "--host",
+ host,
+ "--port",
+ str(port),
+ ]
+ # 若 jiuwenbox 未安装到 site-packages, 尝试用仓库内源码目录注入 PYTHONPATH
+ env = dict(os.environ)
+ local_src = _resolve_jiuwenbox_src_dir()
+ if local_src is not None:
+ existing = env.get("PYTHONPATH", "")
+ parts = [str(local_src)]
+ if existing:
+ parts.append(existing)
+ env["PYTHONPATH"] = os.pathsep.join(parts)
+ logger.info(
+ "[JiuwenBoxRunner] prepending local jiuwenbox src to PYTHONPATH: %s",
+ local_src,
+ )
+ # 把 policy 路径通过环境变量传给 jiuwenbox-server (与 README 中
+ # ``JIUWENBOX_POLICY_PATH`` 用法一致, 即 ``server/app.py`` 启动时读取)。
+ # 如果调用方没给, 显式删掉父进程继承下来的同名变量, 避免误用旧值。
+ if policy_path is not None:
+ env["JIUWENBOX_POLICY_PATH"] = str(policy_path)
+ logger.info(
+ "[JiuwenBoxRunner] injecting JIUWENBOX_POLICY_PATH=%s",
+ policy_path,
+ )
+ else:
+ env.pop("JIUWENBOX_POLICY_PATH", None)
+
+ logger.info("[JiuwenBoxRunner] spawning: %s", " ".join(cmd))
+ try:
+ spawn_kwargs: dict = {
+ "stdout": asyncio.subprocess.PIPE,
+ "stderr": asyncio.subprocess.PIPE,
+ "env": env,
+ }
+ # Linux: 父进程退出时让子进程收到 SIGTERM (PR_SET_PDEATHSIG)
+ if sys.platform.startswith("linux"):
+ spawn_kwargs["preexec_fn"] = _try_set_pdeathsig
+ self._process = await asyncio.create_subprocess_exec(
+ *cmd,
+ **spawn_kwargs,
+ )
+ self._owns_process = True
+ self._spawned_policy_path = policy_path
+ # 同步退出兜底: 即便没走 stop() 也尽可能 terminate 子进程
+ self._register_atexit_once()
+ # 后台持续 drain stdout/stderr, 防止管道堆积阻塞子进程; 同时
+ # 记录滚动 stderr 尾部, 便于失败时反查 uvicorn 的导入/启动错误
+ self._stderr_tail = []
+ self._stdout_pump_task = asyncio.create_task(
+ self._pump_stream(self._process.stdout, "stdout")
+ )
+ self._stderr_pump_task = asyncio.create_task(
+ self._pump_stream(self._process.stderr, "stderr")
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.error("[JiuwenBoxRunner] spawn failed: %s", exc)
+ self._process = None
+ self._owns_process = False
+ self._spawned_policy_path = None
+ return False
+
+ ok = await self._wait_until_ready(host, port, timeout=timeout)
+ if not ok:
+ tail = "\n".join(self._stderr_tail[-40:])
+ if self._process is not None and self._process.returncode is not None:
+ logger.error(
+ "[JiuwenBoxRunner] jiuwenbox subprocess exited rc=%s during startup. "
+ "stderr tail:\n%s",
+ self._process.returncode,
+ tail or "(empty; check if uvicorn / jiuwenbox is installed)",
+ )
+ else:
+ logger.warning(
+ "[JiuwenBoxRunner] health check timeout after %ss; pid=%s. "
+ "stderr tail:\n%s",
+ timeout,
+ self._process.pid if self._process else None,
+ tail or "(empty)",
+ )
+ return ok
+
+ async def _pump_stream(self, stream: Any, kind: str) -> None: # type: ignore[override]
+ """持续读取子进程 stdout/stderr, 写入 logger debug; stderr 额外保留滚动尾部."""
+ if stream is None:
+ return
+ try:
+ while True:
+ line_bytes = await stream.readline()
+ if not line_bytes:
+ return
+ try:
+ line = line_bytes.decode("utf-8", errors="replace").rstrip()
+ except Exception: # noqa: BLE001
+ line = repr(line_bytes)
+ if kind == "stderr":
+ self._stderr_tail.append(line)
+ if len(self._stderr_tail) > self._STDERR_TAIL_MAX:
+ # 保留尾部 N 行
+ del self._stderr_tail[0:len(self._stderr_tail) - self._STDERR_TAIL_MAX]
+ logger.debug("[jiuwenbox/%s] %s", kind, line)
+ # ``asyncio.CancelledError`` 是 ``BaseException`` 子类 (Python 3.8+),
+ # 不会被 ``except Exception`` 捕获, 因此无需显式 ``except ... raise``。
+ except Exception as exc: # noqa: BLE001
+ logger.debug("[JiuwenBoxRunner] pump %s stopped: %s", kind, exc)
+
+ async def _wait_until_ready(self, host: str, port: int, *, timeout: float) -> bool:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if self._process is not None and self._process.returncode is not None:
+ logger.warning(
+ "[JiuwenBoxRunner] subprocess exited prematurely (rc=%s)",
+ self._process.returncode,
+ )
+ return False
+ if await self.health_check(host, port):
+ logger.info(
+ "[JiuwenBoxRunner] jiuwenbox ready at %s:%d",
+ host,
+ port,
+ )
+ return True
+ await asyncio.sleep(0.1)
+ return False
+
+ def _register_atexit_once(self) -> None:
+ if self._atexit_registered:
+ return
+ try:
+ atexit.register(self._sync_terminate)
+ self._atexit_registered = True
+ except Exception as exc: # noqa: BLE001
+ logger.warning("[JiuwenBoxRunner] atexit register failed: %s", exc)
+
+ def _sync_terminate(self) -> None:
+ """同步退出兜底: ``atexit`` / 异常退出场景调用, 不依赖事件循环.
+
+ - 若 ``stop()`` 已正常清理, 则什么都不做;
+ - 否则尽可能 ``terminate`` / ``kill`` 子进程, 避免 jiuwenbox 残留.
+ """
+ proc = self._process
+ if proc is None or not self._owns_process:
+ return
+ # asyncio.subprocess.Process exposes returncode / pid 同步可读
+ if proc.returncode is not None:
+ return
+ pid = proc.pid
+ logger.info("[JiuwenBoxRunner] atexit: terminating subprocess pid=%s", pid)
+ try:
+ os.kill(pid, signal.SIGTERM)
+ except ProcessLookupError:
+ return
+ except Exception as exc: # noqa: BLE001
+ logger.warning("[JiuwenBoxRunner] atexit SIGTERM failed: %s", exc)
+ return
+ # 等待最多 3s
+ deadline = time.monotonic() + 3.0
+ while time.monotonic() < deadline:
+ try:
+ # 0 信号: 探测进程是否存在
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return
+ except Exception: # noqa: BLE001
+ return
+ time.sleep(0.1)
+ # 超时则 SIGKILL
+ with contextlib.suppress(ProcessLookupError, Exception):
+ os.kill(pid, signal.SIGKILL)
+
+ async def stop(self) -> None:
+ """优雅停止由本 runner 启动的子进程."""
+ async with self._lock:
+ await self._stop_no_lock()
+
+ async def _stop_no_lock(self) -> None:
+ """``stop()`` 的去锁版本; 调用方必须已经持有 ``self._lock``.
+
+ 被 ``ensure_running`` 复用: 监测到 policy_path 变更, 需要重启子进程以让
+ 新的 ``JIUWENBOX_POLICY_PATH`` 生效。
+ """
+ for task_attr in ("_stdout_pump_task", "_stderr_pump_task"):
+ task = getattr(self, task_attr, None)
+ if task is not None and not task.done():
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError, Exception):
+ await task
+ setattr(self, task_attr, None)
+
+ proc = self._process
+ if proc is None or proc.returncode is not None:
+ self._process = None
+ self._spawned_policy_path = None
+ return
+ if not self._owns_process:
+ self._process = None
+ self._spawned_policy_path = None
+ return
+ logger.info("[JiuwenBoxRunner] stopping subprocess pid=%s", proc.pid)
+ try:
+ proc.terminate()
+ except ProcessLookupError:
+ self._process = None
+ self._spawned_policy_path = None
+ return
+ # uvicorn 收到 SIGTERM 后会跑 FastAPI lifespan shutdown, 期间会调
+ # ``SandboxManager.shutdown_all_sandboxes`` 给每个活的 sandbox 做
+ # SIGTERM -> wait -> SIGKILL 三段式 teardown (每个最坏要 ~15s,
+ # 见 jiuwenbox.server.runtime.process.SandboxRuntime.stop)。如果这里
+ # 留的 grace 不够长, lifespan 还没清完就被 SIGKILL, sandbox-daemon.py
+ # 会被 reparent 到 init 成为孤儿进程, 留在 host 上一直跑。所以这里
+ # 给一个相对宽松的 60s 上限; 实操中没活 sandbox 时 uvicorn 自己很快
+ # 就退了, 不会真等满。
+ try:
+ await asyncio.wait_for(proc.wait(), timeout=60.0)
+ except asyncio.TimeoutError:
+ logger.warning(
+ "[JiuwenBoxRunner] terminate timeout (60s); killing pid=%s "
+ "(sandbox-daemon orphans may remain on host)",
+ proc.pid,
+ )
+ try:
+ proc.kill()
+ await proc.wait()
+ except Exception as exc: # noqa: BLE001
+ logger.warning("[JiuwenBoxRunner] kill failed: %s", exc)
+ self._process = None
+ self._owns_process = False
+ self._spawned_policy_path = None
diff --git a/pyproject.toml b/pyproject.toml
index e88b536610..0c82b151ed 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -36,7 +36,13 @@ dependencies = [
"opentelemetry-sdk>=1.25.0",
"opentelemetry-exporter-otlp-proto-grpc>=1.25.0",
"opentelemetry-exporter-otlp-proto-http>=1.25.0",
- "sqlite-vec==0.1.6"
+ "sqlite-vec==0.1.6",
+ "fastapi>=0.115",
+ "uvicorn[standard]>=0.30",
+ "python-multipart>=0.0.9",
+ "pydantic>=2.0",
+ "pyyaml>=6.0",
+ "httpx>=0.27",
]
[project.optional-dependencies]
@@ -69,15 +75,18 @@ jiuwenswarm-init = "jiuwenswarm.init_workspace:main"
jiuwenswarm-desktop = "jiuwenswarm.channels.desktop.desktop_app:main"
jiuwenswarm-tui = "jiuwenswarm.channels.acp.app_acp:main"
jiuwenswarm-acp = "jiuwenswarm.gateway.channel_manager.protocol.acp.acp_connect:main"
+jiuwenbox = "jiuwenbox.cli.jiuwenbox:main"
+jiuwenbox-server = "jiuwenbox.server.launcher:main"
[tool.setuptools]
# 入口脚本现在是 jiuwenswarm 包内的一部分,不需要 py-modules
py-modules = []
include-package-data = true
+package-dir = {"jiuwenbox" = "jiuwenbox/src/jiuwenbox"}
[tool.setuptools.packages.find]
-where = ["."]
-include = ["jiuwenswarm*"]
+where = [".", "jiuwenbox/src"]
+include = ["jiuwenswarm*", "jiuwenbox*"]
exclude = ["jiuwenswarm.cli*", "jiuwenswarm.web*"]
namespaces = false
@@ -91,6 +100,10 @@ jiuwenswarm = [
"resources/*",
"resources/.env.template",
]
+jiuwenbox = [
+ "configs/**/*",
+ "configs/*",
+]
[tool.setuptools.exclude-package-data]
jiuwenswarm = ["channels/web/frontend/node_modules/**", "channels/web/frontend/node_modules/*"]
diff --git a/scripts/build.sh b/scripts/build.sh
index 81b3a5f196..ac3b9f3047 100644
--- a/scripts/build.sh
+++ b/scripts/build.sh
@@ -41,12 +41,35 @@ if [[ -d "$NODE_MODULES" ]]; then
NODE_MODULES_MOVED=true
fi
+# 把 jiuwenbox/configs 临时 stage 到 jiuwenbox/src/jiuwenbox/configs,使其
+# 落在 ``jiuwenbox`` 包目录内, 这样 [tool.setuptools.package-data] 才能把它
+# 随 wheel 一并打入 (setuptools 不支持把包外目录作为 package_data 引入)。
+JBX_CFG_SRC="$PROJECT_ROOT/jiuwenbox/configs"
+JBX_CFG_DST="$PROJECT_ROOT/jiuwenbox/src/jiuwenbox/configs"
+JBX_CFG_STAGED=false
+if [[ -d "$JBX_CFG_SRC" ]]; then
+ if [[ -e "$JBX_CFG_DST" ]]; then
+ echo "[build] 警告: $JBX_CFG_DST 已存在, 跳过 stage (可能是上一次未清理)" >&2
+ else
+ echo "[build] 临时 stage jiuwenbox configs → $JBX_CFG_DST"
+ cp -R "$JBX_CFG_SRC" "$JBX_CFG_DST"
+ JBX_CFG_STAGED=true
+ fi
+else
+ echo "[build] 警告: 未找到 $JBX_CFG_SRC, wheel 中不会带 jiuwenbox/configs" >&2
+fi
+
cleanup() {
# 恢复 node_modules
if [[ "$NODE_MODULES_MOVED" == "true" && -d "$NODE_MODULES_BAK" ]]; then
mv "$NODE_MODULES_BAK" "$NODE_MODULES"
echo "[build] 已恢复 node_modules"
fi
+ # 清理 jiuwenbox configs 的 staging 副本
+ if [[ "$JBX_CFG_STAGED" == "true" && -d "$JBX_CFG_DST" ]]; then
+ rm -rf "$JBX_CFG_DST"
+ echo "[build] 已清理 staged jiuwenbox configs"
+ fi
}
trap cleanup EXIT