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(jiuwenbot): adapter jiuwenbox to code agent
zhaozixuanee41fe0d9ebc
diff --git a/jiuwenbox/README.md b/jiuwenbox/README.mdindex 61f8fbe80f..ee514f9161 100644--- a/jiuwenbox/README.md+++ b/jiuwenbox/README.md@@ -57,34 +57,38 @@ sudo apt-get updatesudo apt-get install -y bubblewrap iproute2 iptables nftables python3-pip python3-venv nodejs```-## Install+## Install From Source```bashcd jiuwenclaw/jiuwenbox-python3 -m venv .venv+uv venvsource .venv/bin/activate-python3 -m pip install --upgrade pip build+uv sync+uv pip install --upgrade pip buildpython3 -m build --wheel-python3 -m pip install dist/jiuwenbox-*.whl+uv pip install ./dist/jiuwenbox*.whl```## Start The Server### Local Start-Set the default policy path and start the installed service with `python -m`:+Set the default policy path and start the installed service via the venv+Python:```bash-export JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml"-sudo -E .venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 8321 --log-level debug+sudo env \+ JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml" \+ ./.venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 8321 --log-level debug```Use another policy or port by changing the environment variable or uvicornarguments:```bash-export JIUWENBOX_POLICY_PATH="$(pwd)/configs/jiuwenclaw-policy.yaml"-sudo -E .venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 9000 --log-level debug+sudo env \+ JIUWENBOX_POLICY_PATH="$(pwd)/configs/jiuwenclaw-policy.yaml" \+ ./.venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 9000 --log-level debug```The selected policy path is read from:@@ -115,6 +119,157 @@ Run with the default policy:sudo ./run_docker.sh```+### Unix Domain Socket Deployment++The management HTTP API can be served over a Unix Domain Socket instead of+TCP (one-of-two per process). HTTP/1.1 framing, routes and payloads stay+identical; only the transport changes. UDS is useful for same-host agents,+filesystem-permission-based access control, and avoiding loopback port+conflicts.++Listen address is controlled by a single env var:++```bash+JIUWENBOX_LISTEN=tcp://0.0.0.0:8321 # default, historical behavior+JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock # switch to UDS (absolute path required)+```++Start locally on UDS (same two rules as the ⚠️ in *Local Start*:+`sudo env` for envs, absolute `./.venv/bin/` paths for binaries):++```bash+sudo env \+ JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml" \+ JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock \+ ./.venv/bin/python -m jiuwenbox.server.launcher++# or, with the entry script installed by uv sync / pip install:+sudo env JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock \+ ./.venv/bin/jiuwenbox-server+```++Docker deployment on UDS:++```bash+mkdir -p /tmp/jiuwenbox-sock++sudo env \+ JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock \+ JIUWENBOX_UDS_HOST_DIR=/tmp/jiuwenbox-sock \+ ./run_docker.sh configs/default-policy.yaml+```++`run_docker.sh` skips the management-API TCP port mapping under UDS mode and+bind-mounts the host socket directory into the container; **the proxy port+`${JIUWENBOX_PROXY_PORT:-8322}` is still mapped as TCP** because the+Inference Privacy Proxy is an independent TCP listener.++Reach the server:++```bash+curl --unix-socket /tmp/jiuwenbox-sock/jiuwenbox.sock http://localhost/health+jiuwenbox --base-url unix:///tmp/jiuwenbox-sock/jiuwenbox.sock health+JIUWENBOX_URL=unix:///tmp/jiuwenbox-sock/jiuwenbox.sock jiuwenbox sandbox ls++# pytest in dual transport mode (operator launches the matching server first)+pytest tests/integration --server-endpoint=tcp://127.0.0.1:8321+pytest tests/integration --server-endpoint=unix:///tmp/jiuwenbox-sock/jiuwenbox.sock+```++UDS-related env vars:++| Variable | Default | Notes |+| --- | --- | --- |+| `JIUWENBOX_LISTEN` | `tcp://0.0.0.0:8321` | Management API listen URI; accepts `tcp://host:port` or `unix:///abs/socket/path`. Under UDS mode `JIUWENBOX_PORT` is ignored. |+| `JIUWENBOX_UDS_MODE` | `0666` | UDS socket file permissions (octal string). The Docker default is permissive so a non-root host user can connect; for multi-tenant / hardened deployments set `0660` and pass `docker run --user $(id -u):$(id -g)`. |+| `JIUWENBOX_UDS_HOST_DIR` | `/tmp/jiuwenbox-sock` | Host directory bind-mounted by `run_docker.sh` to expose the socket. |+| `JIUWENBOX_UDS_CONTAINER_DIR` | `/run/jiuwenbox` | Container-side mount point; must match the directory in `JIUWENBOX_LISTEN`'s socket path. |++### Persisting the audit log (`--save-logs DIR`)++**By default jiuwenbox writes no log files at all.** Audit events+surface only on the standard Python logger at ``DEBUG`` level, sandbox+daemon and background-exec stdout/stderr go straight to ``/dev/null``,+and ``/api/v1/sandboxes/{id}/logs`` returns the empty string. This+keeps a fresh install from creating files under ``$HOME`` and prevents+long-running servers from filling the disk silently.++Pass `--save-logs DIR` (or set `JIUWENBOX_SAVE_LOGS_DIR=DIR`) to opt+into per-sandbox **audit log** persistence. Files are **kept after the+sandbox is gone**, which is the shape you want for offline inspection,+log shipping, or postmortem debugging.++> Note: the historical per-sandbox `runtime.log` and `runtime.bg-N.log`+> files (raw daemon and background-exec stdout/stderr) were removed.+> The audit log already carries the truncated per-command stdout/stderr,+> which has proven to be enough for routine debugging while letting us+> drop a class of "two files for the same thing" foot-guns. If you do+> need the full raw byte stream, run the container with `docker run -it`+> so the bwrap output streams to your terminal.++Every operation produces **a single row** in the audit JSONL, emitted+after the call returns so the payload carries both intent (command,+path) and outcome (exit_code, stdout/stderr, error). Reading just the+audit file is enough to answer "did this command succeed?":++| `event_type` | Key fields |+| --- | --- |+| `exec_command` | `command`, `workdir`, `background?`, `ok`, `exit_code`, `stdout`, `stderr`, `duration_ms`, `error?` (stdout/stderr are tail-truncated to 4 KiB; overflow is annotated `[truncated, total N chars]`. Background exec records `started`/`pid` instead of `exit_code`/`stdout`/`stderr`.) |+| `file_transfer` | `direction` (upload/download), `sandbox_path`, `size`, `ok`, `duration_ms`, `path` (`ipc` vs `exec_fallback`), `error?` |++The filename layout is `{sandbox_id}-{ISO8601-basic-timestamp}.audit.log`.+The timestamp is captured the first time a given sandbox writes an+audit event and reused for the rest of that sandbox's lifetime:++```+<DIR>/+ └── 9284a4bf-870-20260515T112345.audit.log # structured JSONL+```++The basic ISO 8601 layout (`%Y%m%dT%H%M%S`) sorts lexicographically+the same way it sorts chronologically; combined with the sandbox_id+prefix, `ls 9284a4bf-870-*` gives you every audit file for that+sandbox in boot order.++Local launch:++```bash+sudo env \+ JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml" \+ ./.venv/bin/jiuwenbox-server --save-logs /var/log/jiuwenbox++# Equivalent via env:+sudo env \+ JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml" \+ JIUWENBOX_SAVE_LOGS_DIR=/var/log/jiuwenbox \+ ./.venv/bin/jiuwenbox-server+```++Docker launch: pass `--save-logs DIR` (or set+`JIUWENBOX_SAVE_LOGS_HOST_DIR=DIR`) and `run_docker.sh` will bind-mount+`DIR` onto `JIUWENBOX_SAVE_LOGS_CONTAINER_DIR` (default+`/var/log/jiuwenbox`) and inject `JIUWENBOX_SAVE_LOGS_DIR=<container+path>` into the launcher — no `Dockerfile` change required. The CLI+flag and the env var are equivalent; the flag wins when both are+present:++```bash+# CLI flag (recommended)+sudo ./run_docker.sh --save-logs /tmp/jiuwenbox-logs++# Equivalent env-var form (kept for backward compatibility)+sudo env JIUWENBOX_SAVE_LOGS_HOST_DIR=/tmp/jiuwenbox-logs ./run_docker.sh++ls /tmp/jiuwenbox-logs+# 9284a4bf-870-20260515T112345.audit.log+```++| Variable | Default | Notes |+| --- | --- | --- |+| `JIUWENBOX_SAVE_LOGS_DIR` | _unset_ | Target audit-log directory inside the container/process. Unset means **no log files at all** (the new default — see above). The launcher resolves `--save-logs` / the env to an absolute path before writing this back. |+| `JIUWENBOX_SAVE_LOGS_HOST_DIR` | _unset_ | `run_docker.sh` only: host-side directory (env-var form of `--save-logs DIR`). Empty disables persistence. When set, the script `mkdir -p`s it, bind-mounts it into the container, and exports `JIUWENBOX_SAVE_LOGS_DIR`. |+| `JIUWENBOX_SAVE_LOGS_CONTAINER_DIR` | `/var/log/jiuwenbox` | `run_docker.sh` mount point inside the container. Override only if something else already owns this path inside the image. |+## Policy FilesThe server loads one static default policy at startup. Policy dynamic update is@@ -262,6 +417,89 @@ network:- 22```+## Enabling jiuwenbox from jiuwenclaw's config file++jiuwenclaw decides **whether the sandbox is on, which jiuwenbox to talk to, whether to spawn its own jiuwenbox subprocess, and which policy file to use** via the `sandbox` section of its `config.yaml`. The TUI's `/sandbox` command writes back to the same section, so you can also pre-populate it by hand.++### Configuration schema++```yaml+sandbox:+ # -- Endpoint & type --+ url: "http://127.0.0.1:8321" # jiuwenbox HTTP endpoint; TCP uses http://, UDS uses unix:///abs/socket/path+ type: "jiuwenbox" # sandbox provider name; currently only "jiuwenbox"++ # -- 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++ # -- 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+ allow: []+ deny: []+```++Field reference:++| Field | Values | Default | Notes |+| --- | --- | --- | --- |+| `sandbox.url` | URL string | `http://127.0.0.1:8321` | jiuwenbox management API endpoint. TCP: `http://host:port`; UDS: `unix:///abs/socket/path` (mirrors `JIUWENBOX_LISTEN`). |+| `sandbox.type` | string | `jiuwenbox` | Sandbox provider name. Currently jiuwenclaw 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.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). |++### Two typical deployment shapes++#### Shape A: `startup_mode: internal` (agent-server spawns jiuwenbox for you)++Good for local development and single-host deployments. Drop this into `config.yaml`:++```yaml+sandbox:+ url: "http://127.0.0.1:8321"+ type: "jiuwenbox"+ startup_mode: "internal"+ policy_file: "code-agent-policy.yaml" # picked up from jiuwenbox/configs/+ enabled: true+```++At boot the agent-server will:++1. Resolve `policy_file` to a host absolute path (bare name → `jiuwenbox/configs/<name>`; otherwise expand `~` / `$VAR` and use as-is).+2. Probe the port in `url`; if taken, switch to a free one and persist the new `url` back into `config.yaml`, so `/sandbox status` shows the real port.+3. Spawn `jiuwenbox-server` with the resolved policy path. On failure, agent-server logs the last 10 lines of stderr; you can retry from the TUI via `/sandbox enable`.++#### Shape B: `startup_mode: external` (you start jiuwenbox-server yourself)++Good when jiuwenbox lives on a different host / container, or when jiuwenclaw should never escalate to root. Example:++```yaml+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 jiuwenclaw 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).++## Inference Privacy ProxyThe inference privacy proxy enables secure LLM API access from edge servers:@@ -345,13 +583,30 @@ Proxy forwards: POST http://192.168.1.100:9000/v1/chat/completions -H "Autho## Run Integration Tests-Run one policy-specific integration suite:+`./tests/test.sh default` runs `test_server_api_default.py` and+`test_cli_default.py` together, exercising both the server HTTP API and the+jiuwenbox CLI. Use `--server-endpoint=URI` to switch between transports;+**the transport is inferred from the URI shape**, so there's no separate+flag to maintain in sync:```bash-./tests/test.sh default # jiuwenbox runs the service using default-policy.yaml as the security policy.-./tests/test.sh yuanrong # jiuwenbox runs the service using yuanrong.yaml with proxy enabled on port 8322.+# TCP (default, equivalent to --server-endpoint=http://127.0.0.1:8321; the+# server should be launched with default-policy.yaml as its security policy)+./tests/test.sh default++# Custom TCP listener (a bare host:port gets http:// prepended automatically)+./tests/test.sh default --server-endpoint=http://127.0.0.1:18321+./tests/test.sh default --server-endpoint=127.0.0.1:18321++# UDS: pass the absolute socket path as a unix:// URL+./tests/test.sh default --server-endpoint=unix:///tmp/jiuwenbox.sock+./tests/test.sh default --server-endpoint=unix:///tmp/jiuwenbox-sock/jiuwenbox.sock```+`test.sh` does **not** start the server; launch jiuwenbox first on the+selected transport (TCP with `JIUWENBOX_LISTEN=tcp://0.0.0.0:8321` or a+custom port, UDS with `JIUWENBOX_LISTEN=unix:///...`).+Run specific test-case:```bash@@ -404,6 +659,49 @@ export JIUWENBOX_TEST_LLM_MODEL="YOUR_MODEL"diagnostics should use debug logging when they would otherwise pollutecommand stderr.+## CLI++`jiuwenbox` ships a single-file Python CLI client wrapping the HTTP API+documented in [`docs/jiuwenbox_server_api.md`](docs/jiuwenbox_server_api.md).++After `pip install` it is exposed as the `jiuwenbox` executable; from source+you can also run it as `python -m jiuwenbox.cli.jiuwenbox`.++```bash+# Health+jiuwenbox health++# Sandbox lifecycle+ID=$(jiuwenbox sandbox create --output plain)+jiuwenbox sandbox exec "$ID" -- python3 -c 'print("hi")'+jiuwenbox sandbox upload "$ID" ./data.csv /tmp/data.csv+jiuwenbox sandbox download "$ID" /tmp/result.json - | jq .+jiuwenbox sandbox ls --output table+jiuwenbox sandbox rm "$ID" --yes++# Policy+jiuwenbox policy get "$ID"++# Proxies+jiuwenbox proxy create --prefix /openai --target https://api.openai.com --api-key sk-xxx+jiuwenbox proxy logs openai --lines 50+```++Global flags:++| Flag | Default | Env var | Description |+| --- | --- | --- | --- |+| `--base-url` | `http://127.0.0.1:8321` | `JIUWENBOX_URL` | Server endpoint. Accepts `http://host:port` or `unix:///abs/socket/path` |+| `--timeout` | `30` | `JIUWENBOX_TIMEOUT` | HTTP timeout seconds |+| `--output / -o` | `json` | – | `json` \| `table` \| `plain` |+| `--verbose / -v` | off | – | Debug logging on stderr |+| `--no-color` | off | `NO_COLOR` | Disable ANSI colors on stderr |++Exit codes: `0` success / sandbox exec returned 0, `1` HTTP 4xx/5xx, `2`+connection failure, `3` local argument or file error, `130` Ctrl+C; the+`sandbox exec` subcommand transparently propagates the in-sandbox process+exit code.+## LicenseApache-2.0diff --git a/jiuwenbox/README_CN.md b/jiuwenbox/README_CN.mdindex 58715614f2..695728532c 100644--- a/jiuwenbox/README_CN.md+++ b/jiuwenbox/README_CN.md@@ -54,33 +54,36 @@ sudo apt-get updatesudo apt-get install -y bubblewrap iproute2 iptables nftables python3-pip python3-venv nodejs```-## 安装+## 从源码安装```bashcd jiuwenclaw/jiuwenbox-python3 -m venv .venv+uv venvsource .venv/bin/activate-python3 -m pip install --upgrade pip build+uv sync+uv pip install --upgrade pip buildpython3 -m build --wheel-python3 -m pip install dist/jiuwenbox-*.whl+uv pip install ./dist/jiuwenbox*.whl```## 启动服务### 本地启动-设置默认 policy 路径,并通过 `python -m` 启动已安装的服务:+设置默认 policy 路径,并通过 venv 里的 python 启动已安装的服务:```bash-export JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml"-sudo -E .venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 8321 --log-level debug+sudo env \+ JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml" \+ ./.venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 8321 --log-level debug```如需使用其他 policy 或端口,可修改环境变量或 uvicorn 参数:```bash-export JIUWENBOX_POLICY_PATH="$(pwd)/configs/jiuwenclaw-policy.yaml"-sudo -E .venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 9000 --log-level debug+sudo env \+ JIUWENBOX_POLICY_PATH="$(pwd)/configs/jiuwenclaw-policy.yaml" \+ ./.venv/bin/python -m uvicorn jiuwenbox.server.app:app --host 0.0.0.0 --port 9000 --log-level debug```服务会从以下环境变量读取默认 policy 路径:@@ -110,6 +113,148 @@ sudo ./build_docker.shsudo ./run_docker.sh```+### 通过 Unix Domain Socket 部署++jiuwenbox 支持把管理 HTTP API 跑在 Unix Domain Socket 上(与 TCP 二选一),+适用于同主机 agent 进程访问、需要文件系统权限控制访问者、或想避开+loopback 端口冲突的场景。上层协议仍是 HTTP/1.1,路由 / 请求体 / 响应都+与 TCP 模式完全一致。++监听地址由统一的环境变量 `JIUWENBOX_LISTEN` 控制,取以下两种形式之一:++```bash+JIUWENBOX_LISTEN=tcp://0.0.0.0:8321 # 默认, 行为与历史一致+JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock # 切到 UDS, 路径必须绝对+```++本地启动 UDS server(同上节 ⚠️ 的两条规则:`sudo env` 注 env、`./.venv/bin/`+绝对路径):++```bash+sudo env \+ JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml" \+ JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock \+ ./.venv/bin/python -m jiuwenbox.server.launcher++# 或直接用 uv sync / pip install 装好的入口脚本:+sudo env JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock \+ ./.venv/bin/jiuwenbox-server+```++Docker 部署 UDS:++```bash+mkdir -p /tmp/jiuwenbox-sock++sudo env \+ JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock \+ JIUWENBOX_UDS_HOST_DIR=/tmp/jiuwenbox-sock \+ ./run_docker.sh configs/default-policy.yaml+```++`run_docker.sh` 在 UDS 模式下会自动跳过管理 API 的 TCP 端口映射、把宿主+socket 目录挂进容器;**代理端口 `${JIUWENBOX_PROXY_PORT:-8322}` 仍按 TCP+映射**——Inference Privacy Proxy 是独立 TCP listener,与管理 API 传输无关。++接入示例:++```bash+# curl+curl --unix-socket /tmp/jiuwenbox-sock/jiuwenbox.sock http://localhost/health++# jiuwenbox CLI+jiuwenbox --base-url unix:///tmp/jiuwenbox-sock/jiuwenbox.sock health+JIUWENBOX_URL=unix:///tmp/jiuwenbox-sock/jiuwenbox.sock jiuwenbox sandbox ls++# pytest 双通路 (操作者先各自起好对应的 server)+pytest tests/integration --server-endpoint=tcp://127.0.0.1:8321+pytest tests/integration --server-endpoint=unix:///tmp/jiuwenbox-sock/jiuwenbox.sock+```++UDS 相关环境变量:++| 变量 | 默认 | 说明 |+| --- | --- | --- |+| `JIUWENBOX_LISTEN` | `tcp://0.0.0.0:8321` | 管理 API 监听 URI;接受 `tcp://host:port` 或 `unix:///abs/socket/path`。UDS 模式下 `JIUWENBOX_PORT` 被忽略。 |+| `JIUWENBOX_UDS_MODE` | `0666` | UDS socket 文件权限 (八进制字符串)。Docker 场景下宿主与容器内 uvicorn uid 通常不同,默认放开;多租户 / 强隔离场景建议显式 `JIUWENBOX_UDS_MODE=0660` 并 `docker run --user $(id -u):$(id -g)` 收紧。 |+| `JIUWENBOX_UDS_HOST_DIR` | `/tmp/jiuwenbox-sock` | `run_docker.sh` 把宿主 socket 目录挂载到容器内的位置。 |+| `JIUWENBOX_UDS_CONTAINER_DIR` | `/run/jiuwenbox` | 容器内挂载点,必须与 `JIUWENBOX_LISTEN` 里 socket 路径所在的目录一致。 |++### 持久化审计日志(`--save-logs DIR`)++**默认情况下 jiuwenbox 不会写任何日志文件**:审计事件只在 Python 标+准 logger 的 `DEBUG` 级别出现,沙箱 daemon 与后台 exec 的 stdout/stderr+直接送到 `/dev/null`,`/api/v1/sandboxes/{id}/logs` 返回空字符串。这样+保证一台新装的机器不会在 `$HOME` 下悄悄留下任何文件,也不会因为长期+运行的服务把磁盘写满。++传 `--save-logs DIR`(或环境变量 `JIUWENBOX_SAVE_LOGS_DIR=DIR`)即可+开启**审计日志**的持久化。文件**销毁沙箱时不再删除**,便于事后离线+分析、滚动归档、外挂到日志收集系统。++> 注意:历史版本曾把沙箱 daemon / 后台 exec 的原始 stdout/stderr 写到+> `runtime.log` / `runtime.bg-N.log` 这一组文件里,现在已经**完全移除**。+> 审计日志里 `exec_command` 事件本身就携带了每条命令截断后的 stdout/stderr+> (默认 4 KiB),日常排障已经够用;如果确实需要看原始字节流,请用+> `docker run -it` 直接看 bwrap 的实时输出。++审计 JSONL 里**每个操作只落一行**,在调用返回后写出,同时携带"做了什么"+和"结果如何"。只看 JSONL 就能回答"这条指令到底成不成功":++| event_type | 关键字段 |+| --- | --- |+| `exec_command` | `command`, `workdir`, `background?`, `ok`, `exit_code`, `stdout`, `stderr`, `duration_ms`, `error?`(stdout/stderr 默认尾部截断到 4 KiB,超出会标 `[truncated, total N chars]`;后台 exec 时改记 `started/pid` 而不是 `exit_code/stdout/stderr`) |+| `file_transfer` | `direction` (upload/download), `sandbox_path`, `size`, `ok`, `duration_ms`, `path`(`ipc` 还是 `exec_fallback`), `error?` |++文件命名固定为 `{sandbox_id}-{ISO8601基本时间戳}.audit.log`,时间戳在+该 sandbox 第一次产生事件时确定并复用:++```+<DIR>/+ └── 9284a4bf-870-20260515T112345.audit.log # 结构化 JSONL+```++ISO 8601 基本格式 (`%Y%m%dT%H%M%S`) 是为了让 `ls` 自然按时间排序;前缀+都是 sandbox_id,所以 `ls 9284a4bf-870-*` 能一次性看到一个沙箱所有+重启的审计文件。++本地启动:++```bash+sudo env \+ JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml" \+ ./.venv/bin/jiuwenbox-server --save-logs /var/log/jiuwenbox++# 或走环境变量, 等价:+sudo env \+ JIUWENBOX_POLICY_PATH="$(pwd)/configs/default-policy.yaml" \+ JIUWENBOX_SAVE_LOGS_DIR=/var/log/jiuwenbox \+ ./.venv/bin/jiuwenbox-server+```++Docker 部署:传 `--save-logs DIR`(或设环境变量+`JIUWENBOX_SAVE_LOGS_HOST_DIR=DIR`),`run_docker.sh` 会自动 bind-mount 到+容器内 `JIUWENBOX_SAVE_LOGS_CONTAINER_DIR`(默认 `/var/log/jiuwenbox`),+并把 `JIUWENBOX_SAVE_LOGS_DIR=<容器路径>` 注入给 launcher,无需改+`Dockerfile`。命令行参数与环境变量等价,两者同时存在时 CLI 参数优先:++```bash+# CLI 参数(推荐)+sudo ./run_docker.sh --save-logs /tmp/jiuwenbox-logs++# 等价的环境变量写法(保留以兼容老脚本)+sudo env JIUWENBOX_SAVE_LOGS_HOST_DIR=/tmp/jiuwenbox-logs ./run_docker.sh++ls /tmp/jiuwenbox-logs+# 9284a4bf-870-20260515T112345.audit.log+```++| 变量 | 默认 | 说明 |+| --- | --- | --- |+| `JIUWENBOX_SAVE_LOGS_DIR` | _未设置_ | 容器内 / 进程内的目标审计日志目录;未设置即**完全不写日志文件**(默认)。launcher 会把 `--save-logs` / 环境变量解析为绝对路径写回此变量。 |+| `JIUWENBOX_SAVE_LOGS_HOST_DIR` | _未设置_ | `run_docker.sh` 专用:宿主侧目录(`--save-logs DIR` 的环境变量形式),留空即不开启日志持久化。设置后会自动 `mkdir -p`、bind-mount 到容器,并设置 `JIUWENBOX_SAVE_LOGS_DIR`。 |+| `JIUWENBOX_SAVE_LOGS_CONTAINER_DIR` | `/var/log/jiuwenbox` | `run_docker.sh` 在容器内的挂载点。一般无需修改;若容器内有别的进程占了这个路径再覆盖。 |+## Policy 文件服务启动时会加载一个静态默认 policy。当前不启用 policy 动态更新功能。@@ -253,6 +398,88 @@ network:- 22```+## 在 jiuwenclaw 中通过配置文件启用 jiuwenbox++jiuwenclaw 通过 `config.yaml` 的 `sandbox` 段决定**是否启用沙箱、连接哪台 jiuwenbox、是否自己拉起 jiuwenbox 子进程、用哪个 policy**。一般用 TUI 的 `/sandbox` 命令操作时会自动落盘到这里,但也可以提前在 `config.yaml` 里手写。++### 配置 schema 与字段++```yaml+sandbox:+ # —— 端点 & 类型 ——+ url: "http://127.0.0.1:8321" # jiuwenbox HTTP 端点;TCP 用 http://,UDS 用 unix:///abs/socket/path+ type: "jiuwenbox" # sandbox provider 名;当前固定为 jiuwenbox++ # —— 启动方式 & 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++ # —— 运行时(也可由 /sandbox 命令维护) ——+ enabled: true # 是否处于沙箱模式+ permission_ask: true # 沙箱内工具调用是否走 permission ask 流程+ excluded_commands: # shell glob,命中后绕过沙箱在本地执行+ - "git *"+ files: # 用户配置的写入策略(auto-managed 路径不需要写在这里,服务端会自动注入)+ allow: []+ deny: []+```++字段说明:++| 字段 | 取值 | 默认 | 说明 |+| --- | --- | --- | --- |+| `sandbox.url` | URL 字符串 | `http://127.0.0.1:8321` | jiuwenbox 管理 API 端点。TCP 用 `http://host:port`;UDS 用 `unix:///abs/socket/path`(与 `JIUWENBOX_LISTEN` 配置的形态一致) |+| `sandbox.type` | 字符串 | `jiuwenbox` | sandbox provider 名。当前 jiuwenclaw 只接通了 `jiuwenbox` |+| `sandbox.startup_mode` | `internal` / `external` | `internal` | `internal`:agent-server 启动时自动 spawn `jiuwenbox-server` 子进程并落盘最终生效的 `url`(端口被占用时自动换端口);`external`:jiuwenclaw 完全不碰 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.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) |++### 两种典型部署方式++#### 方式 A: `startup_mode: internal`(agent-server 帮你拉起 jiuwenbox)++适合本机开发 / 单机部署。直接在 `config.yaml` 里加:++```yaml+sandbox:+ url: "http://127.0.0.1:8321"+ type: "jiuwenbox"+ startup_mode: "internal"+ policy_file: "code-agent-policy.yaml" # 用 jiuwenbox/configs/ 下的 policy+ enabled: true+```++agent-server 启动时会:++1. 把 `policy_file` 解析为宿主机绝对路径(仅文件名→`jiuwenbox/configs/<name>`;其它路径直接展开 `~` / `$VAR`)。+2. 探测 `url` 里的端口是否可用;冲突就自动换端口,并把最终的 `url` 写回 `config.yaml`,TUI `/sandbox status` 看到的就是真实端口。+3. spawn `jiuwenbox-server`,把 policy 路径传进去;启动失败会写一份 stderr 末尾到日志,TUI 仍能用 `/sandbox enable` 重试。++#### 方式 B: `startup_mode: external`(你自己启动 jiuwenbox-server)++适合需要把 jiuwenbox 跑在独立机器、容器里,或者 jiuwenclaw 进程不便用 root 的场景。++```yaml+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`,让 jiuwenclaw 在沙箱启动后把 intrinsic 文件(`AGENT.md` / `HEARTBEAT.md` / `IDENTITY.md` / `SOUL.md` / `USER.md` / `memory/daily_memory/`)上传进去,避免依赖宿主路径。+- 在 jiuwenbox 主机的 policy 里允许这些 intrinsic 文件被沙箱内写入(参考仓库内 `jiuwenbox/configs/code-agent-policy.yaml`)。+## 推理隐私代理推理隐私代理用于在边缘服务器上安全访问 LLM API:@@ -344,13 +571,27 @@ inference_privacy_proxies:## 运行集成测试-运行指定 policy 对应的集成测试:+`./tests/test.sh default` 会一次跑 `test_server_api_default.py` 和+`test_cli_default.py`,覆盖 server HTTP API 与 jiuwenbox CLI。通过+`--server-endpoint=URI` 切换连接方式,**传输协议自动从 URI 形式推断**:```bash-./tests/test.sh default # jiuwenbox 使用 default-policy.yaml 作为安全策略运行服务。-./tests/test.sh yuanrong # jiuwenbox 使用 yuanrong.yaml 运行服务,代理监听端口 8322。+# TCP (默认通路,等价于 --server-endpoint=http://127.0.0.1:8321)+./tests/test.sh default++# 自定义 TCP 监听 (host:port 会自动补 http:// 前缀)+./tests/test.sh default --server-endpoint=http://127.0.0.1:18321+./tests/test.sh default --server-endpoint=127.0.0.1:18321++# UDS 通路: 直接给 socket 文件的绝对路径+./tests/test.sh default --server-endpoint=unix:///tmp/jiuwenbox.sock+./tests/test.sh default --server-endpoint=unix:///tmp/jiuwenbox-sock/jiuwenbox.sock```+注意 test.sh 本身**不会**起 server,请按选定通路先手工启动对应的 jiuwenbox+(TCP 走 `JIUWENBOX_LISTEN=tcp://0.0.0.0:8321` 或自定义端口,UDS 走+`JIUWENBOX_LISTEN=unix:///...`)。+运行指定测试用例:```bash@@ -400,6 +641,48 @@ export JIUWENBOX_TEST_LLM_MODEL="YOUR_MODEL"- `/exec` API 会把命令 stderr 作为命令执行结果返回;如果服务端诊断日志可能污染命令 stderr,应使用 debug 级别日志。+## CLI++`jiuwenbox` 提供单文件 Python CLI 客户端,包装+[`docs/jiuwenbox_server_api.md`](docs/jiuwenbox_server_api.md) 中所有 HTTP 接口。++`pip install` 之后会安装 `jiuwenbox` 可执行命令;源码内运行用+`python -m jiuwenbox.cli.jiuwenbox`。++```bash+# 健康检查+jiuwenbox health++# 沙箱生命周期+ID=$(jiuwenbox sandbox create --output plain)+jiuwenbox sandbox exec "$ID" -- python3 -c 'print("hi")'+jiuwenbox sandbox upload "$ID" ./data.csv /tmp/data.csv+jiuwenbox sandbox download "$ID" /tmp/result.json - | jq .+jiuwenbox sandbox ls --output table+jiuwenbox sandbox rm "$ID" --yes++# 沙箱策略+jiuwenbox policy get "$ID"++# 代理管理+jiuwenbox proxy create --prefix /openai --target https://api.openai.com --api-key sk-xxx+jiuwenbox proxy logs openai --lines 50+```++全局选项:++| 选项 | 默认值 | 环境变量 | 说明 |+| --- | --- | --- | --- |+| `--base-url` | `http://127.0.0.1:8321` | `JIUWENBOX_URL` | jiuwenbox 服务地址。接受 `http://host:port` 或 `unix:///abs/socket/path` |+| `--timeout` | `30` | `JIUWENBOX_TIMEOUT` | HTTP 超时秒数 |+| `--output / -o` | `json` | – | `json` \| `table` \| `plain` |+| `--verbose / -v` | 关闭 | – | stderr 打印 debug 日志 |+| `--no-color` | 关闭 | `NO_COLOR` | 关闭 stderr ANSI 颜色 |++退出码:`0` 成功 / `sandbox exec` 沙箱内退出码为 0;`1` HTTP 4xx/5xx;`2`+连接失败;`3` 本地参数 / 文件错误;`130` Ctrl+C。`sandbox exec` 子命令+会透传沙箱内进程的退出码。+## LicenseApache-2.0diff --git a/jiuwenbox/cli/jiuwenbox.py b/jiuwenbox/cli/jiuwenbox.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/jiuwenbox/configs/code-agent-policy.yaml b/jiuwenbox/configs/code-agent-policy.yamlnew file mode 100644index 0000000000..9056d35eb4--- /dev/null+++ b/jiuwenbox/configs/code-agent-policy.yaml@@ -0,0 +1,99 @@+# Policy schema version. Currently only version 1 is supported.+version: 1++# Human-readable policy name shown by the server policy API.+name: "code-agent"++# Environment variables injected into every process running inside the sandbox.+environment: {}++# Filesystem access rules. Paths are sandbox-visible absolute paths.+filesystem_policy:+ # Lifecycle directories to create for the sandbox and bind into the sandbox path.+ # Items may be either:+ # - "/path": create a server-managed directory with default permissions+ # - path: "/path"+ # permissions: "0755" # optional octal permissions applied on the backing directory+ # The permissions value may be quoted or numeric, but quoted octal strings are recommended.+ # Paths must be absolute sandbox-visible paths. Directories persist for the sandbox+ # lifecycle and are removed when the sandbox is deleted. Access is still controlled+ # by the directory permissions and Landlock.+ directories: []++ # Lifecycle files to create for the sandbox and bind into the sandbox path.+ # Items may be either:+ # - "/path/to/file": create a server-managed empty file with default permissions+ # - path: "/path/to/file"+ # permissions: "0644" # optional octal permissions applied on the backing file+ # Paths must be absolute sandbox-visible paths. Files persist for the sandbox+ # lifecycle and are removed when the sandbox is deleted.+ files: []++ # Read-only paths inside the sandbox. These entries grant read permission only;+ # they do not mount host paths by themselves.++ read_only:+ - "/"+ - "/bin"+ - "/sbin"+ - "/usr"+ - "/lib"+ - "/lib64"+ - "/etc"+ - "/opt"+ - "/tmp"+ - "/home"++ # Read-write paths inside the sandbox. Use directories or bind_mounts to make+ # these paths exist in the sandbox.+ read_write: []++ # Extra bind mounts from host into sandbox.+ # Each item uses:+ # host_path: absolute path on the host (literal "*" is rejected; use+ # bind_root_entries instead to mount every immediate child+ # of a host directory)+ # sandbox_path: absolute path visible inside the sandbox+ # mode: "ro" for read-only or "rw" for read-write+ bind_mounts: []++ # Bind every immediate entry (subdirectory or regular file) directly under+ # ``host_root`` into the sandbox at ``sandbox_path/<child_name>`` with the+ # same uniform ``mode``. Useful when you want to expose all of ``/etc`` or a+ # workspace tree without listing each child by hand in ``bind_mounts``.+ #+ # Each item uses:+ # host_root: absolute host directory whose immediate children get mounted+ # sandbox_path: absolute sandbox directory under which each child appears+ # mode: "ro" for read-only or "rw" for read-write (default "ro")+ # include_hidden: include dot-prefixed children (default false)+ # exclude: list of fnmatch globs applied to each child basename; matched+ # entries are skipped+ bind_root_entries:+ - host_root: "/"+ sandbox_path: "/"+ mode: "ro"++ # Device nodes to expose inside the sandbox with bwrap --dev-bind.+ # Each item uses:+ # host_path: absolute device path on the host+ # sandbox_path: absolute path visible inside the sandbox+ device:+ - host_path: "/dev/null"+ sandbox_path: "/dev/null"+ - host_path: "/dev/tty"+ sandbox_path: "/dev/tty"+ - host_path: "/dev/random"+ sandbox_path: "/dev/random"+ - host_path: "/dev/urandom"+ sandbox_path: "/dev/urandom"++landlock:+ # compatibility:+ # disabled: do not apply Landlock+ # best_effort: apply Landlock when supported, otherwise continue+ # hard_requirement: fail sandbox startup if Landlock is unavailable+ compatibility: best_effort++network:+ mode: host\ No newline at end of filediff --git a/jiuwenbox/configs/default-policy.yaml b/jiuwenbox/configs/default-policy.yamlindex 41e1ffe0d2..3f9a897574 100644--- a/jiuwenbox/configs/default-policy.yaml+++ b/jiuwenbox/configs/default-policy.yaml@@ -291,3 +291,25 @@ network:# TCP destination ports blocked for inbound traffic. Block rules take precedence.blocked_ports: []++# ---------------------------------------------------------------------------+# Cgroup resource limits (optional)+# ---------------------------------------------------------------------------+# Per-sandbox cgroup limits. All three fields default to null which means+# "no limit". Omitting the ``cgroup`` block entirely, or leaving every+# field unset/null, causes jiuwenbox to *skip* cgroup setup completely so+# this default policy still runs on hosts without a writable cgroup tree.+#+# Cgroup v2 is preferred. v1 is used as a fallback when v2 is unavailable.+# If at least one field is non-null and neither backend is writable,+# sandbox creation fails with a CgroupSetupError.+#+# Accepted formats:+# memory_max: integer bytes (e.g. 268435456) or string with binary unit+# suffix B/K/KB/KiB/M/MB/MiB/G/GB/GiB/T/TB/TiB (e.g. "256M", "1G").+# cpu_max: fractional cores (e.g. 0.5 = half a core, 2.0 = two cores)+# or "<quota_us> <period_us>" pair (e.g. "50000 100000"). "max" or null+# means no limit.+# pids_max: positive integer cap on processes/threads (e.g. 256). "max"+# or null means no limit.+cgroup: {}diff --git a/jiuwenbox/docker/Dockerfile b/jiuwenbox/docker/Dockerfileindex f923f8a1a7..4d31b37953 100644--- a/jiuwenbox/docker/Dockerfile+++ b/jiuwenbox/docker/Dockerfile@@ -39,4 +39,8 @@ RUN ln -s /usr/bin/python3 /usr/bin/pythonEXPOSE 8321EXPOSE 8322-CMD ["python3", "-m", "uvicorn", "jiuwenbox.server.app:app", "--host", "0.0.0.0", "--port", "8321"]+# 默认走 TCP, 行为与历史一致; UDS 模式由调用方覆盖 JIUWENBOX_LISTEN, 例如+# `docker run -e JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock \+# -v /tmp/jiuwenbox-sock:/run/jiuwenbox jiuwenbox`。+ENV JIUWENBOX_LISTEN=tcp://0.0.0.0:8321+CMD ["python3", "-m", "jiuwenbox.server.launcher"]diff --git a/jiuwenbox/docs/jiuwenbox_server_api.md b/jiuwenbox/docs/jiuwenbox_server_api.mdindex 06a6dfb59c..1ebb5e02bd 100644--- a/jiuwenbox/docs/jiuwenbox_server_api.md+++ b/jiuwenbox/docs/jiuwenbox_server_api.md@@ -4,14 +4,75 @@## 基础信息-### 默认地址+> **下文所有 `requests.get("http://127.0.0.1:8321/...")` 代码示例的 URL+> 路径不变**;切到 Unix Domain Socket 部署时只需把 base URL 替换成+> "本节通用接入示例" 中的 UDS client 即可。状态码、错误格式、所有请求 /+> 响应字段在两种传输方式下完全一致。++### TCP 监听(默认)++uvicorn 直接 bind `0.0.0.0:8321`,外部走 IP:Port 访问:```texthttp://127.0.0.1:8321```+### Unix Domain Socket 监听++适用于同主机 agent 进程访问、或需要靠文件系统权限做访问控制的场景。+启动方式见仓库根的 [`README_CN.md`](../README_CN.md#通过-unix-domain-socket-部署)+"通过 Unix Domain Socket 部署" 一节;典型 endpoint:++```text+unix:///tmp/jiuwenbox-sock/jiuwenbox.sock # 宿主机视角的 socket 文件+unix:///run/jiuwenbox/jiuwenbox.sock # 容器内 uvicorn 绑定的路径+```++服务端单进程一次只绑一种 listener;并发提供 TCP + UDS 需要部署两份 jiuwenbox。+业务接口统一使用 `/api/v1` 前缀,健康检查接口为 `/health`。+### 通用接入示例++以下三种方式分别通过 TCP 与 UDS 访问同一个 `/health`,请求行为完全等价;+本文后续小节里 `http://127.0.0.1:8321/...` 形式的示例只需照此替换 base URL。++curl:++```bash+# TCP+curl http://127.0.0.1:8321/health++# UDS+curl --unix-socket /tmp/jiuwenbox-sock/jiuwenbox.sock http://localhost/health+```++Python(`requests` 库本身不原生支持 UDS,UDS 路径推荐 `httpx` 或+[`requests-unixsocket`](https://pypi.org/project/requests-unixsocket/)):++```python+# TCP+import requests+resp = requests.get("http://127.0.0.1:8321/health", timeout=30)++# UDS+import httpx+transport = httpx.HTTPTransport(uds="/tmp/jiuwenbox-sock/jiuwenbox.sock")+with httpx.Client(transport=transport, base_url="http://jiuwenbox", timeout=30) as client:+ resp = client.get("/health")+```++jiuwenbox CLI:++```bash+# TCP (默认)+jiuwenbox health++# UDS+jiuwenbox --base-url unix:///tmp/jiuwenbox-sock/jiuwenbox.sock health+JIUWENBOX_URL=unix:///tmp/jiuwenbox-sock/jiuwenbox.sock jiuwenbox health+```+### 请求与响应约定- JSON 请求使用 `Content-Type: application/json`@@ -159,7 +220,6 @@ print(resp.json())| 字段 | 类型 | 必填 | 说明 || --- | --- | --- | --- |-| `command` | string[] | 否 | 兼容字段,当前生命周期进程不会使用该命令 || `workdir` | string/null | 否 | 兼容字段 || `env` | object | 否 | 沙箱公共环境变量 || `policy` | object/null | 否 | 覆盖或追加的 policy 数据 |@@ -972,6 +1032,5 @@ print(resp.text)## 说明-- `sandbox.create` 仍接受 `command` 和 `workdir` 字段,但当前生命周期持有进程为服务内部 daemon,这两个字段不会出现在 `SandboxRef` 返回体中。- `sandbox.exec` 和 `sandbox.exec_background` 中的 `workdir`、`env`、`timeout_seconds` 仍然有效。- 文档示例中的时间、PID、ID 仅为示意。diff --git a/jiuwenbox/pyproject.toml b/jiuwenbox/pyproject.tomlindex 4a20e35818..36663bc25a 100644--- a/jiuwenbox/pyproject.toml+++ b/jiuwenbox/pyproject.toml@@ -26,6 +26,10 @@ dev = ["ruff>=0.6",]+[project.scripts]+jiuwenbox = "jiuwenbox.cli.jiuwenbox:main"+jiuwenbox-server = "jiuwenbox.server.launcher:main"+[tool.setuptools.packages.find]where = ["src"]include = ["jiuwenbox*"]diff --git a/jiuwenbox/scripts/run_docker.sh b/jiuwenbox/scripts/run_docker.shindex 06e0e74fad..54ee3bb73f 100755--- a/jiuwenbox/scripts/run_docker.sh+++ b/jiuwenbox/scripts/run_docker.sh@@ -12,28 +12,121 @@ IMAGE_REF="${IMAGE_NAME}:${IMAGE_TAG}"CONTAINER_NAME="${JIUWENBOX_CONTAINER_NAME:-jiuwenbox}"HOST_PORT="${JIUWENBOX_HOST_PORT:-8321}"PROXY_PORT="${JIUWENBOX_PROXY_PORT:-8322}"++# 下面这一段把每个外部 env 拆成"局部短名"承接, 与上面 HOST_PORT /+# PROXY_PORT 的风格一致; 真正"对外"的环境变量名永远是+# ``JIUWENBOX_LISTEN`` / ``JIUWENBOX_UDS_MODE`` / ``JIUWENBOX_UDS_HOST_DIR`` /+# ``JIUWENBOX_UDS_CONTAINER_DIR``, 这些才是用户在 README 里设的那一份。++# 管理 API listen URI: 默认与 Dockerfile 一致走 TCP; 设成 unix:///abs/path+# 即切到 UDS, 容器内 uvicorn 监听 socket 文件, 由下面 ``-v`` 把宿主目录挂进去。+LISTEN_URI="${JIUWENBOX_LISTEN:-tcp://0.0.0.0:8321}"+# UDS chmod (lifespan 会读); 默认 0666 便于宿主非 root 直接访问, 多租户场景+# 可显式 ``JIUWENBOX_UDS_MODE=0660`` + ``docker run --user`` 收紧。+UDS_MODE="${JIUWENBOX_UDS_MODE:-}"+# 宿主侧 socket 目录 / 容器侧挂载点; 容器路径必须与 JIUWENBOX_LISTEN 里+# socket 所在目录一致, 否则 uvicorn 在容器内 bind 不到。+UDS_HOST_DIR="${JIUWENBOX_UDS_HOST_DIR:-/tmp/jiuwenbox-sock}"+UDS_CONTAINER_DIR="${JIUWENBOX_UDS_CONTAINER_DIR:-/run/jiuwenbox}"++# 持久化沙箱日志: 设置 JIUWENBOX_SAVE_LOGS_HOST_DIR 即开启, 宿主目录会被 bind+# 进容器, 且容器内 launcher 自动加 ``--save-logs <容器路径>``。容器路径可+# 通过 JIUWENBOX_SAVE_LOGS_CONTAINER_DIR 覆盖, 默认 /var/log/jiuwenbox。+SAVE_LOGS_HOST_DIR="${JIUWENBOX_SAVE_LOGS_HOST_DIR:-}"+SAVE_LOGS_CONTAINER_DIR="${JIUWENBOX_SAVE_LOGS_CONTAINER_DIR:-/var/log/jiuwenbox}"+POLICY_CONFIG=""CONTAINER_POLICY_PATH="/app/runtime-config/policy.yaml"CONTAINER_DEFAULT_POLICY_PATH="/app/configs/default-policy.yaml"DOCKER_ENV_ARGS=()DOCKER_VOLUME_ARGS=()+DOCKER_PORT_ARGS=()usage() {cat <<'EOF'-Usage: scripts/run_docker.sh [policy-config.yaml] [docker run args...]+Usage: scripts/run_docker.sh [policy-config.yaml] [--save-logs DIR] [docker run args...]++Options:+ --save-logs DIR Persist the per-sandbox audit JSONL to host+ directory DIR. The script bind-mounts DIR into+ the container and starts jiuwenbox with+ --save-logs pointing at the container-side path.+ Raw daemon / background-exec stdout/stderr is+ never persisted (the audit log already carries+ per-command stdout/stderr). Equivalent to+ setting JIUWENBOX_SAVE_LOGS_HOST_DIR; the CLI+ flag wins when both are present.-Examples:+Examples (TCP, default):scripts/run_docker.shscripts/run_docker.sh configs/default-policy.yaml+ JIUWENBOX_HOST_PORT=18321 scripts/run_docker.sh++Examples (Unix Domain Socket):+ mkdir -p /tmp/jiuwenbox-sock+ JIUWENBOX_LISTEN=unix:///run/jiuwenbox/jiuwenbox.sock \+ JIUWENBOX_UDS_HOST_DIR=/tmp/jiuwenbox-sock \+ scripts/run_docker.sh configs/default-policy.yaml++ curl --unix-socket /tmp/jiuwenbox-sock/jiuwenbox.sock http://localhost/health++Examples (persist sandbox audit log to host):+ scripts/run_docker.sh --save-logs /tmp/jiuwenbox-logs+ scripts/run_docker.sh configs/default-policy.yaml --save-logs /tmp/jiuwenbox-logs+ # ls /tmp/jiuwenbox-logs+ # <id>-20260515T112345.audit.logEOF}-if [[ $# -gt 0 ]]; then+# 第一遍扫描: 把脚本自己识别的 long flag (目前只有 --save-logs) 从 ``$@``+# 里抠出来, 剩下的位置参数 + 透传给 ``docker run`` 的尾部都保留原顺序。+# 这样用户既可以写 ``run_docker.sh --save-logs DIR configs/foo.yaml``+# 也可以写 ``run_docker.sh configs/foo.yaml --save-logs DIR``, 而原来"第一个+# 非 -* 实参当 policy-config" / "尾部任意 docker run 参数透传" 的行为不变。+SAVE_LOGS_CLI=""+REMAINING_ARGS=()+while [[ $# -gt 0 ]]; docase "$1" in-h|--help)usageexit 0;;+ --save-logs=*)+ SAVE_LOGS_CLI="${1#--save-logs=}"+ if [[ -z "$SAVE_LOGS_CLI" ]]; then+ echo "error: --save-logs requires a non-empty directory path" >&2+ exit 2+ fi+ shift+ ;;+ --save-logs)+ if [[ $# -lt 2 || "$2" == --* ]]; then+ echo "error: --save-logs requires a directory path" >&2+ exit 2+ fi+ SAVE_LOGS_CLI="$2"+ shift 2+ ;;+ *)+ REMAINING_ARGS+=("$1")+ shift+ ;;+ esac+done+# 用清洗过的数组覆盖 ``$@``, 让后面所有 ``$1`` / ``"$@"`` 仍按既有顺序工作。+if (( ${#REMAINING_ARGS[@]} > 0 )); then+ set -- "${REMAINING_ARGS[@]}"+else+ set --+fi++# CLI flag 优先于环境变量, 否则继续读 JIUWENBOX_SAVE_LOGS_HOST_DIR (历史接口)。+if [[ -n "$SAVE_LOGS_CLI" ]]; then+ SAVE_LOGS_HOST_DIR="$SAVE_LOGS_CLI"+fi++if [[ $# -gt 0 ]]; then+ case "$1" in-*);;*)@@ -43,10 +136,68 @@ if [[ $# -gt 0 ]]; thenesacfi+# 解析 listen URI: tcp:// 或 unix:///abs/path; 其它形态拒绝。+LISTEN_MODE=""+LISTEN_SOCKET_PATH=""+case "$LISTEN_URI" in+ tcp://*)+ LISTEN_MODE="tcp"+ ;;+ unix:///*)+ LISTEN_MODE="uds"+ LISTEN_SOCKET_PATH="${LISTEN_URI#unix://}"+ ;;+ *)+ echo "error: JIUWENBOX_LISTEN must start with tcp:// or unix:///, got '$LISTEN_URI'" >&2+ exit 1+ ;;+esac+echo "Starting jiuwenbox container:"echo " image: $IMAGE_REF"echo " container: $CONTAINER_NAME"-echo " url: http://127.0.0.1:${HOST_PORT}"+if [[ "$LISTEN_MODE" = "tcp" ]]; then+ echo " listen: tcp -> http://127.0.0.1:${HOST_PORT}"+ DOCKER_PORT_ARGS+=(-p "${HOST_PORT}:8321")+else+ echo " listen: uds -> ${UDS_HOST_DIR}/$(basename "$LISTEN_SOCKET_PATH")"+ # 校验: socket 容器路径必须在容器内挂载点下面, 否则宿主看不见。+ case "$LISTEN_SOCKET_PATH" in+ "${UDS_CONTAINER_DIR}"/*)+ ;;+ *)+ echo "warning: socket path '$LISTEN_SOCKET_PATH' is not under" \+ "container mount dir '$UDS_CONTAINER_DIR'; the host" \+ "won't see the socket file. Adjust JIUWENBOX_LISTEN or" \+ "JIUWENBOX_UDS_CONTAINER_DIR to match." >&2+ ;;+ esac+ mkdir -p "$UDS_HOST_DIR"+ DOCKER_VOLUME_ARGS+=(-v "${UDS_HOST_DIR}:${UDS_CONTAINER_DIR}")+fi+# 代理端口在两种模式下都映射: Inference Privacy Proxy 是独立 TCP listener,+# 与管理 API 传输方式无关; 即便管理面走 UDS, 代理仍可能需要从宿主转出流量。+DOCKER_PORT_ARGS+=(-p "${PROXY_PORT}:8322")++# 把 listen / uds-mode 显式 -e 给容器, 让容器 entrypoint 拿到一致的视图。+# 注意: 这里 -e 后面的"键名"必须仍是 JIUWENBOX_LISTEN / JIUWENBOX_UDS_MODE,+# 它们是 launcher / lifespan 真正读取的环境变量, 与外部用户在 README 里设的+# 名字保持一致; 等号右边才是上面解析好的局部变量值。+DOCKER_ENV_ARGS+=(-e "JIUWENBOX_LISTEN=${LISTEN_URI}")+if [[ -n "$UDS_MODE" ]]; then+ DOCKER_ENV_ARGS+=(-e "JIUWENBOX_UDS_MODE=${UDS_MODE}")+fi++# 沙箱日志持久化: 仅在 SAVE_LOGS_HOST_DIR 显式设置时启用, 默认完全不影响+# 现有部署 (服务沿用 ~/.jiuwenbox/{logs,sandbox_logs} 私有缓存)。+if [[ -n "$SAVE_LOGS_HOST_DIR" ]]; then+ mkdir -p "$SAVE_LOGS_HOST_DIR"+ SAVE_LOGS_HOST_DIR_ABS="$(realpath "$SAVE_LOGS_HOST_DIR")"+ DOCKER_VOLUME_ARGS+=(-v "${SAVE_LOGS_HOST_DIR_ABS}:${SAVE_LOGS_CONTAINER_DIR}")+ # 直接给容器内 launcher 设环境变量, 无需改 CMD; lifespan 会读到。+ DOCKER_ENV_ARGS+=(-e "JIUWENBOX_SAVE_LOGS_DIR=${SAVE_LOGS_CONTAINER_DIR}")+ echo " save-logs: ${SAVE_LOGS_HOST_DIR_ABS} -> ${SAVE_LOGS_CONTAINER_DIR}"+fiif [[ -n "$POLICY_CONFIG" ]]; thenPOLICY_CONFIG_ABS=""@@ -78,8 +229,9 @@ docker run -itd \--cap-add=NET_ADMIN \--security-opt seccomp=unconfined \--security-opt apparmor=unconfined \- -p "${HOST_PORT}:8321" \- -p "${PROXY_PORT}:8322" \+ --cgroupns=host \+ -v /sys/fs/cgroup:/sys/fs/cgroup:rw \+ "${DOCKER_PORT_ARGS[@]}" \"${DOCKER_ENV_ARGS[@]}" \"${DOCKER_VOLUME_ARGS[@]}" \"$@" \diff --git a/jiuwenbox/src/jiuwenbox/cli/__init__.py b/jiuwenbox/src/jiuwenbox/cli/__init__.pynew file mode 100644index 0000000000..a92c89288d--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/cli/__init__.py@@ -0,0 +1,6 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""jiuwenbox CLI 命令行入口包.++`jiuwenbox.cli.jiuwenbox:main` 暴露为 ``jiuwenbox`` 可执行命令+(见 pyproject.toml ``[project.scripts]``)。+"""diff --git a/jiuwenbox/src/jiuwenbox/cli/jiuwenbox.py b/jiuwenbox/src/jiuwenbox/cli/jiuwenbox.pynew file mode 100644index 0000000000..9eb7d5f160--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/cli/jiuwenbox.py@@ -0,0 +1,1366 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""jiuwenbox HTTP API 命令行客户端 (单文件实现).++入口: 通过 ``pyproject.toml`` 的 ``[project.scripts]`` 安装为可执行脚本 ``jiuwenbox``+(行为类似 ``uvicorn``); 也兼容 ``python -m jiuwenbox.cli.jiuwenbox`` 兜底用法。++安装 (在 ``code_agent/jiuwenbox/`` 目录下)::++ pip install -e . # 开发模式+ # 或+ pip install .++总体结构:++- ``_CliClient``: httpx.Client 薄封装, 复刻 ``agent-core`` 中+ ``_JiuwenBoxClient`` 的请求语义, 同时覆盖 ``policies`` / ``proxies`` 端点。+- ``build_parser``: argparse 嵌套子命令 ``health / sandbox / policy / proxy``。+- ``cmd_<group>_<action>``: 每个 leaf 子命令的处理函数;+ 返回 ``dict`` / ``list`` 由 ``_format_output`` 统一格式化;+ 返回 ``_ExecResult`` 时主流程直接透传退出码; 返回 ``None`` 表示已自行输出。+- ``_handle_error``: 区分 HTTPStatusError / ConnectError / 本地错误, 映射退出码。++退出码:+- 0: 成功; 沙箱 exec exit_code=0+- 1: HTTP 4xx/5xx 错误+- 2: 网络不可达+- 3: 本地参数错误 (env 解析、缺文件等)+- 130: Ctrl+C+- 其他正整数: 沙箱 exec 透传退出码+"""++from __future__ import annotations++import argparse+import json+import logging+import os+import sys+import textwrap+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Callable, IO, Optional++import httpx++logger = logging.getLogger("jiuwenbox.cli")+++# ────────────────────────────── CLI output via logging ──────────────────────────────+#+# CLI 的 stdout / stderr 写出统一走 ``logging`` 模块, 满足 G.LOG.02+# (使用日志记录工具) 编码规范, 同时保留"调用方自行控制换行 / 不附加级别前缀"+# 的原始语义, 行为等同 ``sys.stdout/stderr.write``。+#+# 设计要点:+# - ``_NoTerminatorHandler`` 子类化 ``StreamHandler`` 把 ``terminator=""``,+# 不在每条记录后追加 ``\n``;+# - ``%(message)s`` Formatter 不输出级别 / 时间戳前缀;+# - ``propagate=False`` 防止冒泡到 root logger 造成重复输出;+# - 使用 ``logger.info("%s", text)`` 而非 ``logger.info(text)``, 避免 ``text``+# 中含 ``%`` 时被当作格式串。+++class _NoTerminatorHandler(logging.StreamHandler):+ """``StreamHandler`` 不附加 ``\\n`` 终止符, 行为等同 ``stream.write``."""+ terminator = ""+++_cli_stdout_logger = logging.getLogger("jiuwenbox.cli._stdout")+_cli_stderr_logger = logging.getLogger("jiuwenbox.cli._stderr")+_cli_output_loggers_initialized = False+++def _ensure_cli_output_loggers() -> None:+ """首次输出前挂载 handler; 多次调用幂等。"""+ global _cli_output_loggers_initialized+ if _cli_output_loggers_initialized:+ return+ fmt = logging.Formatter("%(message)s")+ if not _cli_stdout_logger.handlers:+ h_out = _NoTerminatorHandler(sys.stdout)+ h_out.setFormatter(fmt)+ _cli_stdout_logger.addHandler(h_out)+ _cli_stdout_logger.setLevel(logging.INFO)+ _cli_stdout_logger.propagate = False+ if not _cli_stderr_logger.handlers:+ h_err = _NoTerminatorHandler(sys.stderr)+ h_err.setFormatter(fmt)+ _cli_stderr_logger.addHandler(h_err)+ _cli_stderr_logger.setLevel(logging.INFO)+ _cli_stderr_logger.propagate = False+ _cli_output_loggers_initialized = True+++def _write_stdout(text: str) -> None:+ """CLI 程序输出 (JSON / table / plain / 透传 stdout); 不附加换行。"""+ _ensure_cli_output_loggers()+ _cli_stdout_logger.info("%s", text)+++def _write_stderr(text: str) -> None:+ """CLI 用户诊断输出 (确认提示 / 进度信息 / 错误消息); 不附加换行。"""+ _ensure_cli_output_loggers()+ _cli_stderr_logger.info("%s", text)+++def _flush_stderr() -> None:+ """同步刷新 stderr handler, 等价于 ``sys.stderr.flush()``。"""+ _ensure_cli_output_loggers()+ for handler in _cli_stderr_logger.handlers:+ handler.flush()+++# ────────────────────────────── constants ──────────────────────────────++_ENV_BASE_URL = "JIUWENBOX_URL"+_ENV_TIMEOUT = "JIUWENBOX_TIMEOUT"+_DEFAULT_BASE_URL = "http://127.0.0.1:8321"+_DEFAULT_TIMEOUT = 30.0+_API_PREFIX = "/api/v1"+_UDS_SCHEME = "unix://"+# UDS transport 仍需要一个合法 absolute base_url 才能让 httpx 拼相对路径;+# 这里给一个占位 host, 实际请求完全走 UDS 不读它。+_UDS_PLACEHOLDER_BASE_URL = "http://jiuwenbox"++# 输出格式枚举+_OUTPUT_JSON = "json"+_OUTPUT_TABLE = "table"+_OUTPUT_PLAIN = "plain"++# 退出码+EXIT_OK = 0+EXIT_API_ERROR = 1+EXIT_CONNECT_ERROR = 2+EXIT_LOCAL_ERROR = 3+EXIT_INTERRUPT = 130+++# ────────────────────────────── sentinels ──────────────────────────────+++@dataclass+class _ExecResult:+ """``sandbox exec`` 哨兵返回值, 让主流程直接透传沙箱退出码。"""+ exit_code: int+++class _CliError(Exception):+ """本地参数 / 配置错误, 退出码 3。"""++ def __init__(self, message: str, *, exit_code: int = EXIT_LOCAL_ERROR) -> None:+ super().__init__(message)+ self.exit_code = exit_code+++# ────────────────────────────── http helpers ──────────────────────────────+++def _response_error_detail(response: httpx.Response) -> str:+ """从响应中尽力提取人类可读的错误信息。"""+ try:+ payload = response.json()+ except ValueError:+ return response.text.strip()++ if isinstance(payload, dict):+ for key in ("error", "detail", "message"):+ value = payload.get(key)+ if value:+ return value if isinstance(value, str) else json.dumps(+ value, ensure_ascii=False,+ )+ return json.dumps(payload, ensure_ascii=False)++ if payload:+ return payload if isinstance(payload, str) else json.dumps(+ payload, ensure_ascii=False,+ )+ return response.text.strip()+++def _raise_for_status(response: httpx.Response) -> None:+ """复刻 agent-core 版本: 非 2xx 抛 HTTPStatusError 并附加 detail。"""+ if response.is_success:+ return+ detail = _response_error_detail(response)+ message = (+ f"HTTP {response.status_code} {response.reason_phrase}"+ f" for {response.request.method} {response.request.url}"+ )+ if detail:+ message = f"{message}: {detail}"+ raise httpx.HTTPStatusError(message, request=response.request, response=response)+++def _split_uds_endpoint(base_url: str) -> Optional[str]:+ """如果 ``base_url`` 是 ``unix:///abs/path`` 则返回 socket 路径, 否则返回 None.++ 与 server 端 :func:`jiuwenbox.server.launcher.parse_listen` 的 UDS 语义保持一致:+ 必须三斜杠 + 绝对路径; 相对路径直接抛 :class:`_CliError`, 走退出码 3。+ """+ if not base_url.startswith(_UDS_SCHEME):+ return None+ path = base_url[len(_UDS_SCHEME):]+ if not path.startswith("/"):+ raise _CliError(+ f"unix endpoint requires absolute path (unix:///abs/path), "+ f"got {base_url!r}"+ )+ return path+++# ────────────────────────────── _CliClient ──────────────────────────────+++class _CliClient:+ """httpx.Client 薄封装。++ 与 ``agent-core/openjiuwen/extensions/sys_operation/sandbox/providers/+ jiuwenbox.py::_JiuwenBoxClient`` 同语义, 额外覆盖 ``policies`` / ``proxies``+ 端点; 文件上传走 multipart, 下载流式收 bytes。++ ``base_url`` 同时支持 TCP (``http://host:port``) 与 Unix Domain Socket+ (``unix:///abs/path/to/sock``) 两种形态; 后者会走+ :class:`httpx.HTTPTransport` 的 ``uds=...`` 参数, 而对外暴露的+ ``self._base_url`` 仍保留原始 URI 串, 便于错误提示 (如+ ``cannot connect to unix:///tmp/jw.sock``) 仍可读。+ """++ def __init__(self, base_url: str, timeout_seconds: float = _DEFAULT_TIMEOUT) -> None:+ cleaned = base_url.rstrip("/")+ self._base_url = cleaned+ self._timeout = timeout_seconds+ uds_path = _split_uds_endpoint(cleaned)+ if uds_path is not None:+ self._client = httpx.Client(+ transport=httpx.HTTPTransport(uds=uds_path),+ base_url=_UDS_PLACEHOLDER_BASE_URL,+ timeout=timeout_seconds,+ )+ else:+ self._client = httpx.Client(+ base_url=cleaned, timeout=timeout_seconds,+ )++ def __enter__(self) -> "_CliClient":+ return self++ def __exit__(self, exc_type, exc, tb) -> None:+ self.close()++ def close(self) -> None:+ try:+ self._client.close()+ except Exception: # noqa: BLE001+ pass++ @property+ def base_url(self) -> str:+ return self._base_url++ # ── 基础 GET/POST/DELETE/PUT 包装 (统一抛 HTTPStatusError) ──++ def _get(self, path: str, **kwargs: Any) -> httpx.Response:+ logger.debug("GET %s params=%s", path, kwargs.get("params"))+ response = self._client.get(path, **kwargs)+ _raise_for_status(response)+ return response++ def _post(self, path: str, **kwargs: Any) -> httpx.Response:+ logger.debug("POST %s", path)+ response = self._client.post(path, **kwargs)+ _raise_for_status(response)+ return response++ def _put(self, path: str, **kwargs: Any) -> httpx.Response:+ logger.debug("PUT %s", path)+ response = self._client.put(path, **kwargs)+ _raise_for_status(response)+ return response++ def _delete(self, path: str, **kwargs: Any) -> httpx.Response:+ logger.debug("DELETE %s", path)+ response = self._client.delete(path, **kwargs)+ _raise_for_status(response)+ return response++ # ── /health ──++ def health(self) -> dict[str, Any]:+ return dict(self._get("/health").json())++ # ── /api/v1/sandboxes/* ──++ def sandbox_create(+ self,+ *,+ env: dict[str, str] | None = None,+ policy: Any = None,+ policy_mode: str | None = None,+ workdir: str | None = None,+ ) -> dict[str, Any]:+ body: dict[str, Any] = {}+ if env is not None:+ body["env"] = env+ if policy is not None:+ body["policy"] = policy+ if policy_mode is not None:+ body["policy_mode"] = policy_mode+ if workdir is not None:+ body["workdir"] = workdir+ return dict(self._post(f"{_API_PREFIX}/sandboxes", json=body).json())++ def sandbox_list(self) -> list[dict[str, Any]]:+ return list(self._get(f"{_API_PREFIX}/sandboxes").json())++ def sandbox_get(self, sandbox_id: str) -> dict[str, Any]:+ return dict(self._get(f"{_API_PREFIX}/sandboxes/{sandbox_id}").json())++ def sandbox_delete(self, sandbox_id: str) -> None:+ self._delete(f"{_API_PREFIX}/sandboxes/{sandbox_id}")++ def sandbox_start(self, sandbox_id: str) -> dict[str, Any]:+ return dict(self._post(f"{_API_PREFIX}/sandboxes/{sandbox_id}/start").json())++ def sandbox_stop(self, sandbox_id: str) -> dict[str, Any]:+ return dict(self._post(f"{_API_PREFIX}/sandboxes/{sandbox_id}/stop").json())++ def sandbox_restart(self, sandbox_id: str) -> dict[str, Any]:+ return dict(self._post(f"{_API_PREFIX}/sandboxes/{sandbox_id}/restart").json())++ def sandbox_exec(+ self,+ sandbox_id: str,+ command: list[str],+ *,+ cwd: str | None = None,+ env: dict[str, str] | None = None,+ stdin: str | None = None,+ timeout_seconds: int | None = None,+ ) -> dict[str, Any]:+ body: dict[str, Any] = {"command": command}+ if cwd is not None:+ body["workdir"] = cwd+ if env is not None:+ body["env"] = env+ if stdin is not None:+ body["stdin"] = stdin+ if timeout_seconds is not None:+ body["timeout_seconds"] = timeout_seconds+ # 让 http 超时大于沙箱内部 timeout, 避免提前断流+ http_timeout = max(self._timeout, (timeout_seconds or 0) + 5)+ return dict(self._post(+ f"{_API_PREFIX}/sandboxes/{sandbox_id}/exec",+ json=body, timeout=http_timeout,+ ).json())++ def sandbox_exec_background(+ self,+ sandbox_id: str,+ command: list[str],+ *,+ cwd: str | None = None,+ env: dict[str, str] | None = None,+ stdin: str | None = None,+ ) -> dict[str, Any]:+ body: dict[str, Any] = {"command": command}+ if cwd is not None:+ body["workdir"] = cwd+ if env is not None:+ body["env"] = env+ if stdin is not None:+ body["stdin"] = stdin+ return dict(self._post(+ f"{_API_PREFIX}/sandboxes/{sandbox_id}/exec_background", json=body,+ ).json())++ def sandbox_logs(self, sandbox_id: str) -> str:+ return self._get(f"{_API_PREFIX}/sandboxes/{sandbox_id}/logs").text++ def sandbox_upload(+ self,+ sandbox_id: str,+ sandbox_path: str,+ *,+ file_name: str,+ content: bytes,+ ) -> None:+ self._post(+ f"{_API_PREFIX}/sandboxes/{sandbox_id}/upload",+ params={"sandbox_path": sandbox_path},+ files={"file": (file_name, content)},+ )++ def sandbox_download(self, sandbox_id: str, sandbox_path: str) -> bytes:+ response = self._get(+ f"{_API_PREFIX}/sandboxes/{sandbox_id}/download",+ params={"sandbox_path": sandbox_path},+ )+ return response.content++ def sandbox_files(+ self,+ sandbox_id: str,+ sandbox_path: str,+ *,+ recursive: bool = False,+ max_depth: int | None = None,+ include_files: bool = True,+ include_dirs: bool = True,+ ) -> list[dict[str, Any]]:+ params: dict[str, Any] = {+ "sandbox_path": sandbox_path,+ "recursive": str(bool(recursive)).lower(),+ "include_files": str(bool(include_files)).lower(),+ "include_dirs": str(bool(include_dirs)).lower(),+ }+ if max_depth is not None:+ params["max_depth"] = int(max_depth)+ payload = self._get(f"{_API_PREFIX}/sandboxes/{sandbox_id}/files", params=params).json()+ return list(payload.get("items") or [])++ def sandbox_search(+ self,+ sandbox_id: str,+ sandbox_path: str,+ pattern: str,+ *,+ exclude_patterns: list[str] | None = None,+ ) -> list[dict[str, Any]]:+ params: list[tuple[str, Any]] = [+ ("sandbox_path", sandbox_path),+ ("pattern", pattern),+ ]+ for ex in exclude_patterns or []:+ params.append(("exclude_patterns", ex))+ payload = self._get(f"{_API_PREFIX}/sandboxes/{sandbox_id}/search", params=params).json()+ return list(payload.get("items") or [])++ # ── /api/v1/policies/* ──++ def policy_get(self, sandbox_id: str) -> dict[str, Any]:+ return dict(self._get(f"{_API_PREFIX}/policies/{sandbox_id}").json())++ # ── /api/v1/proxies/* ──++ def proxy_create(+ self,+ *,+ path_prefix: str,+ target_endpoint: str,+ api_key: str | None = None,+ skip_cert_verify: bool = False,+ ) -> dict[str, Any]:+ body: dict[str, Any] = {+ "path_prefix": path_prefix,+ "target_endpoint": target_endpoint,+ "skip_cert_verify": bool(skip_cert_verify),+ }+ if api_key is not None:+ body["api_key"] = api_key+ return dict(self._post(f"{_API_PREFIX}/proxies", json=body).json())++ def proxy_list(self) -> list[dict[str, Any]]:+ return list(self._get(f"{_API_PREFIX}/proxies").json())++ def proxy_get(self, name: str) -> dict[str, Any]:+ return dict(self._get(f"{_API_PREFIX}/proxies/{name}").json())++ def proxy_delete(self, name: str) -> dict[str, Any]:+ return dict(self._delete(f"{_API_PREFIX}/proxies/{name}").json())++ def proxy_start(self, name: str) -> dict[str, Any]:+ return dict(self._post(f"{_API_PREFIX}/proxies/{name}/start").json())++ def proxy_stop(self, name: str) -> dict[str, Any]:+ return dict(self._post(f"{_API_PREFIX}/proxies/{name}/stop").json())++ def proxy_update(+ self,+ name: str,+ *,+ path_prefix: str,+ target_endpoint: str,+ api_key: str | None = None,+ skip_cert_verify: bool = False,+ ) -> dict[str, Any]:+ body: dict[str, Any] = {+ "path_prefix": path_prefix,+ "target_endpoint": target_endpoint,+ "skip_cert_verify": bool(skip_cert_verify),+ }+ if api_key is not None:+ body["api_key"] = api_key+ return dict(self._put(f"{_API_PREFIX}/proxies/{name}", json=body).json())++ def proxy_logs(self, name: str, *, lines: int | None = None) -> str:+ params: dict[str, Any] = {}+ if lines is not None:+ params["lines"] = int(lines)+ return self._get(f"{_API_PREFIX}/proxies/{name}/logs", params=params).text+++# ────────────────────────────── arg parsers helpers ──────────────────────────────+++def _parse_env_pair(token: str) -> tuple[str, str]:+ if "=" not in token:+ raise _CliError(+ f"invalid --env value: {token!r}; expected KEY=VAL",+ )+ key, _, value = token.partition("=")+ if not key:+ raise _CliError(+ f"invalid --env value: {token!r}; KEY must be non-empty",+ )+ return key, value+++def _parse_env_list(tokens: list[str] | None) -> dict[str, str] | None:+ if not tokens:+ return None+ out: dict[str, str] = {}+ for tok in tokens:+ key, value = _parse_env_pair(tok)+ out[key] = value+ return out+++def _load_policy_file(path: str) -> Any:+ p = Path(path)+ if not p.is_file():+ raise _CliError(f"policy file not found: {path}")+ text = p.read_text(encoding="utf-8")+ suffix = p.suffix.lower()+ if suffix in (".yaml", ".yml"):+ try:+ import yaml # type: ignore+ except ImportError as exc: # pragma: no cover - pyyaml is a dep+ raise _CliError(f"pyyaml required to load {path}: {exc}") from exc+ return yaml.safe_load(text)+ try:+ return json.loads(text)+ except json.JSONDecodeError as exc:+ raise _CliError(f"policy file {path} is not valid JSON: {exc}") from exc+++def _resolve_stdin_input(value: Optional[str]) -> Optional[str]:+ """``--stdin -`` → 从 host stdin 读取整段; 普通字符串 → 直接返回。"""+ if value is None:+ return None+ if value == "-":+ return sys.stdin.read()+ return value+++# ────────────────────────────── output formatters ──────────────────────────────+++# 命令侧通过 cmd_xxx.COLUMNS / cmd_xxx.PLAIN_FIELD 声明列与 plain 字段+_CMD_COLUMNS_ATTR = "COLUMNS"+_CMD_PLAIN_FIELD_ATTR = "PLAIN_FIELD"+++def _print_json(result: Any) -> None:+ _write_stdout(json.dumps(result, ensure_ascii=False, indent=2) + "\n")+++def _print_table(rows: list[dict[str, Any]], columns: list[str]) -> None:+ """简单 ASCII 表格 (无依赖)。"""+ if not rows:+ _write_stdout("(no items)\n")+ return+ # 列宽 = max(列名长度, 单元格 str 长度)+ cells: list[list[str]] = []+ for row in rows:+ line: list[str] = []+ for col in columns:+ v = row.get(col)+ line.append("" if v is None else str(v))+ cells.append(line)+ widths = [len(c) for c in columns]+ for line in cells:+ for i, cell in enumerate(line):+ if len(cell) > widths[i]:+ widths[i] = len(cell)+ fmt = " ".join(f"{{:<{w}}}" for w in widths)+ _write_stdout(fmt.format(*[c.upper() for c in columns]) + "\n")+ for line in cells:+ _write_stdout(fmt.format(*line) + "\n")+++def _print_plain(result: Any, plain_field: Optional[str]) -> None:+ """plain 模式: 优先 plain_field, 否则智能展开。"""+ if isinstance(result, dict):+ if plain_field and plain_field in result:+ value = result[plain_field]+ _write_stdout(("" if value is None else str(value)) + "\n")+ return+ # 兜底: 每行 "key=value"+ for key, value in result.items():+ _write_stdout(f"{key}={value}\n")+ return+ if isinstance(result, list):+ for item in result:+ if isinstance(item, dict) and plain_field and plain_field in item:+ value = item[plain_field]+ _write_stdout(("" if value is None else str(value)) + "\n")+ else:+ _write_stdout(str(item) + "\n")+ return+ _write_stdout(("" if result is None else str(result)) + "\n")+++def _format_output(+ result: Any,+ fmt: str,+ *,+ columns: Optional[list[str]] = None,+ plain_field: Optional[str] = None,+) -> None:+ if result is None:+ return+ if fmt == _OUTPUT_JSON:+ _print_json(result)+ return+ if fmt == _OUTPUT_TABLE:+ if isinstance(result, list) and all(isinstance(it, dict) for it in result) and columns:+ _print_table(result, columns)+ return+ # 不能表格化时退化为 JSON+ _print_json(result)+ return+ if fmt == _OUTPUT_PLAIN:+ _print_plain(result, plain_field)+ return+ # 兜底+ _print_json(result)+++# ────────────────────────────── stderr helpers ──────────────────────────────+++def _stderr_supports_color() -> bool:+ if os.environ.get("NO_COLOR"):+ return False+ return sys.stderr.isatty()+++def _eprint(message: str, *, kind: str = "error", color: bool = True) -> None:+ """带可选颜色的 stderr 输出。"""+ prefix = f"{kind}: "+ if color and _stderr_supports_color():+ # 红色 ERROR / 黄色 WARN+ ansi = "\033[31m" if kind == "error" else "\033[33m"+ prefix = f"{ansi}{prefix}\033[0m"+ _write_stderr(prefix + message + "\n")+++# ────────────────────────────── command handlers ──────────────────────────────+++# ── health ──++def cmd_health(args: argparse.Namespace, client: _CliClient) -> Any:+ return client.health()+++cmd_health.PLAIN_FIELD = "status" # type: ignore[attr-defined]+++# ── sandbox ──++def cmd_sandbox_create(args: argparse.Namespace, client: _CliClient) -> Any:+ env = _parse_env_list(args.env)+ policy = _load_policy_file(args.policy_file) if args.policy_file else None+ return client.sandbox_create(+ env=env,+ policy=policy,+ policy_mode=args.policy_mode,+ )+++cmd_sandbox_create.PLAIN_FIELD = "id" # type: ignore[attr-defined]+++def cmd_sandbox_ls(args: argparse.Namespace, client: _CliClient) -> Any:+ sandboxes = client.sandbox_list()+ if args.phase:+ sandboxes = [s for s in sandboxes if s.get("phase") == args.phase]+ return sandboxes+++cmd_sandbox_ls.COLUMNS = ["id", "phase", "runtime", "pid", "created_at"] # type: ignore[attr-defined]+cmd_sandbox_ls.PLAIN_FIELD = "id" # type: ignore[attr-defined]+++def cmd_sandbox_get(args: argparse.Namespace, client: _CliClient) -> Any:+ return client.sandbox_get(args.sandbox_id)+++cmd_sandbox_get.PLAIN_FIELD = "phase" # type: ignore[attr-defined]+++def cmd_sandbox_rm(args: argparse.Namespace, client: _CliClient) -> Any:+ if not args.yes and sys.stdin.isatty():+ _write_stderr(f"Delete sandbox {args.sandbox_id}? [y/N] ")+ _flush_stderr()+ answer = sys.stdin.readline().strip().lower()+ if answer not in ("y", "yes"):+ _write_stderr("aborted\n")+ return None+ client.sandbox_delete(args.sandbox_id)+ _write_stderr(f"deleted sandbox {args.sandbox_id}\n")+ return None+++def cmd_sandbox_start(args: argparse.Namespace, client: _CliClient) -> Any:+ return client.sandbox_start(args.sandbox_id)+++cmd_sandbox_start.PLAIN_FIELD = "phase" # type: ignore[attr-defined]+++def cmd_sandbox_stop(args: argparse.Namespace, client: _CliClient) -> Any:+ return client.sandbox_stop(args.sandbox_id)+++cmd_sandbox_stop.PLAIN_FIELD = "phase" # type: ignore[attr-defined]+++def cmd_sandbox_restart(args: argparse.Namespace, client: _CliClient) -> Any:+ return client.sandbox_restart(args.sandbox_id)+++cmd_sandbox_restart.PLAIN_FIELD = "phase" # type: ignore[attr-defined]+++def _strip_command_separator(command: list[str]) -> list[str]:+ """``argparse.REMAINDER`` 会把分隔符 ``--`` 也吞进 list, 这里去掉首个 ``--``。"""+ if command and command[0] == "--":+ return command[1:]+ return command+++def cmd_sandbox_exec(args: argparse.Namespace, client: _CliClient) -> Any:+ command: list[str] = _strip_command_separator(list(args.command or []))+ if not command:+ raise _CliError("missing command after `--`; example: exec ID -- ls /tmp")+ env = _parse_env_list(args.env)+ stdin_text = _resolve_stdin_input(args.stdin)+ result = client.sandbox_exec(+ args.sandbox_id,+ command,+ cwd=args.cwd,+ env=env,+ stdin=stdin_text,+ timeout_seconds=args.timeout_seconds,+ )+ if args.output == _OUTPUT_JSON:+ _print_json(result)+ else:+ # 默认 / plain / table 都走 "stdout→stdout, stderr→stderr" 透传+ stdout_text = result.get("stdout") or ""+ stderr_text = result.get("stderr") or ""+ if stdout_text:+ _write_stdout(stdout_text)+ if stderr_text:+ _write_stderr(stderr_text)+ exit_code = int(result.get("exit_code") or 0)+ return _ExecResult(exit_code=exit_code)+++def cmd_sandbox_exec_bg(args: argparse.Namespace, client: _CliClient) -> Any:+ command: list[str] = _strip_command_separator(list(args.command or []))+ if not command:+ raise _CliError("missing command after `--`")+ env = _parse_env_list(args.env)+ stdin_text = _resolve_stdin_input(args.stdin)+ return client.sandbox_exec_background(+ args.sandbox_id,+ command,+ cwd=args.cwd,+ env=env,+ stdin=stdin_text,+ )+++cmd_sandbox_exec_bg.PLAIN_FIELD = "pid" # type: ignore[attr-defined]+++def cmd_sandbox_logs(args: argparse.Namespace, client: _CliClient) -> Any:+ text = client.sandbox_logs(args.sandbox_id)+ # logs 是 text/plain, 直接打 stdout, 不参与 JSON 格式化+ _write_stdout(text)+ if text and not text.endswith("\n"):+ _write_stdout("\n")+ return None+++def cmd_sandbox_upload(args: argparse.Namespace, client: _CliClient) -> Any:+ local = args.local_path+ if local == "-":+ content = sys.stdin.buffer.read()+ file_name = "stdin.bin"+ else:+ path = Path(local)+ if not path.is_file():+ raise _CliError(f"local file not found: {local}")+ content = path.read_bytes()+ file_name = path.name+ client.sandbox_upload(+ args.sandbox_id,+ args.sandbox_path,+ file_name=file_name,+ content=content,+ )+ _write_stderr(f"uploaded {len(content)} bytes -> {args.sandbox_path}\n")+ return None+++def cmd_sandbox_download(args: argparse.Namespace, client: _CliClient) -> Any:+ content = client.sandbox_download(args.sandbox_id, args.sandbox_path)+ local = args.local_path or "-"+ if local == "-":+ # binary-safe to stdout+ sys.stdout.buffer.write(content)+ sys.stdout.buffer.flush()+ else:+ Path(local).write_bytes(content)+ _write_stderr(f"downloaded {len(content)} bytes -> {local}\n")+ return None+++def cmd_sandbox_files(args: argparse.Namespace, client: _CliClient) -> Any:+ return client.sandbox_files(+ args.sandbox_id,+ args.sandbox_path,+ recursive=args.recursive,+ max_depth=args.max_depth,+ include_files=not args.no_files,+ include_dirs=not args.no_dirs,+ )+++def _files_columns_row(item: dict[str, Any]) -> dict[str, Any]:+ return {+ "type": "dir" if item.get("is_directory") else "file",+ "size": item.get("size"),+ "modified": item.get("modified_time"),+ "path": item.get("path"),+ }+++cmd_sandbox_files.COLUMNS = ["type", "size", "modified", "path"] # type: ignore[attr-defined]+++def cmd_sandbox_find(args: argparse.Namespace, client: _CliClient) -> Any:+ return client.sandbox_search(+ args.sandbox_id,+ args.sandbox_path,+ args.pattern,+ exclude_patterns=args.exclude or None,+ )+++cmd_sandbox_find.COLUMNS = ["type", "size", "modified", "path"] # type: ignore[attr-defined]+++# ── policy ──++def cmd_policy_get(args: argparse.Namespace, client: _CliClient) -> Any:+ return client.policy_get(args.sandbox_id)+++cmd_policy_get.PLAIN_FIELD = "name" # type: ignore[attr-defined]+++# ── proxy ──++def cmd_proxy_create(args: argparse.Namespace, client: _CliClient) -> Any:+ return client.proxy_create(+ path_prefix=args.prefix,+ target_endpoint=args.target,+ api_key=args.api_key,+ skip_cert_verify=args.skip_cert,+ )+++cmd_proxy_create.PLAIN_FIELD = "name" # type: ignore[attr-defined]+++def cmd_proxy_ls(args: argparse.Namespace, client: _CliClient) -> Any:+ proxies = client.proxy_list()+ # 把 nested route.target_endpoint 平铺到 table+ rows: list[dict[str, Any]] = []+ for proxy in proxies:+ target = (proxy.get("route") or {}).get("target_endpoint")+ rows.append({+ "name": proxy.get("name"),+ "state": proxy.get("state"),+ "port": proxy.get("listen_port"),+ "target": target,+ })+ if args.output == _OUTPUT_TABLE:+ _print_table(rows, cmd_proxy_ls.COLUMNS) # type: ignore[attr-defined]+ return None+ return proxies+++cmd_proxy_ls.COLUMNS = ["name", "state", "port", "target"] # type: ignore[attr-defined]+cmd_proxy_ls.PLAIN_FIELD = "name" # type: ignore[attr-defined]+++def cmd_proxy_get(args: argparse.Namespace, client: _CliClient) -> Any:+ return client.proxy_get(args.name)+++cmd_proxy_get.PLAIN_FIELD = "state" # type: ignore[attr-defined]+++def cmd_proxy_rm(args: argparse.Namespace, client: _CliClient) -> Any:+ if not args.yes and sys.stdin.isatty():+ _write_stderr(f"Delete proxy {args.name}? [y/N] ")+ _flush_stderr()+ answer = sys.stdin.readline().strip().lower()+ if answer not in ("y", "yes"):+ _write_stderr("aborted\n")+ return None+ return client.proxy_delete(args.name)+++def cmd_proxy_start(args: argparse.Namespace, client: _CliClient) -> Any:+ return client.proxy_start(args.name)+++cmd_proxy_start.PLAIN_FIELD = "state" # type: ignore[attr-defined]+++def cmd_proxy_stop(args: argparse.Namespace, client: _CliClient) -> Any:+ return client.proxy_stop(args.name)+++cmd_proxy_stop.PLAIN_FIELD = "state" # type: ignore[attr-defined]+++def cmd_proxy_update(args: argparse.Namespace, client: _CliClient) -> Any:+ return client.proxy_update(+ args.name,+ path_prefix=args.prefix,+ target_endpoint=args.target,+ api_key=args.api_key,+ skip_cert_verify=args.skip_cert,+ )+++def cmd_proxy_logs(args: argparse.Namespace, client: _CliClient) -> Any:+ text = client.proxy_logs(args.name, lines=args.lines)+ _write_stdout(text)+ if text and not text.endswith("\n"):+ _write_stdout("\n")+ return None+++# ────────────────────────────── argparse build_parser ──────────────────────────────+++def _add_global_options(parser: argparse.ArgumentParser) -> None:+ parser.add_argument(+ "--base-url",+ default=os.environ.get(_ENV_BASE_URL, _DEFAULT_BASE_URL),+ help=(+ f"jiuwenbox HTTP base url; accepts http://host:port or "+ f"unix:///abs/socket/path (env {_ENV_BASE_URL}, "+ f"default {_DEFAULT_BASE_URL})"+ ),+ )+ parser.add_argument(+ "--timeout",+ type=float,+ default=float(os.environ.get(_ENV_TIMEOUT, _DEFAULT_TIMEOUT)),+ help=f"HTTP client timeout seconds (env {_ENV_TIMEOUT}, default {int(_DEFAULT_TIMEOUT)})",+ )+ parser.add_argument(+ "--output", "-o",+ choices=[_OUTPUT_JSON, _OUTPUT_TABLE, _OUTPUT_PLAIN],+ default=None,+ help=(+ "output format (default: json for most commands; "+ "`sandbox exec` defaults to stdout/stderr passthrough)"+ ),+ )+ parser.add_argument(+ "--verbose", "-v",+ action="store_true",+ help="enable debug logging on stderr",+ )+ parser.add_argument(+ "--no-color",+ action="store_true",+ help="disable ANSI colors on stderr",+ )+++def _add_sandbox_id(p: argparse.ArgumentParser) -> None:+ p.add_argument("sandbox_id", help="sandbox id")+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ prog="jiuwenbox",+ description="jiuwenbox HTTP API client CLI",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ epilog=textwrap.dedent("""\+ Examples:+ jiuwenbox health+ jiuwenbox sandbox create+ jiuwenbox sandbox exec <ID> -- python3 -c 'print(1)'+ jiuwenbox sandbox upload <ID> ./local.txt /tmp/remote.txt+ jiuwenbox --base-url unix:///tmp/jw.sock health+ JIUWENBOX_URL=unix:///tmp/jw.sock jiuwenbox sandbox ls+ """),+ )+ _add_global_options(parser)++ groups = parser.add_subparsers(+ dest="group", metavar="GROUP",+ )+ groups.required = True++ # ── health ──+ p_health = groups.add_parser("health", help="server health check")+ p_health.set_defaults(_handler=cmd_health)++ # ── sandbox group ──+ p_sandbox = groups.add_parser("sandbox", help="manage sandboxes")+ sandbox_subs = p_sandbox.add_subparsers(dest="action", metavar="ACTION")+ sandbox_subs.required = True++ p = sandbox_subs.add_parser("create", help="create sandbox")+ p.add_argument(+ "--env", action="append", metavar="KEY=VAL",+ help="environment variable (repeatable)",+ )+ p.add_argument(+ "--policy-file", help="local JSON or YAML policy file",+ )+ p.add_argument(+ "--policy-mode", choices=["override", "append"], default=None,+ help="policy merge mode (default server-side 'override')",+ )+ p.set_defaults(_handler=cmd_sandbox_create)++ p = sandbox_subs.add_parser("ls", help="list sandboxes")+ p.add_argument("--phase", help="filter by phase locally")+ p.set_defaults(_handler=cmd_sandbox_ls)++ p = sandbox_subs.add_parser("get", help="get sandbox state")+ _add_sandbox_id(p)+ p.set_defaults(_handler=cmd_sandbox_get)++ p = sandbox_subs.add_parser("rm", help="delete sandbox")+ _add_sandbox_id(p)+ p.add_argument(+ "--yes", "-y", action="store_true", help="skip confirmation",+ )+ p.set_defaults(_handler=cmd_sandbox_rm)++ for action_name, handler in (+ ("start", cmd_sandbox_start),+ ("stop", cmd_sandbox_stop),+ ("restart", cmd_sandbox_restart),+ ):+ p = sandbox_subs.add_parser(action_name, help=f"{action_name} sandbox")+ _add_sandbox_id(p)+ p.set_defaults(_handler=handler)++ p = sandbox_subs.add_parser(+ "exec", help="execute command in sandbox (sync)",+ )+ _add_sandbox_id(p)+ p.add_argument("--cwd", help="working directory inside sandbox")+ p.add_argument(+ "--env", action="append", metavar="KEY=VAL",+ help="environment variable (repeatable)",+ )+ p.add_argument(+ "--timeout-seconds", type=int, default=None,+ help="command timeout seconds (inside sandbox)",+ )+ p.add_argument(+ "--stdin",+ help="stdin text; use '-' to read from host stdin",+ )+ # 必须用 `--` 把待执行命令与本 CLI 自身的选项隔开 (类似 docker exec / kubectl exec)。+ # 不使用 argparse.REMAINDER, 否则 ``--stdin``/``--cwd`` 等出现在 sandbox_id 之后时+ # 会被一股脑塞进 command 列表; ``nargs="*"`` + 用户加 ``--`` 才能让本侧选项被识别。+ p.add_argument(+ "command", nargs="*",+ help="command to run; place after `--`",+ )+ p.set_defaults(_handler=cmd_sandbox_exec)++ p = sandbox_subs.add_parser(+ "exec-bg", help="execute command in background (non-blocking)",+ )+ _add_sandbox_id(p)+ p.add_argument("--cwd", help="working directory inside sandbox")+ p.add_argument(+ "--env", action="append", metavar="KEY=VAL",+ help="environment variable (repeatable)",+ )+ p.add_argument(+ "--stdin",+ help="stdin text; use '-' to read from host stdin",+ )+ p.add_argument(+ "command", nargs="*",+ help="command to run; place after `--`",+ )+ p.set_defaults(_handler=cmd_sandbox_exec_bg)++ p = sandbox_subs.add_parser("logs", help="get audit logs (text)")+ _add_sandbox_id(p)+ p.set_defaults(_handler=cmd_sandbox_logs)++ p = sandbox_subs.add_parser("upload", help="upload local file to sandbox")+ _add_sandbox_id(p)+ p.add_argument("local_path", help="local file path; '-' = stdin")+ p.add_argument("sandbox_path", help="sandbox destination path")+ p.set_defaults(_handler=cmd_sandbox_upload)++ p = sandbox_subs.add_parser("download", help="download sandbox file")+ _add_sandbox_id(p)+ p.add_argument("sandbox_path", help="sandbox source path")+ p.add_argument(+ "local_path", nargs="?", default=None,+ help="local destination path; '-' or omit = stdout",+ )+ p.set_defaults(_handler=cmd_sandbox_download)++ p = sandbox_subs.add_parser("files", help="list files in sandbox directory")+ _add_sandbox_id(p)+ p.add_argument("sandbox_path", help="sandbox directory")+ p.add_argument("--recursive", "-r", action="store_true")+ p.add_argument("--max-depth", type=int, default=None)+ p.add_argument("--no-files", action="store_true", help="exclude files")+ p.add_argument("--no-dirs", action="store_true", help="exclude directories")+ p.set_defaults(_handler=cmd_sandbox_files)++ p = sandbox_subs.add_parser("find", help="search sandbox files by glob")+ _add_sandbox_id(p)+ p.add_argument("sandbox_path", help="search root")+ p.add_argument("pattern", help="glob pattern")+ p.add_argument(+ "-x", "--exclude", action="append",+ help="exclude pattern (repeatable)",+ )+ p.set_defaults(_handler=cmd_sandbox_find)++ # ── policy group ──+ p_policy = groups.add_parser("policy", help="inspect sandbox policy")+ policy_subs = p_policy.add_subparsers(dest="action", metavar="ACTION")+ policy_subs.required = True++ p = policy_subs.add_parser("get", help="get effective policy of sandbox")+ _add_sandbox_id(p)+ p.set_defaults(_handler=cmd_policy_get)++ # ── proxy group ──+ p_proxy = groups.add_parser("proxy", help="manage inference proxies")+ proxy_subs = p_proxy.add_subparsers(dest="action", metavar="ACTION")+ proxy_subs.required = True++ p = proxy_subs.add_parser("create", help="create proxy route")+ p.add_argument("--prefix", required=True, help="path prefix, e.g. /openai")+ p.add_argument("--target", required=True, help="upstream endpoint")+ p.add_argument("--api-key", default=None)+ p.add_argument("--skip-cert", action="store_true", help="skip TLS verify")+ p.set_defaults(_handler=cmd_proxy_create)++ p = proxy_subs.add_parser("ls", help="list proxies")+ p.set_defaults(_handler=cmd_proxy_ls)++ p = proxy_subs.add_parser("get", help="get proxy detail")+ p.add_argument("name")+ p.set_defaults(_handler=cmd_proxy_get)++ p = proxy_subs.add_parser("rm", help="delete proxy")+ p.add_argument("name")+ p.add_argument("--yes", "-y", action="store_true", help="skip confirmation")+ p.set_defaults(_handler=cmd_proxy_rm)++ for action_name, handler in (+ ("start", cmd_proxy_start),+ ("stop", cmd_proxy_stop),+ ):+ p = proxy_subs.add_parser(action_name, help=f"{action_name} proxy")+ p.add_argument("name")+ p.set_defaults(_handler=handler)++ p = proxy_subs.add_parser("update", help="update proxy route")+ p.add_argument("name")+ p.add_argument("--prefix", required=True)+ p.add_argument("--target", required=True)+ p.add_argument("--api-key", default=None)+ p.add_argument("--skip-cert", action="store_true")+ p.set_defaults(_handler=cmd_proxy_update)++ p = proxy_subs.add_parser("logs", help="tail proxy logs")+ p.add_argument("name")+ p.add_argument("--lines", type=int, default=None)+ p.set_defaults(_handler=cmd_proxy_logs)++ return parser+++# ────────────────────────────── error handler ──────────────────────────────+++def _handle_error(exc: BaseException, *, verbose: bool, base_url: str) -> int:+ if isinstance(exc, KeyboardInterrupt):+ _eprint("interrupted", kind="warn")+ return EXIT_INTERRUPT+ if isinstance(exc, _CliError):+ _eprint(str(exc))+ return exc.exit_code+ if isinstance(exc, httpx.HTTPStatusError):+ _eprint(str(exc))+ return EXIT_API_ERROR+ if isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)):+ _eprint(+ f"cannot connect to {base_url}; is jiuwenbox running?",+ )+ return EXIT_CONNECT_ERROR+ if isinstance(exc, httpx.ReadTimeout):+ _eprint(f"request to {base_url} timed out")+ return EXIT_CONNECT_ERROR+ if isinstance(exc, FileNotFoundError):+ _eprint(f"{exc}")+ return EXIT_LOCAL_ERROR+ # 兜底+ _eprint(f"{type(exc).__name__}: {exc}")+ if verbose:+ import traceback+ traceback.print_exc(file=sys.stderr)+ return EXIT_API_ERROR+++# ────────────────────────────── main entry ──────────────────────────────+++def _configure_logging(verbose: bool) -> None:+ level = logging.DEBUG if verbose else logging.WARNING+ logging.basicConfig(+ level=level,+ format="%(asctime)s %(levelname)s %(name)s: %(message)s",+ stream=sys.stderr,+ )+++_EXEC_SUBCOMMAND_SEQUENCES: tuple[tuple[str, str], ...] = (+ ("sandbox", "exec"),+ ("sandbox", "exec-bg"),+)+++def _split_argv_on_command_separator(+ argv: list[str],+) -> tuple[list[str], list[str] | None]:+ """把首次独立出现的 ``--`` 之后的 token 切出来作为 ``sandbox exec`` 命令尾部。++ 背景: argparse 的 subparser × ``nargs="*"`` × ``--`` 组合长期存在不稳定行为+ (子解析器消费完已声明的选项后, 残留的 ``-- cat`` 会被冒泡回顶层 parser 报+ ``unrecognized arguments``)。我们在送入 argparse 之前手动切, 让 argparse+ 完全看不到 ``--``, 也就不会触发这个坑。++ 只在 argv 中出现连续的 ``sandbox exec`` / ``sandbox exec-bg`` 子命令序列+ 且 ``--`` 出现在该序列之后时才做预切分; 其余命令保留 argparse 标准的+ ``--`` 终止符语义 (比如允许用户写 ``sandbox rm -- --weird-id`` 删除以+ ``--`` 开头的 id)。++ 返回 (head_argv, tail_argv); tail_argv 为 None 表示无需切分。+ """+ if "--" not in argv:+ return list(argv), None+ sep_idx = argv.index("--")+ prefix = argv[:sep_idx]+ has_exec_sequence = False+ for sequence in _EXEC_SUBCOMMAND_SEQUENCES:+ seq_len = len(sequence)+ for start in range(len(prefix) - seq_len + 1):+ if tuple(prefix[start:start + seq_len]) == sequence:+ has_exec_sequence = True+ break+ if has_exec_sequence:+ break+ if not has_exec_sequence:+ return list(argv), None+ return list(prefix), list(argv[sep_idx + 1:])+++def main(argv: list[str] | None = None) -> int:+ if argv is None:+ argv = sys.argv[1:]+ head_argv, tail_argv = _split_argv_on_command_separator(list(argv))++ parser = build_parser()+ args = parser.parse_args(head_argv)+ # 仅 ``sandbox exec`` / ``sandbox exec-bg`` 会声明 ``command`` 属性。+ # 用户在 ``--`` 之后写的 token 一律拼到该 list 末尾。+ if tail_argv is not None and hasattr(args, "command"):+ existing = list(getattr(args, "command", None) or [])+ args.command = existing + tail_argv+ _configure_logging(getattr(args, "verbose", False))++ handler: Callable[[argparse.Namespace, _CliClient], Any] | None = getattr(+ args, "_handler", None,+ )+ if handler is None:+ parser.error("no command specified")++ base_url = args.base_url+ try:+ with _CliClient(base_url=base_url, timeout_seconds=args.timeout) as client:+ try:+ result = handler(args, client)+ except _CliError:+ raise+ except httpx.HTTPError:+ raise+ except KeyboardInterrupt:+ raise+ if isinstance(result, _ExecResult):+ return result.exit_code+ # files / find 命令的 table 行需要平铺 → 处理一次+ columns: Optional[list[str]] = getattr(handler, _CMD_COLUMNS_ATTR, None)+ plain_field: Optional[str] = getattr(handler, _CMD_PLAIN_FIELD_ATTR, None)+ # 全局 ``--output`` 未指定时 (None) 默认走 JSON; ``sandbox exec`` 自己在+ # handler 里把 None 解释成 "stdout/stderr 透传", 走不到这里的 _format_output 兜底。+ effective_output = args.output or _OUTPUT_JSON+ if handler in (cmd_sandbox_files, cmd_sandbox_find) and isinstance(result, list):+ display_rows = [_files_columns_row(it) for it in result if isinstance(it, dict)]+ _format_output(+ display_rows if effective_output == _OUTPUT_TABLE else result,+ effective_output,+ columns=columns,+ plain_field=plain_field,+ )+ else:+ _format_output(+ result, effective_output,+ columns=columns,+ plain_field=plain_field,+ )+ return EXIT_OK+ except BaseException as exc:+ return _handle_error(+ exc,+ verbose=getattr(args, "verbose", False),+ base_url=base_url,+ )+++if __name__ == "__main__": # pragma: no cover - module entry+ raise SystemExit(main())diff --git a/jiuwenbox/src/jiuwenbox/models/common.py b/jiuwenbox/src/jiuwenbox/models/common.pyindex e6f4334913..ed5f390254 100644--- a/jiuwenbox/src/jiuwenbox/models/common.py+++ b/jiuwenbox/src/jiuwenbox/models/common.py@@ -15,6 +15,11 @@ class AuditEventType(str, enum.Enum):SANDBOX_STOPPED = "sandbox_stopped"SANDBOX_DELETED = "sandbox_deleted"POLICY_APPLIED = "policy_applied"+ # Single event per operation, emitted **after** the call returns so+ # the payload carries both intent (command/workdir) and outcome+ # (exit_code, stdout/stderr, duration, error). The earlier "intent+ # only" event was dropped because it doubled the JSONL volume+ # without adding information.EXEC_COMMAND = "exec_command"FILE_TRANSFER = "file_transfer"diff --git a/jiuwenbox/src/jiuwenbox/models/policy.py b/jiuwenbox/src/jiuwenbox/models/policy.pyindex 20691e4da7..b61af9a73b 100644--- a/jiuwenbox/src/jiuwenbox/models/policy.py+++ b/jiuwenbox/src/jiuwenbox/models/policy.py@@ -56,11 +56,249 @@ def _normalize_octal_permissions(value: object, *, label: str) -> str | None:return text.zfill(4)+_MEMORY_UNIT_MULTIPLIERS: dict[str, int] = {+ "": 1,+ "B": 1,+ "K": 1024,+ "KB": 1024,+ "KIB": 1024,+ "M": 1024 ** 2,+ "MB": 1024 ** 2,+ "MIB": 1024 ** 2,+ "G": 1024 ** 3,+ "GB": 1024 ** 3,+ "GIB": 1024 ** 3,+ "T": 1024 ** 4,+ "TB": 1024 ** 4,+ "TIB": 1024 ** 4,+}++_CPU_DEFAULT_PERIOD_US = 100_000 # 100ms, matches cgroup v2 default+_CPU_MIN_PERIOD_US = 1_000+_CPU_MAX_PERIOD_US = 1_000_000+_CPU_MAX_CORES = 4096+_PIDS_MAX_VALUE = (1 << 31) - 1+++def _parse_memory_max(value: object) -> int | None:+ """Parse user-facing ``memory_max`` literal into bytes.++ Accepts:+ - ``None`` -> no limit.+ - positive ``int`` -> raw bytes.+ - ``str`` of the form ``<int><unit?>`` where unit is one of+ ``B / K / KB / KiB / M / MB / MiB / G / GB / GiB / T / TB / TiB``+ (binary multipliers, case-insensitive). Decimal magnitudes+ (e.g. ``"1.5G"``) are explicitly rejected.+ """+ if value is None:+ return None+ if isinstance(value, bool):+ # ``bool`` is a subclass of ``int``; reject it explicitly so+ # ``cgroup: {memory_max: true}`` never silently becomes 1 byte.+ raise ValueError(+ "memory_max must be an integer byte count or a '<N><K|M|G|T>' "+ "suffixed string, not a boolean"+ )+ if isinstance(value, int):+ bytes_value = value+ elif isinstance(value, str):+ text = value.strip()+ if not text:+ raise ValueError("memory_max cannot be an empty string")+ # Split numeric prefix from suffix.+ idx = 0+ while idx < len(text) and (text[idx].isdigit() or (idx == 0 and text[idx] == "+")):+ idx += 1+ number_part = text[:idx]+ suffix_part = text[idx:].strip().upper()+ if not number_part:+ raise ValueError(+ f"memory_max must start with a non-negative integer, got {value!r}"+ )+ try:+ magnitude = int(number_part)+ except ValueError as exc:+ raise ValueError(+ f"memory_max numeric prefix is not an integer: {value!r}"+ ) from exc+ multiplier = _MEMORY_UNIT_MULTIPLIERS.get(suffix_part)+ if multiplier is None:+ raise ValueError(+ f"memory_max has unknown unit suffix {suffix_part!r}; "+ "expected one of B/K/KB/KiB/M/MB/MiB/G/GB/GiB/T/TB/TiB"+ )+ bytes_value = magnitude * multiplier+ else:+ raise ValueError(+ f"memory_max must be int or str, got {type(value).__name__}"+ )+ if bytes_value <= 0:+ raise ValueError("memory_max must be > 0")+ return bytes_value+++def _parse_cpu_max(value: object) -> tuple[int, int] | None:+ """Parse user-facing ``cpu_max`` literal into ``(quota_us, period_us)``.++ Accepts:+ - ``None`` or string ``"max"`` -> no limit.+ - ``int`` / ``float`` -> fractional cores (period fixed at+ ``_CPU_DEFAULT_PERIOD_US``, quota = ``round(cores * period)``).+ - ``str`` numeric (e.g. ``"0.5"``) -> same as float.+ - ``str`` ``"<quota> <period>"`` (two positive integers, microseconds)+ -> directly passed through.+ - ``tuple`` / ``list`` of exactly two positive ints -> passed through+ as ``(quota_us, period_us)``. This case exists so the value+ survives a round-trip through ``model_dump(mode="json")`` (which+ turns the stored tuple into a list) and back through+ ``SecurityPolicy.model_validate`` (e.g. when the sandbox policy is+ reloaded from disk by the supervisor).+ """+ if value is None:+ return None+ if isinstance(value, bool):+ raise ValueError(+ "cpu_max must be a number (fractional cores) or '<quota> <period>' "+ "string, not a boolean"+ )+ if isinstance(value, (tuple, list)):+ if len(value) != 2:+ raise ValueError(+ f"cpu_max sequence form must have exactly 2 elements "+ f"(quota_us, period_us), got {len(value)}"+ )+ quota_raw, period_raw = value+ if isinstance(quota_raw, bool) or isinstance(period_raw, bool):+ raise ValueError(+ "cpu_max (quota_us, period_us) must be ints, not bool"+ )+ if not (isinstance(quota_raw, int) and isinstance(period_raw, int)):+ raise ValueError(+ f"cpu_max (quota_us, period_us) must be ints, "+ f"got ({type(quota_raw).__name__}, {type(period_raw).__name__})"+ )+ quota = int(quota_raw)+ period = int(period_raw)+ if quota <= 0:+ raise ValueError("cpu_max quota must be > 0")+ if not (_CPU_MIN_PERIOD_US <= period <= _CPU_MAX_PERIOD_US):+ raise ValueError(+ f"cpu_max period must be in [{_CPU_MIN_PERIOD_US}, "+ f"{_CPU_MAX_PERIOD_US}] microseconds"+ )+ if quota > period * _CPU_MAX_CORES:+ raise ValueError(+ f"cpu_max quota {quota} implies more than {_CPU_MAX_CORES} cores"+ )+ return (quota, period)+ if isinstance(value, (int, float)):+ cores = float(value)+ if cores <= 0:+ raise ValueError("cpu_max must be > 0 cores")+ if cores > _CPU_MAX_CORES:+ raise ValueError(+ f"cpu_max cores {cores} exceeds sanity limit {_CPU_MAX_CORES}"+ )+ quota = max(1, int(round(cores * _CPU_DEFAULT_PERIOD_US)))+ return (quota, _CPU_DEFAULT_PERIOD_US)+ if isinstance(value, str):+ text = value.strip()+ if not text:+ raise ValueError("cpu_max cannot be an empty string")+ if text.lower() == "max":+ return None+ parts = text.split()+ if len(parts) == 2:+ try:+ quota = int(parts[0])+ period = int(parts[1])+ except ValueError as exc:+ raise ValueError(+ f"cpu_max '<quota> <period>' must be two integers, got {value!r}"+ ) from exc+ if quota <= 0:+ raise ValueError("cpu_max quota must be > 0")+ if not (_CPU_MIN_PERIOD_US <= period <= _CPU_MAX_PERIOD_US):+ raise ValueError(+ f"cpu_max period must be in [{_CPU_MIN_PERIOD_US}, "+ f"{_CPU_MAX_PERIOD_US}] microseconds"+ )+ if quota > period * _CPU_MAX_CORES:+ raise ValueError(+ f"cpu_max quota {quota} implies more than {_CPU_MAX_CORES} cores"+ )+ return (quota, period)+ if len(parts) == 1:+ try:+ cores = float(parts[0])+ except ValueError as exc:+ raise ValueError(+ f"cpu_max string must parse as cores or '<quota> <period>': {value!r}"+ ) from exc+ return _parse_cpu_max(cores)+ raise ValueError(+ f"cpu_max string must be cores or '<quota> <period>', got {value!r}"+ )+ raise ValueError(+ f"cpu_max must be number or string, got {type(value).__name__}"+ )+++def _parse_pids_max(value: object) -> int | None:+ """Parse ``pids_max`` literal into a positive int (or None)."""+ if value is None:+ return None+ if isinstance(value, bool):+ raise ValueError("pids_max must be a positive integer, not a boolean")+ if isinstance(value, str):+ text = value.strip()+ if not text:+ raise ValueError("pids_max cannot be an empty string")+ if text.lower() == "max":+ return None+ try:+ int_value = int(text)+ except ValueError as exc:+ raise ValueError(+ f"pids_max must be 'max' or a positive integer, got {value!r}"+ ) from exc+ elif isinstance(value, int):+ int_value = value+ else:+ raise ValueError(+ f"pids_max must be int or str, got {type(value).__name__}"+ )+ if int_value < 1:+ raise ValueError("pids_max must be >= 1")+ if int_value > _PIDS_MAX_VALUE:+ raise ValueError(+ f"pids_max must be <= {_PIDS_MAX_VALUE}"+ )+ return int_value++class BindMount(BaseModel):host_path: strsandbox_path: strmode: Literal["ro", "rw"] = "ro"+ @field_validator("host_path", mode="before")+ @classmethod+ def reject_wildcard_host_path(cls, value: object) -> object:+ # Historically some policy yamls used ``host_path: "*"`` as a+ # "mount everything under root" placeholder, but bwrap has no such+ # semantics and the entry was silently a no-op. We now reject this+ # explicitly so misconfigurations surface at policy load time and+ # point users at ``bind_root_entries`` which supports that intent.+ if isinstance(value, str) and value.strip() == "*":+ raise ValueError(+ "bind_mounts.host_path cannot be literal '*'; "+ "use filesystem_policy.bind_root_entries to mount all "+ "immediate entries under a host directory"+ )+ return value+@field_validator("host_path", "sandbox_path", mode="before")@classmethoddef expand_paths(cls, value: object) -> object:@@ -69,6 +307,31 @@ class BindMount(BaseModel):return value+class BindRootEntries(BaseModel):+ """Mount every immediate child entry of ``host_root`` into the sandbox.++ For each file or directory directly under ``host_root`` (no recursion past+ the first level), a bind mount is added at+ ``f"{sandbox_path}/{child_name}"`` with the configured ``mode``. Hidden+ entries (names starting with ``.``) are excluded by default; pass+ ``include_hidden: true`` to keep them. ``exclude`` accepts fnmatch globs+ applied against the child basename.+ """++ host_root: str+ sandbox_path: str+ mode: Literal["ro", "rw"] = "ro"+ include_hidden: bool = False+ exclude: list[str] = Field(default_factory=list)++ @field_validator("host_root", "sandbox_path", mode="before")+ @classmethod+ def expand_paths(cls, value: object) -> object:+ if isinstance(value, str):+ return _expand_path(value)+ return value++class DeviceMount(BaseModel):host_path: strsandbox_path: str@@ -121,6 +384,7 @@ class FilesystemPolicy(BaseModel):read_only: list[str] = Field(default_factory=list)read_write: list[str] = Field(default_factory=list)bind_mounts: list[BindMount] = Field(default_factory=list)+ bind_root_entries: list[BindRootEntries] = Field(default_factory=list)device: list[DeviceMount] = Field(default_factory=list)@field_validator("directories", mode="before")@@ -326,6 +590,46 @@ class NetworkPolicy(BaseModel):ingress: NetworkRulePolicy = Field(default_factory=NetworkRulePolicy)+class CgroupPolicy(BaseModel):+ """Per-sandbox cgroup resource limits.++ All three fields default to ``None`` which means *no limit applied*. If+ every field is ``None`` (also true when the user omits ``cgroup``+ entirely or passes ``cgroup: {}``), ``ProcessRuntime`` skips cgroup+ setup completely, so this field is safe to leave alone on hosts that+ don't expose a writable cgroup hierarchy.+ """++ model_config = ConfigDict(extra="forbid")++ memory_max: int | None = None+ cpu_max: tuple[int, int] | None = None+ pids_max: int | None = None++ @field_validator("memory_max", mode="before")+ @classmethod+ def normalize_memory_max(cls, value: object) -> int | None:+ return _parse_memory_max(value)++ @field_validator("cpu_max", mode="before")+ @classmethod+ def normalize_cpu_max(cls, value: object) -> tuple[int, int] | None:+ return _parse_cpu_max(value)++ @field_validator("pids_max", mode="before")+ @classmethod+ def normalize_pids_max(cls, value: object) -> int | None:+ return _parse_pids_max(value)++ def is_empty(self) -> bool:+ """Return True when no field is set, i.e. cgroup setup should be skipped."""+ return (+ self.memory_max is None+ and self.cpu_max is None+ and self.pids_max is None+ )++class SecurityPolicy(BaseModel):"""Complete static security policy for a sandbox."""@@ -339,6 +643,7 @@ class SecurityPolicy(BaseModel):landlock: LandlockPolicy = Field(default_factory=LandlockPolicy)syscall: SyscallPolicy = Field(default_factory=SyscallPolicy)network: NetworkPolicy = Field(default_factory=NetworkPolicy)+ cgroup: CgroupPolicy = Field(default_factory=CgroupPolicy)inference_privacy_proxies: InferencePrivacyProxyPolicy = Field(default_factory=InferencePrivacyProxyPolicy)def tostring(self) -> str:diff --git a/jiuwenbox/src/jiuwenbox/server/app.py b/jiuwenbox/src/jiuwenbox/server/app.pyindex 4deeef8a27..0f6ccd310f 100644--- a/jiuwenbox/src/jiuwenbox/server/app.py+++ b/jiuwenbox/src/jiuwenbox/server/app.py@@ -8,13 +8,16 @@ import loggingimport osfrom concurrent.futures import ThreadPoolExecutorfrom contextlib import asynccontextmanager+from pathlib import Pathfrom fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse+from pydantic import ValidationErrorfrom jiuwenbox.logging_config import configure_loggingfrom jiuwenbox import __version__+from jiuwenbox.server.audit_logger import AuditLoggerfrom jiuwenbox.server.sandbox_manager import (SandboxManager,SandboxNotFoundError,@@ -22,6 +25,16 @@ from jiuwenbox.server.sandbox_manager import ()from jiuwenbox.server.proxy_manager import ProxyManagerfrom jiuwenbox.server.policy_engine import PolicyValidationError+from jiuwenbox.server.runtime.process import enable_child_subreaper++# Operator-facing env: when set, the audit JSONL is persisted to this+# directory using a ``{sandbox_id}-{ts}.audit.log`` filename per sandbox.+# Raw daemon / background-exec stdout/stderr is NOT persisted any more+# (the historical ``runtime.log`` files were removed); the audit log is+# the single source of truth and already carries truncated per-command+# stdout/stderr. The launcher (``jiuwenbox-server --save-logs DIR``)+# normalizes the value to an absolute path and writes it back here.+ENV_SAVE_LOGS_DIR = "JIUWENBOX_SAVE_LOGS_DIR"configure_logging()logger = logging.getLogger(__name__)@@ -109,10 +122,63 @@ def _configure_loop_default_executor() -> None:)+def _build_sandbox_manager() -> SandboxManager:+ """Construct the global ``SandboxManager``, honoring ``--save-logs DIR``.++ Behaviour matrix:++ - ``JIUWENBOX_SAVE_LOGS_DIR`` **set**: the audit logger uses that+ directory with the ``timestamped`` filename strategy so each+ sandbox produces a stable, identifiable file:++ - ``{sandbox_id}-{ts}.audit.log`` (structured JSONL)++ Files are kept after the sandbox is destroyed.++ - ``JIUWENBOX_SAVE_LOGS_DIR`` **unset** (default): no log files are+ written at all. Audit events still flow through the standard+ Python logger at ``DEBUG`` level, and sandbox daemon /+ background-exec stdout/stderr are routed to ``/dev/null`` by+ :class:`ProcessRuntime`. Opt in via ``--save-logs DIR``.++ Note: the historical per-sandbox ``runtime.log`` and ``runtime.bg-N.log``+ files were removed; raw stdout/stderr is no longer persisted. The+ structured audit log already carries the truncated stdout/stderr of+ every ``exec`` call, which is enough for routine debugging.+ """+ save_dir_raw = os.environ.get(ENV_SAVE_LOGS_DIR)+ if not save_dir_raw:+ # Single, prominent breadcrumb: ops should immediately know why+ # ``/api/v1/sandboxes/{id}/logs`` returns empty bodies.+ logger.info(+ "Audit log persistence is disabled (default). Pass "+ "--save-logs DIR or set %s to capture the per-sandbox "+ "audit JSONL.",+ ENV_SAVE_LOGS_DIR,+ )+ return SandboxManager()+ save_dir = Path(save_dir_raw).expanduser()+ try:+ save_dir.mkdir(parents=True, exist_ok=True)+ except OSError as exc:+ # Fall back to defaults rather than crashing the server: the user+ # can fix the path and restart. We log loudly so the misconfig+ # does not silently degrade to "no logs".+ logger.error(+ "Cannot create %s=%s (%s); falling back to disabled log persistence",+ ENV_SAVE_LOGS_DIR, save_dir_raw, exc,+ )+ return SandboxManager()+ logger.info("Per-sandbox audit log will be saved under %s", save_dir)+ return SandboxManager(+ audit_logger=AuditLogger(log_dir=save_dir, filename_strategy="timestamped"),+ )++def get_sandbox_manager() -> SandboxManager:global _sandbox_managerif _sandbox_manager is None:- _sandbox_manager = SandboxManager()+ _sandbox_manager = _build_sandbox_manager()return _sandbox_manager@@ -123,6 +189,39 @@ def get_proxy_manager() -> ProxyManager:return _proxy_manager+def _chmod_uds_socket_if_any() -> None:+ """启动后给 UDS socket 文件打权限位.++ 背景: uvicorn 自己创建 UDS 时不暴露 ``--uds-mode`` flag, 落地权限完全由+ 进程 umask 决定 (典型容器内 root umask=022 -> 0755), 这对宿主机非 root+ 用户经常不够友好。launcher 会把 socket 路径写进 ``JIUWENBOX_UDS_PATH``;+ 本函数在 lifespan startup 阶段读一次 ``JIUWENBOX_UDS_MODE`` (默认 0666)+ 做一次同步 ``chmod``。socket 文件由 uvicorn 在监听阶段已经创建, 这里+ 无需 polling。任何失败仅 warn, 不阻塞服务起动。+ """+ uds_path = os.environ.get("JIUWENBOX_UDS_PATH")+ if not uds_path:+ return+ mode_str = os.environ.get("JIUWENBOX_UDS_MODE", "0666")+ try:+ mode_value = int(mode_str, 8)+ except ValueError as exc:+ logger.warning(+ "Ignoring invalid JIUWENBOX_UDS_MODE=%r (%s); UDS socket %s keeps "+ "uvicorn default permissions",+ mode_str, exc, uds_path,+ )+ return+ try:+ os.chmod(uds_path, mode_value)+ except FileNotFoundError:+ logger.warning("UDS path %s missing before chmod", uds_path)+ except OSError as exc:+ logger.warning("UDS chmod %s failed: %s", uds_path, exc)+ else:+ logger.info("UDS socket %s chmod to %s", uds_path, mode_str)++@asynccontextmanagerasync def lifespan(_application: FastAPI):global _sandbox_manager, _proxy_manager@@ -133,13 +232,81 @@ async def lifespan(_application: FastAPI):# already benefits from the larger executor._raise_open_file_limit()_configure_loop_default_executor()- _sandbox_manager = SandboxManager()+ # Become the subreaper for our descendant tree *before* any sandbox+ # spawns bwrap. PR_SET_CHILD_SUBREAPER only affects *future* children,+ # so doing it here (after the loop is up but before SandboxManager+ # might create a runtime that spawns bwrap) is the earliest safe point.+ # No-op on non-Linux / when prctl is denied; logs internally.+ enable_child_subreaper()+ _sandbox_manager = _build_sandbox_manager()_proxy_manager = ProxyManager()+ # Wire the SIGCHLD-driven zombie reaper onto the running uvicorn loop.+ # This must happen after ``_build_sandbox_manager`` (so a runtime is+ # constructed and can publish its ``register_zombie_reaper`` method)+ # but before ``_proxy_manager.start`` (which may itself fork helper+ # processes whose orphans we now want reaped). Failure is non-fatal:+ # the manager logs and the server keeps running; zombies just won't+ # be cleaned up automatically until the next ``stop()``/``cleanup()``.+ try:+ loop = asyncio.get_running_loop()+ _sandbox_manager.register_zombie_reaper(loop)+ except Exception: # noqa: BLE001+ logger.exception(+ "register_zombie_reaper failed during lifespan startup; bwrap "+ "<defunct> processes may accumulate under the box-server pid",+ )logger.info("box-server started (version %s)", __version__)await _proxy_manager.start()- yield- await _proxy_manager.stop()- logger.info("box-server shutting down")+ # 在 proxy 起来之后、yield (接受请求) 之前给 UDS 打权限: 此刻 uvicorn 已+ # 经 bind 并 listen 完成, socket inode 必然存在; 改 mode 不会和首个请求+ # 抢时序。+ _chmod_uds_socket_if_any()+ try:+ yield+ finally:+ # Stop proxies first so any in-flight clients are torn down before we+ # wipe sandbox descriptors. All steps below are best-effort: a failure+ # here cannot abort uvicorn's shutdown sequence so we just log and+ # continue.+ try:+ await _proxy_manager.stop()+ except Exception: # noqa: BLE001+ logger.exception("proxy_manager.stop failed during lifespan shutdown")+ # Tear down every live sandbox before exiting. Without this, each+ # sandbox-daemon.py (spawned with ``start_new_session=True`` so it owns+ # its session/pgrp) would be reparented to init when uvicorn dies and+ # keep running indefinitely. ``shutdown_all_sandboxes`` routes through+ # ``runtime.cleanup`` which sends SIGTERM/SIGKILL to the daemon's pgrp+ # and wipes netns / launcher dirs.+ try:+ if _sandbox_manager is not None:+ await _sandbox_manager.shutdown_all_sandboxes()+ except Exception: # noqa: BLE001+ logger.exception(+ "sandbox_manager.shutdown_all_sandboxes failed during lifespan shutdown",+ )+ try:+ # Wipe state_dir / policies_dir contents so the next jiuwenbox boot+ # starts with an empty registry instead of resurrecting descriptors+ # whose backing bubblewrap / netns state no longer exists.+ if _sandbox_manager is not None:+ _sandbox_manager.clear_persistent_state()+ except Exception: # noqa: BLE001+ logger.exception(+ "sandbox_manager.clear_persistent_state failed during lifespan shutdown",+ )+ # Remove the SIGCHLD handler last so any zombies generated by the+ # teardown above (sandbox shutdown sends SIGTERM/SIGKILL to the+ # daemon pgrp, which produces a fresh batch of SIGCHLDs) are still+ # reaped by the handler we are about to remove.+ try:+ if _sandbox_manager is not None:+ _sandbox_manager.unregister_zombie_reaper()+ except Exception: # noqa: BLE001+ logger.exception(+ "sandbox_manager.unregister_zombie_reaper failed during lifespan shutdown",+ )+ logger.info("box-server shutting down")def create_app() -> FastAPI:@@ -170,6 +337,16 @@ def create_app() -> FastAPI:async def policy_validation_error_handler(request: Request, exc: PolicyValidationError):return JSONResponse(status_code=400, content={"error": str(exc)})+ @application.exception_handler(ValidationError)+ async def pydantic_validation_error_handler(request: Request, exc: ValidationError):+ # Pydantic ``ValidationError`` raised inside a route handler (e.g. when+ # ``SecurityPolicy.model_validate`` rejects a payload from+ # ``_resolve_effective_policy``) would otherwise hit the catch-all+ # ``Exception`` handler below and surface as a 500. Surface it as 400+ # so policy authors see the validation message via the standard error+ # envelope used by ``PolicyValidationError``.+ return JSONResponse(status_code=400, content={"error": str(exc)})+@application.exception_handler(Exception)async def unhandled_exception_handler(request: Request, exc: Exception):# Without this catch-all, an unexpected error inside a route handlerdiff --git a/jiuwenbox/src/jiuwenbox/server/audit_logger.py b/jiuwenbox/src/jiuwenbox/server/audit_logger.pyindex d9f3fa36cb..5bd86c5c5c 100644--- a/jiuwenbox/src/jiuwenbox/server/audit_logger.py+++ b/jiuwenbox/src/jiuwenbox/server/audit_logger.py@@ -1,9 +1,29 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""Structured audit logging in JSONL format.-Each sandbox gets its own log file under ~/.jiuwenbox/logs/. Writes are routed-through a dedicated single-thread executor so disk I/O does not stall the-asyncio event loop on hot paths such as ``exec_in_sandbox``.+Each sandbox can get its own log file under ``log_dir``; whether it+actually does depends on the ``filename_strategy`` selected at+construction time:++- ``"disabled"`` (**default**): no log files are written at all and the+ ``log_dir`` is never created on disk. ``log_event*`` becomes a no-op+ (the call still hits the standard Python ``logging`` debug stream so+ developers can wire it into stderr if needed) and ``read_logs*``+ returns empty. This keeps a fresh jiuwenbox install from polluting+ the user's home dir; opt in via ``--save-logs DIR``.+- ``"plain"``: ``{sandbox_id}.log`` (legacy layout, useful for embedders+ who manage their own retention; not selected by the bundled server).+- ``"timestamped"``: ``{sandbox_id}-{YYYYMMDDTHHMMSS}.audit.log``. The+ timestamp is captured the **first** time a given sandbox is logged and+ cached for the rest of the process lifetime, so all events for a single+ sandbox land in a single file. The ``.audit.log`` suffix lets multiple+ components (e.g. ProcessRuntime daemon stdout) share the same target+ directory without filename collisions. This is what ``--save-logs DIR``+ / ``JIUWENBOX_SAVE_LOGS_DIR`` selects.++When persistence is on, writes are routed through a dedicated+single-thread executor so disk I/O does not stall the asyncio event+loop on hot paths such as ``exec_in_sandbox``."""from __future__ import annotations@@ -12,7 +32,9 @@ import jsonimport loggingimport threadingfrom concurrent.futures import ThreadPoolExecutor+from datetime import datetime, timezonefrom pathlib import Path+from typing import Literalfrom jiuwenbox.logging_config import configure_loggingfrom jiuwenbox.models.common import AuditEvent, AuditEventType@@ -22,6 +44,13 @@ configure_logging()logger = logging.getLogger(__name__)+# ISO 8601 basic format keeps lexicographic order == chronological order,+# which is exactly what we want when ``ls``/``find`` enumerates the dir.+_TIMESTAMP_FORMAT = "%Y%m%dT%H%M%S"++FilenameStrategy = Literal["disabled", "plain", "timestamped"]++def _write_jsonl_line(log_file: Path, line: str) -> None:"""Append ``line`` (already serialized JSON) to ``log_file``.@@ -36,19 +65,72 @@ def _write_jsonl_line(log_file: Path, line: str) -> None:class AuditLogger:"""Append-only JSONL audit logger, one file per sandbox."""- def __init__(self, log_dir: Path | None = None) -> None:+ def __init__(+ self,+ log_dir: Path | None = None,+ *,+ filename_strategy: FilenameStrategy = "disabled",+ ) -> None:+ # ``log_dir`` is still recorded so callers / tests can inspect it,+ # but it is only realised on disk when persistence is actually on.+ # That avoids a ``mkdir ~/.jiuwenbox/logs`` side effect on first+ # import for users who never opt into ``--save-logs``.self.log_dir = log_dir or JIUWENBOX_HOME / "logs"- self.log_dir.mkdir(parents=True, exist_ok=True)+ self.filename_strategy: FilenameStrategy = filename_strategy+ if self.filename_strategy != "disabled":+ self.log_dir.mkdir(parents=True, exist_ok=True)# A single worker keeps writes ordered without forcing the event loop# to wait on disk I/O. ``thread_name_prefix`` aids in debugging.+ # We construct it even when disabled so ``flush`` etc. behave+ # uniformly (the executor is cheap to keep idle).self._executor = ThreadPoolExecutor(max_workers=1,thread_name_prefix="jiuwenbox-audit",)self._lock = threading.Lock()+ # Per-sandbox path cache. ``timestamped`` strategy needs it so all+ # events for one sandbox stay in a single file (timestamp is fixed+ # at first sighting). Other strategies leave it empty.+ self._sandbox_files: dict[str, Path] = {}++ def _resolve_log_file(self, sandbox_id: str) -> Path:+ """Return the (possibly cached) log file path for ``sandbox_id``.++ Thread-safe: callers from ``log_event`` and ``read_logs`` may race.+ """+ with self._lock:+ cached = self._sandbox_files.get(sandbox_id)+ if cached is not None:+ return cached++ if self.filename_strategy == "timestamped":+ # If a previous process left a file for this id (rare —+ # SandboxManager wipes registry on boot — but possible if+ # an operator pre-populates the dir or restarts mid-session),+ # reuse the most recent one rather than scattering events+ # across multiple files for one logical sandbox.+ existing = sorted(+ self.log_dir.glob(f"{sandbox_id}-*.audit.log"),+ key=lambda p: p.stat().st_mtime,+ reverse=True,+ )+ if existing:+ self._sandbox_files[sandbox_id] = existing[0]+ return existing[0]+ # UTC keeps filenames globally sortable across hosts and+ # avoids ambiguity when operators correlate logs collected+ # from differently-tz'd machines. The format itself drops+ # tz info, but the underlying instant is unambiguous.+ ts = datetime.now(timezone.utc).strftime(_TIMESTAMP_FORMAT)+ path = self.log_dir / f"{sandbox_id}-{ts}.audit.log"+ else:+ path = self.log_dir / f"{sandbox_id}.log"++ self._sandbox_files[sandbox_id] = path+ return pathdef _serialize_event(self, event: AuditEvent) -> tuple[Path, str]:- log_file = self.log_dir / f"{event.sandbox_id}.log"+ log_file = self._resolve_log_file(event.sandbox_id)line = json.dumps(event.model_dump(mode="json"), ensure_ascii=False)return log_file, line@@ -59,7 +141,17 @@ class AuditLogger:cheap for the small audit payloads jiuwenbox produces) but the filewrite is dispatched to a dedicated background thread so callers inthe asyncio event loop are not blocked on disk I/O.++ ``disabled`` strategy: drops the event. We still hit the standard+ Python ``logging`` debug stream so anyone wiring a stderr handler+ can observe events without needing the on-disk JSONL."""+ if self.filename_strategy == "disabled":+ logger.debug(+ "Audit (disabled, dropped): %s %s",+ event.event_type.value, event.sandbox_id,+ )+ returnlog_file, line = self._serialize_event(event)with self._lock:self._executor.submit(_write_jsonl_line, log_file, line)@@ -67,6 +159,12 @@ class AuditLogger:def log_event_sync(self, event: AuditEvent) -> None:"""Synchronous append used by tests and shutdown paths."""+ if self.filename_strategy == "disabled":+ logger.debug(+ "Audit (disabled, sync, dropped): %s %s",+ event.event_type.value, event.sandbox_id,+ )+ returnlog_file, line = self._serialize_event(event)_write_jsonl_line(log_file, line)logger.debug("Audit (sync): %s %s", event.event_type.value, event.sandbox_id)@@ -94,9 +192,16 @@ class AuditLogger:future.result(timeout=timeout)def read_logs(self, sandbox_id: str) -> list[AuditEvent]:- """Read all audit events for a sandbox."""+ """Read all audit events for a sandbox.++ ``disabled`` strategy returns ``[]`` because nothing was ever+ persisted; the ``/api/v1/sandboxes/{id}/logs`` endpoint therefore+ also returns empty unless ``--save-logs DIR`` was set at boot.+ """+ if self.filename_strategy == "disabled":+ return []self.flush()- log_file = self.log_dir / f"{sandbox_id}.log"+ log_file = self._resolve_log_file(sandbox_id)if not log_file.exists():return []events: list[AuditEvent] = []@@ -106,15 +211,35 @@ class AuditLogger:return eventsdef read_logs_raw(self, sandbox_id: str) -> str:- """Read raw log text for a sandbox."""+ """Read raw log text for a sandbox.++ ``disabled`` strategy returns ``""`` (see ``read_logs``).+ """+ if self.filename_strategy == "disabled":+ return ""self.flush()- log_file = self.log_dir / f"{sandbox_id}.log"+ log_file = self._resolve_log_file(sandbox_id)if not log_file.exists():return ""return log_file.read_text()def delete_logs(self, sandbox_id: str) -> None:- """Delete logs for a sandbox."""+ """Delete logs for a sandbox.++ ``disabled`` strategy is a no-op (there is nothing on disk).+ ``timestamped`` strategy may have multiple historical files for a+ re-used sandbox id (extremely unlikely but possible across process+ restarts that pre-populated the dir); wipe all of them so callers+ get a clean ``read_logs`` result afterwards. The cache is cleared+ regardless so the next event allocates a fresh file.+ """+ if self.filename_strategy == "disabled":+ returnself.flush()- log_file = self.log_dir / f"{sandbox_id}.log"- log_file.unlink(missing_ok=True)+ with self._lock:+ self._sandbox_files.pop(sandbox_id, None)+ if self.filename_strategy == "timestamped":+ for f in self.log_dir.glob(f"{sandbox_id}-*.audit.log"):+ f.unlink(missing_ok=True)+ else:+ (self.log_dir / f"{sandbox_id}.log").unlink(missing_ok=True)diff --git a/jiuwenbox/src/jiuwenbox/server/launcher.py b/jiuwenbox/src/jiuwenbox/server/launcher.pynew file mode 100644index 0000000000..2027dfb53c--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/server/launcher.py@@ -0,0 +1,279 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""jiuwenbox server 启动器 (TCP / UDS 二选一).++承担两件事:++1. 把 "怎么 listen" 从 ``Dockerfile`` 命令行硬编码解耦, 改由 ``JIUWENBOX_LISTEN``+ URI 控制 (``tcp://host:port`` 或 ``unix:///abs/socket/path``); 兼容老的+ ``--host/--port`` 用法只能由用户直接调 ``python -m uvicorn ...``。本入口+ 不再透出 host/port flag, 仅暴露 ``--listen``。+2. UDS 模式下做必要的 socket 文件预处理 (清理 stale socket、拒绝普通文件残留),+ 并把解析后的最终 URI / socket path 写回 ``os.environ``, 让 ASGI lifespan+ 能拿到 path 做后续 ``chmod``。++通过 ``[project.scripts] jiuwenbox-server = jiuwenbox.server.launcher:main`` 安装+后, 可直接 ``jiuwenbox-server`` 启动; 同时支持 ``python -m jiuwenbox.server.launcher``。+"""++from __future__ import annotations++import argparse+import logging+import os+import stat+from pathlib import Path+from typing import Tuple, Union+from urllib.parse import urlparse++logger = logging.getLogger("jiuwenbox.server.launcher")++ENV_LISTEN = "JIUWENBOX_LISTEN"+ENV_UDS_PATH = "JIUWENBOX_UDS_PATH"+ENV_UDS_MODE = "JIUWENBOX_UDS_MODE"+# Mirrors ``app.ENV_SAVE_LOGS_DIR``; intentionally re-declared here to keep+# the launcher independent of the FastAPI app module (``main`` runs before+# anything imports ``jiuwenbox.server.app`` lazily inside ``uvicorn.run``).+ENV_SAVE_LOGS_DIR = "JIUWENBOX_SAVE_LOGS_DIR"++DEFAULT_LISTEN = "tcp://0.0.0.0:8321"++TcpSpec = Tuple[str, str, int] # ("tcp", host, port)+UnixSpec = Tuple[str, str] # ("unix", abs_socket_path)+ListenSpec = Union[TcpSpec, UnixSpec]+++class ListenURIError(ValueError):+ """``JIUWENBOX_LISTEN`` URI 解析失败."""+++def parse_listen(uri: str) -> ListenSpec:+ """把 ``tcp://host:port`` / ``unix:///abs/path`` 解析成结构化形式.++ Args:+ uri: 监听地址 URI. ``scheme`` 必须是 ``tcp`` 或 ``unix``;+ ``unix`` 路径必须是绝对路径 (以 ``/`` 起头), 否则不同 cwd 下行为+ 不一致, 且 lifespan / Docker volume 一律按绝对路径处理。++ Returns:+ - TCP: ``("tcp", host, port)``;+ - UDS: ``("unix", absolute_socket_path)``.++ Raises:+ ListenURIError: scheme 未知 / TCP 缺 host 或 port / UDS 路径相对。+ """+ if not uri:+ raise ListenURIError("listen URI is empty")++ parsed = urlparse(uri)+ scheme = (parsed.scheme or "").lower()++ if scheme == "tcp":+ host = parsed.hostname+ port = parsed.port+ if not host or port is None:+ raise ListenURIError(+ f"tcp listen URI requires host and port, got {uri!r}"+ )+ if not (1 <= port <= 65535):+ raise ListenURIError(+ f"tcp port out of range in {uri!r}: {port}"+ )+ return ("tcp", host, int(port))++ if scheme == "unix":+ # 三斜杠 ``unix:///tmp/jw.sock`` -> netloc="", path="/tmp/jw.sock";+ # 两斜杠 ``unix://tmp/jw.sock`` -> netloc="tmp", path="/jw.sock"+ # —— 后者绝对会把绝对路径切碎, 直接拒绝。+ if parsed.netloc:+ raise ListenURIError(+ f"unix listen URI must use three slashes (unix:///abs/path), "+ f"got {uri!r}"+ )+ path = parsed.path+ if not path or not path.startswith("/"):+ raise ListenURIError(+ f"unix listen URI requires absolute path, got {uri!r}"+ )+ # ``/`` 本身是目录, 不能 bind socket; 提前拒掉而不是把错误推给+ # uvicorn 的 bind() 报 EISDIR / EACCES。+ if path == "/" or path.endswith("/"):+ raise ListenURIError(+ f"unix listen URI must point to a socket file, not a directory: "+ f"{uri!r}"+ )+ return ("unix", path)++ raise ListenURIError(+ f"unknown listen URI scheme {scheme!r} in {uri!r}; "+ f"expected 'tcp' or 'unix'"+ )+++def _prepare_uds(path: str) -> None:+ """UDS 监听前的 socket 文件预处理.++ - 父目录不存在时 ``mkdir -p`` (用 caller umask, 不主动放权)。+ - ``path`` 已存在时:+ * 是一个 socket 文件 -> ``unlink`` (典型场景: 上一次 server crash+ 留下的 stale socket; 不清理会让 uvicorn 在 ``bind()`` 阶段+ ``EADDRINUSE``)。+ * 是普通文件 / 目录 / 其它 -> raise ``FileExistsError`` 拒绝静默+ 覆盖, 防止误删用户数据。+ """+ sock_path = Path(path)+ parent = sock_path.parent+ if parent and not parent.exists():+ parent.mkdir(parents=True, exist_ok=True)++ if sock_path.exists() or sock_path.is_symlink():+ try:+ st = sock_path.lstat()+ except OSError as exc:+ raise FileExistsError(+ f"cannot stat existing path at {path!r}: {exc}"+ ) from exc+ if stat.S_ISSOCK(st.st_mode):+ try:+ sock_path.unlink()+ except OSError as exc:+ raise FileExistsError(+ f"failed to unlink stale socket at {path!r}: {exc}"+ ) from exc+ logger.info("[launcher] removed stale socket %s", path)+ else:+ raise FileExistsError(+ f"refusing to listen on {path!r}: a non-socket file/dir "+ f"already exists; remove it manually if you really intend to."+ )+++def _build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ prog="jiuwenbox-server",+ description=(+ "Launch the jiuwenbox HTTP management server over TCP or UDS. "+ "Listen address is controlled by --listen or the JIUWENBOX_LISTEN "+ "environment variable; default is tcp://0.0.0.0:8321."+ ),+ )+ parser.add_argument(+ "--listen",+ default=None,+ help=(+ "Listen URI: 'tcp://host:port' or 'unix:///abs/socket/path'. "+ f"Falls back to ${ENV_LISTEN} env, then {DEFAULT_LISTEN}."+ ),+ )+ parser.add_argument(+ "--log-level",+ default=os.environ.get("JIUWENBOX_LOG_LEVEL", "info"),+ help="uvicorn log level (env JIUWENBOX_LOG_LEVEL, default 'info').",+ )+ parser.add_argument(+ "--save-logs",+ metavar="DIR",+ default=None,+ help=(+ "Persist the per-sandbox audit JSONL under DIR with a "+ "'{sandbox_id}-{timestamp}.audit.log' filename. "+ f"Falls back to ${ENV_SAVE_LOGS_DIR} env; unset means no "+ "log file is written at all (audit events stay only in the "+ "standard Python logger at DEBUG level). Raw daemon / "+ "background-exec stdout/stderr is never persisted; the "+ "audit log carries the truncated per-command stdout/stderr. "+ "The directory is created if missing; existing files are "+ "kept across boots."+ ),+ )+ return parser+++def _resolve_listen_uri(cli_value: str | None) -> str:+ if cli_value:+ return cli_value+ env_value = os.environ.get(ENV_LISTEN)+ if env_value:+ return env_value+ return DEFAULT_LISTEN+++def _resolve_save_logs_dir(cli_value: str | None) -> str | None:+ """Pick CLI > env > unset; normalize to absolute path.++ We resolve to an absolute path here (not in app.lifespan) for two+ reasons: the launcher's CWD is more predictable than uvicorn's, and+ operators inspecting ``ps``/``env`` should see the real target dir,+ not a relative ``./logs`` whose meaning depends on where the server+ was started.+ """+ raw = cli_value if cli_value else os.environ.get(ENV_SAVE_LOGS_DIR)+ if not raw:+ return None+ return str(Path(raw).expanduser().resolve())+++def main(argv: list[str] | None = None) -> int:+ """jiuwenbox-server CLI 入口.++ Returns:+ 进程退出码; URI 非法直接 ``sys.exit(2)``。+ """+ parser = _build_parser()+ args = parser.parse_args(argv)++ # 启动期错误报告 (URI 解析 / uvicorn 导入 / UDS 文件冲突) 走 logger.error,+ # 而非 print(..., file=sys.stderr)。Python 的 ``logging.lastResort`` 在无+ # 自定义 handler 时会把 ERROR 级别消息写入 stderr, 与原 print 行为对齐;+ # 同时满足 G.LOG.02 (使用 logging 模块) 编码规范。+ raw_uri = _resolve_listen_uri(args.listen)+ try:+ spec = parse_listen(raw_uri)+ except ListenURIError as exc:+ logger.error("jiuwenbox-server: %s", exc)+ return 2++ # 把解析后的最终值塞回 env, 让 lifespan / 子模块都能看到一致的视图;+ # 即便用户没设 env 而是走了 --listen / 默认值, 后续也读得到。+ os.environ[ENV_LISTEN] = raw_uri++ # ``--save-logs`` 同样原则: 解析 + 落 env, app.lifespan 里只 ``os.environ.get``+ # 一处读取, 不必再做 CLI / env 优先级判定。未设置时把 env 也清掉,+ # 避免上一次启动残留干扰 (尤其本进程内多次调用 main 的测试场景)。+ save_logs_dir = _resolve_save_logs_dir(args.save_logs)+ if save_logs_dir:+ os.environ[ENV_SAVE_LOGS_DIR] = save_logs_dir+ logger.info("[launcher] sandbox logs will be saved under %s", save_logs_dir)+ else:+ os.environ.pop(ENV_SAVE_LOGS_DIR, None)++ try:+ import uvicorn # 延迟导入: argparse / URI 校验失败时不必拖 uvicorn 进来+ except ImportError as exc: # pragma: no cover - declared in pyproject+ logger.error("jiuwenbox-server: uvicorn is required (%s)", exc)+ return 3++ uvicorn_kwargs: dict = {"log_level": args.log_level}+ if spec[0] == "tcp":+ _, host, port = spec+ # 清掉残留的 UDS_PATH, 避免多次启动时 lifespan 读到陈旧值+ os.environ.pop(ENV_UDS_PATH, None)+ uvicorn_kwargs["host"] = host+ uvicorn_kwargs["port"] = port+ logger.info("[launcher] starting jiuwenbox on tcp://%s:%d", host, port)+ else:+ _, path = spec+ try:+ _prepare_uds(path)+ except FileExistsError as exc:+ logger.error("jiuwenbox-server: %s", exc)+ return 2+ os.environ[ENV_UDS_PATH] = path+ uvicorn_kwargs["uds"] = path+ logger.info("[launcher] starting jiuwenbox on unix://%s", path)++ uvicorn.run("jiuwenbox.server.app:app", **uvicorn_kwargs)+ return 0+++if __name__ == "__main__": # pragma: no cover - module entry+ raise SystemExit(main())diff --git a/jiuwenbox/src/jiuwenbox/server/runtime/process.py b/jiuwenbox/src/jiuwenbox/server/runtime/process.pyindex 655b4f1c3c..e63aff2cd3 100644--- a/jiuwenbox/src/jiuwenbox/server/runtime/process.py+++ b/jiuwenbox/src/jiuwenbox/server/runtime/process.py@@ -31,6 +31,7 @@ import shutilimport signalimport socketimport subprocess+import sysimport tempfilefrom pathlib import Pathfrom typing import Any@@ -45,7 +46,8 @@ from jiuwenbox.server.runtime.base import (RuntimeExecRequest,RuntimeFileOpResult,)-from jiuwenbox.server.workspace import SANDBOX_WORKSPACE, JIUWENBOX_HOME+from jiuwenbox.server.workspace import SANDBOX_WORKSPACE+from jiuwenbox.supervisor import cgroup as cgroup_modulefrom jiuwenbox.supervisor import network as network_modulefrom jiuwenbox.supervisor.bwrap import BwrapConfigfrom jiuwenbox.supervisor.daemon_ipc import (@@ -75,7 +77,58 @@ RUNTIME_SANDBOX_ENV = "JIUWENBOX_SANDBOX_ENV"RUNTIME_SANDBOX_WORKDIR = "JIUWENBOX_SANDBOX_WORKDIR"RUNTIME_POLICY_BINDS = "JIUWENBOX_POLICY_BINDS"SERVER_PROTECT_PORTS_ENV = "JIUWENBOX_SERVER_PROTECT_PORTS"-DEFAULT_SERVER_PROTECT_PORTS = (8321,)+# Host-level firewall protection: for ``network.mode: host`` sandboxes we+# attempt to install an iptables OUTPUT block by-sandbox-uid against the+# box-server's own HTTP port, so untrusted code running inside the sandbox+# cannot ``curl http://127.0.0.1:8321/...`` and pivot through the management+# API. The default tracks the listener configured via ``JIUWENBOX_LISTEN``+# (set by ``launcher.py``); operators who run the server on a non-default+# port no longer have to remember to also bump this list. When+# ``JIUWENBOX_LISTEN`` is UDS or unparseable we fall back to the historical+# default of port 8321 so existing setups behave unchanged. The list can+# still be overridden via ``JIUWENBOX_SERVER_PROTECT_PORTS=...``+# (comma-separated integers) or disabled entirely by exporting empty.+#+# The install path needs root for ``iptables -L OUTPUT`` and ``-I OUTPUT``;+# when jiuwenbox runs unprivileged (e.g. the code-agent setup from+# ``configs/code-agent-policy.yaml``) those calls return EPERM. In that case+# we log a warning and **continue** sandbox creation without installing the+# rule rather than aborting - the user picked an unprivileged deployment and+# explicitly accepted that the box-server has no host-level protection.+LISTEN_URI_ENV = "JIUWENBOX_LISTEN"+DEFAULT_SERVER_PROTECT_PORTS: tuple[int, ...] = (8321,)+++def _derive_protect_ports_from_listen() -> tuple[int, ...]:+ """Extract a TCP port from ``$JIUWENBOX_LISTEN`` for self-protection.++ Recognized shapes (matching ``launcher.parse_listen``):+ - ``tcp://host:port`` -> ``(port,)``+ - ``unix:///abs/path`` -> ``()`` (no TCP port to protect)++ Anything else (env unset, malformed) returns the historical default of+ ``(8321,)`` so existing operator workflows that never set+ ``JIUWENBOX_LISTEN`` (e.g. test harnesses that call ``ProcessRuntime``+ directly) keep their previous behavior.+ """+ uri = os.environ.get(LISTEN_URI_ENV, "")+ if not uri:+ return DEFAULT_SERVER_PROTECT_PORTS+ if uri.startswith("unix://"):+ return ()+ if uri.startswith("tcp://"):+ # ``tcp://0.0.0.0:8321`` -> ``("0.0.0.0", "8321")``. ``rsplit``+ # guards against IPv6 hosts like ``tcp://[::]:8321`` where ``:``+ # appears multiple times.+ host_port = uri[len("tcp://"):]+ try:+ _, port_str = host_port.rsplit(":", 1)+ port = int(port_str)+ except (ValueError, IndexError):+ return DEFAULT_SERVER_PROTECT_PORTS+ if 1 <= port <= 65535:+ return (port,)+ return DEFAULT_SERVER_PROTECT_PORTS_SUPERVISOR_DIR = Path(__file__).resolve().parents[2] / "supervisor"LANDLOCK_LAUNCHER_SOURCE = _SUPERVISOR_DIR / "landlock_launcher.py"@@ -205,6 +258,127 @@ class _DaemonListDirCall:# CPU quotas get the right value automatically.EXEC_CONCURRENCY_ENV = "JIUWENBOX_EXEC_CONCURRENCY"+# ---------------------------------------------------------------------------+# Zombie reaper plumbing.+#+# Background: each ``bwrap`` invocation (sandbox daemon spawn, or+# ``exec_background``) creates the bwrap monitor process as a direct child of+# box-server. With ``--unshare-user`` (default in jiuwenbox) bwrap additionally+# clones a userns helper via ``CLONE_PARENT`` so the helper's parent is *also*+# box-server, not bwrap. When that helper finishes its short setup and exits,+# it becomes a zombie of box-server until somebody calls ``waitpid`` on it.+# Without proactive reaping the host process table fills up with+# ``[bwrap] <defunct>`` entries (visible as a child of the box-server pid).+#+# The historical code only reaped lazily:+# - daemon bwrap monitor: ``Popen.poll()`` is called from ``stop()``/+# ``cleanup()``/``is_running()``; if the user never invokes any of these+# the monitor's eventual exit lingers indefinitely.+# - background bwrap: ``_reap_background_processes`` runs at the start of the+# *next* ``exec_background`` call; a workload that does one background exec+# and then nothing else leaks a zombie until shutdown.+# - userns helper / other bwrap-internal forks: never tracked, never reaped.+#+# The fix is three-pronged:+# - ``prctl(PR_SET_CHILD_SUBREAPER, 1)`` so even when box-server isn't PID 1+# of its namespace, any descendant orphan reparents to us instead of+# escaping to the real init (which would silently mask the leak).+# - SIGCHLD-driven reaper installed via ``asyncio.loop.add_signal_handler``+# for the fast (sub-millisecond) wake path. This is the preferred channel+# on stock asyncio; uvloop, however, *refuses* SIGCHLD handlers+# unconditionally (loop.pyx raises ``RuntimeError`` because uvloop reserves+# it for its own libuv child watcher). Since uvicorn auto-selects uvloop+# when the package is installed (the docker image does ship uvloop), we+# cannot rely on this channel in production.+# - Periodic ``asyncio.Task`` fallback that polls every+# ``ZOMBIE_REAPER_INTERVAL_ENV`` seconds (default 2.0). 2 s keeps the peak+# ``<defunct>`` count tiny under realistic loads (bwrap spawn rate is+# bounded by the exec admission semaphore) while costing essentially zero+# CPU on an idle server.+#+# At startup we *try* the SIGCHLD path; if it raises, we silently degrade to+# the periodic task. ``register_zombie_reaper`` returns ``True`` as long as+# *either* path is active, so the lifespan hook doesn't need to know which.+PR_SET_CHILD_SUBREAPER = 36 # Linux prctl(2)+_subreaper_enabled: bool = False+ZOMBIE_REAPER_INTERVAL_ENV = "JIUWENBOX_ZOMBIE_REAPER_INTERVAL"+ZOMBIE_REAPER_DEFAULT_INTERVAL_SECONDS = 2.0+++def _resolve_zombie_reaper_interval() -> float:+ """Return the periodic-reaper interval in seconds.++ Operators can tune via ``JIUWENBOX_ZOMBIE_REAPER_INTERVAL``. Invalid /+ non-positive values fall back to the default and emit a warning rather+ than crashing the server -- a misconfigured env var must never block+ box-server startup.+ """+ raw = os.environ.get(ZOMBIE_REAPER_INTERVAL_ENV)+ if not raw:+ return ZOMBIE_REAPER_DEFAULT_INTERVAL_SECONDS+ try:+ value = float(raw)+ except ValueError:+ logger.warning(+ "%s=%r is not a number; using default %.1fs",+ ZOMBIE_REAPER_INTERVAL_ENV,+ raw,+ ZOMBIE_REAPER_DEFAULT_INTERVAL_SECONDS,+ )+ return ZOMBIE_REAPER_DEFAULT_INTERVAL_SECONDS+ if value <= 0:+ logger.warning(+ "%s=%r must be positive; using default %.1fs",+ ZOMBIE_REAPER_INTERVAL_ENV,+ raw,+ ZOMBIE_REAPER_DEFAULT_INTERVAL_SECONDS,+ )+ return ZOMBIE_REAPER_DEFAULT_INTERVAL_SECONDS+ return value+++def enable_child_subreaper() -> bool:+ """Make the current process a subreaper for its descendant tree.++ Idempotent and best-effort; logs (but does not raise) when prctl is+ unavailable (non-Linux) or denied. Returns ``True`` when the flag is+ active after the call. The flag persists for the lifetime of the+ process, so it is safe to call again on a hot reload.+ """+ global _subreaper_enabled+ if _subreaper_enabled:+ return True+ if not sys.platform.startswith("linux"):+ logger.debug("PR_SET_CHILD_SUBREAPER unavailable on %s", sys.platform)+ return False+ try:+ import ctypes++ libc = ctypes.CDLL("libc.so.6", use_errno=True)+ ret = libc.prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0)+ except OSError as exc:+ logger.warning("PR_SET_CHILD_SUBREAPER prctl failed: %s", exc)+ return False+ except Exception: # noqa: BLE001 - ctypes is permissive about errors+ logger.warning("PR_SET_CHILD_SUBREAPER prctl raised", exc_info=True)+ return False+ if ret != 0:+ logger.warning(+ "PR_SET_CHILD_SUBREAPER prctl returned %d (errno=%d); box-server "+ "will not act as a subreaper, orphan bwrap helpers may escape "+ "to PID 1",+ ret,+ ctypes.get_errno(),+ )+ return False+ _subreaper_enabled = True+ logger.info(+ "PR_SET_CHILD_SUBREAPER enabled; orphan descendants will reparent "+ "to box-server (pid=%d) and be reaped by the SIGCHLD handler",+ os.getpid(),+ )+ return True+def _read_cgroup_cpu_quota() -> int | None:"""Return the cgroup-imposed CPU count, or ``None`` if uncapped.@@ -326,7 +500,16 @@ def _summarize_command(command: list[str], max_length: int = 180) -> str:class ProcessRuntime(RuntimeAdapter):- """Runtime that spawns supervisor as a local process."""+ """Runtime that spawns supervisor as a local process.++ Sandbox stdout/stderr (both the daemon and any background ``exec``)+ is dropped at the kernel level via ``subprocess.DEVNULL``: the+ historical ``runtime.log`` files were removed in favour of the+ single structured ``audit.log`` written by :class:`AuditLogger`,+ which already carries truncated stdout/stderr per command. Anyone+ needing the raw byte stream should attach a debugger or run the+ container with ``-it``; we no longer persist it to disk.+ """def __init__(self) -> None:self._processes: dict[str, subprocess.Popen] = {}@@ -345,14 +528,27 @@ class ProcessRuntime(RuntimeAdapter):self._background_processes: dict[str, list[subprocess.Popen]] = {}self._host_firewall_refcounts: dict[tuple[int, int], int] = {}self._sandbox_host_firewall_rules: dict[str, list[tuple[int, int]]] = {}- self._log_dir = JIUWENBOX_HOME / "sandbox_logs"- self._log_dir.mkdir(parents=True, exist_ok=True)+ self._cgroup_handles: dict[str, cgroup_module.CgroupHandle] = {}# Admission-control semaphore for ``exec``. Lazy-initialized in# ``_ensure_exec_semaphore`` because ``asyncio.Semaphore`` binds to# the running loop on first use, and ``ProcessRuntime`` is built# outside the asyncio loop in some startup paths (CLI, tests).self._exec_concurrency_limit: int = _resolve_exec_concurrency()self._exec_semaphore: asyncio.Semaphore | None = None+ # Zombie reaper plumbing. Plumbed in via ``register_zombie_reaper``+ # once an event loop is available (lifespan startup); we cannot+ # install a signal handler / create a Task before the loop exists.+ # ``_sigchld_loop`` is the loop the SIGCHLD handler is bound to+ # (None when the SIGCHLD fast path is unavailable, e.g. under+ # uvloop). ``_reaper_task`` is the periodic asyncio.Task that+ # always runs as the universal fallback. They are not mutually+ # exclusive on purpose: even when SIGCHLD works, the periodic task+ # serves as a backstop in case a signal is missed during a busy+ # loop iteration.+ self._sigchld_loop: asyncio.AbstractEventLoop | None = None+ self._reaper_task: asyncio.Task[None] | None = None+ self._reaper_loop: asyncio.AbstractEventLoop | None = None+ self._zombie_reaper_interval: float = _resolve_zombie_reaper_interval()logger.info("ProcessRuntime exec concurrency limit = %d ""(override via %s; cgroup_cpus=%s, os.cpu_count=%s, "@@ -727,7 +923,12 @@ class ProcessRuntime(RuntimeAdapter):def _server_protect_ports() -> list[int]:raw_ports = os.environ.get(SERVER_PROTECT_PORTS_ENV)if raw_ports is None:- return list(DEFAULT_SERVER_PROTECT_PORTS)+ # No explicit override: track whatever port uvicorn actually+ # bound. ``launcher.main`` always writes the resolved listen+ # URI back to ``$JIUWENBOX_LISTEN`` (see launcher.py:234) so+ # this stays consistent even when the operator passed+ # ``--listen tcp://0.0.0.0:18321``.+ return list(_derive_protect_ports_from_listen())if not raw_ports.strip():return []@@ -821,6 +1022,15 @@ class ProcessRuntime(RuntimeAdapter):ports = self._server_protect_ports()if not ports:+ # ``JIUWENBOX_SERVER_PROTECT_PORTS=""`` lets operators turn the+ # default off explicitly. Debug-only breadcrumb (info-level would+ # spam production logs under heavy sandbox churn).+ logger.debug(+ "Skipping host firewall install for sandbox %s "+ "(%s set to empty; mode=host has no host-level uid blocks)",+ sandbox_id,+ SERVER_PROTECT_PORTS_ENV,+ )returninstalled: list[tuple[int, int]] = []@@ -828,6 +1038,26 @@ class ProcessRuntime(RuntimeAdapter):for uid in self._host_firewall_uids(policy):for port in ports:installed.append(self._install_host_firewall_rule(uid, port))+ except network_module.NetworkSetupError as exc:+ # Most common cause: jiuwenbox runs unprivileged so ``iptables``+ # returns ``Permission denied (you must be root)``. Roll back any+ # partial install but DO NOT raise - the deployment explicitly+ # chose to run without root, and the alternative (failing sandbox+ # creation) would make even fully-local-only policies unusable.+ for installed_uid, installed_port in reversed(installed):+ self._remove_host_firewall_rule(installed_uid, installed_port)+ logger.warning(+ "Skipping host firewall install for sandbox %s; the "+ "box-server's port(s) %s remain reachable from the sandbox "+ "host netns (iptables unavailable: %s). Re-run jiuwenbox "+ "with sufficient privileges or set %s='' to silence this "+ "warning.",+ sandbox_id,+ ports,+ exc,+ SERVER_PROTECT_PORTS_ENV,+ )+ returnexcept Exception:for installed_uid, installed_port in reversed(installed):self._remove_host_firewall_rule(installed_uid, installed_port)@@ -1095,6 +1325,279 @@ class ProcessRuntime(RuntimeAdapter):else:self._background_processes.pop(sandbox_id, None)+ # ------------------------------------------------------------------+ # SIGCHLD-driven zombie reaper.+ #+ # The reaper has two responsibilities:+ # 1. Poll every tracked ``Popen`` (sandbox daemon monitor + every+ # ``exec_background`` invocation) so their exit status is recorded+ # and they leave the host process table promptly. This uses+ # ``Popen.poll()``, which acquires ``Popen._waitpid_lock`` and is+ # therefore race-safe with concurrent ``Popen.wait()`` calls that+ # stop()/_stop_background_processes() issue on an executor thread.+ # 2. Drain any residual zombie via ``os.waitpid(-1, WNOHANG)``. These+ # are bwrap-internal helpers (most importantly the ``--unshare-user``+ # userns helper that is cloned with ``CLONE_PARENT`` and is therefore+ # a direct child of box-server, *not* a child of the bwrap monitor)+ # plus anything else that landed on us via ``PR_SET_CHILD_SUBREAPER``.+ # We then look up the pid in our tracked-Popen map and, if found,+ # back-fill ``proc.returncode`` so a later ``Popen.poll()``/``wait()``+ # returns the actual exit status instead of taking the ``ECHILD``+ # branch (which silently sets ``returncode = 0``).+ # ------------------------------------------------------------------+ def _iter_tracked_popens(self) -> list[subprocess.Popen]:+ """Snapshot of all ``Popen`` objects tracked by this runtime."""+ result: list[subprocess.Popen] = []+ result.extend(self._processes.values())+ for proc_list in self._background_processes.values():+ result.extend(proc_list)+ return result++ def _reap_zombies(self) -> None:+ """Reap every zombie child (tracked + orphan).++ Safe to call from the asyncio event-loop thread (which is where+ ``loop.add_signal_handler`` delivers SIGCHLD callbacks); not safe+ from a signal context outside asyncio because it allocates and+ logs, which Python signal handlers must avoid.+ """+ tracked_popens = self._iter_tracked_popens()+ tracked_pids: dict[int, subprocess.Popen] = {}+ for proc in tracked_popens:+ pid = proc.pid+ if pid is not None:+ tracked_pids[pid] = proc+ if proc.returncode is None:+ try:+ proc.poll()+ except OSError:+ logger.debug(+ "Popen.poll() raised during reap", exc_info=True,+ )++ reaped_tracked: list[tuple[int, int]] = []+ reaped_orphans: list[int] = []+ while True:+ try:+ pid, status = os.waitpid(-1, os.WNOHANG)+ except ChildProcessError:+ break+ except OSError:+ logger.debug("waitpid(-1) raised during reap", exc_info=True)+ break+ if pid == 0:+ break+ proc = tracked_pids.get(pid)+ if proc is not None:+ # Race: ``Popen.poll()`` above did not catch this child+ # (it was still running then; it exited between the poll+ # and our ``waitpid(-1)``). Back-fill the returncode so+ # downstream ``stop()``/``is_running()`` see the real exit+ # status.+ if proc.returncode is None:+ try:+ proc.returncode = os.waitstatus_to_exitcode(status)+ except ValueError:+ # Stopped/continued status; ignore so a later+ # ``Popen.wait()`` can resync properly.+ logger.debug(+ "waitstatus_to_exitcode rejected status %r for pid %d",+ status,+ pid,+ )+ reaped_tracked.append((pid, status))+ else:+ reaped_orphans.append(pid)++ if reaped_orphans or reaped_tracked:+ logger.debug(+ "zombie reaper: tracked=%d orphans=%d",+ len(reaped_tracked),+ len(reaped_orphans),+ )++ def register_zombie_reaper(+ self,+ loop: asyncio.AbstractEventLoop | None = None,+ ) -> bool:+ """Install the zombie reaper on the given event loop.++ Tries the SIGCHLD ``add_signal_handler`` fast path first; on+ failure (most notably under uvloop, which uvicorn auto-selects+ when the package is installed) silently falls back to the+ periodic-Task reaper. Always starts the periodic Task as a+ backstop so a missed signal cannot strand zombies indefinitely.++ Returns ``True`` if *any* reaping channel is active. Idempotent+ on the same loop; replaces an existing registration when called+ with a different loop (only realistic in unit tests).+ """+ if loop is None:+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ logger.warning(+ "register_zombie_reaper called without a running loop;"+ " zombie reaper not installed",+ )+ return False+ if self._reaper_loop is not None and self._reaper_loop is not loop:+ # Different loop -> tear down whatever we had on the old one+ # before re-installing here. Practically only fires in tests+ # that recreate event loops between cases.+ self.unregister_zombie_reaper(self._reaper_loop)++ sigchld_ok = self._install_sigchld_handler(loop)+ task_ok = self._install_periodic_reaper(loop)++ if not sigchld_ok and not task_ok:+ return False++ # Drain anything that piled up before the reaper was wired in.+ # Safe to call even when only one channel was installed.+ self._reap_zombies()+ logger.info(+ "zombie reaper active on loop %s (pid=%d, sigchld=%s, "+ "periodic=%.1fs)",+ id(loop),+ os.getpid(),+ "on" if sigchld_ok else "off",+ self._zombie_reaper_interval if task_ok else 0.0,+ )+ return True++ def unregister_zombie_reaper(+ self,+ loop: asyncio.AbstractEventLoop | None = None,+ ) -> None:+ """Tear down everything ``register_zombie_reaper`` set up.++ Runs one final synchronous reap before returning so the caller+ (lifespan shutdown) does not have to schedule another loop tick+ for the periodic Task's ``CancelledError`` final-pass to fire --+ by the time we are unregistered the event loop is typically+ winding down and the cancelled coroutine may not get another+ slot. A sync sweep here makes shutdown cleanup deterministic.+ """+ target = loop or self._reaper_loop or self._sigchld_loop+ if target is None:+ return+ if self._sigchld_loop is target:+ self._uninstall_sigchld_handler(target)+ self._sigchld_loop = None+ if self._reaper_loop is target:+ self._cancel_periodic_reaper()+ self._reaper_loop = None+ try:+ self._reap_zombies()+ except Exception: # noqa: BLE001+ logger.debug(+ "final _reap_zombies pass raised during unregister",+ exc_info=True,+ )++ # ------------------------------------------------------------------+ # SIGCHLD fast path.+ # ------------------------------------------------------------------+ def _install_sigchld_handler(self, loop: asyncio.AbstractEventLoop) -> bool:+ if self._sigchld_loop is loop:+ return True+ try:+ loop.add_signal_handler(signal.SIGCHLD, self._reap_zombies)+ except (ValueError, RuntimeError) as exc:+ # ``RuntimeError`` covers uvloop's "SIGCHLD reserved" path+ # *and* ``NotImplementedError`` (the latter is a RuntimeError+ # subclass, raised by non-Unix selector loops). ``ValueError``+ # covers the "signal handlers must be set from the main+ # thread of the main interpreter" case. All of them are+ # benign here -- the periodic task picks up the slack.+ logger.info(+ "SIGCHLD fast-path reaper unavailable (%s); relying on "+ "periodic poll only",+ exc,+ )+ return False+ self._sigchld_loop = loop+ return True++ def _uninstall_sigchld_handler(+ self, loop: asyncio.AbstractEventLoop,+ ) -> None:+ try:+ loop.remove_signal_handler(signal.SIGCHLD)+ except (ValueError, RuntimeError) as exc:+ # All benign at unregister time:+ # - ``ValueError`` -> handler was never installed for that+ # sig on this loop (already-cleaned state);+ # - ``RuntimeError`` (incl. ``NotImplementedError``) ->+ # non-Unix loop or already-closed loop during shutdown.+ # Either way, nothing left to clean up; log at DEBUG so the+ # shutdown path stays quiet on the success case.+ logger.debug("remove_signal_handler(SIGCHLD) raised: %s", exc)++ # ------------------------------------------------------------------+ # Periodic asyncio.Task fallback / backstop.+ # ------------------------------------------------------------------+ async def _periodic_reaper_loop(self, interval: float) -> None:+ """Run ``_reap_zombies`` every ``interval`` seconds until cancelled.++ A single iteration's exception is logged and swallowed: the+ reaper is best-effort plumbing and a transient OSError (e.g.+ ``EINTR`` racing with shutdown) must not silently kill the loop+ and resurrect the leak we are trying to plug.+ """+ try:+ while True:+ await asyncio.sleep(interval)+ try:+ self._reap_zombies()+ except Exception: # noqa: BLE001+ logger.exception(+ "periodic zombie reaper iteration raised",+ )+ except asyncio.CancelledError:+ # Drain one last time on shutdown so anything that died+ # between the previous tick and now is still cleaned up+ # before the event loop closes.+ try:+ self._reap_zombies()+ except Exception: # noqa: BLE001+ logger.exception(+ "periodic zombie reaper final pass raised",+ )+ raise++ def _install_periodic_reaper(+ self, loop: asyncio.AbstractEventLoop,+ ) -> bool:+ if self._reaper_task is not None and not self._reaper_task.done():+ if self._reaper_loop is loop:+ return True+ # Different loop; cancel old, create new below.+ self._cancel_periodic_reaper()+ try:+ self._reaper_task = loop.create_task(+ self._periodic_reaper_loop(self._zombie_reaper_interval),+ name="jiuwenbox-zombie-reaper",+ )+ except RuntimeError as exc:+ logger.warning(+ "could not start periodic zombie reaper task: %s", exc,+ )+ self._reaper_task = None+ return False+ self._reaper_loop = loop+ return True++ def _cancel_periodic_reaper(self) -> None:+ task = self._reaper_task+ if task is None:+ return+ self._reaper_task = None+ if task.done():+ return+ task.cancel()+async def _stop_background_processes(self, sandbox_id: str, timeout: float = 5.0) -> None:processes = self._background_processes.pop(sandbox_id, [])if not processes:@@ -1187,7 +1690,6 @@ class ProcessRuntime(RuntimeAdapter):# daemon) via env so the daemon can recover it without having to# parse ``argv``.process_env[LISTENER_FD_ENV] = str(listener_fd)- log_file = self._log_dir / f"{sandbox_id}.log"logger.info("Spawning sandbox daemon for %s", sandbox_id)logger.debug("Sandbox daemon bwrap command for %s: %s", sandbox_id, daemon_cmd)@@ -1196,19 +1698,79 @@ class ProcessRuntime(RuntimeAdapter):if seccomp_fd is not None:pass_fd_list.append(seccomp_fd)pass_fds = tuple(pass_fd_list)- try:- log_fd = open(log_file, "w", encoding="utf-8")++ # Apply cgroup resource limits *before* spawning bwrap, then migrate+ # the freshly-forked child into the per-sandbox cgroup via+ # ``preexec_fn`` (which runs in the child after ``fork`` but before+ # ``execve``). This is the only race-free way: ``bwrap`` clones+ # immediately on startup to set up its requested namespaces, and any+ # post-spawn ``cgroup.procs`` write from the parent only catches the+ # bwrap host PID -- descendants forked between Popen and the parent+ # attach call remain in the *old* cgroup (cgroup v2 inherits at+ # fork time, not retroactively). Migrating from the child side+ # closes the window entirely.+ #+ # Empty cgroup policies (``policy.cgroup.is_empty()``) are a no-op:+ # ``ProcessRuntime`` does not even probe for a writable cgroup+ # backend, which keeps existing behavior unchanged on hosts without+ # cgroup support.+ cgroup_handle: cgroup_module.CgroupHandle | None = None+ cgroup_procs_paths: list[str] = []+ if not policy.cgroup.is_empty():try:- proc = subprocess.Popen(- daemon_cmd,- stdout=log_fd,- stderr=subprocess.STDOUT,- env=process_env,- pass_fds=pass_fds,- start_new_session=True,+ cgroup_handle = cgroup_module.setup(sandbox_id, policy.cgroup)+ except cgroup_module.CgroupSetupError as exc:+ logger.error(+ "Failed to apply cgroup limits for sandbox %s: %s",+ sandbox_id,+ exc,)- finally:- log_fd.close()+ if seccomp_fd is not None:+ _safe_close_fd(seccomp_fd)+ try:+ listener.close()+ except OSError:+ pass+ self._cleanup_sandbox_artifacts(sandbox_id, netns_name)+ raise RuntimeError(+ f"Failed to apply cgroup limits for sandbox "+ f"{sandbox_id}: {exc}"+ ) from exc+ cgroup_procs_paths = [+ str(group_dir / "cgroup.procs") for group_dir in cgroup_handle.paths+ ]++ def _preexec_attach_to_cgroup() -> None:+ # Runs in the child after fork, before execve. Writing our own+ # PID into each cgroup.procs migrates this process (and so+ # bwrap, and every descendant bwrap spawns) into the per-sandbox+ # cgroup before any user-controlled code starts. Any OSError+ # here propagates as a nonzero child exit, which the daemon+ # readiness probe surfaces to the caller -- silently leaving+ # the sandbox unconstrained would defeat the policy.+ child_pid = os.getpid()+ for procs_path in cgroup_procs_paths:+ with open(procs_path, "w", encoding="utf-8") as fh:+ fh.write(str(child_pid))++ preexec = _preexec_attach_to_cgroup if cgroup_procs_paths else None++ try:+ # Daemon stdout/stderr is unconditionally dropped at the+ # kernel level: the audit.log already captures per-command+ # stdout/stderr (truncated to 4 KiB) and the historical+ # runtime.log file was removed. Anyone needing the raw+ # stream should run the container with ``-it`` and inspect+ # the bwrap output live; persistence is intentionally gone.+ proc = subprocess.Popen(+ daemon_cmd,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ env=process_env,+ pass_fds=pass_fds,+ start_new_session=True,+ preexec_fn=preexec,+ )except Exception:if seccomp_fd is not None:_safe_close_fd(seccomp_fd)@@ -1216,6 +1778,17 @@ class ProcessRuntime(RuntimeAdapter):listener.close()except OSError:pass+ if cgroup_handle is not None:+ # The cgroup was created but never populated; tear it down+ # so we don't leak an empty per-sandbox group on the host.+ try:+ cgroup_module.teardown(cgroup_handle)+ except Exception:+ logger.warning(+ "cgroup teardown failed after Popen error for %s",+ sandbox_id,+ exc_info=True,+ )self._cleanup_sandbox_artifacts(sandbox_id, netns_name)raise@@ -1229,12 +1802,10 @@ class ProcessRuntime(RuntimeAdapter):passself._processes[sandbox_id] = proc- await self._wait_daemon_ready(- sandbox_id,- proc,- log_file,- netns_name,- )+ if cgroup_handle is not None:+ self._cgroup_handles[sandbox_id] = cgroup_handle++ await self._wait_daemon_ready(sandbox_id, proc, netns_name)logger.info("Sandbox daemon started for %s (pid=%d)", sandbox_id, proc.pid)return proc.pid@@ -1242,7 +1813,6 @@ class ProcessRuntime(RuntimeAdapter):self,sandbox_id: str,proc: subprocess.Popen,- log_file: Path,netns_name: str | None,) -> None:"""Verify the daemon is alive and mark its IPC channel ready.@@ -1256,26 +1826,28 @@ class ProcessRuntime(RuntimeAdapter):already exited with an error."""await asyncio.sleep(DAEMON_STARTUP_GRACE_SECONDS)- self._verify_daemon_alive(sandbox_id, proc, log_file, netns_name)+ self._verify_daemon_alive(sandbox_id, proc, netns_name)self._daemon_socket_ready[sandbox_id] = Truedef _verify_daemon_alive(self,sandbox_id: str,proc: subprocess.Popen,- log_file: Path,netns_name: str | None,) -> None:if proc.poll() is None:returnself._processes.pop(sandbox_id, None)self._cleanup_sandbox_artifacts(sandbox_id, netns_name)- log_tail = ""- if log_file.exists():- log_tail = log_file.read_text(encoding="utf-8", errors="replace")[-4000:]+ # Raw daemon stdout/stderr is no longer persisted (see the+ # ``Popen(DEVNULL)`` call in ``_spawn_supervisor``); we surface+ # only the returncode here. For deeper debugging the operator+ # should re-run with ``docker run -it`` so the bwrap output+ # streams to the terminal.raise RuntimeError(f"Sandbox daemon exited during startup with code {proc.returncode}; "- f"see log {log_file}. Log tail: {log_tail}"+ f"runtime stdout/stderr persistence is disabled (only audit.log "+ f"is written).")def _cleanup_sandbox_artifacts(@@ -1306,16 +1878,23 @@ class ProcessRuntime(RuntimeAdapter):self._landlock_payloads.pop(sandbox_id, None)self._policy_paths.pop(sandbox_id, None)self._remove_sandbox_host_firewall_rules(sandbox_id)+ # Drop any cgroup handle that survived a partially-completed create+ # (e.g. setup succeeded but daemon readiness then failed). Calling+ # teardown here keeps the failure path symmetric with stop() so we+ # never leak per-sandbox cgroup dirs in /sys/fs/cgroup.+ self._teardown_cgroup(sandbox_id)async def stop(self, sandbox_id: str, timeout: float = 10.0) -> None:await self._stop_background_processes(sandbox_id)proc = self._processes.get(sandbox_id)if proc is None:self._remove_sandbox_host_firewall_rules(sandbox_id)+ self._teardown_cgroup(sandbox_id)returnif proc.poll() is not None:self._processes.pop(sandbox_id, None)self._remove_sandbox_host_firewall_rules(sandbox_id)+ self._teardown_cgroup(sandbox_id)returnlogger.info("Stopping sandbox %s (pid=%d)", sandbox_id, proc.pid)@@ -1339,6 +1918,7 @@ class ProcessRuntime(RuntimeAdapter):self._processes.pop(sandbox_id, None)self._daemon_socket_ready.pop(sandbox_id, None)self._remove_sandbox_host_firewall_rules(sandbox_id)+ self._teardown_cgroup(sandbox_id)returntry:@@ -1351,12 +1931,35 @@ class ProcessRuntime(RuntimeAdapter):self._processes.pop(sandbox_id, None)self._daemon_socket_ready.pop(sandbox_id, None)self._remove_sandbox_host_firewall_rules(sandbox_id)+ self._teardown_cgroup(sandbox_id)returnawait loop.run_in_executor(None, proc.wait, 5.0)self._processes.pop(sandbox_id, None)self._daemon_socket_ready.pop(sandbox_id, None)self._remove_sandbox_host_firewall_rules(sandbox_id)+ self._teardown_cgroup(sandbox_id)++ def _teardown_cgroup(self, sandbox_id: str) -> None:+ """Drop the per-sandbox cgroup (if any) created during ``create``.++ No-op when ``create`` never set up a cgroup (e.g. the policy left+ ``cgroup`` empty, or setup failed and was already rolled back).+ Cgroup teardown is best-effort and must not block sandbox+ deletion - any retained directory only wastes a few inodes in+ ``/sys/fs/cgroup`` and gets noticed via the warning log.+ """+ handle = self._cgroup_handles.pop(sandbox_id, None)+ if handle is None:+ return+ try:+ cgroup_module.teardown(handle)+ except Exception:+ logger.warning(+ "cgroup teardown raised for sandbox %s; ignoring",+ sandbox_id,+ exc_info=True,+ )async def is_running(self, sandbox_id: str) -> bool:proc = self._processes.get(sandbox_id)@@ -1365,16 +1968,18 @@ class ProcessRuntime(RuntimeAdapter):return proc.poll() is Nonedef get_exit_diagnostics(self, sandbox_id: str) -> str:- """Return diagnostics for a sandbox whose lifecycle process is not running."""+ """Return diagnostics for a sandbox whose lifecycle process is not running.++ Per-sandbox runtime stdout/stderr is no longer captured to disk+ (the legacy ``runtime.log`` was removed; audit.log carries the+ per-command stdout/stderr instead). Callers should treat this+ as a short "process gone" signal and rely on ``audit.log`` plus+ the standard Python logger for context.+ """proc = self._processes.get(sandbox_id)returncode = None if proc is None else proc.poll()- log_file = self._log_dir / f"{sandbox_id}.log"- log_tail = ""- if log_file.exists():- log_tail = log_file.read_text(encoding="utf-8", errors="replace")[-4000:]return (- f"Sandbox lifecycle process is not running; "- f"returncode={returncode}; log={log_file}; log_tail={log_tail}"+ f"Sandbox lifecycle process is not running; returncode={returncode}")def _prepare_exec_invocation(@@ -2001,27 +2606,27 @@ class ProcessRuntime(RuntimeAdapter):process_env = {**os.environ, **(request.env or {})}self._reap_background_processes(sandbox_id)- log_index = len(self._background_processes.get(sandbox_id, []))- log_file = self._log_dir / f"{sandbox_id}-background-{log_index}.log"stdin_target = subprocess.PIPE if request.stdin_data is not None else subprocess.DEVNULLpass_fds = (seccomp_fd,) if seccomp_fd is not None else ()try:- log_fd = open(log_file, "ab")- try:- proc = subprocess.Popen(- bwrap_cmd,- stdin=stdin_target,- stdout=log_fd,- stderr=subprocess.STDOUT,- env=process_env,- pass_fds=pass_fds,- start_new_session=True,- )- if request.stdin_data is not None and proc.stdin is not None:- proc.stdin.write(request.stdin_data)- proc.stdin.close()- finally:- log_fd.close()+ # Background exec stdout/stderr is unconditionally dropped+ # at the kernel level. The historical per-process+ # ``runtime.bg-N.log`` files were removed together with the+ # daemon ``runtime.log``; the only persistent record of a+ # background command lives in ``audit.log`` (one row carrying+ # ``started`` / ``pid`` / ``error_message`` / ``duration_ms``).+ proc = subprocess.Popen(+ bwrap_cmd,+ stdin=stdin_target,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ env=process_env,+ pass_fds=pass_fds,+ start_new_session=True,+ )+ if request.stdin_data is not None and proc.stdin is not None:+ proc.stdin.write(request.stdin_data)+ proc.stdin.close()except Exception as exc:return BackgroundExecResult(started=False,@@ -2034,16 +2639,14 @@ class ProcessRuntime(RuntimeAdapter):await asyncio.sleep(0.2)if proc.poll() is not None:- log_tail = ""- if log_file.exists():- log_tail = log_file.read_text(encoding="utf-8", errors="replace")[-4000:]return BackgroundExecResult(started=False,pid=proc.pid,command=list(request.command),error_message=(f"Background command exited during startup with code "- f"{proc.returncode}; log={log_file}; log_tail={log_tail}"+ f"{proc.returncode}; runtime stdout/stderr is not "+ f"persisted (only audit.log is written)."),)@@ -2108,8 +2711,6 @@ class ProcessRuntime(RuntimeAdapter):if control_dir is not None and control_dir.exists():shutil.rmtree(control_dir, ignore_errors=True)self._daemon_socket_ready.pop(sandbox_id, None)-- log_file = self._log_dir / f"{sandbox_id}.log"- log_file.unlink(missing_ok=True)- for background_log in self._log_dir.glob(f"{sandbox_id}-background-*.log"):- background_log.unlink(missing_ok=True)+ # Runtime log files used to live here too; they were removed in+ # favour of the single ``audit.log`` written by ``AuditLogger``.+ # Nothing extra to clean up on this side any more.diff --git a/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py b/jiuwenbox/src/jiuwenbox/server/sandbox_manager.pyindex b13f9e388c..7f2c10f1fe 100644--- a/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py+++ b/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py@@ -15,12 +15,34 @@ import jsonimport loggingimport osimport textwrap+import timeimport uuidfrom collections.abc import Mappingfrom dataclasses import dataclassfrom datetime import datetime, timezonefrom pathlib import Path+# Cap stdout/stderr at this many chars per audit event. Large model+# completions can dump megabytes, which is fine to keep in the runtime+# log file but explodes the audit JSONL (one line per event, designed to+# be cheap to ``tail -f``). 4 KiB is enough to keep error messages /+# tracebacks intact while keeping the audit file bounded.+_AUDIT_OUTPUT_LIMIT = 4096+++def _truncate_for_audit(text: str | None, *, limit: int = _AUDIT_OUTPUT_LIMIT) -> str:+ """Return ``text`` clipped to ``limit`` chars with a visible marker.++ The tail is preferred over the head because errors typically surface+ at the end of stderr; truncation is annotated inline so the operator+ is not misled into thinking they have the full output.+ """+ if not text:+ return ""+ if len(text) <= limit:+ return text+ return text[-limit:] + f"\n[truncated, total {len(text)} chars]"+from jiuwenbox.logging_config import configure_loggingfrom jiuwenbox.models.common import AuditEventTypefrom jiuwenbox.models.policy import SecurityPolicy@@ -99,7 +121,16 @@ class SandboxManager:self._lock = asyncio.Lock()self._sandboxes: dict[str, SandboxRef] = {}self._policies: dict[str, SecurityPolicy] = {}- self._load_state()+ # Sandbox state is treated as ephemeral: jiuwenbox starts up with an empty+ # registry, regardless of any leftover files under ``state_dir`` /+ # ``policies_dir``. The dirs themselves are recreated above so subsequent+ # ``create_sandbox`` calls can still persist YAML / JSON during a single+ # process lifetime, but nothing is read back on boot.+ #+ # On graceful shutdown ``clear_persistent_state`` wipes both dirs so a+ # subsequent jiuwenbox launch never sees stale sandbox descriptors. This+ # avoids accidentally "reviving" dead sandboxes whose backing bubblewrap+ # processes / netns / cgroup state no longer exist.def _resolve_effective_policy(self,@@ -124,7 +155,13 @@ class SandboxManager:return SecurityPolicy.model_validate(policy_payload)def _load_state(self) -> None:- """Load persisted sandbox state on startup."""+ """Load persisted sandbox state from ``state_dir``.++ No longer invoked from ``__init__``: jiuwenbox treats sandbox registry+ as ephemeral across restarts (see ``__init__`` for rationale). Kept as+ an opt-in helper for tooling that explicitly wants to inspect leftover+ state files.+ """for state_file in self.state_dir.glob("*.json"):try:data = json.loads(state_file.read_text())@@ -134,6 +171,114 @@ class SandboxManager:except Exception:logger.warning("Failed to load state from %s", state_file, exc_info=True)+ def clear_persistent_state(self) -> None:+ """Remove all sandbox / policy descriptors from disk.++ Called from the FastAPI lifespan shutdown hook so the next boot starts+ from a clean slate. The directories themselves are preserved (recreated+ if missing) so other code that grabs ``state_dir`` / ``policies_dir``+ paths during shutdown won't ``FileNotFoundError``.++ This method is *best-effort*: any single-file removal failure is logged+ but does not abort the rest of the cleanup. Note that this method only+ wipes on-disk descriptors; live ``sandbox-daemon.py`` / bubblewrap+ children are spawned with ``start_new_session=True`` (their own session+ + pgrp) so they **do not** die automatically when uvicorn exits. To+ actually tear down running sandboxes during shutdown, call+ :meth:`shutdown_all_sandboxes` first.+ """+ for label, directory, pattern in (+ ("sandbox state", self.state_dir, "*.json"),+ ("sandbox policy", self.policy_engine.policies_dir, "*.yaml"),+ ):+ if not directory.exists():+ continue+ removed = 0+ for entry in directory.glob(pattern):+ try:+ entry.unlink()+ removed += 1+ except FileNotFoundError:+ continue+ except OSError as exc:+ logger.warning(+ "clear_persistent_state: failed to remove %s %s: %s",+ label,+ entry,+ exc,+ )+ logger.info(+ "clear_persistent_state: removed %d %s file(s) under %s",+ removed,+ label,+ directory,+ )++ async def shutdown_all_sandboxes(self) -> None:+ """Best-effort teardown of every registered sandbox.++ Called from the FastAPI lifespan shutdown hook *before*+ :meth:`clear_persistent_state` so that the per-sandbox bubblewrap+ process group (and the ``sandbox-daemon.py`` running inside it) are+ actually terminated instead of being reparented to PID 1 when the+ jiuwenbox-server process exits. Each sandbox is torn down via+ :meth:`delete_sandbox`, which routes through+ ``runtime.cleanup`` -> ``runtime.stop`` -> ``os.killpg(SIGTERM/SIGKILL)``+ on the daemon's own session group.++ Individual failures are logged but do not abort the remaining+ teardowns; the goal is to avoid leaking orphan processes even if one+ sandbox's daemon refuses to cooperate.+ """+ async with self._lock:+ sandbox_ids = list(self._sandboxes.keys())+ if not sandbox_ids:+ logger.info("shutdown_all_sandboxes: no live sandboxes to tear down")+ return+ logger.info(+ "shutdown_all_sandboxes: tearing down %d sandbox(es): %s",+ len(sandbox_ids),+ sandbox_ids,+ )+ for sandbox_id in sandbox_ids:+ try:+ await self.delete_sandbox(sandbox_id)+ except SandboxNotFoundError:+ # Already deleted between the snapshot above and now; treat+ # as a clean teardown.+ continue+ except Exception: # noqa: BLE001+ logger.exception(+ "shutdown_all_sandboxes: delete_sandbox(%s) failed",+ sandbox_id,+ )++ def register_zombie_reaper(+ self,+ loop: asyncio.AbstractEventLoop | None = None,+ ) -> bool:+ """Forward SIGCHLD reaper registration to the underlying runtime.++ Defined as a thin pass-through so the FastAPI lifespan hook can talk+ to the manager (the only object it already holds) instead of having+ to reach into ``self.runtime`` -- runtimes other than+ :class:`ProcessRuntime` may not need a reaper at all, in which case+ they can return ``True`` and the lifespan code stays uniform.+ """+ register = getattr(self.runtime, "register_zombie_reaper", None)+ if register is None:+ return True+ return register(loop)++ def unregister_zombie_reaper(+ self,+ loop: asyncio.AbstractEventLoop | None = None,+ ) -> None:+ unregister = getattr(self.runtime, "unregister_zombie_reaper", None)+ if unregister is None:+ return+ unregister(loop)+def _save_state(self, sandbox: SandboxRef) -> None:"""Persist a single sandbox's state to disk."""path = self.state_dir / f"{sandbox.id}.json"@@ -317,23 +462,46 @@ class SandboxManager:f"Cannot exec in sandbox '{sandbox_id}': state is {ref.phase.value}")+ # One audit row per exec, emitted **after** the runtime returns so+ # the payload covers both intent (command/workdir) and outcome+ # (exit_code, stdout/stderr tail, duration, error). The earlier+ # pre-call ``EXEC_COMMAND`` was dropped: it doubled the JSONL+ # volume without adding any information not already present here.+ start = time.monotonic()+ try:+ result = await self.runtime.exec(+ sandbox_id,+ RuntimeExecRequest(+ command=request.command,+ workdir=request.workdir,+ env=request.env,+ stdin_data=request.stdin_data,+ timeout=request.timeout,+ ),+ )+ except Exception as exc:+ self.audit.log(+ AuditEventType.EXEC_COMMAND,+ sandbox_id,+ command=request.command,+ workdir=request.workdir,+ ok=False,+ error=repr(exc),+ duration_ms=int((time.monotonic() - start) * 1000),+ )+ raiseself.audit.log(AuditEventType.EXEC_COMMAND,sandbox_id,command=request.command,workdir=request.workdir,+ ok=result.exit_code == 0,+ exit_code=result.exit_code,+ stdout=_truncate_for_audit(result.stdout),+ stderr=_truncate_for_audit(result.stderr),+ duration_ms=int((time.monotonic() - start) * 1000),)-- return await self.runtime.exec(- sandbox_id,- RuntimeExecRequest(- command=request.command,- workdir=request.workdir,- env=request.env,- stdin_data=request.stdin_data,- timeout=request.timeout,- ),- )+ return resultasync def exec_background_in_sandbox(self,@@ -347,24 +515,47 @@ class SandboxManager:f"Cannot exec in sandbox '{sandbox_id}': state is {ref.phase.value}")+ # Background exec returns a "started yes/no + pid" envelope+ # rather than stdout/stderr — the raw byte stream is dropped+ # at the kernel level (runtime.log was removed). One audit row+ # per call, post-return.+ start = time.monotonic()+ try:+ result = await self.runtime.exec_background(+ sandbox_id,+ RuntimeExecRequest(+ command=request.command,+ workdir=request.workdir,+ env=request.env,+ stdin_data=request.stdin_data,+ timeout=request.timeout,+ ),+ )+ except Exception as exc:+ self.audit.log(+ AuditEventType.EXEC_COMMAND,+ sandbox_id,+ command=request.command,+ workdir=request.workdir,+ background=True,+ ok=False,+ error=repr(exc),+ duration_ms=int((time.monotonic() - start) * 1000),+ )+ raiseself.audit.log(AuditEventType.EXEC_COMMAND,sandbox_id,command=request.command,workdir=request.workdir,background=True,+ ok=result.started,+ started=result.started,+ pid=result.pid,+ error=result.error_message,+ duration_ms=int((time.monotonic() - start) * 1000),)-- return await self.runtime.exec_background(- sandbox_id,- RuntimeExecRequest(- command=request.command,- workdir=request.workdir,- env=request.env,- stdin_data=request.stdin_data,- timeout=request.timeout,- ),- )+ return resultasync def upload_file_to_sandbox(self,@@ -379,12 +570,23 @@ class SandboxManager:f"Cannot upload to sandbox '{sandbox_id}': state is {ref.phase.value}")- self.audit.log(- AuditEventType.FILE_TRANSFER,- sandbox_id,- direction="upload",- sandbox_path=sandbox_path,- )+ # One audit row per upload, emitted after the call returns so the+ # payload covers both intent (path/size) and outcome (ok, error,+ # which transport landed it). The earlier pre-call event was+ # dropped (see ``exec_in_sandbox`` for the same rationale).+ start = time.monotonic()++ def _emit_result(ok: bool, **extra) -> None:+ self.audit.log(+ AuditEventType.FILE_TRANSFER,+ sandbox_id,+ direction="upload",+ sandbox_path=sandbox_path,+ size=len(content),+ ok=ok,+ duration_ms=int((time.monotonic() - start) * 1000),+ **extra,+ )# Fast path: tell the in-sandbox daemon to write the file in its# own process. The daemon already runs with the sandbox uid/gid,@@ -392,20 +594,36 @@ class SandboxManager:# the write in-process is exactly equivalent (security-wise) to# spawning ``bash -c 'cat > "$target"'`` but skips the bash# cold-start and an extra fork/exec roundtrip per upload.- result = await self.runtime.write_file(- sandbox_id,- sandbox_path,- content,- mkdir_parents=True,- )+ try:+ result = await self.runtime.write_file(+ sandbox_id,+ sandbox_path,+ content,+ mkdir_parents=True,+ )+ except Exception as exc:+ _emit_result(False, error=repr(exc), path="ipc")+ raiseif result.ok:+ _emit_result(True, path="ipc")returnif result.error in ("daemon_unavailable", "transport_failure", "unsupported"):- await self._upload_via_exec_fallback(sandbox_id, sandbox_path, content)+ # Fallback path runs ``exec_in_sandbox`` internally which+ # itself emits one ``EXEC_COMMAND`` row for the bash+cat+ # invocation; we still emit ``FILE_TRANSFER`` here so the+ # per-transfer summary is one greppable line regardless of+ # whether IPC or the fallback ran.+ try:+ await self._upload_via_exec_fallback(sandbox_id, sandbox_path, content)+ except Exception as exc:+ _emit_result(False, error=repr(exc), path="exec_fallback")+ raise+ _emit_result(True, path="exec_fallback")returndetail = result.detail or result.error or "unknown failure"+ _emit_result(False, error=detail, path="ipc")raise SandboxStateError(f"Failed to upload file to '{sandbox_path}': {detail}")@@ -480,33 +698,63 @@ class SandboxManager:f"Cannot download from sandbox '{sandbox_id}': state is {ref.phase.value}")- self.audit.log(- AuditEventType.FILE_TRANSFER,- sandbox_id,- direction="download",- sandbox_path=sandbox_path,- )+ # Mirror of ``upload_file_to_sandbox``: a single post-result row+ # carrying intent + outcome. ``size`` is filled in on success+ # (from the actual bytes returned), 0 otherwise.+ start = time.monotonic()++ def _emit_result(ok: bool, size: int = 0, **extra) -> None:+ self.audit.log(+ AuditEventType.FILE_TRANSFER,+ sandbox_id,+ direction="download",+ sandbox_path=sandbox_path,+ size=size,+ ok=ok,+ duration_ms=int((time.monotonic() - start) * 1000),+ **extra,+ )# Fast path: ask the daemon to read the file directly. The daemon# carries the sandbox's full security envelope so it cannot read# any path that user code couldn't read. Binary content survives# the IPC unchanged - no base64 round-trip.- result = await self.runtime.read_file(sandbox_id, sandbox_path)+ try:+ result = await self.runtime.read_file(sandbox_id, sandbox_path)+ except Exception as exc:+ _emit_result(False, error=repr(exc), path="ipc")+ raiseif result.ok:- return result.content or b""+ content = result.content or b""+ _emit_result(True, size=len(content), path="ipc")+ return contentif result.error == "not_found":+ _emit_result(False, error="not_found", path="ipc")raise FileNotFoundError(sandbox_path)if result.error in ("is_directory", "is_a_directory"):+ _emit_result(False, error=result.error, path="ipc")raise SandboxStateError(f"Sandbox path '{sandbox_path}' is a directory")if result.error == "is_symlink":+ _emit_result(False, error="is_symlink", path="ipc")raise SandboxStateError(f"Refusing to follow symlink at '{sandbox_path}'")if result.error in ("daemon_unavailable", "transport_failure", "unsupported"):- return await self._download_via_exec_fallback(sandbox_id, sandbox_path)+ # Fallback path emits its own ``EXEC_COMMAND`` row for the+ # bash+base64 invocation; we still emit ``FILE_TRANSFER`` so+ # the per-transfer summary is one greppable line regardless+ # of which transport landed it.+ try:+ content = await self._download_via_exec_fallback(sandbox_id, sandbox_path)+ except Exception as exc:+ _emit_result(False, error=repr(exc), path="exec_fallback")+ raise+ _emit_result(True, size=len(content), path="exec_fallback")+ return contentdetail = result.detail or result.error or "unknown failure"+ _emit_result(False, error=detail, path="ipc")raise SandboxStateError(f"Failed to download file from '{sandbox_path}': {detail}")diff --git a/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py b/jiuwenbox/src/jiuwenbox/supervisor/bwrap.pyindex ffd270fb3d..6e64c91b3e 100644--- a/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py+++ b/jiuwenbox/src/jiuwenbox/supervisor/bwrap.py@@ -7,15 +7,19 @@ the lifecycle of the sandboxed process.from __future__ import annotations+import fnmatchimport loggingimport posixpathimport signal+import stat as stat_moduleimport subprocessfrom dataclasses import dataclass, field+from pathlib import Pathfrom typing import IOfrom jiuwenbox.logging_config import configure_loggingfrom jiuwenbox.models.policy import (+ BindRootEntries,CapabilityPolicy,FilesystemPolicy,NetworkPolicy,@@ -139,6 +143,20 @@ class BwrapConfig:# read_only/read_write are also enforced by Landlock when available.# Only bind_mounts expose host paths in the sandbox.+ #+ # ``bind_root_entries`` is processed BEFORE ``bind_mounts`` on purpose:+ # bind_root_entries is the "wildcard / generic" parent mount (e.g.+ # ``host_root="/"`` expanded into every immediate child of the host+ # rootfs), while ``bind_mounts`` are user-explicit per-path overrides+ # (``/sandbox files allow|deny <path>`` lowered by jiuwenclaw's+ # ``sysop_builder``). bwrap's later-overrides-earlier mount semantics+ # means whichever entry we ``append`` last wins on conflicting paths;+ # putting bind_root_entries first guarantees the explicit+ # bind_mounts can selectively flip a child to rw (allow) or stack a+ # rw + remount-ro pair on top (deny) without being clobbered by the+ # wildcard parent re-binding the path back to ro afterwards.+ for spec in fs.bind_root_entries:+ BwrapConfig._apply_bind_root_entries(cfg, spec)for mount in fs.bind_mounts:if mount.mode == "ro":cfg.ro_binds.append((mount.host_path, mount.sandbox_path))@@ -147,6 +165,77 @@ class BwrapConfig:for device in fs.device:cfg.device_binds.append((device.host_path, device.sandbox_path))+ @staticmethod+ def _apply_bind_root_entries(cfg: BwrapConfig, spec: BindRootEntries) -> None:+ """Expand one ``BindRootEntries`` spec into per-child bwrap binds.++ Each immediate child of ``spec.host_root`` becomes its own+ ``--ro-bind``/``--bind`` so the sandbox sees the same names at+ ``spec.sandbox_path/<child>``. Hidden entries and excluded names are+ filtered out; non-regular non-directory entries (sockets, fifos,+ block/char devices, broken symlinks) are skipped to avoid bwrap+ failures.+ """+ host_root_str = spec.host_root+ host_root = Path(host_root_str)++ if not host_root.exists():+ logger.warning(+ "bind_root_entries: host_root %r does not exist; skipping",+ host_root_str,+ )+ return+ if not host_root.is_dir():+ logger.warning(+ "bind_root_entries: host_root %r is not a directory; skipping",+ host_root_str,+ )+ return++ sandbox_root = spec.sandbox_path.rstrip("/") or "/"++ try:+ children = sorted(host_root.iterdir(), key=lambda p: p.name)+ except OSError as exc:+ logger.warning(+ "bind_root_entries: cannot list %r: %s; skipping",+ host_root_str,+ exc,+ )+ return++ for child in children:+ name = child.name+ if not spec.include_hidden and name.startswith("."):+ continue+ if any(fnmatch.fnmatch(name, pattern) for pattern in spec.exclude):+ continue++ try:+ stat_result = child.stat()+ except OSError as exc:+ logger.warning(+ "bind_root_entries: skipping %r: %s",+ str(child),+ exc,+ )+ continue++ mode_bits = stat_result.st_mode+ if not (stat_module.S_ISDIR(mode_bits) or stat_module.S_ISREG(mode_bits)):+ logger.debug(+ "bind_root_entries: skipping non-regular entry %r",+ str(child),+ )+ continue++ target = f"{sandbox_root}/{name}" if sandbox_root != "/" else f"/{name}"+ source = str(child)+ if spec.mode == "ro":+ cfg.ro_binds.append((source, target))+ else:+ cfg.rw_binds.append((source, target))+@staticmethoddef _apply_process(cfg: BwrapConfig, proc: ProcessPolicy) -> None:# Resolve user/group names to numeric IDs; fall back to 65534 (nobody)diff --git a/jiuwenbox/src/jiuwenbox/supervisor/cgroup.py b/jiuwenbox/src/jiuwenbox/supervisor/cgroup.pynew file mode 100644index 0000000000..281cc2808b--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/supervisor/cgroup.py@@ -0,0 +1,521 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+"""Per-sandbox cgroup resource limits.++This module abstracts the cgroup v2 / v1 differences behind a small set of+operations consumed by :mod:`jiuwenbox.server.runtime.process`:++- :func:`detect_backend` - probe the host once for the preferred backend.+- :func:`setup` - create a per-sandbox cgroup and write the limit files.+- :func:`attach` - place the bwrap host-side PID into ``cgroup.procs``.+- :func:`teardown` - kill stragglers, then rmdir the cgroup.++When neither cgroup v2 nor v1 is writable but :class:`CgroupPolicy` is+non-empty, :func:`setup` raises :class:`CgroupSetupError` so the runtime+can abort sandbox creation rather than silently dropping the limits.++Cgroup writes are performed by the box-server process (typically root) on+the host; the sandbox itself never touches the cgroup tree. PID attachment+happens *after* the bwrap process is spawned, which is sufficient for+cgroup v2 (the migration applies to the existing process and is inherited+by all subsequent forks).+"""++from __future__ import annotations++import enum+import logging+import os+import shutil+import time+from dataclasses import dataclass, field+from pathlib import Path++from jiuwenbox.models.policy import CgroupPolicy++logger = logging.getLogger(__name__)+++class CgroupSetupError(RuntimeError):+ """Raised when cgroup limits are requested but cannot be applied."""+++class CgroupBackend(str, enum.Enum):+ V2 = "v2"+ V1 = "v1"+++# Required controllers for the minimal v1/v2 surface we support.+_REQUIRED_CONTROLLERS: tuple[str, ...] = ("memory", "cpu", "pids")++_CGROUP_ROOT = Path("/sys/fs/cgroup")+_JIUWENBOX_ROOT_NAME = "jiuwenbox"++# Maximum number of attempts when rmdir-ing a cgroup that still has+# transient processes attached.+_TEARDOWN_RETRIES = 5+_TEARDOWN_BACKOFF_SECONDS = 0.1+++@dataclass+class CgroupHandle:+ """Bookkeeping handed back from :func:`setup` and consumed by+ :func:`attach` / :func:`teardown`.++ For v2 ``paths`` contains exactly one entry (the unified group dir).+ For v1 it contains one entry per controller in ``_REQUIRED_CONTROLLERS``+ that was actually used by the policy.+ """++ backend: CgroupBackend+ sandbox_id: str+ paths: list[Path] = field(default_factory=list)+++# ---------------------------------------------------------------------------+# Detection+# ---------------------------------------------------------------------------+++def _v2_controllers_enabled_at(path: Path) -> set[str]:+ try:+ text = (path / "cgroup.controllers").read_text(encoding="utf-8")+ except OSError:+ return set()+ return set(text.split())+++def _v2_available() -> bool:+ """Return True when cgroup v2 is mounted and our controllers are exposed.++ We require :data:`_CGROUP_ROOT` / cgroup.controllers to exist and to+ expose ``memory``, ``cpu`` and ``pids``. Writability is verified at+ setup time (creating the jiuwenbox subtree) rather than here, so the+ detection is cheap and side-effect-free.+ """+ controllers_file = _CGROUP_ROOT / "cgroup.controllers"+ if not controllers_file.is_file():+ return False+ available = _v2_controllers_enabled_at(_CGROUP_ROOT)+ return all(name in available for name in _REQUIRED_CONTROLLERS)+++def _v1_available() -> bool:+ """Return True when cgroup v1 exposes a writable hierarchy for each of+ our required controllers under :data:`_CGROUP_ROOT`.+ """+ for controller in _REQUIRED_CONTROLLERS:+ ctrl_root = _CGROUP_ROOT / controller+ if not ctrl_root.is_dir():+ return False+ # cgroup v1 controller root is always writable by root; we don't+ # touch it here to avoid leaving leftover dirs in detection.+ return True+++def detect_backend() -> CgroupBackend | None:+ """Probe the host for a usable cgroup backend.++ Returns ``CgroupBackend.V2`` when cgroup v2 is mounted with our+ controllers exposed, falling back to ``CgroupBackend.V1`` when each+ required controller has its own hierarchy. Returns ``None`` if+ neither is present (the caller decides whether that's fatal).+ """+ if _v2_available():+ return CgroupBackend.V2+ if _v1_available():+ return CgroupBackend.V1+ return None+++# ---------------------------------------------------------------------------+# Setup+# ---------------------------------------------------------------------------+++def _write_file(path: Path, content: str) -> None:+ """Write ``content`` to ``path`` using ``open(..., "w")`` semantics.++ Cgroup interface files are sysfs-like and require a single write of the+ exact value (no newline appended by the kernel parser); using ``"w"``+ keeps the behaviour predictable across both v2 and v1.+ """+ with open(path, "w", encoding="utf-8") as fh:+ fh.write(content)+++def _try_write_file(path: Path, content: str, *, what: str) -> None:+ try:+ _write_file(path, content)+ except OSError as exc:+ raise CgroupSetupError(+ f"failed to write {what} ({path}): {exc.strerror or exc}"+ ) from exc+++def _ensure_jiuwenbox_root_v2() -> Path:+ """Create ``/sys/fs/cgroup/jiuwenbox/`` and enable required controllers.++ On cgroup v2 controllers must be enabled in every ancestor's+ ``cgroup.subtree_control`` before the leaf can use them. We enable+ ``+memory +cpu +pids`` at the unified root, then mkdir+ ``/sys/fs/cgroup/jiuwenbox/`` if it doesn't already exist.+ """+ enable_line = " ".join(f"+{c}" for c in _REQUIRED_CONTROLLERS)+ subtree_control = _CGROUP_ROOT / "cgroup.subtree_control"+ try:+ _write_file(subtree_control, enable_line)+ except OSError as exc:+ raise CgroupSetupError(+ f"failed to enable controllers {enable_line!r} in {subtree_control}: "+ f"{exc.strerror or exc}"+ ) from exc++ jiuwenbox_root = _CGROUP_ROOT / _JIUWENBOX_ROOT_NAME+ try:+ jiuwenbox_root.mkdir(parents=False, exist_ok=True)+ except OSError as exc:+ raise CgroupSetupError(+ f"failed to create {jiuwenbox_root}: {exc.strerror or exc}"+ ) from exc++ # Enable controllers on the jiuwenbox subtree as well so per-sandbox+ # children can read/write the limit files.+ try:+ _write_file(jiuwenbox_root / "cgroup.subtree_control", enable_line)+ except OSError as exc:+ # If the jiuwenbox root already has the controllers enabled, this+ # write either succeeds or returns EBUSY; treat any other failure+ # as a real error.+ if getattr(exc, "errno", None) not in (0, None):+ raise CgroupSetupError(+ f"failed to enable controllers in {jiuwenbox_root}: "+ f"{exc.strerror or exc}"+ ) from exc++ return jiuwenbox_root+++def _setup_v2(sandbox_id: str, policy: CgroupPolicy) -> CgroupHandle:+ parent = _ensure_jiuwenbox_root_v2()+ group_dir = parent / sandbox_id+ try:+ group_dir.mkdir(parents=False, exist_ok=False)+ except FileExistsError as exc:+ raise CgroupSetupError(+ f"cgroup directory {group_dir} already exists"+ ) from exc+ except OSError as exc:+ raise CgroupSetupError(+ f"failed to create {group_dir}: {exc.strerror or exc}"+ ) from exc++ try:+ if policy.memory_max is not None:+ _try_write_file(+ group_dir / "memory.max",+ str(policy.memory_max),+ what="memory.max",+ )+ # Also clamp swap to zero so ``memory.max`` behaves as a true+ # hard cap. Without this, a memory-hungry process can simply+ # page out to swap once it hits ``memory.max`` and keep running+ # -- the kernel only invokes the OOM killer when reclaim cannot+ # free pages, and "evict to swap" counts as reclaim. WSL2 and+ # most desktop Linuxes ship with swap enabled, so this is the+ # common case rather than an edge case.+ #+ # The swap controller may be absent on hosts that booted with+ # ``swapaccount=0`` (or without ``CONFIG_MEMCG_SWAP``); missing+ # ``memory.swap.max`` is non-fatal because such hosts have no+ # swap to begin with and ``memory.max`` already behaves as the+ # hard cap users expect.+ swap_max_file = group_dir / "memory.swap.max"+ if swap_max_file.exists():+ try:+ _write_file(swap_max_file, "0")+ except OSError as exc:+ logger.warning(+ "cgroup v2: failed to clamp memory.swap.max=0 for %s: %s",+ sandbox_id,+ exc,+ )+ if policy.cpu_max is not None:+ quota, period = policy.cpu_max+ _try_write_file(+ group_dir / "cpu.max",+ f"{quota} {period}",+ what="cpu.max",+ )+ if policy.pids_max is not None:+ _try_write_file(+ group_dir / "pids.max",+ str(policy.pids_max),+ what="pids.max",+ )+ except CgroupSetupError:+ # Roll back the empty cgroup so we don't leak it on failure.+ try:+ group_dir.rmdir()+ except OSError:+ logger.warning(+ "cgroup: failed to remove %s after setup error; manual cleanup needed",+ group_dir,+ )+ raise++ return CgroupHandle(+ backend=CgroupBackend.V2,+ sandbox_id=sandbox_id,+ paths=[group_dir],+ )+++def _setup_v1(sandbox_id: str, policy: CgroupPolicy) -> CgroupHandle:+ """Create one v1 cgroup per controller actually used by the policy.++ Unlike v2 (unified hierarchy), each cgroup v1 controller has its own+ mount under ``/sys/fs/cgroup/<controller>/``. We only create the+ sub-directories for controllers the policy actually constrains so we+ don't leave empty memory/cpu/pids cgroups behind when the user only+ set, e.g., ``pids_max``.+ """+ created_paths: list[Path] = []+ try:+ if policy.memory_max is not None:+ path = _create_v1_group("memory", sandbox_id)+ created_paths.append(path)+ _try_write_file(+ path / "memory.limit_in_bytes",+ str(policy.memory_max),+ what="memory.limit_in_bytes",+ )+ # Cap memory+swap to the same value so the swap controller can't+ # be used to bypass ``memory.limit_in_bytes``. ``memory.memsw``+ # is only present when the kernel was booted with swap accounting+ # enabled (``swapaccount=1`` or built-in default); a missing+ # file is non-fatal -- such hosts can't account swap usage per+ # cgroup anyway, so the user's ``memory_max`` setting is already+ # the hardest cap available.+ memsw_file = path / "memory.memsw.limit_in_bytes"+ if memsw_file.exists():+ try:+ _write_file(memsw_file, str(policy.memory_max))+ except OSError as exc:+ logger.warning(+ "cgroup v1: failed to set memory.memsw.limit_in_bytes "+ "for %s: %s",+ sandbox_id,+ exc,+ )+ if policy.cpu_max is not None:+ quota, period = policy.cpu_max+ path = _create_v1_group("cpu", sandbox_id)+ created_paths.append(path)+ # ``cpu.cfs_period_us`` must be written before ``cpu.cfs_quota_us``+ # if the new quota exceeds the old period; flipping the order+ # would briefly violate the kernel's quota <= period * cpus+ # invariant. Writing period first is always safe.+ _try_write_file(+ path / "cpu.cfs_period_us",+ str(period),+ what="cpu.cfs_period_us",+ )+ _try_write_file(+ path / "cpu.cfs_quota_us",+ str(quota),+ what="cpu.cfs_quota_us",+ )+ if policy.pids_max is not None:+ path = _create_v1_group("pids", sandbox_id)+ created_paths.append(path)+ _try_write_file(+ path / "pids.max",+ str(policy.pids_max),+ what="pids.max",+ )+ except CgroupSetupError:+ for path in created_paths:+ try:+ path.rmdir()+ except OSError:+ logger.warning(+ "cgroup v1: failed to remove %s after setup error", path+ )+ raise++ return CgroupHandle(+ backend=CgroupBackend.V1,+ sandbox_id=sandbox_id,+ paths=created_paths,+ )+++def _create_v1_group(controller: str, sandbox_id: str) -> Path:+ parent = _CGROUP_ROOT / controller / _JIUWENBOX_ROOT_NAME+ try:+ parent.mkdir(parents=False, exist_ok=True)+ except OSError as exc:+ raise CgroupSetupError(+ f"failed to create {parent}: {exc.strerror or exc}"+ ) from exc+ group_dir = parent / sandbox_id+ try:+ group_dir.mkdir(parents=False, exist_ok=False)+ except FileExistsError as exc:+ raise CgroupSetupError(+ f"cgroup directory {group_dir} already exists"+ ) from exc+ except OSError as exc:+ raise CgroupSetupError(+ f"failed to create {group_dir}: {exc.strerror or exc}"+ ) from exc+ return group_dir+++def setup(sandbox_id: str, policy: CgroupPolicy) -> CgroupHandle:+ """Create a cgroup for ``sandbox_id`` and apply ``policy``'s limits.++ Tries cgroup v2 first, then falls back to v1. Raises+ :class:`CgroupSetupError` if neither backend is available or any of+ the writes fails; callers should treat that as a sandbox-create+ failure.+ """+ if policy.is_empty():+ raise ValueError(+ "cgroup.setup called with an empty policy; caller must "+ "check CgroupPolicy.is_empty() and skip cgroup entirely"+ )+ backend = detect_backend()+ if backend is None:+ raise CgroupSetupError(+ "no writable cgroup backend available: cgroup v2 "+ f"({_CGROUP_ROOT}/cgroup.controllers) is missing/incomplete "+ "and cgroup v1 controllers (memory/cpu/pids) are not mounted"+ )+ if backend is CgroupBackend.V2:+ return _setup_v2(sandbox_id, policy)+ return _setup_v1(sandbox_id, policy)+++# ---------------------------------------------------------------------------+# Attach+# ---------------------------------------------------------------------------+++def attach(handle: CgroupHandle, pid: int) -> None:+ """Migrate ``pid`` into every cgroup directory associated with ``handle``.++ Writing the PID into ``cgroup.procs`` moves both the process and its+ threads; future forks automatically inherit the cgroup, so attaching+ the freshly-spawned bwrap PID is sufficient to constrain the entire+ sandbox subtree.+ """+ if not handle.paths:+ return+ for group_dir in handle.paths:+ procs_file = group_dir / "cgroup.procs"+ try:+ _write_file(procs_file, str(pid))+ except OSError as exc:+ raise CgroupSetupError(+ f"failed to attach pid {pid} to {procs_file}: "+ f"{exc.strerror or exc}"+ ) from exc+++# ---------------------------------------------------------------------------+# Teardown+# ---------------------------------------------------------------------------+++def _kill_cgroup_processes(group_dir: Path, backend: CgroupBackend) -> None:+ """Best-effort: ask the kernel to kill anything still in the cgroup.++ On v2 ``cgroup.kill`` does this atomically with a single write of+ ``"1"``. On v1 the controller hierarchies don't have ``cgroup.kill``;+ we read ``cgroup.procs`` and ``kill(SIGKILL)`` each PID individually.+ Both paths swallow ``OSError`` since teardown should never block+ sandbox deletion.+ """+ if backend is CgroupBackend.V2:+ kill_file = group_dir / "cgroup.kill"+ if kill_file.exists():+ try:+ _write_file(kill_file, "1")+ except OSError as exc:+ logger.warning(+ "cgroup teardown: failed to write %s: %s", kill_file, exc+ )+ return+ procs_file = group_dir / "cgroup.procs"+ try:+ raw = procs_file.read_text(encoding="utf-8")+ except OSError:+ return+ for line in raw.splitlines():+ try:+ pid = int(line.strip())+ except ValueError:+ continue+ if pid <= 1:+ continue+ try:+ os.kill(pid, 9) # SIGKILL+ except OSError:+ pass+++def _rmdir_with_retry(group_dir: Path) -> bool:+ """Attempt ``rmdir`` with short backoff while EBUSY is reported.++ Returns True on success, False when the cgroup was still busy after+ the configured retries. Callers should only log a warning on failure+ rather than propagating: a stuck cgroup is unfortunate but doesn't+ block sandbox cleanup from the user's perspective.+ """+ for attempt in range(_TEARDOWN_RETRIES):+ try:+ group_dir.rmdir()+ return True+ except FileNotFoundError:+ return True+ except OSError as exc:+ if attempt + 1 == _TEARDOWN_RETRIES:+ logger.warning(+ "cgroup teardown: %s still busy after %d attempts (%s)",+ group_dir,+ _TEARDOWN_RETRIES,+ exc,+ )+ return False+ time.sleep(_TEARDOWN_BACKOFF_SECONDS)+ return False+++def teardown(handle: CgroupHandle) -> None:+ """Remove the cgroup(s) associated with ``handle``.++ First nudges out any straggler processes (via ``cgroup.kill`` on v2 or+ a manual SIGKILL loop on v1), then rmdir-s each directory with a+ short retry loop. Failures only emit a warning and never propagate -+ sandbox deletion must remain idempotent and side-effect-free for the+ caller's perspective.+ """+ for group_dir in handle.paths:+ if not group_dir.exists():+ continue+ _kill_cgroup_processes(group_dir, handle.backend)+ # Give the kernel a brief moment to flush the killed processes+ # before we attempt rmdir; the retry loop in _rmdir_with_retry+ # handles the still-EBUSY case.+ time.sleep(_TEARDOWN_BACKOFF_SECONDS)+ if not _rmdir_with_retry(group_dir):+ # Last-ditch effort: try a non-recursive rmtree to clean up+ # if rmdir keeps failing (e.g. leftover sub-cgroups created+ # by some user code inside the sandbox). shutil.rmtree on a+ # cgroup dir is generally a no-op because the interface+ # files cannot be unlinked, but it's harmless on success.+ try:+ shutil.rmtree(group_dir, ignore_errors=True)+ except OSError:+ passdiff --git a/jiuwenbox/tests/conftest.py b/jiuwenbox/tests/conftest.pyindex 6701cba450..9da9f6fb5e 100644--- a/jiuwenbox/tests/conftest.py+++ b/jiuwenbox/tests/conftest.py@@ -17,7 +17,10 @@ def pytest_addoption(parser):"--server-endpoint",action="store",default=None,- help="Server endpoint (host:port or URL). Default: 127.0.0.1:8321",+ help=(+ "Server endpoint. Accepts 'host:port', 'http://host:port', or "+ "'unix:///abs/socket/path'. Default: 127.0.0.1:8321"+ ),)parser.addoption("--proxy-port",@@ -46,9 +49,12 @@ def pytest_addoption(parser):)-def server_endpoint(pytestconfig) -> str:- """Server endpoint as host:port or URL string."""+def _is_uds_endpoint(endpoint: str) -> bool:+ """Whether ``endpoint`` 指向 Unix Domain Socket (scheme ``unix://``)."""+ return endpoint.startswith("unix://")+++def _resolve_raw_endpoint(pytestconfig) -> str:return (pytestconfig.getoption("server_endpoint")or os.environ.get("JIUWENBOX_TEST_SERVER")@@ -56,6 +62,19 @@ def server_endpoint(pytestconfig) -> str:)+def _normalize_endpoint_url(endpoint: str) -> str:+ """Turn ``host:port`` / ``http://host:port`` / ``unix:///path`` 一律转成完整 URL."""+ if "://" in endpoint:+ return endpoint+ return f"http://{endpoint}"+++def server_endpoint(pytestconfig) -> str:+ """Server endpoint as host:port, http(s)://... or unix:///abs/path string."""+ return _resolve_raw_endpoint(pytestconfig)++@pytest.fixturedef proxy_port(pytestconfig) -> int:"""Proxy listen port."""@@ -67,7 +86,17 @@ def proxy_port(pytestconfig) -> int:@pytest.fixturedef server_host_port(server_endpoint):- """Parse server_endpoint into (host, port) tuple."""+ """Parse server_endpoint into (host, port) tuple.++ UDS 端点没有 host/port 概念 (socket 文件本身就是 listener); 需要它的+ fixture (proxy / docker-gateway 探测等) 在 UDS 模式下统一 ``skip``,+ 避免在源头解析阶段抛 ``ValueError``。+ """+ if _is_uds_endpoint(server_endpoint):+ pytest.skip(+ "fixture requires TCP endpoint; server is configured for UDS "+ f"({server_endpoint!r})",+ )endpoint = server_endpointif "://" in endpoint:endpoint = endpoint.split("://", 1)[1]@@ -77,29 +106,29 @@ def server_host_port(server_endpoint):@pytest.fixturedef server_url(server_endpoint):- """Server endpoint as full URL."""- return server_endpoint if "://" in server_endpoint else f"http://{server_endpoint}"+ """Server endpoint as full URL.++ TCP 端点补 ``http://`` 前缀; UDS 端点 (``unix:///path``) 直接透传——+ 下游 httpx fixture 与 jiuwenbox CLI 的 ``--base-url`` 都识别这种 scheme。+ """+ return _normalize_endpoint_url(server_endpoint)@pytest.fixture(scope="session")def server_url_session(pytestconfig):- """Session-scoped server URL."""- endpoint = (- pytestconfig.getoption("server_endpoint")- or os.environ.get("JIUWENBOX_TEST_SERVER")- or "127.0.0.1:8321"- )- return endpoint if "://" in endpoint else f"http://{endpoint}"+ """Session-scoped server URL (与 :func:`server_url` 同语义)."""+ return _normalize_endpoint_url(_resolve_raw_endpoint(pytestconfig))@pytest.fixture(scope="session")def server_host_port_session(pytestconfig):- """Session-scoped parsed host and port."""- endpoint = (- pytestconfig.getoption("server_endpoint")- or os.environ.get("JIUWENBOX_TEST_SERVER")- or "127.0.0.1:8321"- )+ """Session-scoped parsed host and port (UDS 模式 skip)."""+ endpoint = _resolve_raw_endpoint(pytestconfig)+ if _is_uds_endpoint(endpoint):+ pytest.skip(+ "fixture requires TCP endpoint; server is configured for UDS "+ f"({endpoint!r})",+ )if "://" in endpoint:endpoint = endpoint.split("://", 1)[1]host, port = endpoint.rsplit(":", 1)diff --git a/jiuwenbox/tests/integration/conftest.py b/jiuwenbox/tests/integration/conftest.pyindex 22b455aa4b..65a8e9add5 100644--- a/jiuwenbox/tests/integration/conftest.py+++ b/jiuwenbox/tests/integration/conftest.py@@ -90,13 +90,40 @@ class SandboxTrackingClient:return suffix or None+_UDS_SCHEME = "unix://"+# httpx 在用 UDS transport 时仍需要一个合法 absolute base_url 才能拼相对路径;+# 实际请求路由完全走 socket transport, 不读 host。+_UDS_PLACEHOLDER_BASE_URL = "http://jiuwenbox"++def _normalize_endpoint(endpoint: str) -> str:return endpoint if "://" in endpoint else f"http://{endpoint}"+def _build_httpx_client(endpoint: str, *, timeout: float = 30.0) -> httpx.Client:+ """按 endpoint scheme 构造 httpx.Client (UDS / TCP 统一入口).++ ``unix:///abs/path`` 走 :class:`httpx.HTTPTransport` 的 ``uds=...``;+ 其它形式走 base_url 模式。两种模式对 ``SandboxTrackingClient`` 透明,+ 因此 ``test_server_api_default.py`` 业务断言一行不用改。+ """+ if endpoint.startswith(_UDS_SCHEME):+ uds_path = endpoint[len(_UDS_SCHEME):]+ if not uds_path.startswith("/"):+ raise ValueError(+ f"unix endpoint requires absolute path: {endpoint!r}",+ )+ return httpx.Client(+ transport=httpx.HTTPTransport(uds=uds_path),+ base_url=_UDS_PLACEHOLDER_BASE_URL,+ timeout=timeout,+ )+ return httpx.Client(base_url=_normalize_endpoint(endpoint), timeout=timeout)++@pytest.fixturedef client(server_endpoint):- with httpx.Client(base_url=_normalize_endpoint(server_endpoint), timeout=30.0) as external:+ with _build_httpx_client(server_endpoint, timeout=30.0) as external:tracking = SandboxTrackingClient(external)try:yield tracking@@ -256,6 +283,14 @@ def docker_gateway_ip(Raises:RuntimeError: If API server unreachable or topology detection fails"""+ if server_url_session.startswith(_UDS_SCHEME):+ # Docker-gateway 探测 + IPP 端口联通性测试天然依赖 TCP listener; UDS+ # 模式下整套 proxy/IPP 用例都该 skip, 在源头一次性 skip 简化下游。+ pytest.skip(+ "docker gateway detection requires a TCP server endpoint; "+ f"got {server_url_session!r}",+ )+port = http_target_portlogger.info("[docker_gateway_ip] Starting checks")diff --git a/jiuwenbox/tests/integration/test_cli_default.py b/jiuwenbox/tests/integration/test_cli_default.pynew file mode 100644index 0000000000..a258053e30--- /dev/null+++ b/jiuwenbox/tests/integration/test_cli_default.py@@ -0,0 +1,687 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""端到端 CLI 集成测试.++仅做端到端: 通过 ``subprocess.run`` 真实拉起已安装的 ``jiuwenbox`` 可执行脚本+(由 ``pyproject.toml`` 的 ``[project.scripts]`` 声明, 类似 ``uvicorn``),+断言 stdout / stderr / 退出码 / HTTP 副作用; 不写单元测试、不 mock httpx。++运行测试前请先在仓库根 (``code_agent/jiuwenbox/``) 安装本包::++ pip install -e .++若 ``jiuwenbox`` 不在 PATH 上, 测试会自动到 ``sys.executable`` 同级目录寻找;+均找不到则在 collect 阶段直接报错并提示安装方式。++假设 jiuwenbox server 已在运行 (与既有 ``test_server_api_default.py`` 一致),+由 ``--server-endpoint`` 或 ``JIUWENBOX_TEST_SERVER`` 指定。+"""++from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import time+from pathlib import Path++import pytest++pytestmark = pytest.mark.integration+++def _resolve_jiuwenbox_bin() -> str:+ """定位已安装的 ``jiuwenbox`` 可执行脚本。++ 查找顺序:+ 1. ``PATH`` 上的 ``jiuwenbox`` / ``jiuwenbox.exe``;+ 2. 当前 Python 解释器同级目录 (venv ``bin/`` 或 ``Scripts/``);+ 3. 找不到则报错, 提示先 ``pip install -e .``。+ """+ found = shutil.which("jiuwenbox")+ if found:+ return found+ py_dir = Path(sys.executable).resolve().parent+ candidates = [py_dir / "jiuwenbox", py_dir / "jiuwenbox.exe"]+ # venv 上 ``python`` 可能在 ``bin/``, scripts 也在 ``bin/``; Windows venv+ # 则 ``python.exe`` 与 ``jiuwenbox.exe`` 同在 ``Scripts/``。+ for candidate in candidates:+ if candidate.is_file():+ return str(candidate)+ raise RuntimeError(+ "jiuwenbox CLI is not installed. Run `pip install -e .` from "+ "`code_agent/jiuwenbox/` before running the CLI integration tests.",+ )+++_JIUWENBOX_BIN = _resolve_jiuwenbox_bin()+++_PROXY_ENV_VARS = (+ "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY",+ "http_proxy", "https_proxy", "all_proxy",+)+++def _subprocess_env(extra_env: dict[str, str] | None = None) -> dict[str, str]:+ """为子进程构造环境变量。++ 本测试运行已安装的脚本, 无需再注入 ``PYTHONPATH``;+ 保留 ``NO_COLOR`` 以确保 stderr 不含 ANSI 转义码, 便于断言。+ """+ env = os.environ.copy()+ for key in _PROXY_ENV_VARS:+ env.pop(key, None)+ env["NO_PROXY"] = "*"+ env["no_proxy"] = "*"+ env.setdefault("NO_COLOR", "1")+ if extra_env:+ env.update(extra_env)+ return env+++def _run_cli(+ args: list[str],+ *,+ base_url: str | None = None,+ extra_env: dict[str, str] | None = None,+ input_bytes: bytes | None = None,+ timeout: float = 60.0,+ check: bool = False,+) -> subprocess.CompletedProcess:+ """运行 CLI 并返回 ``CompletedProcess`` (stdout/stderr 为 bytes)。"""+ cmd: list[str] = [_JIUWENBOX_BIN]+ if base_url is not None:+ cmd += ["--base-url", base_url]+ cmd += args+ return subprocess.run(+ cmd,+ input=input_bytes,+ capture_output=True,+ timeout=timeout,+ check=check,+ env=_subprocess_env(extra_env),+ )+++def _run_cli_json(args: list[str], *, base_url: str, **kwargs) -> tuple[subprocess.CompletedProcess, object]:+ """运行 CLI, 期待 stdout 是合法 JSON, 返回 (proc, parsed_json)。"""+ proc = _run_cli(args, base_url=base_url, **kwargs)+ assert proc.returncode == 0, (+ f"CLI exited {proc.returncode}\n"+ f"args={args!r}\nstdout={proc.stdout!r}\nstderr={proc.stderr!r}"+ )+ return proc, json.loads(proc.stdout.decode("utf-8"))+++def _wait_phase(client, sandbox_id: str, phase: str, *, timeout: float = 10.0) -> dict:+ """轮询直到 ``sandbox.phase == phase`` 或超时, 返回最后一次 state。"""+ deadline = time.monotonic() + timeout+ state: dict = {}+ while time.monotonic() < deadline:+ response = client.get(f"/api/v1/sandboxes/{sandbox_id}")+ if response.status_code == 200:+ state = response.json()+ if state.get("phase") == phase:+ return state+ time.sleep(0.3)+ raise AssertionError(+ f"sandbox {sandbox_id} did not reach phase={phase} within {timeout}s; "+ f"last state: {state}"+ )+++def tracking_sandboxes(client):+ """模块内手动登记 sandbox_id, 测试结束兜底删除。"""+ ids: list[str] = []+ yield ids+ for sandbox_id in reversed(ids):+ try:+ client.delete(f"/api/v1/sandboxes/{sandbox_id}")+ except Exception: # noqa: BLE001+ pass+++def _create_sandbox_via_cli(server_url: str, tracking_sandboxes: list[str]) -> str:+ """CLI 创建 sandbox, 登记到 tracking 列表, 返回 sandbox_id。"""+ proc, data = _run_cli_json(["sandbox", "create"], base_url=server_url)+ assert isinstance(data, dict), data+ sandbox_id = data.get("id")+ assert isinstance(sandbox_id, str) and sandbox_id, data+ tracking_sandboxes.append(sandbox_id)+ return sandbox_id+++# ────────────────────────────── health ──────────────────────────────+++def test_cli_health_ok(server_url):+ proc, data = _run_cli_json(["health"], base_url=server_url)+ assert isinstance(data, dict)+ assert data.get("status") == "ok"+++def test_cli_health_plain(server_url):+ proc = _run_cli(["--output", "plain", "health"], base_url=server_url)+ assert proc.returncode == 0, proc.stderr+ assert proc.stdout.strip() == b"ok"++# ────────────────────────────── sandbox ──────────────────────────────+++def test_cli_sandbox_create_and_get(server_url, tracking_sandboxes):+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)++ proc, data = _run_cli_json(+ ["sandbox", "get", sandbox_id], base_url=server_url,+ )+ assert data.get("id") == sandbox_id+ assert data.get("phase") in ("ready", "provisioning", "stopped")+++def test_cli_sandbox_ls(server_url, tracking_sandboxes):+ _create_sandbox_via_cli(server_url, tracking_sandboxes)++ proc, data = _run_cli_json(["sandbox", "ls"], base_url=server_url)+ assert isinstance(data, list)+ assert len(data) >= 1++ proc_tbl = _run_cli(+ ["--output", "table", "sandbox", "ls"], base_url=server_url,+ )+ assert proc_tbl.returncode == 0, proc_tbl.stderr+ assert b"ID" in proc_tbl.stdout and b"PHASE" in proc_tbl.stdout+++def test_cli_sandbox_ls_plain_lists_ids(server_url, tracking_sandboxes):+ """``--output plain`` 配合 ``PLAIN_FIELD=id`` 每行一个 sandbox id。"""+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)++ proc = _run_cli(+ ["--output", "plain", "sandbox", "ls"], base_url=server_url,+ )+ assert proc.returncode == 0, proc.stderr+ lines = [line for line in proc.stdout.decode("utf-8").splitlines() if line.strip()]+ assert sandbox_id in lines, (sandbox_id, lines)+++def test_cli_sandbox_ls_phase_filter(server_url, tracking_sandboxes, client):+ """``--phase`` 在 CLI 侧本地过滤; 不匹配时返回空列表。"""+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ _, ready = _run_cli_json(+ ["sandbox", "ls", "--phase", "ready"], base_url=server_url,+ )+ assert isinstance(ready, list)+ assert sandbox_id in {item.get("id") for item in ready if isinstance(item, dict)}++ _, empty = _run_cli_json(+ ["sandbox", "ls", "--phase", "no_such_phase"], base_url=server_url,+ )+ assert empty == []+++def test_cli_sandbox_lifecycle(server_url, tracking_sandboxes, client):+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ _, stopped = _run_cli_json(+ ["sandbox", "stop", sandbox_id], base_url=server_url,+ )+ assert stopped.get("phase") == "stopped"++ _, started = _run_cli_json(+ ["sandbox", "start", sandbox_id], base_url=server_url,+ )+ assert started.get("phase") == "ready"++ _, restarted = _run_cli_json(+ ["sandbox", "restart", sandbox_id], base_url=server_url,+ )+ assert restarted.get("phase") == "ready"+++def test_cli_sandbox_exec_stdout_and_exitcode(server_url, tracking_sandboxes, client):+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ proc = _run_cli(+ [+ "sandbox", "exec", sandbox_id, "--",+ "python3", "-c", "print(7); import sys; sys.exit(3)",+ ],+ base_url=server_url,+ )+ assert proc.returncode == 3, (proc.stdout, proc.stderr)+ assert proc.stdout.strip() == b"7"+++def test_cli_sandbox_exec_stderr(server_url, tracking_sandboxes, client):+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ proc = _run_cli(+ [+ "sandbox", "exec", sandbox_id, "--",+ "python3", "-c", "import sys; sys.stderr.write('e_marker')",+ ],+ base_url=server_url,+ )+ assert proc.returncode == 0, proc.stderr+ assert b"e_marker" in proc.stderr+++def test_cli_sandbox_exec_stdin_dash(server_url, tracking_sandboxes, client):+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ proc = _run_cli(+ [+ "sandbox", "exec", sandbox_id, "--stdin", "-", "--",+ "cat",+ ],+ base_url=server_url,+ input_bytes=b"hello from stdin",+ )+ assert proc.returncode == 0, proc.stderr+ assert proc.stdout == b"hello from stdin"+++def test_cli_sandbox_exec_json_output(server_url, tracking_sandboxes, client):+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ proc = _run_cli(+ [+ "--output", "json",+ "sandbox", "exec", sandbox_id, "--",+ "python3", "-c", "print('hi'); import sys; sys.exit(5)",+ ],+ base_url=server_url,+ )+ assert proc.returncode == 5, (proc.stdout, proc.stderr)+ payload = json.loads(proc.stdout.decode("utf-8"))+ assert payload.get("exit_code") == 5+ assert "hi" in (payload.get("stdout") or "")+++def test_cli_sandbox_exec_env_cwd(server_url, tracking_sandboxes, client):+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ proc = _run_cli(+ [+ "sandbox", "exec", sandbox_id,+ "--cwd", "/tmp",+ "--env", "MY_TEST_VAR=marker42",+ "--",+ "python3", "-c",+ "import os; print(os.environ.get('MY_TEST_VAR')); print(os.getcwd())",+ ],+ base_url=server_url,+ )+ assert proc.returncode == 0, proc.stderr+ out_text = proc.stdout.decode("utf-8")+ assert "marker42" in out_text+ assert "/tmp" in out_text+++def test_cli_sandbox_exec_missing_command(server_url, tracking_sandboxes, client):+ """``sandbox exec`` 不带任何命令时应抛 ``_CliError`` → exit 3。"""+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ proc = _run_cli(+ ["sandbox", "exec", sandbox_id], base_url=server_url,+ )+ assert proc.returncode == 3, (proc.stdout, proc.stderr)+ assert b"missing command" in proc.stderr+++def test_cli_sandbox_exec_stdin_inline(server_url, tracking_sandboxes, client):+ """``--stdin <text>``: 直接把命令行参数作为 stdin 喂给沙箱命令。"""+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ proc = _run_cli(+ [+ "sandbox", "exec", sandbox_id,+ "--stdin", "inline-payload",+ "--", "cat",+ ],+ base_url=server_url,+ )+ assert proc.returncode == 0, proc.stderr+ assert proc.stdout == b"inline-payload"+++def test_cli_sandbox_exec_timeout_seconds(server_url, tracking_sandboxes, client):+ """``--timeout-seconds`` 透传到沙箱; 极短超时 + 长 sleep → 非零退出。"""+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ proc = _run_cli(+ [+ "sandbox", "exec", sandbox_id,+ "--timeout-seconds", "1",+ "--",+ "python3", "-c", "import time; time.sleep(30); print('should-not-print')",+ ],+ base_url=server_url,+ timeout=30.0,+ )+ # 超时后沙箱 kill 进程; 不绑定具体退出码 (137/124/-9/etc 都可能),+ # 只断言"没有完整执行" + "退出码非零"。+ assert proc.returncode != 0, (proc.stdout, proc.stderr)+ assert b"should-not-print" not in proc.stdout+++def test_cli_sandbox_exec_bg(server_url, tracking_sandboxes, client):+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ proc, data = _run_cli_json(+ [+ "sandbox", "exec-bg", sandbox_id, "--",+ "python3", "-c", "import time; time.sleep(60)",+ ],+ base_url=server_url,+ )+ assert isinstance(data, dict)+ assert data.get("started") is True+ assert isinstance(data.get("pid"), int) and data["pid"] > 0+++def test_cli_sandbox_upload_download_roundtrip(+ server_url, tracking_sandboxes, client, tmp_path,+):+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ payload = b"hello-roundtrip\n\x00\x01binary\xff"+ local = tmp_path / "src.bin"+ local.write_bytes(payload)+ remote = "/tmp/roundtrip.bin"++ up = _run_cli(+ [+ "sandbox", "upload", sandbox_id,+ str(local), remote,+ ],+ base_url=server_url,+ )+ assert up.returncode == 0, up.stderr++ down = _run_cli(+ ["sandbox", "download", sandbox_id, remote, "-"],+ base_url=server_url,+ )+ assert down.returncode == 0, down.stderr+ assert down.stdout == payload+++def test_cli_sandbox_upload_from_stdin(server_url, tracking_sandboxes, client):+ """``upload <id> - <remote>``: 把 host stdin 的内容写入沙箱文件。"""+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ payload = b"from-stdin-content\nbinary:\x00\x7f"+ remote = "/tmp/from-stdin.bin"++ up = _run_cli(+ ["sandbox", "upload", sandbox_id, "-", remote],+ base_url=server_url,+ input_bytes=payload,+ )+ assert up.returncode == 0, up.stderr++ down = _run_cli(+ ["sandbox", "download", sandbox_id, remote, "-"],+ base_url=server_url,+ )+ assert down.returncode == 0, down.stderr+ assert down.stdout == payload+++def test_cli_sandbox_upload_local_not_found(+ server_url, tracking_sandboxes, client, tmp_path,+):+ """本地路径不存在 → CLI 抛 ``_CliError`` → exit 3 (不打到 server)。"""+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ missing = tmp_path / "definitely-missing.bin"+ proc = _run_cli(+ ["sandbox", "upload", sandbox_id, str(missing), "/tmp/x.bin"],+ base_url=server_url,+ )+ assert proc.returncode == 3, (proc.stdout, proc.stderr)+ assert b"local file not found" in proc.stderr+++def test_cli_sandbox_download_to_file(+ server_url, tracking_sandboxes, client, tmp_path,+):+ """``download <id> <remote> <local_path>``: 写到本地文件而非 stdout。"""+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ payload = b"download-target\x00\xfe"+ src = tmp_path / "src.bin"+ src.write_bytes(payload)+ remote = "/tmp/download-target.bin"+ _run_cli(+ ["sandbox", "upload", sandbox_id, str(src), remote],+ base_url=server_url, check=True,+ )++ dst = tmp_path / "downloaded.bin"+ proc = _run_cli(+ ["sandbox", "download", sandbox_id, remote, str(dst)],+ base_url=server_url,+ )+ assert proc.returncode == 0, proc.stderr+ assert dst.read_bytes() == payload+ # 写文件路径时, 进度提示应落在 stderr 而不是 stdout, stdout 不应有内容。+ assert proc.stdout == b""+++def test_cli_sandbox_files(server_url, tracking_sandboxes, client, tmp_path):+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ local = tmp_path / "sample.txt"+ local.write_bytes(b"hello")+ _run_cli(+ [+ "sandbox", "upload", sandbox_id,+ str(local), "/tmp/sample.txt",+ ],+ base_url=server_url, check=True,+ )++ proc, data = _run_cli_json(+ [+ "sandbox", "files", sandbox_id, "/tmp",+ "--recursive", "--max-depth", "2",+ ],+ base_url=server_url,+ )+ assert isinstance(data, list)+ paths = {item.get("path") for item in data if isinstance(item, dict)}+ assert "/tmp/sample.txt" in paths+++def test_cli_sandbox_files_no_dirs(+ server_url, tracking_sandboxes, client, tmp_path,+):+ """``--no-dirs`` 只返回文件项, 不包含目录条目。"""+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ local = tmp_path / "only-file.txt"+ local.write_bytes(b"hi")+ _run_cli(+ ["sandbox", "upload", sandbox_id, str(local), "/tmp/only-file.txt"],+ base_url=server_url, check=True,+ )++ proc, data = _run_cli_json(+ [+ "sandbox", "files", sandbox_id, "/tmp",+ "--recursive", "--max-depth", "2",+ "--no-dirs",+ ],+ base_url=server_url,+ )+ assert isinstance(data, list)+ for item in data:+ assert isinstance(item, dict), data+ assert item.get("is_directory") is False, item+ paths = {item.get("path") for item in data}+ assert "/tmp/only-file.txt" in paths+++def test_cli_sandbox_find(server_url, tracking_sandboxes, client, tmp_path):+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ local = tmp_path / "hit.txt"+ local.write_bytes(b"x")+ _run_cli(+ [+ "sandbox", "upload", sandbox_id,+ str(local), "/tmp/hit.txt",+ ],+ base_url=server_url, check=True,+ )++ proc, data = _run_cli_json(+ ["sandbox", "find", sandbox_id, "/tmp", "*.txt"],+ base_url=server_url,+ )+ assert isinstance(data, list)+ paths = {item.get("path") for item in data if isinstance(item, dict)}+ assert "/tmp/hit.txt" in paths+++def test_cli_sandbox_create_policy_file_not_found(server_url, tmp_path):+ """``--policy-file`` 指向不存在路径 → ``_CliError`` → exit 3。"""+ missing = tmp_path / "no-such.json"+ proc = _run_cli(+ ["sandbox", "create", "--policy-file", str(missing)],+ base_url=server_url,+ )+ assert proc.returncode == 3, (proc.stdout, proc.stderr)+ assert b"policy file not found" in proc.stderr+++def test_cli_sandbox_create_policy_file_invalid_json(server_url, tmp_path):+ """``--policy-file`` 内容非合法 JSON → 本地解析失败 → exit 3。"""+ bad = tmp_path / "bad.json"+ bad.write_text("{not valid json,,,", encoding="utf-8")+ proc = _run_cli(+ ["sandbox", "create", "--policy-file", str(bad)],+ base_url=server_url,+ )+ assert proc.returncode == 3, (proc.stdout, proc.stderr)+ assert b"not valid JSON" in proc.stderr+++def test_cli_sandbox_rm_yes(server_url, tracking_sandboxes, client):+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)++ proc = _run_cli(+ ["sandbox", "rm", sandbox_id, "--yes"],+ base_url=server_url,+ )+ assert proc.returncode == 0, proc.stderr+ # 之后 GET 应为 404+ response = client.get(f"/api/v1/sandboxes/{sandbox_id}")+ assert response.status_code == 404+++def test_cli_sandbox_rm_not_found(server_url):+ proc = _run_cli(+ ["sandbox", "rm", "nonexistent-id-12345", "--yes"],+ base_url=server_url,+ )+ assert proc.returncode == 1, (proc.stdout, proc.stderr)+ assert b"HTTP 404" in proc.stderr+++# ────────────────────────────── policy ──────────────────────────────+++def test_cli_policy_get(server_url, tracking_sandboxes, client):+ sandbox_id = _create_sandbox_via_cli(server_url, tracking_sandboxes)+ _wait_phase(client, sandbox_id, "ready")++ proc, data = _run_cli_json(+ ["policy", "get", sandbox_id], base_url=server_url,+ )+ assert isinstance(data, dict)+ # policy 至少含 name 字段+ assert "name" in data+++def test_cli_policy_get_not_found(server_url):+ """policy get 不存在的 sandbox → HTTP 404 → exit 1 + stderr 含状态码。"""+ proc = _run_cli(+ ["policy", "get", "nonexistent-policy-target-9999"],+ base_url=server_url,+ )+ assert proc.returncode == 1, (proc.stdout, proc.stderr)+ assert b"HTTP 404" in proc.stderr+++# ────────────────────────────── global / parsing ──────────────────────────────+++def test_cli_global_env_var_base_url(server_url):+ # 不传 --base-url, 改用 JIUWENBOX_URL 环境变量+ proc = _run_cli(+ ["health"], base_url=None,+ extra_env={"JIUWENBOX_URL": server_url},+ )+ assert proc.returncode == 0, proc.stderr+ data = json.loads(proc.stdout.decode("utf-8"))+ assert data.get("status") == "ok"+++def test_cli_invalid_env_token(server_url):+ proc = _run_cli(+ ["sandbox", "create", "--env", "BAD_TOKEN"],+ base_url=server_url,+ )+ assert proc.returncode == 3, (proc.stdout, proc.stderr)+ assert b"KEY=VAL" in proc.stderr+++def test_cli_help_exits_zero():+ for args in (["--help"], ["sandbox", "--help"], ["sandbox", "exec", "--help"]):+ proc = _run_cli(args, base_url="http://127.0.0.1:8321")+ assert proc.returncode == 0, (args, proc.stdout, proc.stderr)+ assert proc.stdout, args+++def test_cli_unknown_subcommand(server_url):+ """未知顶层子命令 → argparse 报错并以非零退出。"""+ proc = _run_cli(["no_such_group"], base_url=server_url)+ assert proc.returncode != 0, (proc.stdout, proc.stderr)+ # argparse 把错误打到 stderr; 内容里通常含 ``invalid choice`` 或 ``usage:``。+ err = proc.stderr.lower()+ assert (b"invalid choice" in err) or (b"usage:" in err), proc.stderr+++def test_cli_verbose_debug_logs(server_url):+ """``-v`` 开启 DEBUG 日志, ``_CliClient`` 的 GET 调试行应出现在 stderr 上。"""+ proc = _run_cli(["-v", "health"], base_url=server_url)+ assert proc.returncode == 0, proc.stderr+ # 至少能看到 DEBUG 标记 (logging.basicConfig 格式: "%(levelname)s") 或 GET 请求行。+ err = proc.stderr+ assert b"DEBUG" in err, err+ assert b"GET" in err and b"/health" in err, err\ No newline at end of filediff --git a/jiuwenbox/tests/integration/test_server_api_default.py b/jiuwenbox/tests/integration/test_server_api_default.pyindex 405804f6c4..bf334fab86 100644--- a/jiuwenbox/tests/integration/test_server_api_default.py+++ b/jiuwenbox/tests/integration/test_server_api_default.py@@ -3,9 +3,11 @@import copyimport logging+import posixpathimport socketimport textwrapimport time+import uuidfrom pathlib import Pathimport httpx@@ -78,11 +80,54 @@ class SandboxTrackingClient:return suffix or None+_UDS_SCHEME = "unix://"+# httpx UDS transport 仍要求一个合法 absolute base_url 才能拼相对路径; 实际+# 请求由 socket transport 接管, 这个 host 字段不会被解析。与+# ``tests/integration/conftest.py`` 中的 ``_UDS_PLACEHOLDER_BASE_URL`` 保持一致。+_UDS_PLACEHOLDER_BASE_URL = "http://jiuwenbox"+++def _is_uds_endpoint(endpoint: str) -> bool:+ return endpoint.startswith(_UDS_SCHEME)++def _normalize_endpoint(endpoint: str) -> str:return endpoint if "://" in endpoint else f"http://{endpoint}"+def _build_httpx_client(endpoint: str, *, timeout: float = 30.0) -> httpx.Client:+ """按 endpoint scheme 构造 httpx.Client (与 conftest._build_httpx_client 同语义).++ 存在的原因: 本文件原先有一份本地 ``client`` fixture, 覆盖了 conftest 里+ UDS-aware 的版本。保留本地 fixture 是为了让用例显式可见, 但实现委托给+ 这个工厂, 避免再写一份 base_url + transport 的分叉逻辑。+ """+ if _is_uds_endpoint(endpoint):+ uds_path = endpoint[len(_UDS_SCHEME):]+ if not uds_path.startswith("/"):+ raise ValueError(f"unix endpoint requires absolute path: {endpoint!r}")+ return httpx.Client(+ transport=httpx.HTTPTransport(uds=uds_path),+ base_url=_UDS_PLACEHOLDER_BASE_URL,+ timeout=timeout,+ )+ return httpx.Client(base_url=_normalize_endpoint(endpoint), timeout=timeout)++def _sandbox_health_url(server_endpoint: str) -> str:+ """构造一个"从沙箱内 urlopen 回服务端 /health"的 URL.++ 这个 helper 只在两处用到, 都是"isolated 沙箱不能反向连服务端"类的网络+ 隔离断言。UDS 模式下服务端根本没暴露 TCP listener, 沙箱无论隔离与否+ 都拿不到一个可拨号的 host:port, 该断言失去意义—— ``pytest.skip`` 而+ 不是返回一个 ``unix://`` URL (urllib 会以 ``unknown url type`` 提前+ 报错, 看上去像通过了, 实际并未验证隔离)。+ """+ if _is_uds_endpoint(server_endpoint):+ pytest.skip(+ "sandbox-to-host TCP isolation test needs a TCP server endpoint; "+ f"got {server_endpoint!r}"+ )return f"{_normalize_endpoint(server_endpoint).rstrip('/')}/health"@@ -252,7 +297,7 @@ def _has_arg_pair(args: list[str], flag: str, value: str) -> bool:@pytest.fixturedef client(server_endpoint):- with httpx.Client(base_url=_normalize_endpoint(server_endpoint), timeout=30.0) as external:+ with _build_httpx_client(server_endpoint, timeout=30.0) as external:tracking = SandboxTrackingClient(external)try:yield tracking@@ -2855,3 +2900,1194 @@ class TestSandboxListing:resp = client.get("/api/v1/sandboxes")assert resp.status_code == 200assert len(resp.json()) == 3+++def _run_python(client, sandbox_id: str, source: str, *, timeout: int = 10):+ """Run a snippet of Python in the sandbox and return the parsed exec result."""+ response = client.post(+ f"/api/v1/sandboxes/{sandbox_id}/exec",+ json={+ "command": ["python3", "-c", source],+ "timeout_seconds": timeout,+ },+ )+ assert response.status_code == 200, response.text+ return response.json()+++# bind_root_entries fixture layout. Each entry is (relative path, contents):+# * subdirs are auto-created+# * regular files get the listed bytes written verbatim+# * dot-prefixed names exercise ``include_hidden`` semantics+# The mirror of this layout lives on the box-server's filesystem (not on the+# pytest host) because the box-server typically runs inside Docker and the+# test process runs outside; see ``_seed_bind_root_entries_host_tree`` for the+# rationale.+_BIND_ROOT_ENTRIES_LAYOUT: list[tuple[str, str]] = [+ ("file1.txt", "hello-file1"),+ ("nested_dir/inner.txt", "hello-inner"),+ (".hidden.txt", "secret"),+ ("skip_me/sentinel", "x"),+]+++def _seed_bind_root_entries_host_tree(+ client,+ tracked_ids: list[str],+ *,+ fixture_label: str,+) -> str:+ """Seed a fixed bind_root_entries layout on the box-server's filesystem.++ The integration suite typically runs the box-server inside Docker while+ the pytest process runs on the host, so ``tmp_path`` is not visible to+ ``bind_root_entries`` (which resolves paths in the box-server's mount+ namespace). To work around that we spin up a short-lived "setup sandbox"+ with ``/tmp`` bind-mounted to ``/host-tmp rw`` and seed the fixture there+ via a single ``exec`` Python script. The fixture directory lives under+ the box-server's ``/tmp`` and is returned as an absolute host path that+ can be plugged directly into ``bind_root_entries.host_root``.+ """+ fixture_dir_name = f"jiuwenbox-bind-root-entries-{fixture_label}-{uuid.uuid4().hex[:8]}"+ sandbox_setup_root = f"/host-tmp/{fixture_dir_name}"+ server_host_root = f"/tmp/{fixture_dir_name}"++ setup_resp = client.post(+ "/api/v1/sandboxes",+ json={+ "policy_mode": "override",+ "policy": _with_runtime_support({+ "name": f"bind-root-entries-setup-{fixture_label}",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp", "/host-tmp"],+ "bind_mounts": [{+ "host_path": "/tmp",+ "sandbox_path": "/host-tmp",+ "mode": "rw",+ }],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ }),+ },+ )+ assert setup_resp.status_code == 201, setup_resp.text+ setup_id = setup_resp.json()["id"]+ tracked_ids.append(setup_id)++ seed_script = textwrap.dedent(+ f"""+ import os+ import sys++ root = {sandbox_setup_root!r}+ layout = {_BIND_ROOT_ENTRIES_LAYOUT!r}++ os.makedirs(root, exist_ok=True)+ os.chmod(root, 0o755)+ for relpath, content in layout:+ target = os.path.join(root, relpath)+ os.makedirs(os.path.dirname(target), exist_ok=True)+ with open(target, "w") as fh:+ fh.write(content)+ os.chmod(target, 0o644)+ sys.exit(0)+ """+ ).strip()++ seed_result = _run_python(client, setup_id, seed_script, timeout=15)+ assert seed_result["exit_code"] == 0, seed_result++ # Tear the setup sandbox down right away; we keep the seeded files on the+ # box-server's /tmp until the cleanup fixture removes them. Keeping the+ # setup sandbox alive for the duration of the test would mean holding the+ # rw bind on /tmp open, which a stricter policy could legitimately reject.+ delete_resp = client.delete(f"/api/v1/sandboxes/{setup_id}")+ assert delete_resp.status_code in (200, 202, 204), delete_resp.text+ try:+ tracked_ids.remove(setup_id)+ except ValueError:+ pass++ return server_host_root+++def _cleanup_bind_root_entries_host_tree(+ client,+ tracked_ids: list[str],+ server_host_root: str,+) -> None:+ """Best-effort removal of files seeded into the box-server's /tmp."""+ if not server_host_root.startswith("/tmp/"):+ return+ cleanup_resp = client.post(+ "/api/v1/sandboxes",+ json={+ "policy_mode": "override",+ "policy": _with_runtime_support({+ "name": "bind-root-entries-cleanup",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp", "/host-tmp"],+ "bind_mounts": [{+ "host_path": "/tmp",+ "sandbox_path": "/host-tmp",+ "mode": "rw",+ }],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ }),+ },+ )+ if cleanup_resp.status_code != 201:+ logger.warning(+ "bind_root_entries cleanup: failed to start cleanup sandbox (%s)",+ cleanup_resp.text,+ )+ return+ cleanup_id = cleanup_resp.json()["id"]+ tracked_ids.append(cleanup_id)+ try:+ in_sandbox = posixpath.join("/host-tmp", server_host_root[len("/tmp/"):])+ client.post(+ f"/api/v1/sandboxes/{cleanup_id}/exec",+ json={+ "command": ["rm", "-rf", in_sandbox],+ "timeout_seconds": 10,+ },+ )+ finally:+ client.delete(f"/api/v1/sandboxes/{cleanup_id}")+ try:+ tracked_ids.remove(cleanup_id)+ except ValueError:+ pass+++def bind_root_entries_host_tree(client, request):+ """Yield an absolute host_root path on the box-server's filesystem.++ Each test gets a uniquely-named directory under the box-server's ``/tmp``+ seeded with ``_BIND_ROOT_ENTRIES_LAYOUT``. Cleanup is best-effort: even+ if the test crashes we run a cleanup sandbox to ``rm -rf`` the seeded+ directory so the box-server's /tmp doesn't accumulate test debris across+ sessions.+ """+ label = request.node.name.replace("test_", "")[:16]+ tracked: list[str] = []+ host_root = _seed_bind_root_entries_host_tree(+ client, tracked, fixture_label=label,+ )+ try:+ yield host_root+ finally:+ _cleanup_bind_root_entries_host_tree(client, tracked, host_root)+++class TestBindRootEntries:+ """End-to-end coverage for the ``filesystem_policy.bind_root_entries`` field.++ Each child entry (regular file or subdirectory) directly under ``host_root``+ is bind-mounted into ``sandbox_path/<child_name>`` with the configured+ uniform ``mode``. Hidden entries and excluded basenames are filtered out.+ These tests run against the default jiuwenbox server (which loads+ ``configs/default-policy.yaml``) but always supply their own+ ``filesystem_policy`` in the request, with ``_with_runtime_support`` layering+ the system bind_mounts and directories on top for a runnable rootfs.+ """++ @staticmethod+ def test_bind_root_entries_ro_default_lists_visible_children(+ client,+ create_sandbox_with_policy,+ bind_root_entries_host_tree,+ ):+ host_root = bind_root_entries_host_tree+ sandbox = create_sandbox_with_policy(+ name_prefix="bind-root-entries-ro",+ policy={+ "name": "bind-root-entries-ro-policy",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ "bind_root_entries": [{+ "host_root": host_root,+ "sandbox_path": "/mnt/data",+ "mode": "ro",+ }],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ },+ )++ listing = _run_python(+ client,+ sandbox["id"],+ "import os; print('\\n'.join(sorted(os.listdir('/mnt/data'))))",+ )+ assert listing["exit_code"] == 0, listing+ visible = listing["stdout"].splitlines()+ assert visible == ["file1.txt", "nested_dir", "skip_me"], visible+ assert ".hidden.txt" not in visible++ for path, expected in [+ ("/mnt/data/file1.txt", "hello-file1"),+ ("/mnt/data/nested_dir/inner.txt", "hello-inner"),+ ]:+ result = _run_python(+ client,+ sandbox["id"],+ f"print(open({path!r}).read())",+ )+ assert result["exit_code"] == 0, result+ assert result["stdout"].rstrip("\n") == expected, result++ write_attempt = _run_python(+ client,+ sandbox["id"],+ "open('/mnt/data/file1.txt', 'w').write('nope')",+ )+ assert write_attempt["exit_code"] != 0, write_attempt+ combined = (write_attempt["stdout"] + write_attempt["stderr"]).lower()+ assert any(+ marker in combined+ for marker in ("read-only", "readonly", "erofs", "permission denied")+ ), write_attempt++ @staticmethod+ def test_bind_root_entries_rw_allows_writes(+ client,+ create_sandbox_with_policy,+ bind_root_entries_host_tree,+ ):+ host_root = bind_root_entries_host_tree+ sandbox = create_sandbox_with_policy(+ name_prefix="bind-root-entries-rw",+ policy={+ "name": "bind-root-entries-rw-policy",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp", "/mnt/data"],+ "bind_root_entries": [{+ "host_root": host_root,+ "sandbox_path": "/mnt/data",+ "mode": "rw",+ }],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ },+ )++ overwrite = _run_python(+ client,+ sandbox["id"],+ "open('/mnt/data/file1.txt', 'w').write('rewritten')",+ )+ assert overwrite["exit_code"] == 0, overwrite+ read_back = _run_python(+ client,+ sandbox["id"],+ "print(open('/mnt/data/file1.txt').read())",+ )+ assert read_back["exit_code"] == 0, read_back+ assert read_back["stdout"].rstrip("\n") == "rewritten", read_back++ nested_write = _run_python(+ client,+ sandbox["id"],+ (+ "open('/mnt/data/nested_dir/new.txt', 'w').write('new-content'); "+ "print(open('/mnt/data/nested_dir/new.txt').read())"+ ),+ )+ assert nested_write["exit_code"] == 0, nested_write+ assert nested_write["stdout"].rstrip("\n") == "new-content", nested_write++ # Round-trip the writes through a separate verification sandbox so we+ # confirm the bind actually shares the host inode rather than landing+ # on a tmpfs unique to this sandbox.+ verify_sandbox = create_sandbox_with_policy(+ name_prefix="bind-root-entries-rw-verify",+ policy={+ "name": "bind-root-entries-rw-verify-policy",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ "bind_mounts": [{+ "host_path": host_root,+ "sandbox_path": "/mnt/host-view",+ "mode": "ro",+ }],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ },+ )+ verify_one = _run_python(+ client,+ verify_sandbox["id"],+ "print(open('/mnt/host-view/file1.txt').read())",+ )+ assert verify_one["exit_code"] == 0, verify_one+ assert verify_one["stdout"].rstrip("\n") == "rewritten", verify_one+ verify_two = _run_python(+ client,+ verify_sandbox["id"],+ "print(open('/mnt/host-view/nested_dir/new.txt').read())",+ )+ assert verify_two["exit_code"] == 0, verify_two+ assert verify_two["stdout"].rstrip("\n") == "new-content", verify_two++ @staticmethod+ def test_bind_root_entries_exclude_and_include_hidden(+ client,+ create_sandbox_with_policy,+ bind_root_entries_host_tree,+ ):+ host_root = bind_root_entries_host_tree+ sandbox = create_sandbox_with_policy(+ name_prefix="bind-root-entries-filter",+ policy={+ "name": "bind-root-entries-filter-policy",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ "bind_root_entries": [{+ "host_root": host_root,+ "sandbox_path": "/mnt/data",+ "mode": "ro",+ "include_hidden": True,+ # ``*.txt`` should drop ``file1.txt`` and ``.hidden.txt``+ # so we get a clean assertion that hidden inclusion and+ # fnmatch exclusion compose as expected.+ "exclude": ["skip_me", "*.txt"],+ }],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ },+ )++ listing = _run_python(+ client,+ sandbox["id"],+ "import os; print('\\n'.join(sorted(os.listdir('/mnt/data'))))",+ )+ assert listing["exit_code"] == 0, listing+ visible = listing["stdout"].splitlines()+ # ``nested_dir`` is the only child not caught by either exclude pattern.+ assert visible == ["nested_dir"], visible++ @staticmethod+ def test_bind_root_entries_missing_host_root_is_noop(+ client,+ create_sandbox_with_policy,+ ):+ # Pick a box-server-side path that is guaranteed not to exist. We use+ # /tmp/<uuid> rather than tmp_path because tmp_path lives on the pytest+ # host while the box-server typically runs inside Docker - the two+ # processes see different /tmp filesystems and we want this assertion+ # to be independent of that topology.+ missing = f"/tmp/jiuwenbox-bind-root-entries-missing-{uuid.uuid4().hex}"+ sandbox = create_sandbox_with_policy(+ name_prefix="bind-root-entries-missing",+ policy={+ "name": "bind-root-entries-missing-policy",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ "bind_root_entries": [{+ "host_root": missing,+ "sandbox_path": "/mnt/data",+ "mode": "ro",+ }],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ },+ )+ assert sandbox["phase"] == "ready", sandbox++ probe = _run_python(+ client,+ sandbox["id"],+ (+ "import os; "+ "print('exists=', os.path.exists('/mnt/data')); "+ "print('contents=', sorted(os.listdir('/mnt/data')) "+ " if os.path.isdir('/mnt/data') else [])"+ ),+ )+ assert probe["exit_code"] == 0, probe+ lines = probe["stdout"].splitlines()+ # Either the parent dir was never created (no children to mount) or it+ # exists but is empty. Both outcomes are acceptable; what matters is+ # that the sandbox came up cleanly and host_root absence didn't error.+ assert lines[0] in ("exists= False", "exists= True"), probe+ assert lines[1] == "contents= []", probe++ @staticmethod+ def test_policy_api_round_trips_bind_root_entries(+ client,+ create_sandbox_with_policy,+ bind_root_entries_host_tree,+ ):+ host_root = bind_root_entries_host_tree+ nested_host_root = f"{host_root}/nested_dir"+ sandbox = create_sandbox_with_policy(+ name_prefix="bind-root-entries-roundtrip",+ policy={+ "name": "bind-root-entries-roundtrip-policy",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ "bind_root_entries": [+ {+ "host_root": host_root,+ "sandbox_path": "/mnt/data",+ "mode": "ro",+ },+ {+ "host_root": nested_host_root,+ "sandbox_path": "/mnt/nested",+ "mode": "rw",+ "include_hidden": True,+ "exclude": ["skip_me"],+ },+ ],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ },+ )++ resp = client.get(f"/api/v1/policies/{sandbox['id']}")+ assert resp.status_code == 200, resp.text+ data = resp.json()+ round_tripped = data["filesystem_policy"]["bind_root_entries"]+ assert round_tripped == [+ {+ "host_root": host_root,+ "sandbox_path": "/mnt/data",+ "mode": "ro",+ "include_hidden": False,+ "exclude": [],+ },+ {+ "host_root": nested_host_root,+ "sandbox_path": "/mnt/nested",+ "mode": "rw",+ "include_hidden": True,+ "exclude": ["skip_me"],+ },+ ], round_tripped++ @staticmethod+ def test_bind_mount_rejects_star_host_path(client):+ resp = client.post(+ "/api/v1/sandboxes",+ json={+ "policy": {+ "name": "bind-mount-star-rejected",+ "filesystem_policy": {+ "bind_mounts": [{+ "host_path": "*",+ "sandbox_path": "/mnt/all",+ "mode": "ro",+ }],+ },+ "network": {"mode": "host"},+ },+ },+ )+ assert resp.status_code == 400, resp.text+ body = resp.json()+ message = body.get("error") or body.get("detail") or ""+ assert "bind_root_entries" in message, body++ @staticmethod+ def test_bind_root_entries_root_with_overriding_rw_bind_mount(+ client,+ create_sandbox_with_policy,+ ):+ """``bind_root_entries`` covers the whole host root ``/`` read-only,+ then ``bind_mounts`` re-mounts ``/app/build`` at the *same* path with+ read-write permissions.++ Layering order inside bwrap:++ 1. ``--ro-bind`` for each immediate child of host ``/`` at sandbox+ ``/<child>`` (emitted by ``bind_root_entries``). The kernel+ pseudo filesystems (``proc``, ``dev``, ``sys``, ``run``) and the+ bwrap-managed scratch dirs (``tmp``, ``home``) are excluded so+ we don't shadow bwrap's own ``--proc`` / ``--dev`` mounts or the+ ``directories`` block injected by ``_with_runtime_support``.+ 2. ``--bind /app/build /app/build`` (emitted by ``bind_mounts``)+ overlays the rw mount on top of the ro ``/app`` bind at the very+ same sandbox path.++ The net effect is: the entire rootfs (including ``/app``,+ ``/app/pyproject.toml``, ``/usr``, ``/etc``, ...) is ro, but+ ``/app/build`` is writable. We deliberately use the same+ ``host_path`` and ``sandbox_path`` for the rw overlay so the test+ mirrors a real "ro by default, selected rw" mount strategy rather+ than aliasing ``/app/build`` to an unrelated backing directory.+ """+ # /app exists in the box-server's image (Dockerfile WORKDIR=/app)+ # but /app/build does not. We need it to exist on the host so+ # ``bind_mounts`` can resolve it. Use a privileged setup sandbox+ # that rw-binds host /app into the sandbox and creates the dir+ # there. Run as root so the dir creation and chmod succeed; chmod+ # 0o0777 + 0o0666 ensures the subsequent unprivileged test sandbox+ # (uid 65534) can both read the seeded binary and write fresh+ # files.+ setup_resp = client.post(+ "/api/v1/sandboxes",+ json={+ "policy_mode": "override",+ "policy": _with_runtime_support({+ "name": "bind-root-entries-app-build-setup",+ "filesystem_policy": {+ "bind_mounts": [{+ "host_path": "/app",+ "sandbox_path": "/app",+ "mode": "rw",+ }],+ },+ "process": {+ "run_as_user": "root",+ "run_as_group": "root",+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ }),+ },+ )+ assert setup_resp.status_code == 201, setup_resp.text+ setup_id = setup_resp.json()["id"]+ try:+ seed_script = textwrap.dedent(+ """+ import os+ os.makedirs("/app/build", exist_ok=True)+ os.chmod("/app/build", 0o0777)+ with open("/app/build/binary", "w") as fh:+ fh.write("v1-from-host")+ os.chmod("/app/build/binary", 0o0666)+ """+ ).strip()+ seed_result = _run_python(client, setup_id, seed_script, timeout=15)+ assert seed_result["exit_code"] == 0, seed_result+ finally:+ client.delete(f"/api/v1/sandboxes/{setup_id}")++ try:+ sandbox = create_sandbox_with_policy(+ name_prefix="bind-root-entries-app-build-rw-overlay",+ policy={+ "name": "bind-root-entries-app-build-rw-overlay-policy",+ "filesystem_policy": {+ # Mount every immediate child of host / at the+ # corresponding sandbox path read-only. /app is one+ # of those children and lands recursively at sandbox+ # /app (including /app/build) as ro. Kernel pseudo+ # filesystems and bwrap-managed scratch dirs are+ # excluded so they don't clobber bwrap's own+ # --proc/--dev/--tmpfs setup.+ "bind_root_entries": [{+ "host_root": "/",+ "sandbox_path": "/",+ "mode": "ro",+ "exclude": [+ "proc",+ "dev",+ "sys",+ "run",+ "tmp",+ "home",+ ],+ }],+ # Re-mount /app/build at the *same* sandbox path+ # with rw permissions. bwrap layers this --bind on+ # top of the earlier --ro-bind /app, so /app/build+ # becomes writable while the rest of /app (e.g.+ # /app/pyproject.toml) and the rest of the rootfs+ # (e.g. /etc/passwd, /usr/bin/python3) stay+ # read-only.+ "bind_mounts": [{+ "host_path": "/app/build",+ "sandbox_path": "/app/build",+ "mode": "rw",+ }],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ },+ )+ assert sandbox["phase"] == "ready", sandbox++ # /app/pyproject.toml is one of the children that bind_root_entries+ # mounted ro. Reading it confirms the ro side of /app is wired up.+ read_pyproject = _run_python(+ client,+ sandbox["id"],+ "import os; print(os.path.isfile('/app/pyproject.toml'))",+ )+ assert read_pyproject["exit_code"] == 0, read_pyproject+ assert read_pyproject["stdout"].rstrip("\n") == "True", read_pyproject++ # Writing to a file inside /app but outside /app/build must fail+ # because that path is still ro from bind_root_entries.+ write_pyproject = _run_python(+ client,+ sandbox["id"],+ "open('/app/pyproject.toml', 'w').write('nope')",+ )+ assert write_pyproject["exit_code"] != 0, write_pyproject+ combined = (+ write_pyproject["stdout"] + write_pyproject["stderr"]+ ).lower()+ assert any(+ marker in combined+ for marker in ("read-only", "readonly", "erofs", "permission denied")+ ), write_pyproject++ # /app/build is the rw overlay. The pre-seeded binary file must+ # round-trip from the host through the rw bind, and the sandbox+ # must be able to add a fresh file there.+ read_existing = _run_python(+ client,+ sandbox["id"],+ "print(open('/app/build/binary').read())",+ )+ assert read_existing["exit_code"] == 0, read_existing+ assert read_existing["stdout"].rstrip("\n") == "v1-from-host", read_existing++ write_new = _run_python(+ client,+ sandbox["id"],+ (+ "open('/app/build/new.txt', 'w').write('v2-from-sandbox'); "+ "print(open('/app/build/new.txt').read())"+ ),+ )+ assert write_new["exit_code"] == 0, write_new+ assert write_new["stdout"].rstrip("\n") == "v2-from-sandbox", write_new++ # Independent verification: a fresh sandbox that only ro-binds+ # host /app/build observes the same file the test sandbox just+ # wrote, proving the rw bind shares the host inode rather than a+ # per-sandbox tmpfs.+ verify_sandbox = create_sandbox_with_policy(+ name_prefix="bind-root-entries-app-build-verify",+ policy={+ "name": "bind-root-entries-app-build-verify-policy",+ "filesystem_policy": {+ "bind_mounts": [{+ "host_path": "/app/build",+ "sandbox_path": "/mnt/build-view",+ "mode": "ro",+ }],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ },+ )+ verify = _run_python(+ client,+ verify_sandbox["id"],+ "print(open('/mnt/build-view/new.txt').read())",+ )+ assert verify["exit_code"] == 0, verify+ assert verify["stdout"].rstrip("\n") == "v2-from-sandbox", verify+ finally:+ # Best-effort cleanup: remove /app/build so the box-server's+ # /app doesn't accumulate state between test runs. Needs the+ # same privileged setup as the seed step.+ cleanup_resp = client.post(+ "/api/v1/sandboxes",+ json={+ "policy_mode": "override",+ "policy": _with_runtime_support({+ "name": "bind-root-entries-app-build-cleanup",+ "filesystem_policy": {+ "bind_mounts": [{+ "host_path": "/app",+ "sandbox_path": "/app",+ "mode": "rw",+ }],+ },+ "process": {+ "run_as_user": "root",+ "run_as_group": "root",+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ }),+ },+ )+ if cleanup_resp.status_code == 201:+ cleanup_id = cleanup_resp.json()["id"]+ try:+ client.post(+ f"/api/v1/sandboxes/{cleanup_id}/exec",+ json={+ "command": ["rm", "-rf", "/app/build"],+ "timeout_seconds": 10,+ },+ )+ finally:+ client.delete(f"/api/v1/sandboxes/{cleanup_id}")+++# ---------------------------------------------------------------------------+# Cgroup policy field+# ---------------------------------------------------------------------------+++_CGROUP_PROBE_POLICY: dict[str, object] = {+ "name": "cgroup-probe",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ "cgroup": {"pids_max": 1024},+}++# Module-level cache for the cgroup-probe result. The first ``_cgroup_supported``+# fixture invocation pays the one-time cost of creating a sandbox with a real+# cgroup policy; subsequent invocations short-circuit on the cached verdict so+# we don't slow the rest of the suite down. ``None`` means "not probed yet";+# ``True`` / ``False`` is the cached verdict.+_cgroup_probe_cached: bool | None = None+_cgroup_probe_skip_reason: str | None = None+++def _is_cgroup_unsupported_error(text: str) -> bool:+ """Return True when ``text`` looks like a cgroup-not-writable diagnostic.++ Both the runtime layer and the cgroup backend wrap the underlying+ ``CgroupSetupError`` into different strings (``RuntimeError`` from+ ``ProcessRuntime.create``, plain ``CgroupSetupError`` from the backend+ helper). Matching the lowercased message keeps the probe robust against+ future wording changes.+ """+ lowered = (text or "").lower()+ return "cgroup" in lowered and (+ "cgroupsetuperror" in lowered+ or "no writable cgroup backend" in lowered+ or "failed to apply cgroup limits" in lowered+ or "failed to write" in lowered+ or "failed to create" in lowered+ or "failed to enable controllers" in lowered+ or "permission denied" in lowered+ )+++class TestCgroupPolicy:+ """End-to-end coverage for the ``cgroup`` policy field.++ Tests are split into two groups:++ - Group A is independent of cgroup availability and exercises Pydantic+ validation plus the "no cgroup field -> skip" early-exit. Every test+ in this group must pass even on hosts without a writable cgroup tree.+ - Group B exercises actual kernel enforcement (memory.max, pids.max,+ cpu.max) and depends on ``_cgroup_supported`` to skip when the host+ lacks a writable cgroup backend.+ """++ # ------------------------------------------------------------------+ # Group A: cgroup-independent+ # ------------------------------------------------------------------++ @staticmethod+ def _expect_no_limit_policy(extra_cgroup: dict | None) -> dict:+ """Build a policy dict whose ``cgroup`` part should be a no-op.++ ``extra_cgroup`` lets each test pick the exact equivalent form+ (omitted, ``{}``, all-null) we want to assert is treated the same+ way as the others.+ """+ policy: dict[str, object] = {+ "name": "cgroup-skip",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ }+ if extra_cgroup is not None:+ policy["cgroup"] = extra_cgroup+ return policy++ @staticmethod+ def _assert_skip_path_runs_cleanly(client, sandbox_id: str) -> None:+ """Allocate 64MB inside the sandbox to prove no cgroup limit is in+ play. We don't push to 128MB to avoid spurious OOM on CI machines+ whose docker containers are constrained by the *parent* cgroup.+ """+ result = _run_python(+ client,+ sandbox_id,+ (+ "import sys; "+ "buf = bytearray(64 * 1024 * 1024); "+ "print('len=', len(buf), 'last=', buf[-1])"+ ),+ timeout=15,+ )+ assert result["exit_code"] == 0, result+ assert "len= 67108864" in result["stdout"], result++ @staticmethod+ def test_no_cgroup_field_skips_setup_entirely(client, create_sandbox_with_policy):+ sandbox = create_sandbox_with_policy(+ name_prefix="cgroup-skip-noField",+ policy=TestCgroupPolicy._expect_no_limit_policy(None),+ )+ TestCgroupPolicy._assert_skip_path_runs_cleanly(client, sandbox["id"])++ @staticmethod+ def test_empty_cgroup_field_skips_setup(client, create_sandbox_with_policy):+ sandbox = create_sandbox_with_policy(+ name_prefix="cgroup-skip-empty",+ policy=TestCgroupPolicy._expect_no_limit_policy({}),+ )+ TestCgroupPolicy._assert_skip_path_runs_cleanly(client, sandbox["id"])++ @staticmethod+ def test_all_null_cgroup_field_skips_setup(client, create_sandbox_with_policy):+ sandbox = create_sandbox_with_policy(+ name_prefix="cgroup-skip-allNull",+ policy=TestCgroupPolicy._expect_no_limit_policy({+ "memory_max": None,+ "cpu_max": None,+ "pids_max": None,+ }),+ )+ TestCgroupPolicy._assert_skip_path_runs_cleanly(client, sandbox["id"])++ @staticmethod+ def test_cgroup_rejects_invalid_memory_max(client):+ resp = client.post(+ "/api/v1/sandboxes",+ json={+ "policy_mode": "override",+ "policy": _with_runtime_support({+ "name": "cgroup-invalid-memory",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ "cgroup": {"memory_max": "not-a-size"},+ }),+ },+ )+ assert resp.status_code == 400, resp.text+ body = resp.json()+ message = body.get("error") or body.get("detail") or ""+ assert "memory_max" in message, body++ @staticmethod+ def test_cgroup_rejects_invalid_cpu_max(client):+ resp = client.post(+ "/api/v1/sandboxes",+ json={+ "policy_mode": "override",+ "policy": _with_runtime_support({+ "name": "cgroup-invalid-cpu",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ "cgroup": {"cpu_max": "weird"},+ }),+ },+ )+ assert resp.status_code == 400, resp.text+ body = resp.json()+ message = body.get("error") or body.get("detail") or ""+ assert "cpu_max" in message, body++ @staticmethod+ def test_cgroup_rejects_invalid_pids_max(client):+ resp = client.post(+ "/api/v1/sandboxes",+ json={+ "policy_mode": "override",+ "policy": _with_runtime_support({+ "name": "cgroup-invalid-pids",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ "cgroup": {"pids_max": -1},+ }),+ },+ )+ assert resp.status_code == 400, resp.text+ body = resp.json()+ message = body.get("error") or body.get("detail") or ""+ assert "pids_max" in message, body++ # ------------------------------------------------------------------+ # Group B: requires a writable cgroup backend+ # ------------------------------------------------------------------++ @pytest.fixture+ def _cgroup_supported(self, client):+ """Probe the box-server for a writable cgroup backend by trying to+ create a sandbox with a minimal cgroup policy.++ The probe result is cached at module level (``_cgroup_probe_cached``)+ so only the first test in the group actually pays the+ sandbox-create cost; subsequent tests short-circuit on the cached+ verdict. We can't use ``scope="class"`` here because ``client``+ is function-scoped (pytest ``ScopeMismatch``), and we don't want+ to broaden the client fixture's scope just for this probe.+ """+ global _cgroup_probe_cached, _cgroup_probe_skip_reason+ if _cgroup_probe_cached is False:+ pytest.skip(_cgroup_probe_skip_reason or "cgroup not writable")+ if _cgroup_probe_cached is None:+ resp = client.post(+ "/api/v1/sandboxes",+ json={+ "policy_mode": "override",+ "policy": _with_runtime_support(_CGROUP_PROBE_POLICY),+ },+ )+ if resp.status_code == 201:+ sandbox_id = resp.json()["id"]+ client.delete(f"/api/v1/sandboxes/{sandbox_id}")+ _cgroup_probe_cached = True+ else:+ _cgroup_probe_cached = False+ if resp.status_code >= 500 and _is_cgroup_unsupported_error(resp.text):+ _cgroup_probe_skip_reason = (+ "cgroup not writable in this environment"+ )+ else:+ _cgroup_probe_skip_reason = (+ f"cgroup probe sandbox failed to start "+ f"(status={resp.status_code}): {resp.text}"+ )+ pytest.skip(_cgroup_probe_skip_reason)+ return True++ @staticmethod+ def test_cgroup_policy_round_trips_via_api(+ client,+ _cgroup_supported,+ create_sandbox_with_policy,+ ):+ sandbox = create_sandbox_with_policy(+ name_prefix="cgroup-roundtrip",+ policy={+ "name": "cgroup-roundtrip-policy",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ "cgroup": {+ "memory_max": "256M",+ "cpu_max": "0.5",+ "pids_max": 64,+ },+ },+ )++ resp = client.get(f"/api/v1/policies/{sandbox['id']}")+ assert resp.status_code == 200, resp.text+ cgroup_data = resp.json().get("cgroup")+ assert cgroup_data is not None, resp.text+ assert cgroup_data["memory_max"] == 256 * 1024 * 1024, cgroup_data+ # ``cpu_max`` is a Python tuple internally; FastAPI serializes it+ # as a 2-element list.+ assert cgroup_data["cpu_max"] == [50000, 100000], cgroup_data+ assert cgroup_data["pids_max"] == 64, cgroup_data++ @staticmethod+ def test_cgroup_memory_max_kills_offending_process(+ client,+ _cgroup_supported,+ create_sandbox_with_policy,+ ):+ sandbox = create_sandbox_with_policy(+ name_prefix="cgroup-memory-limit",+ policy={+ "name": "cgroup-memory-policy",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ "cgroup": {"memory_max": "32M"},+ },+ )+ # Allocate 128MB - 4x the 32M cap. Touching the buffer forces real+ # page allocation so the OOM killer (cgroup v2) or memory.failcnt+ # (cgroup v1) actually fires. Without the touch the kernel might+ # only reserve virtual address space.+ result = _run_python(+ client,+ sandbox["id"],+ (+ "buf = bytearray(128 * 1024 * 1024); "+ "buf[::4096] = b'x' * (len(buf) // 4096); "+ "print('survived')"+ ),+ timeout=30,+ )+ assert result["exit_code"] != 0, result+ assert "survived" not in result["stdout"], result+ combined = (result["stdout"] + result["stderr"]).lower()+ # The python process is either killed by SIGKILL (OOM kill) or+ # raises MemoryError before printing "survived"; both outcomes+ # confirm memory_max enforcement.+ assert (+ "memoryerror" in combined+ or "killed" in combined+ or "cannot allocate memory" in combined+ or result["exit_code"] < 0+ or result["exit_code"] == 137 # 128 + SIGKILL+ or result["exit_code"] == 9+ ), result++ @staticmethod+ def test_cgroup_pids_max_limits_fork_count(+ client,+ _cgroup_supported,+ create_sandbox_with_policy,+ ):+ sandbox = create_sandbox_with_policy(+ name_prefix="cgroup-pids-limit",+ policy={+ "name": "cgroup-pids-policy",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ "cgroup": {"pids_max": 5},+ },+ )+ # Try to fork 32 children. With pids_max=5 the cgroup should reject+ # at least one fork with EAGAIN well before we get to 32. We catch+ # OSError so the script prints how many succeeded before bailing.+ script = textwrap.dedent(+ """+ import os+ import sys+ import time++ children = []+ try:+ for _ in range(32):+ pid = os.fork()+ if pid == 0:+ time.sleep(2)+ os._exit(0)+ children.append(pid)+ except OSError as exc:+ print('blocked_after=', len(children), 'errno=', exc.errno)+ else:+ print('blocked_after=', len(children), 'errno= none')+ finally:+ for pid in children:+ try:+ os.kill(pid, 9)+ os.waitpid(pid, 0)+ except OSError:+ pass+ sys.exit(0)+ """+ ).strip()+ result = _run_python(client, sandbox["id"], script, timeout=20)+ assert result["exit_code"] == 0, result+ stdout = result["stdout"]+ # The exact threshold depends on whether the parent process and+ # any helper threads count toward pids_max, but in every realistic+ # case at least a few forks must fail before we reach 32.+ assert "errno= 11" in stdout or "errno= 35" in stdout, result+ # Extract ``blocked_after=`` value and assert it's well below 32.+ marker = "blocked_after="+ idx = stdout.find(marker)+ assert idx >= 0, result+ blocked_value = stdout[idx + len(marker):].split()[0]+ assert int(blocked_value) < 32, result++ @staticmethod+ def test_cgroup_cpu_max_throttles_busy_loop(+ client,+ _cgroup_supported,+ create_sandbox_with_policy,+ ):+ sandbox = create_sandbox_with_policy(+ name_prefix="cgroup-cpu-throttle",+ policy={+ "name": "cgroup-cpu-policy",+ "filesystem_policy": {+ "read_only": ["/usr", "/lib", "/lib64", "/etc", "/opt"],+ "read_write": ["/tmp"],+ },+ "landlock": {"compatibility": "disabled"},+ "network": {"mode": "host"},+ "cgroup": {"cpu_max": "0.1"},+ },+ )+ # Spin for ~2 seconds of wall-clock time and report how much CPU+ # time we actually got. With cpu_max=0.1 cores, process_time+ # should be ~10% of wall-clock or less; we assert <30% to leave a+ # generous margin for measurement noise on busy CI hosts.+ script = textwrap.dedent(+ """+ import time++ target_wall = 2.0+ start_wall = time.monotonic()+ start_cpu = time.process_time()+ while time.monotonic() - start_wall < target_wall:+ pass+ wall = time.monotonic() - start_wall+ cpu = time.process_time() - start_cpu+ print('wall=', wall)+ print('cpu=', cpu)+ print('ratio=', cpu / wall if wall > 0 else 0)+ """+ ).strip()+ result = _run_python(client, sandbox["id"], script, timeout=20)+ assert result["exit_code"] == 0, result+ ratio_line = next(+ (line for line in result["stdout"].splitlines() if line.startswith("ratio=")),+ "",+ )+ assert ratio_line, result+ try:+ ratio_value = float(ratio_line.split("=", 1)[1].strip())+ except ValueError:+ pytest.fail(f"unparseable ratio line: {ratio_line!r}; full: {result}")+ # Heuristic threshold. cpu_max=0.1 caps CPU usage at ~10% on a+ # single core; on multi-core busy CI hosts ratios slightly above+ # 0.1 are tolerable, but anything north of 0.3 indicates the+ # cgroup didn't actually throttle the process.+ assert ratio_value < 0.3, (ratio_value, result)diff --git a/jiuwenbox/tests/test.sh b/jiuwenbox/tests/test.shindex c6c09af69d..3e982dc900 100755--- a/jiuwenbox/tests/test.sh+++ b/jiuwenbox/tests/test.sh@@ -8,13 +8,43 @@ cd "$PROJECT_DIR"JIUWENBOX_DIR="$(realpath "$PROJECT_DIR/src")"-TEST_TARGET="tests/integration/"+# 默认 test 目标 & 类别; 各子命令可以覆盖。+TEST_TARGETS=("tests/integration/")TEST_KIND="integration"PERF_SANDBOX_COUNT="${JIUWENBOX_PERF_SANDBOX_COUNT:-1}"PERF_CONCURRENCY="${JIUWENBOX_PERF_CONCURRENCY:-4}"PERF_LOOP="${JIUWENBOX_PERF_LOOP:-8}"PERF_EXEC_TIMEOUT_SECONDS="${JIUWENBOX_PERF_EXEC_TIMEOUT_SECONDS:-180}"+usage() {+ cat <<'EOF'+Usage: tests/test.sh [target] [--server-endpoint=URI] [pytest args...]++Targets:+ default Run test_server_api_default.py + test_cli_default.py+ inference-privacy-proxy Run test_inference_privacy_proxy.py+ performance Run performance suite (accepts --sandbox-count /+ --concurrency / --loop)+ (omitted) Run the whole tests/integration/ directory++Server endpoint:+ --server-endpoint=URI Pick the listener to test against. Transport is+ inferred from the URI shape:++ http(s)://host:port TCP listener+ host:port TCP listener (http:// added)+ unix:///abs/path Unix Domain Socket file++ Defaults to the pytest fixture default+ (http://127.0.0.1:8321) when omitted.++Examples:+ tests/test.sh default+ tests/test.sh default --server-endpoint=http://127.0.0.1:18321+ tests/test.sh default --server-endpoint=unix:///tmp/jiuwenbox.sock+EOF+}+require_value() {local option="$1"if [[ $# -lt 2 || "$2" == --* ]]; then@@ -23,20 +53,28 @@ require_value() {fi}+# 子命令选择 (default / performance / etc).if [[ $# -gt 0 ]]; thencase "$1" in+ -h|--help)+ usage+ exit 0+ ;;default)- TEST_TARGET="tests/integration/test_server_api_default.py"+ TEST_TARGETS=(+ "tests/integration/test_server_api_default.py"+ "tests/integration/test_cli_default.py"+ )TEST_KIND="integration"shift;;inference-privacy-proxy)- TEST_TARGET="tests/integration/test_inference_privacy_proxy.py"+ TEST_TARGETS=("tests/integration/test_inference_privacy_proxy.py")TEST_KIND="integration"shift;;performance)- TEST_TARGET="tests/performance/"+ TEST_TARGETS=("tests/performance/")TEST_KIND="performance"shift;;@@ -44,6 +82,9 @@ if [[ $# -gt 0 ]]; thenfiPYTEST_ARGS=()++# performance target 还需要识别 --sandbox-count / --concurrency / --loop;+# 其余一律透传给 pytest, 包括 --server-endpoint (conftest.py 自己解析).if [[ "$TEST_KIND" == "performance" ]]; thenPYTEST_ARGS+=("-s"@@ -76,7 +117,49 @@ if [[ "$TEST_KIND" == "performance" ]]; thenesacdoneelse- PYTEST_ARGS=("$@")+ while [[ $# -gt 0 ]]; do+ PYTEST_ARGS+=("$1")+ shift+ done+fi++# 友好提示: 在用户传了 --server-endpoint 时回显, 没传时回显 pytest fixture+# 默认值, 让 CI 日志里一眼看清打的是哪个 listener (TCP or UDS).+user_endpoint=""+if (( ${#PYTEST_ARGS[@]} > 0 )); then+ for ((i = 0; i < ${#PYTEST_ARGS[@]}; i++)); do+ arg="${PYTEST_ARGS[$i]}"+ case "$arg" in+ --server-endpoint=*)+ user_endpoint="${arg#--server-endpoint=}"+ break+ ;;+ --server-endpoint)+ next_idx=$((i + 1))+ if (( next_idx < ${#PYTEST_ARGS[@]} )); then+ user_endpoint="${PYTEST_ARGS[$next_idx]}"+ fi+ break+ ;;+ esac+ done+fi++if [[ -n "$user_endpoint" ]]; then+ case "$user_endpoint" in+ unix://*)+ echo "[test.sh] endpoint=${user_endpoint} (uds)" >&2+ ;;+ http://*|https://*)+ echo "[test.sh] endpoint=${user_endpoint} (tcp)" >&2+ ;;+ *)+ # ``host:port`` 形式: conftest.py 会自动补 http:// 前缀。+ echo "[test.sh] endpoint=${user_endpoint} (tcp, http:// inferred)" >&2+ ;;+ esac+else+ echo "[test.sh] endpoint=(pytest default http://127.0.0.1:8321)" >&2fiif [[ "$TEST_KIND" == "performance" ]]; then@@ -85,8 +168,8 @@ if [[ "$TEST_KIND" == "performance" ]]; thenJIUWENBOX_PERF_LOOP=${PERF_LOOP} \JIUWENBOX_PERF_EXEC_TIMEOUT_SECONDS=${PERF_EXEC_TIMEOUT_SECONDS} \PYTHONPATH=${JIUWENBOX_DIR} \- python3 -m pytest "$TEST_TARGET" -v --tb=short "${PYTEST_ARGS[@]}"+ python3 -m pytest "${TEST_TARGETS[@]}" -v --tb=short "${PYTEST_ARGS[@]}"elsePYTHONPATH=${JIUWENBOX_DIR} \- python3 -m pytest "$TEST_TARGET" -v --tb=short "${PYTEST_ARGS[@]}"+ python3 -m pytest "${TEST_TARGETS[@]}" -v --tb=short "${PYTEST_ARGS[@]}"fi