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
fix(jiuwenbox): jiuwenbox add timeout and retry action
zhaozixuanc66523b321d8
diff --git a/jiuwenbox/configs/default-policy.yaml b/jiuwenbox/configs/default-policy.yamlindex 3f9a897574..017903d9a7 100644--- a/jiuwenbox/configs/default-policy.yaml+++ b/jiuwenbox/configs/default-policy.yaml@@ -313,3 +313,24 @@ network:# pids_max: positive integer cap on processes/threads (e.g. 256). "max"# or null means no limit.cgroup: {}++# Idle sandbox reaping (jiuwenbox 服务端行为, 不下传到 bwrap / landlock / cgroup).+#+# 仅在 server 启动时加载的根 policy 上生效; per-sandbox policy 上的同名字段不会+# 影响沙箱隔离, 也不会改变正在运行的沙箱的淘汰判定。+#+# 字段:+# idle_timeout: 沙箱最大空闲时长 (秒). null / 0 / 负值 = 禁用淘汰 (默认).+# "空闲" = 自最后一次 exec / file IO / 列目录 等 API 调用以来的时长;+# 单纯查询接口 (get_sandbox / list_sandboxes / get_logs) 不会刷新计时器.+# idle_check_interval: reaper 轮询间隔 (秒). 必须 > 0, 默认 60.+#+# 行为: 默认禁用. 显式配置 idle_timeout 后, 后台 task 每隔 idle_check_interval+# 秒扫一次, 超时的沙箱直接走 delete_sandbox (跟 ``DELETE /sandboxes/{id}``+# 同一路径), 审计日志会带 ``reason: idle_timeout``.+#+# 示例:+# timeout:+# idle_timeout: 1800 # 30 分钟无活动即淘汰+# idle_check_interval: 60 # 每分钟扫一次+timeout: {}diff --git a/jiuwenbox/configs/enterprise-policy.yaml b/jiuwenbox/configs/enterprise-policy.yamlnew file mode 100644index 0000000000..356ae1dd12--- /dev/null+++ b/jiuwenbox/configs/enterprise-policy.yaml@@ -0,0 +1,300 @@+# Policy schema version. Currently only version 1 is supported.+version: 1++# Human-readable policy name shown by the server policy API.+name: "server-enterprise"++# 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:+ - path: "/tmp"+ permissions: "1777"++ # 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"++ # Read-write paths inside the sandbox. Use directories or bind_mounts to make+ # these paths exist in the sandbox.+ read_write:+ - "/tmp"++ # Extra bind mounts from host into sandbox.+ # Each item uses:+ # host_path: absolute path on the host+ # sandbox_path: absolute path visible inside the sandbox+ # mode: "ro" for read-only or "rw" for read-write+ bind_mounts:+ - host_path: "/bin"+ sandbox_path: "/bin"+ mode: "ro"+ - host_path: "/sbin"+ sandbox_path: "/sbin"+ mode: "ro"+ - host_path: "/usr"+ sandbox_path: "/usr"+ mode: "ro"+ - host_path: "/lib"+ sandbox_path: "/lib"+ mode: "ro"+ - host_path: "/lib64"+ sandbox_path: "/lib64"+ mode: "ro"+ - host_path: "/etc/resolv.conf"+ sandbox_path: "/etc/resolv.conf"+ mode: "ro"+ - host_path: "/etc/hosts"+ sandbox_path: "/etc/hosts"+ mode: "ro"+ - host_path: "/etc/nsswitch.conf"+ sandbox_path: "/etc/nsswitch.conf"+ mode: "ro"+ - host_path: "/etc/host.conf"+ sandbox_path: "/etc/host.conf"+ mode: "ro"+ - host_path: "/etc/ssl/certs"+ sandbox_path: "/etc/ssl/certs"+ mode: "ro"+ - host_path: "/etc/pki"+ sandbox_path: "/etc/pki"+ mode: "ro"+ - host_path: "/opt"+ sandbox_path: "/opt"+ 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/urandom"+ sandbox_path: "/dev/urandom"+ - host_path: "/dev/null"+ sandbox_path: "/dev/null"++# Process identity inside the sandbox.+process:+ # User name to run as. If the user cannot be resolved, runtime falls back to nobody-style IDs.+ run_as_user: sandbox++ # Group name to run as. If the group cannot be resolved, runtime falls back to nobody-style IDs.+ run_as_group: sandbox++# Linux namespace isolation controlled by bubblewrap.+namespace:+ # user:+ # true: create a new user namespace+ # false: reuse the current user namespace+ user: true++ # pid:+ # true: create a new PID namespace+ # false: reuse the current PID namespace+ pid: true++ # ipc:+ # true: create a new IPC namespace+ # false: reuse the current IPC namespace+ ipc: true++ # cgroup:+ # true: create a new cgroup namespace+ # false: reuse the current cgroup namespace+ cgroup: true++ # uts:+ # true: create a new UTS namespace+ # false: reuse the current UTS namespace+ uts: true++# Linux capability rules applied by bubblewrap.+capabilities:+ # Capabilities to add, for example ["CAP_NET_RAW"] or ["NET_RAW"].+ add: []++ # Capabilities to drop. "ALL" drops all capabilities when supported by bubblewrap.+ drop: []++# Landlock filesystem access enforcement.+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++# Seccomp syscall filtering.+syscall:+ # Syscall names to block on x86_64. Leave empty to disable explicit syscall blocking.+ x86_64:+ blocked:+ - "kexec_load"+ - "kexec_file_load"+ - "reboot"+ - "pivot_root"+ - "swapon"+ - "swapoff"+ - "nfsservctl"+ - "lookup_dcookie"+ - "ptrace"+ - "mount"+ - "umount2"+ - "unshare"+ - "setns"+ - "userfaultfd"+ - "perf_event_open"+ - "bpf"+ - "add_key"+ - "request_key"+ - "keyctl"+ - "io_uring_setup"+ - "io_uring_enter"+ - "io_uring_register"+ - "open_by_handle_at"+ - "name_to_handle_at"+ - "init_module"+ - "finit_module"+ - "delete_module"+ - "acct"+ # Syscall names to block on arm64/aarch64.+ arm64:+ blocked:+ - "kexec_load"+ - "kexec_file_load"+ - "reboot"+ - "pivot_root"+ - "swapon"+ - "swapoff"+ - "nfsservctl"+ - "lookup_dcookie"+ - "ptrace"+ - "mount"+ - "umount2"+ - "unshare"+ - "setns"+ - "userfaultfd"+ - "perf_event_open"+ - "bpf"+ - "add_key"+ - "request_key"+ - "keyctl"+ - "io_uring_setup"+ - "io_uring_enter"+ - "io_uring_register"+ - "open_by_handle_at"+ - "name_to_handle_at"+ - "init_module"+ - "finit_module"+ - "delete_module"+ - "acct"++# Network policy. Egress controls outbound traffic; ingress controls inbound traffic.+network:+ # mode:+ # isolated: create a dedicated network namespace and apply these rules+ # host: use host networking and skip namespace firewall setup+ mode: host++ # Outbound traffic from sandbox to outside destinations.+ egress:+ # default:+ # deny: block traffic unless it matches allowed_domains/allowed_ips and allowed_ports+ # allow: allow traffic unless it matches blocked_domains/blocked_ips/blocked_ports+ default: allow++ # Domain names allowed as outbound destinations. Wildcards like "*.example.com" are accepted+ # by resolving the base domain; rules are applied to resolved IPs.+ allowed_domains: []++ # Domain names blocked as outbound destinations. Block rules take precedence over allow rules.+ blocked_domains: []++ # IP/CIDR ranges allowed as outbound destinations, for example "203.0.113.10/32" or+ # "10.0.0.0/8". With default: deny, destinations not listed here are blocked.+ allowed_ips: []++ # IP/CIDR ranges blocked as outbound destinations. Block rules take precedence.+ blocked_ips: []++ # TCP destination ports allowed for outbound traffic when default is deny.+ allowed_ports: []++ # TCP destination ports blocked for outbound traffic. Block rules take precedence.+ blocked_ports: []++ # Inbound traffic from outside sources into the sandbox.+ ingress:+ # default:+ # deny: block traffic unless it matches allowed_domains/allowed_ips and allowed_ports+ # allow: allow traffic unless it matches blocked_domains/blocked_ips/blocked_ports+ default: allow++ # Domain names allowed as inbound sources. These are resolved to source IP rules.+ allowed_domains: []++ # Domain names blocked as inbound sources. Block rules take precedence over allow rules.+ blocked_domains: []++ # IP/CIDR ranges allowed as inbound sources. With default: deny, sources not listed here+ # are blocked unless allowed by allowed_ports-only rules.+ allowed_ips: []++ # IP/CIDR ranges blocked as inbound sources. Block rules take precedence.+ blocked_ips: []++ # TCP destination ports allowed for inbound traffic when default is deny.+ allowed_ports: []++ # 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/scripts/run_docker.sh b/jiuwenbox/scripts/run_docker.shindex 5b71c9be6c..1e5178b74f 100755--- a/jiuwenbox/scripts/run_docker.sh+++ b/jiuwenbox/scripts/run_docker.sh@@ -1,6 +1,6 @@#!/usr/bin/env bash# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.-set -euo pipefail+set -euox pipefailSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"@@ -225,6 +225,7 @@ echodocker run -itd \--name "$CONTAINER_NAME" \+ --restart=unless-stopped \--cap-add=SYS_ADMIN \--cap-add=NET_ADMIN \--security-opt seccomp=unconfined \diff --git a/jiuwenbox/src/jiuwenbox/models/policy.py b/jiuwenbox/src/jiuwenbox/models/policy.pyindex b61af9a73b..eeff7dd931 100644--- a/jiuwenbox/src/jiuwenbox/models/policy.py+++ b/jiuwenbox/src/jiuwenbox/models/policy.py@@ -630,6 +630,85 @@ class CgroupPolicy(BaseModel):)+class TimeoutPolicy(BaseModel):+ """jiuwenbox 服务端的空闲沙箱淘汰配置.++ 本字段仅在 server 启动时加载的根 policy (``SandboxManager.policy``) 上生效,+ 用于驱动后台 reaper task; per-sandbox policy 上的同名字段不会影响沙箱隔离+ (不下传到 bwrap / landlock / cgroup), 仅用于配置回显。++ Fields:+ idle_timeout: 沙箱最大空闲时长 (秒). ``None`` 或 ``<= 0`` 表示禁用淘汰+ (默认禁用, 与未配置 timeout 字段时行为完全一致)。+ idle_check_interval: reaper 轮询间隔 (秒). 必须 ``> 0``。+ """++ model_config = ConfigDict(extra="forbid")++ idle_timeout: float | None = None+ idle_check_interval: float = 60.0++ @field_validator("idle_timeout", mode="before")+ @classmethod+ def normalize_idle_timeout(cls, value: object) -> float | None:+ if value is None:+ return None+ if isinstance(value, bool):+ raise ValueError("idle_timeout must be a number, not a boolean")+ if isinstance(value, (int, float)):+ number = float(value)+ elif isinstance(value, str):+ text = value.strip()+ if not text:+ return None+ try:+ number = float(text)+ except ValueError as exc:+ raise ValueError(+ f"idle_timeout must parse as a number of seconds, got {value!r}"+ ) from exc+ else:+ raise ValueError(+ f"idle_timeout must be number or string, got {type(value).__name__}"+ )+ if number <= 0:+ # Treat 0 / negative as "disabled" so users can flip the feature+ # off without removing the whole key from their YAML.+ return None+ return number++ @field_validator("idle_check_interval", mode="before")+ @classmethod+ def normalize_idle_check_interval(cls, value: object) -> float:+ if value is None:+ return 60.0+ if isinstance(value, bool):+ raise ValueError(+ "idle_check_interval must be a positive number, not a boolean"+ )+ if isinstance(value, (int, float)):+ number = float(value)+ elif isinstance(value, str):+ text = value.strip()+ if not text:+ return 60.0+ try:+ number = float(text)+ except ValueError as exc:+ raise ValueError(+ f"idle_check_interval must parse as a number of seconds, "+ f"got {value!r}"+ ) from exc+ else:+ raise ValueError(+ f"idle_check_interval must be number or string, "+ f"got {type(value).__name__}"+ )+ if number <= 0:+ raise ValueError("idle_check_interval must be > 0")+ return number++class SecurityPolicy(BaseModel):"""Complete static security policy for a sandbox."""@@ -644,6 +723,7 @@ class SecurityPolicy(BaseModel):syscall: SyscallPolicy = Field(default_factory=SyscallPolicy)network: NetworkPolicy = Field(default_factory=NetworkPolicy)cgroup: CgroupPolicy = Field(default_factory=CgroupPolicy)+ timeout: TimeoutPolicy = Field(default_factory=TimeoutPolicy)inference_privacy_proxies: InferencePrivacyProxyPolicy = Field(default_factory=InferencePrivacyProxyPolicy)def tostring(self) -> str:diff --git a/jiuwenbox/src/jiuwenbox/models/sandbox.py b/jiuwenbox/src/jiuwenbox/models/sandbox.pyindex 74a9582174..0cd7c976c8 100644--- a/jiuwenbox/src/jiuwenbox/models/sandbox.py+++ b/jiuwenbox/src/jiuwenbox/models/sandbox.py@@ -37,6 +37,11 @@ class SandboxRef(BaseModel):pid: int | None = Nonecreated_at: datetime = Field(default_factory=datetime.now)started_at: datetime | None = None+ # 最后一次 sandbox API 调用 (exec / file IO / lifecycle 切换) 的时间戳, 仅+ # 供 jiuwenbox 服务端 reaper 用于判定空闲淘汰; 不持久化 (重启时跟整个+ # sandbox 注册表一起被清空) 也不下传到 daemon。``None`` 表示尚未发生过+ # 任何交互, reaper 会用 ``started_at`` 兜底。+ last_active_at: datetime | None = Noneerror_message: str | None = Noneenv: dict[str, str] = Field(default_factory=dict)diff --git a/jiuwenbox/src/jiuwenbox/server/app.py b/jiuwenbox/src/jiuwenbox/server/app.pyindex 0f6ccd310f..c4bc8c748c 100644--- a/jiuwenbox/src/jiuwenbox/server/app.py+++ b/jiuwenbox/src/jiuwenbox/server/app.py@@ -255,6 +255,15 @@ async def lifespan(_application: FastAPI):"register_zombie_reaper failed during lifespan startup; bwrap ""<defunct> processes may accumulate under the box-server pid",)+ # 起 idle sandbox reaper: 只在 root policy 的 ``timeout.idle_timeout`` 显式+ # 配置时生效, 否则是 no-op (默认禁用), 跟未引入本特性前行为完全等价。+ try:+ _sandbox_manager.start_idle_reaper()+ except Exception: # noqa: BLE001+ logger.exception(+ "start_idle_reaper failed during lifespan startup; idle sandboxes "+ "will not be auto-reaped",+ )logger.info("box-server started (version %s)", __version__)await _proxy_manager.start()# 在 proxy 起来之后、yield (接受请求) 之前给 UDS 打权限: 此刻 uvicorn 已@@ -272,6 +281,18 @@ async def lifespan(_application: FastAPI):await _proxy_manager.stop()except Exception: # noqa: BLE001logger.exception("proxy_manager.stop failed during lifespan shutdown")+ # Stop the idle reaper *before* shutdown_all_sandboxes so the reaper+ # cannot race with the explicit teardown below (both grab+ # ``manager._lock`` and call ``delete_sandbox``; letting them+ # interleave just wastes time deleting things that are about to be+ # deleted anyway).+ try:+ if _sandbox_manager is not None:+ await _sandbox_manager.stop_idle_reaper()+ except Exception: # noqa: BLE001+ logger.exception(+ "sandbox_manager.stop_idle_reaper 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 anddiff --git a/jiuwenbox/src/jiuwenbox/server/routes/policy.py b/jiuwenbox/src/jiuwenbox/server/routes/policy.pyindex 9b5008c9ea..f0b63616b6 100644--- a/jiuwenbox/src/jiuwenbox/server/routes/policy.py+++ b/jiuwenbox/src/jiuwenbox/server/routes/policy.py@@ -5,10 +5,12 @@ from __future__ import annotationsimport logging-from fastapi import APIRouter+from fastapi import APIRouter, HTTPExceptionfrom fastapi.responses import JSONResponse+from pydantic import BaseModel, Field, ValidationErrorfrom jiuwenbox.logging_config import configure_logging+from jiuwenbox.models.policy import TimeoutPolicyrouter = APIRouter(tags=["policies"])@@ -32,3 +34,83 @@ async def get_policy(sandbox_id: str):content={"error": f"No policy found for sandbox '{sandbox_id}'"},)return policy.model_dump(mode="json")+++class UpdateTimeoutRequest(BaseModel):+ """Partial update payload for ``PUT /timeout``.++ Both fields are optional; only those explicitly present in the JSON body+ are applied (detected via :attr:`pydantic.BaseModel.model_fields_set`).+ This lets a client flip just one knob -- e.g. ``{"idle_timeout": null}``+ to disable reaping without resetting ``idle_check_interval`` -- instead+ of having to round-trip the full state.++ Semantics:++ - ``idle_timeout`` accepts a positive number of seconds, or ``null`` /+ ``<= 0`` to disable reaping. Same normalization as+ :class:`TimeoutPolicy.idle_timeout`.+ - ``idle_check_interval`` accepts a positive number of seconds. Passing+ ``null`` here is rejected (use the GET endpoint to learn the current+ value, or restart the server to fall back to the YAML default).+ """++ idle_timeout: float | None = Field(default=None)+ idle_check_interval: float | None = Field(default=None)++[email protected]("/timeout")+async def get_timeout():+ """Return the server-level idle-sandbox reaping configuration.++ Reflects ``mgr.policy.timeout`` -- i.e. the values currently driving the+ background reaper (after any ``PUT /timeout`` updates). When+ ``idle_timeout`` is ``null``, the reaper is disabled.+ """+ mgr = _mgr()+ return mgr.policy.timeout.model_dump(mode="json")++[email protected]("/timeout")+async def update_timeout(request: UpdateTimeoutRequest):+ """Update one or both timeout fields and atomically restart the reaper.++ Only fields *explicitly* present in the request body are touched; omitted+ fields preserve their current value. Validation failures (e.g.+ ``idle_check_interval <= 0``) surface as HTTP 400 with the pydantic+ message. Returns the resulting (post-update) :class:`TimeoutPolicy`.+ """+ mgr = _mgr()+ updates = request.model_dump(exclude_unset=True)++ # ``idle_check_interval: null`` is ambiguous -- "unset" already maps to+ # "don't touch this field", so an explicit null here would mean+ # "interval is None", which TimeoutPolicy rejects anyway. Catch it early+ # with a clear message instead of leaking a generic pydantic error.+ if "idle_check_interval" in updates and updates["idle_check_interval"] is None:+ raise HTTPException(+ status_code=400,+ detail=(+ "idle_check_interval cannot be null; omit the field to "+ "preserve the current value, or pass a positive number"+ ),+ )++ current = mgr.policy.timeout.model_dump()+ current.update(updates)+ try:+ new_timeout = TimeoutPolicy.model_validate(current)+ except ValidationError as exc:+ # Surface as 400 instead of bubbling up to the generic exception+ # handler (which would turn it into a 500 here because the handler+ # only catches ``ValidationError`` raised by request body parsing,+ # not by manual ``model_validate`` calls inside route handlers).+ raise HTTPException(status_code=400, detail=str(exc)) from exc++ applied = await mgr.update_timeout_policy(new_timeout)+ logger.info(+ "timeout policy updated: idle_timeout=%s idle_check_interval=%s",+ applied.idle_timeout,+ applied.idle_check_interval,+ )+ return applied.model_dump(mode="json")diff --git a/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py b/jiuwenbox/src/jiuwenbox/server/sandbox_manager.pyindex 7f2c10f1fe..faccc01771 100644--- a/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py+++ b/jiuwenbox/src/jiuwenbox/server/sandbox_manager.py@@ -45,7 +45,7 @@ def _truncate_for_audit(text: str | None, *, limit: int = _AUDIT_OUTPUT_LIMIT) -from jiuwenbox.logging_config import configure_loggingfrom jiuwenbox.models.common import AuditEventType-from jiuwenbox.models.policy import SecurityPolicy+from jiuwenbox.models.policy import SecurityPolicy, TimeoutPolicyfrom jiuwenbox.models.sandbox import (BackgroundExecResult,ExecResult,@@ -121,6 +121,10 @@ class SandboxManager:self._lock = asyncio.Lock()self._sandboxes: dict[str, SandboxRef] = {}self._policies: dict[str, SecurityPolicy] = {}+ # 空闲沙箱淘汰: 后台 reaper task 句柄 + stop event。``None`` 表示当前没有+ # reaper 在跑 (idle_timeout 未配置 / 已被禁用 / 服务尚未 startup)。+ self._idle_reaper_task: asyncio.Task | None = None+ self._idle_reaper_stop: asyncio.Event | None = None# 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@@ -253,6 +257,193 @@ class SandboxManager:sandbox_id,)+ def start_idle_reaper(self) -> None:+ """Spin up the background idle-sandbox reaper task if configured.++ Reads ``self.policy.timeout``; if ``idle_timeout`` is ``None`` or+ ``<= 0`` (the default), the feature is disabled and this method is+ a no-op. Otherwise a single asyncio task runs forever in the+ background polling every ``idle_check_interval`` seconds and+ deletes any sandbox whose ``last_active_at`` is older than+ ``idle_timeout``.++ Must be called from inside the running event loop (e.g. the+ FastAPI lifespan startup hook). Safe to call multiple times --+ subsequent calls become no-ops when a reaper is already running.+ """+ timeout_cfg = self.policy.timeout+ if timeout_cfg.idle_timeout is None:+ return+ if self._idle_reaper_task is not None and not self._idle_reaper_task.done():+ return+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ logger.warning(+ "start_idle_reaper called outside a running event loop; "+ "idle sandbox reaping will not be active",+ )+ return+ self._idle_reaper_stop = asyncio.Event()+ self._idle_reaper_task = loop.create_task(+ self._idle_reaper_loop(+ idle_timeout=timeout_cfg.idle_timeout,+ check_interval=timeout_cfg.idle_check_interval,+ stop_event=self._idle_reaper_stop,+ ),+ name="jiuwenbox-idle-reaper",+ )+ logger.info(+ "idle reaper started: idle_timeout=%.1fs check_interval=%.1fs",+ timeout_cfg.idle_timeout,+ timeout_cfg.idle_check_interval,+ )++ async def update_timeout_policy(+ self,+ new_timeout: TimeoutPolicy,+ ) -> TimeoutPolicy:+ """Replace the server-level ``timeout`` policy and restart the reaper.++ Atomically: stops the currently running reaper (if any), swaps in+ ``new_timeout`` on the root policy, then starts a fresh reaper using+ the new values. The new reaper only actually launches when+ ``idle_timeout`` is configured (``not None``); otherwise the call+ leaves no reaper running. Returns the resulting ``TimeoutPolicy`` so+ callers (e.g. the PUT route) can echo back the canonical state.++ This only mutates the *root* policy used by the reaper; per-sandbox+ policies cached in ``self._policies`` are unaffected (timeout has no+ bearing on sandbox isolation anyway).++ Idempotency: if ``new_timeout`` 与当前 ``self.policy.timeout`` 字段值+ 完全一致 *且* 已有活着的 reaper task (或两者都为 ``None`` 即"禁用且+ 未运行"), 直接 no-op 返回, 不做 stop/start。 这一短路对反复调用+ ``PUT /api/v1/timeout`` 写入同一组值的客户端 (典型场景: 每次创建+ 沙箱前都重申 idle 配置) 至关重要 —— 否则 ``stop_idle_reaper`` 要等+ 当前 reaper 从 ``stop_event.wait(timeout=check_interval)`` 这一觉+ 醒过来 (最坏 5s 兜底超时), 整个 PUT 调用会平白多出几秒延迟, 把+ 沙箱创建链路一起拖慢。+ """+ if new_timeout == self.policy.timeout:+ reaper_alive = (+ self._idle_reaper_task is not None+ and not self._idle_reaper_task.done()+ )+ # ``idle_timeout is None`` 时 ``start_idle_reaper`` 永远是 no-op,+ # 所以 "无 reaper" 与 "禁用" 等价, 同样可以短路掉。+ if reaper_alive or new_timeout.idle_timeout is None:+ return self.policy.timeout+ # Stop first so the old reaper -- which captured the previous+ # idle_timeout / idle_check_interval by value when it was launched --+ # does not race the new one.+ await self.stop_idle_reaper()+ self.policy = self.policy.model_copy(update={"timeout": new_timeout})+ self.start_idle_reaper()+ return self.policy.timeout++ async def stop_idle_reaper(self) -> None:+ """Signal the reaper to exit and await its termination.++ Called from the lifespan shutdown hook *before*+ :meth:`shutdown_all_sandboxes` so the reaper cannot race with+ explicit teardown (the reaper holds ``self._lock`` briefly when+ sampling, and ``delete_sandbox`` also grabs it -- letting the+ reaper run during shutdown would interleave their work and waste+ time deleting things that are about to be deleted anyway).+ """+ task = self._idle_reaper_task+ stop_event = self._idle_reaper_stop+ if task is None or stop_event is None:+ return+ stop_event.set()+ try:+ await asyncio.wait_for(task, timeout=5.0)+ except asyncio.TimeoutError:+ logger.warning("idle reaper did not stop within 5s; cancelling")+ task.cancel()+ try:+ await task+ except (asyncio.CancelledError, Exception): # noqa: BLE001+ pass+ except Exception: # noqa: BLE001+ logger.exception("idle reaper raised on shutdown")+ finally:+ self._idle_reaper_task = None+ self._idle_reaper_stop = None++ async def _idle_reaper_loop(+ self,+ *,+ idle_timeout: float,+ check_interval: float,+ stop_event: asyncio.Event,+ ) -> None:+ """Per-``check_interval`` poll: delete sandboxes idle longer than+ ``idle_timeout``.++ Idleness is measured against ``last_active_at`` (in-memory only),+ falling back to ``started_at`` / ``created_at`` for sandboxes that+ somehow have no recorded activity yet. ``DELETING`` / ``STOPPED``+ sandboxes are skipped because they are either already on the way+ out or carry no live daemon to reap. Per-sandbox failures are+ swallowed (logged with stack trace) so a single broken sandbox+ cannot stall the entire reaper.+ """+ while True:+ try:+ await asyncio.wait_for(stop_event.wait(), timeout=check_interval)+ # Stop event fired -> exit cleanly.+ return+ except asyncio.TimeoutError:+ pass++ now = datetime.now(timezone.utc)+ cutoff = now.timestamp() - idle_timeout+ async with self._lock:+ expired_ids: list[str] = []+ for sid, ref in self._sandboxes.items():+ # Only consider READY sandboxes: PROVISIONING is still+ # spinning up its bwrap / daemon (user code hasn't had a+ # chance to touch it yet, so an idle judgment would be+ # bogus); DELETING/STOPPED/ERROR have no live daemon to+ # reap.+ if ref.phase != SandboxPhase.READY:+ continue+ reference_ts = ref.last_active_at or ref.started_at or ref.created_at+ if reference_ts.tzinfo is None:+ # SandboxRef.created_at uses datetime.now() (naive) by+ # default; coerce to UTC so the comparison is well-defined.+ reference_ts = reference_ts.replace(tzinfo=timezone.utc)+ if reference_ts.timestamp() < cutoff:+ expired_ids.append(sid)++ if not expired_ids:+ continue++ logger.info(+ "idle reaper: deleting %d sandbox(es) idle > %.1fs: %s",+ len(expired_ids),+ idle_timeout,+ expired_ids,+ )+ for sid in expired_ids:+ try:+ self.audit.log(+ AuditEventType.SANDBOX_DELETED,+ sid,+ reason="idle_timeout",+ idle_timeout_seconds=idle_timeout,+ )+ await self.delete_sandbox(sid)+ except SandboxNotFoundError:+ # Raced with an external delete; treat as a clean teardown.+ continue+ except Exception: # noqa: BLE001+ logger.exception(+ "idle reaper: delete_sandbox(%s) failed", sid,+ )+def register_zombie_reaper(self,loop: asyncio.AbstractEventLoop | None = None,@@ -294,6 +485,17 @@ class SandboxManager:raise SandboxNotFoundError(f"Sandbox '{sandbox_id}' not found")return ref+ @staticmethod+ def _mark_active(ref: SandboxRef) -> None:+ """Stamp ``ref.last_active_at`` with the current UTC time.++ Caller must already hold ``self._lock`` (typical pattern: call this+ right after the phase==READY check inside the same ``async with``+ block, so the timestamp is established before the IO call leaves the+ lock and races with the idle reaper).+ """+ ref.last_active_at = datetime.now(timezone.utc)+async def create_sandbox(self,spec: SandboxSpec,@@ -339,7 +541,11 @@ class SandboxManager:else:ref.phase = SandboxPhase.READYref.pid = pid- ref.started_at = datetime.now(timezone.utc)+ now = datetime.now(timezone.utc)+ ref.started_at = now+ # 沙箱刚创建即视为最近一次活跃, 避免在第一次 exec 到来之前就被+ # reaper 当成 idle 误杀 (理论上不会, 但显式初始化更直白)。+ ref.last_active_at = nowself._save_state(ref)if cleanup_after_create:await self.runtime.cleanup(sandbox_id)@@ -403,7 +609,9 @@ class SandboxManager:)ref.phase = SandboxPhase.READYref.pid = pid- ref.started_at = datetime.now(timezone.utc)+ now = datetime.now(timezone.utc)+ ref.started_at = now+ ref.last_active_at = nowref.error_message = Noneexcept Exception as e:logger.error("Failed to start sandbox %s: %s", sandbox_id, e, exc_info=True)@@ -461,6 +669,7 @@ class SandboxManager:raise SandboxStateError(f"Cannot exec in sandbox '{sandbox_id}': state is {ref.phase.value}")+ self._mark_active(ref)# One audit row per exec, emitted **after** the runtime returns so# the payload covers both intent (command/workdir) and outcome@@ -514,6 +723,7 @@ class SandboxManager:raise SandboxStateError(f"Cannot exec in sandbox '{sandbox_id}': state is {ref.phase.value}")+ self._mark_active(ref)# Background exec returns a "started yes/no + pid" envelope# rather than stdout/stderr — the raw byte stream is dropped@@ -569,6 +779,7 @@ class SandboxManager:raise SandboxStateError(f"Cannot upload to sandbox '{sandbox_id}': state is {ref.phase.value}")+ self._mark_active(ref)# One audit row per upload, emitted after the call returns so the# payload covers both intent (path/size) and outcome (ok, error,@@ -697,6 +908,7 @@ class SandboxManager:raise SandboxStateError(f"Cannot download from sandbox '{sandbox_id}': state is {ref.phase.value}")+ self._mark_active(ref)# Mirror of ``upload_file_to_sandbox``: a single post-result row# carrying intent + outcome. ``size`` is filled in on success@@ -811,6 +1023,7 @@ class SandboxManager:raise SandboxStateError(f"Cannot list files in sandbox '{sandbox_id}': state is {ref.phase.value}")+ self._mark_active(ref)# Fast path: ask the daemon to walk the directory in-process.# Saves the python3 cold start and the fork+exec that the legacydiff --git a/jiuwenbox/tests/integration/test_server_api_default.py b/jiuwenbox/tests/integration/test_server_api_default.pyindex bf334fab86..488de0a515 100644--- a/jiuwenbox/tests/integration/test_server_api_default.py+++ b/jiuwenbox/tests/integration/test_server_api_default.py@@ -952,6 +952,195 @@ class TestPolicyAPI:assert SANDBOX_WORKSPACE in resp.json()["error"]+def restore_timeout(client):+ """Snapshot the server-level timeout config and restore it on teardown.++ Required because integration tests share one jiuwenbox-server process+ for the whole session: a test that mutates ``mgr.policy.timeout`` must+ not leak that state into the next test (in particular, leaving an+ aggressive idle_timeout active would silently reap sandboxes created+ by unrelated tests).++ Yields the captured snapshot so the test can sanity-check the starting+ state if it cares.+ """+ snapshot_resp = client.get("/api/v1/timeout")+ assert snapshot_resp.status_code == 200, snapshot_resp.text+ snapshot = snapshot_resp.json()+ try:+ yield snapshot+ finally:+ # ``idle_timeout`` may legitimately be ``None`` (= reaping disabled),+ # which the PUT endpoint accepts. ``idle_check_interval`` is always+ # numeric on the manager side, so the restore body is unambiguous.+ client.put("/api/v1/timeout", json={+ "idle_timeout": snapshot["idle_timeout"],+ "idle_check_interval": snapshot["idle_check_interval"],+ })+++class TestTimeoutAPI:+ """Cover the ``GET /timeout`` / ``PUT /timeout`` administrative endpoints+ that drive the server-level idle-sandbox reaper.++ Each test takes the ``restore_timeout`` fixture so the global+ ``mgr.policy.timeout`` is rolled back even when the test asserts halfway+ through.+ """++ @staticmethod+ def test_get_timeout_returns_current_config(client, restore_timeout):+ resp = client.get("/api/v1/timeout")+ assert resp.status_code == 200+ data = resp.json()+ # Schema only: don't hardcode "reaping disabled by default" because+ # ``default-policy.yaml`` could legitimately be changed to opt in.+ assert set(data.keys()) == {"idle_timeout", "idle_check_interval"}+ assert data["idle_check_interval"] is not None+ assert data["idle_check_interval"] > 0+ if data["idle_timeout"] is not None:+ assert data["idle_timeout"] > 0++ @staticmethod+ def test_put_timeout_full_update_round_trips(client, restore_timeout):+ resp = client.put("/api/v1/timeout", json={+ "idle_timeout": 600,+ "idle_check_interval": 30,+ })+ assert resp.status_code == 200, resp.text+ assert resp.json() == {"idle_timeout": 600.0, "idle_check_interval": 30.0}+ # GET must reflect the PUT immediately (single in-memory source of truth).+ assert client.get("/api/v1/timeout").json() == {+ "idle_timeout": 600.0,+ "idle_check_interval": 30.0,+ }++ @staticmethod+ def test_put_timeout_partial_updates_only_idle_timeout(client, restore_timeout):+ client.put("/api/v1/timeout", json={+ "idle_timeout": 600,+ "idle_check_interval": 30,+ })+ # Omit ``idle_check_interval`` -> server keeps the prior value.+ resp = client.put("/api/v1/timeout", json={"idle_timeout": 1200})+ assert resp.status_code == 200, resp.text+ data = resp.json()+ assert data["idle_timeout"] == 1200.0+ assert data["idle_check_interval"] == 30.0++ @staticmethod+ def test_put_timeout_partial_updates_only_idle_check_interval(+ client, restore_timeout,+ ):+ client.put("/api/v1/timeout", json={+ "idle_timeout": 600,+ "idle_check_interval": 30,+ })+ resp = client.put("/api/v1/timeout", json={"idle_check_interval": 120})+ assert resp.status_code == 200, resp.text+ data = resp.json()+ assert data["idle_timeout"] == 600.0+ assert data["idle_check_interval"] == 120.0++ @staticmethod+ def test_put_timeout_disables_reaping_via_null(client, restore_timeout):+ client.put("/api/v1/timeout", json={+ "idle_timeout": 600,+ "idle_check_interval": 30,+ })+ # Explicit null -> reaping disabled, but check_interval is preserved.+ resp = client.put("/api/v1/timeout", json={"idle_timeout": None})+ assert resp.status_code == 200, resp.text+ data = resp.json()+ assert data["idle_timeout"] is None+ assert data["idle_check_interval"] == 30.0++ @staticmethod+ def test_put_timeout_disables_reaping_via_zero(client, restore_timeout):+ # Zero / negative idle_timeout is normalized to None by TimeoutPolicy+ # (lets operators flip the feature off without removing the key).+ client.put("/api/v1/timeout", json={+ "idle_timeout": 600,+ "idle_check_interval": 30,+ })+ resp = client.put("/api/v1/timeout", json={"idle_timeout": 0})+ assert resp.status_code == 200, resp.text+ assert resp.json()["idle_timeout"] is None++ @staticmethod+ def test_put_timeout_rejects_non_positive_check_interval(+ client, restore_timeout,+ ):+ for bad in (0, -1, -0.5):+ resp = client.put(+ "/api/v1/timeout", json={"idle_check_interval": bad},+ )+ assert resp.status_code == 400, (bad, resp.text)++ @staticmethod+ def test_put_timeout_rejects_null_check_interval(client, restore_timeout):+ # ``idle_check_interval: null`` is ambiguous: omitting the key already+ # means "don't touch this field", so an explicit null can only mean+ # "set it to None" -- which TimeoutPolicy forbids. Reject up-front+ # with a 400 instead of leaking a generic pydantic ValidationError.+ resp = client.put(+ "/api/v1/timeout", json={"idle_check_interval": None},+ )+ assert resp.status_code == 400++ @staticmethod+ def test_put_timeout_empty_body_is_noop(client, restore_timeout):+ before = client.get("/api/v1/timeout").json()+ resp = client.put("/api/v1/timeout", json={})+ assert resp.status_code == 200, resp.text+ assert resp.json() == before+ assert client.get("/api/v1/timeout").json() == before++ @staticmethod+ def test_timeout_reaper_deletes_idle_sandbox_end_to_end(+ client, restore_timeout,+ ):+ """End-to-end: configure aggressive timeout, observe reaper deleting+ an untouched sandbox.++ Uses ``idle_timeout=1.5s`` / ``idle_check_interval=0.5s`` so the+ whole test finishes well under 10s. The sandbox is intentionally+ *not* touched after creation -- any exec / file IO would refresh+ ``last_active_at`` and reset the clock.+ """+ resp = client.put("/api/v1/timeout", json={+ "idle_timeout": 1.5,+ "idle_check_interval": 0.5,+ })+ assert resp.status_code == 200, resp.text++ create = client.post("/api/v1/sandboxes", json={})+ assert create.status_code == 201, create.text+ sandbox_id = create.json()["id"]+ # Sanity: sandbox visible right after create.+ listing = client.get("/api/v1/sandboxes").json()+ assert any(item["id"] == sandbox_id for item in listing), listing++ # idle_timeout (1.5s) + worst-case check_interval delay (0.5s) ++ # generous slack for ProcessRuntime.cleanup -> 8s deadline.+ deadline = time.monotonic() + 8.0+ reaped = False+ while time.monotonic() < deadline:+ still_present = any(+ item["id"] == sandbox_id+ for item in client.get("/api/v1/sandboxes").json()+ )+ if not still_present:+ reaped = True+ break+ time.sleep(0.25)+ assert reaped, (+ f"reaper did not delete idle sandbox {sandbox_id} within 8s "+ f"(idle_timeout=1.5s, idle_check_interval=0.5s)"+ )++class TestPolicyEnforcement:@staticmethoddef test_filesystem_read_write_rule_allows_upload_and_download(diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.pyindex b13b4c5029..76b8b7b0b0 100644--- a/jiuwenswarm/common/config.py+++ b/jiuwenswarm/common/config.py@@ -8,7 +8,7 @@ import sysimport uuidfrom copy import deepcopyfrom pathlib import Path-from typing import Any+from typing import Any, Optionalimport yaml@@ -1349,21 +1349,70 @@ def get_model_config(name: str, index: int | None = None) -> dict[str, Any] | No# enabled: true# excluded_commands: [...]# files: { allow: [...], deny: [...] }+# idle_ttl_seconds: 600 # 可选, 默认 None = 不进行 idle 驱逐+# idle_check_interval: 60 # 可选, 默认 None = 让 jiuwenbox 端用自身默认值## ``get_sandbox_runtime`` 把这些 key 读出来填默认值;# ``update_sandbox_runtime`` 写回时也只动这几个 key, 不动 endpoint 字段。+#+# ``idle_ttl_seconds`` / ``idle_check_interval`` 透传给+# ``create_sandbox_sysop_card`` 作为同名参数, 最终在 jiuwenbox provider 里通过+# ``PUT /api/v1/timeout`` 写到 jiuwenbox server 根 policy 上 (per-sandbox policy+# 的 ``timeout`` 子段不驱动 reaper, 必须改根 policy 才能让空闲淘汰生效)。# =====================================================================_SANDBOX_RUNTIME_DEFAULTS: dict[str, Any] = {"enabled": False,"excluded_commands": [],"files": {"allow": [], "deny": []},+ "idle_ttl_seconds": None,+ "idle_check_interval": None,}# 受 ``get_sandbox_runtime`` / ``update_sandbox_runtime`` 管辖的 sandbox 字段。_SANDBOX_RUNTIME_KEYS: tuple[str, ...] = tuple(_SANDBOX_RUNTIME_DEFAULTS.keys())+def _coerce_optional_positive_int(+ value: Any, *, field: str, allow_zero: bool = False+) -> Optional[int]:+ """把 yaml/json 来的 idle 配置值归一化为 ``Optional[int]``.++ - ``None`` / 缺失 / 空字符串 → ``None``。+ - ``int`` / 数字字符串 → ``int(value)``; ``allow_zero=False`` 时 ``<= 0``+ 也归一化为 ``None`` (避免后续负值流到 jiuwenbox 端引发歧义)。+ - 其它 (``bool`` / 不可解析字符串等) → ``ValueError``。+ """+ if value is None:+ return None+ if isinstance(value, bool):+ # bool 是 int 子类, 必须先排掉; ``True`` -> 1 这种隐式转换在配置文件里+ # 几乎肯定是误写, 不要静默放行。+ raise ValueError(f"{field} must be a number, not a boolean")+ if isinstance(value, str):+ text = value.strip()+ if not text:+ return None+ try:+ number = int(text)+ except ValueError:+ try:+ number = int(float(text))+ except ValueError as exc:+ raise ValueError(+ f"{field} must parse as an integer of seconds, got {value!r}"+ ) from exc+ elif isinstance(value, (int, float)):+ number = int(value)+ else:+ raise ValueError(+ f"{field} must be number or string, got {type(value).__name__}"+ )+ if not allow_zero and number <= 0:+ return None+ return number++def _ensure_sandbox_runtime_shape(runtime: Any) -> dict[str, Any]:"""填充 sandbox runtime 缺省字段,返回归一化后的 dict(不写盘)。"""base = {k: (list(v) if isinstance(v, list) else dict(v) if isinstance(v, dict) else v)@@ -1386,6 +1435,16 @@ def _ensure_sandbox_runtime_shape(runtime: Any) -> dict[str, Any]:"allow": list(allow) if isinstance(allow, list) else [],"deny": list(deny) if isinstance(deny, list) else [],}+ if "idle_ttl_seconds" in runtime:+ # ``<= 0`` 归一化成 ``None`` (= 禁用淘汰), 与 jiuwenbox server 端+ # ``TimeoutPolicy.idle_timeout`` 的语义对齐。+ out["idle_ttl_seconds"] = _coerce_optional_positive_int(+ runtime["idle_ttl_seconds"], field="sandbox.idle_ttl_seconds",+ )+ if "idle_check_interval" in runtime:+ out["idle_check_interval"] = _coerce_optional_positive_int(+ runtime["idle_check_interval"], field="sandbox.idle_check_interval",+ )return out@@ -1728,7 +1787,9 @@ def update_sandbox_runtime(patch: dict[str, Any]) -> dict[str, Any]:Args:patch: 部分字段更新;支持顶层键 ``enabled`` / ``excluded_commands``- / ``files``。 ``files`` 字典若提供则整体替换;其余键按值合并。+ / ``files`` / ``idle_ttl_seconds`` / ``idle_check_interval``。+ ``files`` 字典若提供则整体替换;其余键按值合并。 ``idle_*`` 字段+ 接受整数秒数 (``<= 0`` 归一化为 ``None`` = 禁用淘汰) 或 ``None``。"""if not isinstance(patch, dict):raise ValueError("patch must be an object")@@ -1755,6 +1816,14 @@ def update_sandbox_runtime(patch: dict[str, Any]) -> dict[str, Any]:"allow": list(allow) if isinstance(allow, list) else merged["files"]["allow"],"deny": list(deny) if isinstance(deny, list) else merged["files"]["deny"],}+ if "idle_ttl_seconds" in patch:+ merged["idle_ttl_seconds"] = _coerce_optional_positive_int(+ patch["idle_ttl_seconds"], field="sandbox.idle_ttl_seconds",+ )+ if "idle_check_interval" in patch:+ merged["idle_check_interval"] = _coerce_optional_positive_int(+ patch["idle_check_interval"], field="sandbox.idle_check_interval",+ )data = _load_yaml_round_trip(_CONFIG_YAML_PATH)if "sandbox" not in data or not isinstance(data.get("sandbox"), dict):diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex 919fd5ceee..2906077216 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -2957,10 +2957,12 @@ class AgentWebSocketServer:校验失败时直接拒绝命令, 不让 yaml 进入"build 不出 policy"的死局。"""project_dir = self._resolve_active_project_dir(channel_id, params)+ is_code_agent = self._resolve_active_is_code_agent(channel_id)try:build_filesystem_policy(files,project_dir=project_dir,+ is_code_agent=is_code_agent,)except FileNotFoundError as exc:raise ValueError(str(exc)) from exc@@ -2991,9 +2993,11 @@ class AgentWebSocketServer:# project_dir`` 以便 TUI 通过 ``trusted_dirs`` / ``cwd`` 显式声明的# 项目目录也参与 auto 路径的判定。project_dir = self._resolve_active_project_dir(channel_id, params)+ is_code_agent = self._resolve_active_is_code_agent(channel_id)match = find_auto_managed_match(path,project_dir=project_dir,+ is_code_agent=is_code_agent,)if match is not None:matched_bucket, canonical = match@@ -3062,9 +3066,11 @@ class AgentWebSocketServer:# 而不是让 /sandbox 默默地把同一个 auto-managed 名字从用户配置里抹掉# ——后者会让用户误以为他/她真的把 sandbox 自动条目摘掉了。project_dir = self._resolve_active_project_dir(channel_id, params)+ is_code_agent = self._resolve_active_is_code_agent(channel_id)match = find_auto_managed_match(path,project_dir=project_dir,+ is_code_agent=is_code_agent,)if match is not None:matched_bucket, canonical = match@@ -3148,6 +3154,34 @@ class AgentWebSocketServer:return firstreturn None+ def _resolve_active_is_code_agent(self, channel_id: str) -> bool:+ """Look up whether ``channel_id``'s adapter is the code-agent flavor.++ Mirrors :meth:`_resolve_active_project_dir`'s adapter lookup so the+ three sandbox call sites (``_dry_run_files_policy``,+ ``_handle_sandbox_files_set`` / ``_remove``'s ``find_auto_managed_+ match``, ``_attach_effective_sandbox_files``'s+ ``list_effective_sandbox_files``) all hand the same flag into+ ``sysop_builder``. Without this, the dry-run / display side would+ always assume non-code-agent and mismatch the actual mount layout+ a Code adapter produces at sandbox-start time (project_dir vs+ ``get_agent_workspace_dir``).++ Returns ``False`` on any failure path (no agent, no adapter, attr+ absent) — that matches the base class default and keeps the dry-run+ / display strictly aligned with what :class:`JiuWenClawDeepAdapter`+ emits when ``_is_code_agent`` was never set.+ """+ try:+ agent = self._agent_manager.get_agent_nowait(channel_id)+ except Exception as exc: # noqa: BLE001+ logger.debug("[command.sandbox] is_code_agent lookup: get_agent_nowait failed: %s", exc)+ return False+ adapter = self._resolve_adapter(agent)+ if adapter is None:+ return False+ return bool(getattr(adapter, "_is_code_agent", False))+def _attach_effective_sandbox_files(self,payload: dict[str, Any],@@ -3188,9 +3222,11 @@ class AgentWebSocketServer:if files_runtime is None:files_runtime = get_sandbox_runtime().get("files") or {}project_dir = self._resolve_active_project_dir(channel_id, params)+ is_code_agent = self._resolve_active_is_code_agent(channel_id)payload["effective_files"] = list_effective_sandbox_files(files_runtime,project_dir=project_dir,+ is_code_agent=is_code_agent,)except Exception as exc: # noqa: BLE001logger.warning("[command.sandbox] attach effective_files failed: %s", exc)diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex ae09a3115b..0696c42546 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -134,6 +134,12 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):self._project_memory_rail: ProjectMemoryRail | None = Noneself._coding_memory_rail: CodingMemoryRail | None = Noneself._worktree_rail: WorktreeRail | None = None+ # 单点 source-of-truth, 让 sysop_builder 的"主写入根"分支+ # (project_dir vs get_agent_workspace_dir) 落到 code-agent 这一支。+ # 父类默认 False (deep agent → workspace), Code adapter override 成+ # True (code-agent → project_dir). 见+ # ``sysop_builder.build_filesystem_policy`` 中 line 545 附近的分支。+ self._is_code_agent: bool = True# ─── Language override ────────────────────────diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 13b0332569..a848b9a9ba 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -450,6 +450,14 @@ class JiuWenClawDeepAdapter:self._project_dir: str | None = Noneself._workspace_dir: str = str(get_agent_workspace_dir())self._agent_name: str = "main_agent"+ # 是否是 code-agent 形态. 基类 (deep adapter) 默认 False, 由子类+ # JiuwenClawCodeAdapter 在 __init__ 里改成 True. 该字段透传给+ # sysop_builder 的 ``build_filesystem_policy`` / ``create_sandbox_+ # sysop_card``, 决定沙箱挂的"主写入根"是用户工程目录 (project_dir,+ # code-agent 场景) 还是 agent 自己的 workspace 目录 (deep agent+ # 场景). 单点 source-of-truth, 避免分布在多个方法里靠 isinstance+ # 或字符串嗅探 agent_name 反推。+ self._is_code_agent: bool = Falseself._vision_tools_registered: bool = Falseself._audio_tools_registered: bool = Falseself._video_tool_registered: bool = False@@ -1611,8 +1619,8 @@ class JiuWenClawDeepAdapter:rail = Nonereturn rail- @staticmethoddef _create_sandbox_sys_operation(+ self,sandbox_url: str,sandbox_type: str,*,@@ -1624,14 +1632,24 @@ class JiuWenClawDeepAdapter:Delegates the actual construction to ``sysop_builder.py`` so that both``interface_deep.py`` and ``interface_code.py`` share one implementation.+ 历史上这是 ``@staticmethod``——但 sysop_builder 现在需要知道适配器形态+ (``is_code_agent`` 决定是否把 ``project_dir`` 挂为 rw bind), 这个信号是+ instance state (``self._is_code_agent``, 基类默认 False, ``JiuwenClaw+ CodeAdapter`` 子类 override 成 True), staticmethod 拿不到。 因此必须降+ 成 instance method 才能透传; 调用方相应把 ``JiuWenClawDeepAdapter+ ._create_sandbox_sys_operation(...)`` 改成 ``self._create_sandbox_+ sys_operation(...)``, 走类 MRO 让 Code 子类覆写时也能命中。+Args:sandbox_url: jiuwenbox HTTP base url.sandbox_type: provider 名 (jiuwenbox).- runtime: ``sandbox`` 字段字典 (含 enabled / files / excluded_commands),- 来自 ``get_sandbox_runtime``.- project_dir: 用户项目目录 (一般是 ``trusted_dirs[0]``); 透传给- :func:`create_sandbox_sysop_card` 让其作为 rw bind mount。``None``- 时由下游 :func:`build_filesystem_policy` 回落到 cwd / env。+ runtime: ``sandbox`` 字段字典 (含 enabled / files / excluded_commands+ / idle_ttl_seconds / idle_check_interval), 来自+ ``get_sandbox_runtime``.+ project_dir: 用户项目目录 (一般是 ``trusted_dirs[0]``); 仅在+ ``self._is_code_agent=True`` 时被 :func:`build_filesystem_policy`+ 消费作为 rw bind mount, 否则 (deep adapter 等通用形态) 完全+ 忽略——sysop_builder 不会有 cwd / env 之类的 fallback 接管。"""runtime = runtime or {}return create_sandbox_sysop_card(@@ -1639,7 +1657,10 @@ class JiuWenClawDeepAdapter:sandbox_type,files_runtime=runtime.get("files"),excluded_commands=runtime.get("excluded_commands"),+ idle_ttl_seconds=runtime.get("idle_ttl_seconds"),+ idle_check_interval=runtime.get("idle_check_interval"),project_dir=project_dir,+ is_code_agent=self._is_code_agent,)def _resolve_project_dir_for_sandbox(self) -> str | None:@@ -1704,8 +1725,10 @@ class JiuWenClawDeepAdapter:是否走沙箱由 ``config.yaml::sandbox.enabled`` 决定(同时要求``sandbox.url`` / ``sandbox.type`` 已配置)。其他 sandbox 字段- (``excluded_commands`` / ``files``) 透传给 ``create_sandbox_sysop_card``- 写入 ``launcher_config.extra_params``。+ (``excluded_commands`` / ``files`` / ``idle_ttl_seconds`` /+ ``idle_check_interval``) 透传给 ``create_sandbox_sysop_card``,+ 分别写入 ``launcher_config.extra_params`` 与 ``launcher_config`` 上+ 的同名字段。注意: 每次都从 ``get_config()`` 读最新 sandbox.url/type, 因为``/sandbox enable`` 会动态写入这两个字段。@@ -1720,7 +1743,12 @@ class JiuWenClawDeepAdapter:runtime = get_sandbox_runtime()sysop_card: SysOperationCard | Noneif runtime.get("enabled") and sandbox_url and sandbox_type:- sysop_card = JiuWenClawDeepAdapter._create_sandbox_sys_operation(+ # 走 ``self.`` 而不是 ``JiuWenClawDeepAdapter.``——_create_sandbox_+ # sys_operation 已从 staticmethod 改成 instance method (要透传+ # ``self._is_code_agent``), 用类名直接调会绕过 MRO 把 Code 子类+ # 的 override (如果将来需要的话) 静默吃掉, 且 staticmethod 时代+ # 的 caller 风格不再适用。+ sysop_card = self._create_sandbox_sys_operation(sandbox_url,sandbox_type,runtime=runtime,@@ -1800,6 +1828,7 @@ class JiuWenClawDeepAdapter:new_policy, upload_list = build_filesystem_policy(runtime.get("files") or {},project_dir=self._resolve_project_dir_for_sandbox(),+ is_code_agent=self._is_code_agent,)extra["policy"] = new_policy# provider 侧契约: 沙箱 sysop 永远带这两个 key, mode 固定 ``mount``,diff --git a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.pyindex f984d89d2e..2418e89c19 100644--- a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py+++ b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py@@ -69,6 +69,7 @@ from openjiuwen.core.sys_operation.config import (from jiuwenswarm.common.utils import (get_agent_memory_dir,+ get_agent_skills_dir,get_config_file,get_deepagent_agent_md_path,get_deepagent_heartbeat_path,@@ -84,7 +85,10 @@ PreserveFileSharingMode = Literal["mount"]_PRESERVE_FILE_SHARING_MODE: PreserveFileSharingMode = "mount"-_INTRINSIC_FILE_PATH_FUNCS = (+# Read-write intrinsic 文件: deep agent 在沙箱里持续读写的 markdown state 文件.+# 这些路径由 _record_rw_bind 处理 (mode=rw + 0666), 不存在时由 _ensure_intrinsic_file+# 自动 touch 空文件.+_INTRINSIC_RW_FILE_PATH_FUNCS = (get_deepagent_agent_md_path,get_deepagent_heartbeat_path,get_deepagent_identity_md_path,@@ -92,6 +96,22 @@ _INTRINSIC_FILE_PATH_FUNCS = (get_deepagent_user_md_path,)+# Read-only intrinsic 文件: 沙箱必须能读但绝不能写的 host 资源.+# 当前只含 ``config.yaml`` (jiuwenswarm 主配置, 含模型 API key / OAuth secret /+# 用户偏好等), 即使整个 ``/`` 已被 ro-bind / project_dir 把 ``~/.jiuwenswarm/``+# 暴露进沙箱, 这条 ro bind 也能配合末尾 ``--remount-ro`` 兜住, 让沙箱内的 agent+# 不能写回任何修改。+#+# 与 _INTRINSIC_RW_FILE_PATH_FUNCS 的差异:+# - 走 _record_ro_resource_bind (mode=ro bind + read_only_promote 兜底), 既让+# 首挂语义直观, 又能在出现 rw 父挂覆盖时由末尾 --remount-ro 翻回 ro;+# - **不**自动创建空文件: config.yaml 缺失意味着 jiuwenswarm 装得有问题,+# 塞一份空 yaml 会让 loadconfig 端解析失败更早夯死 + 真实问题被掩盖。+# 这里改成 warn + 跳过, 让上层早点暴露。+_INTRINSIC_RO_FILE_PATH_FUNCS = (+ get_config_file,+)+def _normalize_fs_entry(entry: Any, default_permissions: str) -> dict[str, Any] | None:"""归一化 {path, permissions} 项;接受 str/dict,过滤空值。"""@@ -135,62 +155,98 @@ def _ensure_intrinsic_file(path: Path) -> bool:return False-def _ensure_intrinsic_dir(path: Path) -> bool:- """确保固有目录存在; 不存在则 ``mkdir -p``。返回是否就绪可用。"""- try:- path.mkdir(parents=True, exist_ok=True)- if not path.is_dir():- logger.warning(- "[sysop_builder] intrinsic path %s exists but is not a directory; "- "skipping from sandbox bind/upload list",- path,- )- return False- return True- except OSError as exc:- logger.warning(- "[sysop_builder] could not ensure intrinsic dir %s: %s; "- "skipping from sandbox bind/upload list",- path,- exc,- )- return False+def _collect_intrinsic_targets() -> tuple[list[str], list[str], list[str]]:+ """收集 deep agent 固有路径 (host 上的绝对路径), 分 rw / ro 两类返回.+ 分类规则:-def _collect_intrinsic_targets() -> tuple[list[str], list[str]]:- """收集 deep agent 固有文件路径与目录路径 (host 上的绝对路径).+ - **rw_files** (``mode=rw``, ``0666``): agent 在沙箱里持续读写的 state 文件+ (``_INTRINSIC_RW_FILE_PATH_FUNCS``). 不存在时由 :func:`_ensure_intrinsic_file`+ 自动 touch 空文件, 保证 bwrap ``--bind`` 的 host_src 存在。+ - **rw_dirs** (``mode=rw``, ``0777``): agent 需要读写的目录 (``daily_memory``).+ **不自动创建**——host 上不存在 (例如该 agent 还没生成过 daily_memory)+ 时, 跳过该条目, 不进沙箱 bind list, 也不主动 ``mkdir``。 这样可避免:+ (a) 因 ``get_agent_memory_dir()`` 解析出意外路径而误建目录;+ (b) 用户清理本地 memory 后, sandbox 启动反而把它静默重建。+ - **ro_files** (``mode=ro``, ``0444``): 沙箱必须只读访问的 host 资源+ (``_INTRINSIC_RO_FILE_PATH_FUNCS``, 当前只有 ``config.yaml``). **绝不**自动+ 创建——主配置缺失意味着 jiuwenswarm 没装好, 创建空文件只会让真问题晚些时候+ 在 loadconfig 时炸出, 加大排查难度; 这里改成 warn + 跳过。- 会对每个解析到的路径做存在性检查; 不存在则创建空文件 / 空目录,- 保证下游 bind_mount 时 host_path 一定存在。 创建失败的条目会被静默剔除,- 避免污染 sandbox 启动路径。+ 解析或副作用失败的条目都被静默剔除 (rw) / warn-跳过 (ro), 防止污染 sandbox 启动路径。Returns:- ``(file_paths, dir_paths)``; 解析或创建失败的条目均跳过。+ ``(rw_files, rw_dirs, ro_files)``."""- file_paths: list[str] = []- dir_paths: list[str] = []+ rw_files: list[str] = []+ rw_dirs: list[str] = []+ ro_files: list[str] = []- for func in _INTRINSIC_FILE_PATH_FUNCS:+ for func in _INTRINSIC_RW_FILE_PATH_FUNCS:try:raw = func()except Exception as exc: # noqa: BLE001- logger.debug("[sysop_builder] intrinsic file path func failed: %s", exc)+ logger.debug(+ "[sysop_builder] intrinsic rw file path func failed: %s", exc,+ )continueif raw is None:continuepath = Path(raw)if _ensure_intrinsic_file(path):- file_paths.append(str(path))+ rw_files.append(str(path))try:daily_memory = Path(get_agent_memory_dir()) / "daily_memory"except Exception as exc: # noqa: BLE001logger.debug("[sysop_builder] daily_memory dir resolve failed: %s", exc)else:- if _ensure_intrinsic_dir(daily_memory):- dir_paths.append(str(daily_memory))+ # mount 前显式检查 host 上是否存在 daily_memory 目录; 不存在则跳过, 不+ # 自动 ``mkdir``。 bwrap 在 ``--bind`` 时要求 host_src 必须存在, 这里+ # 提前剔掉避免后续沙箱启动失败; 同时拒绝"沙箱启动反而把已被用户清理+ # 的 memory 目录静默重建"的行为。+ if daily_memory.is_dir():+ rw_dirs.append(str(daily_memory))+ else:+ logger.info(+ "[sysop_builder] daily_memory %s does not exist on host; "+ "skipping from sandbox bind list (mount only when present)",+ daily_memory,+ )- return file_paths, dir_paths+ for func in _INTRINSIC_RO_FILE_PATH_FUNCS:+ try:+ raw = func()+ except Exception as exc: # noqa: BLE001+ logger.debug(+ "[sysop_builder] intrinsic ro file path func failed: %s", exc,+ )+ continue+ if raw is None:+ continue+ try:+ resolved = Path(raw).expanduser().resolve()+ except OSError as exc:+ logger.warning(+ "[sysop_builder] intrinsic ro file %s could not be resolved: %s; "+ "skipping from sandbox bind list",+ raw, exc,+ )+ continue+ if not resolved.exists():+ # 故意不 _ensure_intrinsic_file: 见函数 docstring 关于 ro 类不自动建空文件+ # 的原因。这里 warn 不报错让 sandbox 仍能启动 (沙箱内 agent 只是看不到+ # 这条 ro 文件); 真正的 jiuwenswarm 主进程会在 loadconfig 阶段炸出更准确+ # 的错误。+ logger.warning(+ "[sysop_builder] intrinsic ro file %s does not exist on host; "+ "skipping from sandbox bind list",+ resolved,+ )+ continue+ ro_files.append(str(resolved))++ return rw_files, rw_dirs, ro_filesdef _resolve_project_dir(override: str | Path | None) -> Path | None:@@ -247,10 +303,55 @@ def _resolve_project_dir(override: str | Path | None) -> Path | None:return None+def _resolve_agent_skills_dir() -> Path | None:+ """Resolve the package-bundled built-in skills dir for sandbox mounting.++ :func:`get_agent_skills_dir` returns the path inside the installed+ jiuwenswarm package (``resources/agent/workspace/skills`` or its+ fallback ``resources/agent/skills``). The sandboxed agent both reads+ the bundled skill templates and may mutate / install new skills under+ this directory at runtime, so :func:`build_filesystem_policy` binds it+ rw (intentionally **not** added to ``filesystem_policy.read_only``).+ Mutations therefore propagate back to the host package install, which+ is by design for the skills lifecycle.++ Returns ``None`` when:+ - resolution itself raises (broken install / unusual layout);+ - the resolved path doesn't exist on disk;+ - the resolved path exists but isn't a directory.++ A ``None`` return is treated by ``build_filesystem_policy`` as "skip+ silently" (development checkouts without the ``resources/`` directory+ shipped will keep working; the sandbox just won't see the built-in+ skills, same as before this hook was added).+ """+ try:+ raw = get_agent_skills_dir()+ except Exception as exc: # noqa: BLE001+ logger.debug("[sysop_builder] builtin skills dir resolve failed: %s", exc)+ return None+ try:+ resolved = Path(raw).expanduser().resolve()+ except OSError as exc:+ logger.debug(+ "[sysop_builder] builtin skills dir %s could not be resolved: %s",+ raw, exc,+ )+ return None+ if not resolved.is_dir():+ logger.debug(+ "[sysop_builder] builtin skills dir %s is not a directory; skipping",+ resolved,+ )+ return None+ return resolved++def build_filesystem_policy(files_runtime: dict[str, Any] | None,*,project_dir: str | Path | None = None,+ is_code_agent: bool = False,) -> tuple[dict[str, Any], list[dict[str, str]]]:"""组装 jiuwenbox 沙箱的 filesystem policy.@@ -258,9 +359,19 @@ def build_filesystem_policy(files_runtime: ``config.yaml::sandbox.files`` 的字典,可能包含``allow`` / ``deny`` 列表(项支持 str 或 {path, permissions} 形式)project_dir: 当前工程目录的覆盖值, 缺省时回落到 :func:`_resolve_project_dir`- (优先级 override -> 环境变量 -> ``cwd``). 解析成功时会作为 ``rw``- bind mount 进沙箱, 并同步登记到 allow 列表; 解析失败 (例如指向- ``/``) 时静默跳过。+ (优先级 override -> 环境变量 -> ``cwd``). 仅在 ``is_code_agent=True``+ 时会被消费并作为 ``rw`` bind mount 进沙箱; ``is_code_agent=False``+ 时该字段被完全忽略 (不会有 fallback 挂 workspace 之类), 沙箱里也+ 不会出现对应 rw bind。 解析失败 (例如指向 ``/``) 时静默跳过。+ is_code_agent: 是否是 code-agent 形态. ``True`` → mount 用户工程目录+ (``project_dir`` / ``cwd``, 由 :func:`_resolve_project_dir` 解析),+ agent 在沙箱里直接编辑用户仓库; ``False`` (默认, deep agent 等+ 通用形态) → **完全不挂主写入根**, 沙箱只保留 intrinsic 文件+ (AGENT/HEARTBEAT/...) + daily_memory + agent_skills + 用户+ 显式 ``files.allow``。 不挂 workspace 是为了避免把 agent-server+ 进程的工作区 (含历史 session checkpoint / 边角持久化文件) 整片+ 暴露进沙箱; 真要带额外 host 路径请走 ``/sandbox files allow`` 显式+ 声明。Returns:``(policy_dict, upload_list)``:@@ -375,7 +486,48 @@ def build_filesystem_policy(if sandbox_path not in read_only_promote:read_only_promote.append(sandbox_path)- intrinsic_files, intrinsic_dirs = _collect_intrinsic_targets()+ def _record_ro_resource_bind(host_path: str, sandbox_path: str) -> None:+ """Register a built-in readonly resource bind (intrinsic host data).++ Used for resources the sandbox must be able to *read* but never+ write — currently only :func:`get_config_file` (sensitive+ credentials). The intent is distinct from :func:`_record_user_deny_bind`,+ which represents a user-driven ``files.deny`` entry where the+ underlying host path is normally rw and deny is just an extra+ constraint. Here the host path is *intrinsically* read-only from+ the sandbox's perspective and there is no user-side rw semantics+ to preserve.++ The built-in skills directory is intentionally **not** routed+ through this helper; it is rw-mountable so the sandboxed agent+ can also edit / install skills. See the call site in+ :func:`build_filesystem_policy`.++ Implementation: ``mode=ro`` bind + ``read_only_promote`` belt-and-+ suspenders.++ - ``mode=ro`` makes the first-pass mount land in bwrap's+ ``--ro-bind`` stage, which is the natural and self-documenting+ encoding for "ro intrinsic resource".+ - The :data:`read_only_promote` entry survives the case where a+ later rw parent bind (e.g. a user-configured ``files.allow`` on+ the parent directory of ``config.yaml``) overlays the same+ subtree and silently upgrades the mount back to rw. bwrap's+ ``created_paths`` set is the union of ro_binds + rw_binds+ destinations (see ``bwrap.py``), so the trailing+ ``--remount-ro <path>`` is guaranteed to fire on this dst and+ flip it back to read-only regardless of which stage owned the+ mount last.+ """+ bind_mounts.append({+ "host_path": host_path,+ "sandbox_path": sandbox_path,+ "mode": "ro",+ })+ if sandbox_path not in read_only_promote:+ read_only_promote.append(sandbox_path)++ intrinsic_files, intrinsic_dirs, intrinsic_ro_files = _collect_intrinsic_targets()for path in intrinsic_files:_record_rw_bind(path, path, is_dir=False, permissions="0666")@@ -383,12 +535,40 @@ def build_filesystem_policy(for path in intrinsic_dirs:_record_rw_bind(path, path, is_dir=True, permissions="0777")- # 当前工程目录 (cwd) 走 rw bind, 让 sandbox 内的 agent 能读写用户的代码- # 仓库。 解析失败 / 指向 ``/`` 一律跳过 (由 _resolve_project_dir 内部 warn)。- resolved_project = _resolve_project_dir(project_dir)- if resolved_project is not None:- project_str = str(resolved_project)- _record_rw_bind(project_str, project_str, is_dir=True, permissions="0777")+ # Readonly intrinsic 资源 (目前只有 ``config.yaml``): 跟 agent_skills 同类,+ # 沙箱必须能读但绝不能写。统一走 ``_record_ro_resource_bind``, 末尾+ # ``--remount-ro`` 兜底, 保证 "父 rw + 子 ro" 拓扑下 ro 仍然鲁棒。+ #+ # config.yaml 的过去实现是散落在 build_filesystem_policy 末尾的内联 try/except+ # 调用 ``_record_user_deny_bind``——但 config.yaml 是服务强制 deny 而非用户主动+ # deny, 跟 ``files.deny`` 用户配置完全是两种语义; 归到这里跟 agent_skills /+ # 未来其他 ro intrinsic 一起统一处理, 语义和入口都更清晰。+ for path in intrinsic_ro_files:+ _record_ro_resource_bind(path, path)++ agent_skills = _resolve_agent_skills_dir()+ if agent_skills is not None:+ skills_str = str(agent_skills)+ _record_rw_bind(skills_str, skills_str, is_dir=True, permissions="0777")++ # 仅 code-agent 才挂用户工程目录 (cwd / 显式 project_dir): code-agent 的+ # 核心场景就是在用户仓库里读写源码, 不挂工程目录 agent 几乎无事可做。+ # 解析失败 / 指向 ``/`` 由 _resolve_project_dir 内部 warn 并返回 ``None``,+ # 这里静默跳过。+ #+ # 非 code-agent (deep agent 等通用形态) **不挂任何"主写入根"**: 通用+ # agent 没有"用户工程"的概念, 它持续读写的状态都是 intrinsic 文件+ # (AGENT/HEARTBEAT/IDENTITY/SOUL/USER.md, 上面 _record_rw_bind 已分别+ # 挂入) + daily_memory + agent_skills + 用户显式配置的 files.allow,+ # 不需要再额外 rw-bind 一整个 workspace 目录; 把 workspace 整挂会顺势+ # 暴露 agent 不该让沙箱读写的边角文件 (历史 session checkpoint 等),+ # 安全收益不明确, 反而扩大 attack surface。 真要往沙箱带额外路径,+ # 走 ``/sandbox files allow`` 显式声明。+ if is_code_agent:+ resolved_project = _resolve_project_dir(project_dir)+ if resolved_project is not None:+ project_str = str(resolved_project)+ _record_rw_bind(project_str, project_str, is_dir=True, permissions="0777")# ``files.allow`` 与 ``files.deny`` 走完全对称的处理流程:#@@ -430,24 +610,9 @@ def build_filesystem_policy(if path not in read_write_promote:read_write_promote.append(path)- # jiuwenswarm 自己的 config.yaml 永远 deny_write: 文件里有模型 API key /- # OAuth secret 之类的凭据。 即便 ``/`` 被 ro-bind 进沙箱 (code-agent-- # policy.yaml 默认行为) 或 project_dir 把整个 ``~/.jiuwenswarm/`` 暴露- # 进来, 沙箱内还能读到这份 config.yaml; 我们这条 auto-deny 通过- # ``_record_user_deny_bind`` 把它翻成 ``bind_mount rw`` + ``read_only``- # patch, 末尾 ``--remount-ro`` 把它从用户 ``allow`` 升出来的 rw 区域里- # 挑出来禁写。 读权限不变 (符合 deny_write 语义), 但 agent 已无法把任何- # 修改写回 host config.yaml.- try:- config_yaml_path = str(Path(get_config_file()).expanduser().resolve())- if config_yaml_path and Path(config_yaml_path).exists():- _record_user_deny_bind(config_yaml_path, config_yaml_path)- except Exception as exc: # noqa: BLE001- logger.warning(- "[sysop_builder] could not resolve config.yaml for auto deny: %s",- exc,- )-+ # jiuwenswarm 自己的 config.yaml 走 ``_INTRINSIC_RO_FILE_PATH_FUNCS`` 路径,+ # 跟 agent_skills 一起在上面统一注册; 这里不再单独处理。 (见+ # ``_collect_intrinsic_targets`` 与 ``_record_ro_resource_bind`` 的注释.)for entry in files_runtime.get("deny") or []:normalized = _normalize_fs_entry(entry, default_permissions="0000")if normalized is None:@@ -489,8 +654,10 @@ def create_sandbox_sysop_card(*,files_runtime: dict[str, Any] | None = None,excluded_commands: list[str] | None = None,- idle_ttl_seconds: int = 600,+ idle_ttl_seconds: int | None = None,+ idle_check_interval: int | None = None,project_dir: str | Path | None = None,+ is_code_agent: bool = False,) -> SysOperationCard | None:"""构造 jiuwenbox 沙箱模式 SysOperationCard.@@ -499,9 +666,18 @@ def create_sandbox_sysop_card(sandbox_type: jiuwenbox provider 名, 通常为 ``jiuwenbox``files_runtime: ``config.yaml::sandbox.files`` 字典, 含 allow/denyexcluded_commands: 命令 glob 列表; 命中时 provider 直接走本地- idle_ttl_seconds: 沙箱空闲超时+ idle_ttl_seconds: 沙箱空闲超时 (秒). 默认 ``None`` 表示不进行 idle 驱逐;+ jiuwenbox provider 会把它转成 ``timeout.idle_timeout`` 注入到+ ``create_sandbox`` 的 policy 中。+ idle_check_interval: idle reaper 轮询间隔 (秒). 默认 ``None`` 让+ jiuwenbox 服务端使用自身默认值; jiuwenbox provider 会把它转成+ ``timeout.idle_check_interval`` 注入到 policy 中, 与+ ``idle_ttl_seconds`` 同样传递给沙箱.project_dir: 透传给 :func:`build_filesystem_policy` 的工程目录覆盖值;- ``None`` 时由其内部回落到 ``cwd``.+ 仅当 ``is_code_agent=True`` 时被消费, 否则忽略.+ is_code_agent: 是否是 code-agent. 透传给 :func:`build_filesystem_policy`:+ ``True`` 时把 ``project_dir`` 挂为 rw bind, ``False`` 时不挂任何+ "主写入根" (workspace 也不挂); 见该函数 docstring 的详细说明.Returns:构造成功返回 ``SysOperationCard``; 失败 (``build_filesystem_policy``@@ -515,6 +691,7 @@ def create_sandbox_sysop_card(policy, upload_list = build_filesystem_policy(files_runtime,project_dir=project_dir,+ is_code_agent=is_code_agent,)extra_params: dict[str, Any] = {"policy": policy,@@ -525,6 +702,14 @@ def create_sandbox_sysop_card("preserve_file_sharing_mode": _PRESERVE_FILE_SHARING_MODE,"preserve_files_upload": upload_list,}+ # ``idle_check_interval`` 走 ``extra_params`` 而非 ``launcher_config`` 上+ # 的独立字段, 这样不需要给 ``SandboxLauncherConfig`` 加 jiuwenbox 私有的+ # schema —— ``idle_check_interval`` 是 jiuwenbox 服务端 reaper 轮询间隔,+ # 别的 provider 用不到, 只在 jiuwenbox provider 里读出来 PUT 到+ # ``/api/v1/timeout``。 ``None`` 时不写入 extra_params, 让 provider 端+ # 走 "缺省即沿用 server 默认值" 的语义。+ if idle_check_interval is not None:+ extra_params["idle_check_interval"] = idle_check_intervalgateway_config = SandboxGatewayConfig(isolation=SandboxIsolationConfig(container_scope=ContainerScope.SYSTEM),@@ -544,7 +729,8 @@ def create_sandbox_sysop_card(fs_policy = policy.get("filesystem_policy", {}) if isinstance(policy, dict) else {}logger.info("[sysop_builder] sandbox SysOperationCard created:\n"- " base_url=%s sandbox_type=%s idle_ttl=%ds\n"+ " base_url=%s sandbox_type=%s\n"+ " idle_ttl=%s idle_check_interval=%s\n"" preserve_file_sharing_mode=%s\n"" excluded_commands(%d)=%s\n"" filesystem_policy.files(%d)=%s\n"@@ -557,6 +743,7 @@ def create_sandbox_sysop_card(sandbox_url,sandbox_type,idle_ttl_seconds,+ idle_check_interval,_PRESERVE_FILE_SHARING_MODE,len(extra_params["excluded_commands"]),extra_params["excluded_commands"] or "[]",@@ -648,6 +835,8 @@ def _resolve_display_path(raw: str | Path | None) -> str | None:def list_auto_managed_sandbox_paths(project_dir: str | Path | None = None,+ *,+ is_code_agent: bool = False,) -> dict[str, list[dict[str, str]]]:"""Auto-configured sandbox entries that users cannot mutate via ``/sandbox``.@@ -655,8 +844,10 @@ def list_auto_managed_sandbox_paths(with regardless of user-supplied ``files.allow`` / ``files.deny``:- intrinsic agent files (AGENT/HEARTBEAT/IDENTITY/SOUL/USER.md) +- ``daily_memory`` dir + project directory are all rw bind-mounted from- host.+ ``daily_memory`` dir + agent_skills dir are always rw bind-mounted+ from host. The user project directory is rw bind-mounted only when+ ``is_code_agent=True``; deep / generic adapters skip this mount+ entirely (workspace is **not** auto-mounted as a fallback).- jiuwenswarm's own ``config.yaml`` is auto-added to ``deny_write`` soLandlock blocks writes to the api-key file even when the bind mountsotherwise expose the parent directory.@@ -664,7 +855,14 @@ def list_auto_managed_sandbox_paths(Args:project_dir: explicit project-root override (typically``trusted_dirs[0]`` cached on the adapter); ``None`` skips the- project entry rather than falling back to cwd.+ project entry rather than falling back to cwd. Only consumed+ when ``is_code_agent=True``.+ is_code_agent: 与 :func:`build_filesystem_policy` 同义——决定是否+ 把 ``project_dir`` 加进 allow_write. ``False`` 时连 project+ 条目也不会出现 (不存在 workspace fallback), 跟 build 侧保持+ 完全一致; 否则 TUI 列出来的 ``files.allow_write`` 跟沙箱启动+ 后实际 mount 的目录会脱节, 用户看到一条 "项目目录已挂"+ 但实际并没有挂。Returns:``{"allow_write": [...], "deny_write": [...]}`` where each entry is@@ -674,12 +872,12 @@ def list_auto_managed_sandbox_paths(allow: list[dict[str, str]] = []deny: list[dict[str, str]] = []- for func in _INTRINSIC_FILE_PATH_FUNCS:+ for func in _INTRINSIC_RW_FILE_PATH_FUNCS:try:raw = func()except Exception as exc: # noqa: BLE001logger.debug(- "[sysop_builder] auto view: intrinsic path func failed: %s",+ "[sysop_builder] auto view: intrinsic rw path func failed: %s",exc,)continue@@ -691,19 +889,32 @@ def list_auto_managed_sandbox_paths()try:- daily_memory = str(Path(get_agent_memory_dir()) / "daily_memory")+ daily_memory_path = Path(get_agent_memory_dir()) / "daily_memory"except Exception as exc: # noqa: BLE001logger.debug("[sysop_builder] auto view: daily_memory resolve failed: %s",exc,)else:- _append_unique(- allow,- {"path": daily_memory + "/", "permissions": "0777", "kind": "directory"},- )+ # 显示侧与 ``_collect_intrinsic_targets`` 的 mount 决策保持一致: host+ # 上没有 daily_memory 目录就不进 auto-managed allow_write 列表 (不会+ # 实际被 mount, UI 列出来会误导用户)。+ if daily_memory_path.is_dir():+ _append_unique(+ allow,+ {+ "path": str(daily_memory_path) + "/",+ "permissions": "0777",+ "kind": "directory",+ },+ )- if project_dir is not None:+ # 显示侧的"主写入根"必须跟 :func:`build_filesystem_policy` 完全镜像:+ # 仅 code-agent 才挂 project_dir, 非 code-agent 这一栏直接为空 (没有+ # workspace fallback)。 不一致就会让 TUI 列的 allow_write 跟沙箱里实际+ # mount 的 rw bind 脱节, 用户看到 "项目目录已挂", 但 deep agent 模式+ # 下实际并没有挂 — 那条 entry 一来本来就不存在。+ if is_code_agent and project_dir is not None:try:resolved_project: Path | None = Path(project_dir).expanduser().resolve()except OSError as exc:@@ -729,23 +940,51 @@ def list_auto_managed_sandbox_paths(},)- # config.yaml 一律加入 auto-deny: 注: 现在 deny 用 ``bind_mount rw + 末尾- # --remount-ro`` 实现 (见 ``build_filesystem_policy`` 的- # ``_record_user_deny_bind``), "父 rw + 子 deny" 已经是合法配置, 不再有- # 过去 ``_validate_deny_not_under_writable`` 那种冲突自检的负担。- try:- config_yaml_path = str(Path(get_config_file()).expanduser().resolve())- except Exception as exc: # noqa: BLE001- logger.debug(- "[sysop_builder] auto view: config.yaml resolve failed: %s",- exc,- )- else:- if config_yaml_path:- _append_unique(- deny,- {"path": config_yaml_path, "permissions": "0000", "kind": "file"},+ # Readonly intrinsic 文件 (含 config.yaml) 统一从 _INTRINSIC_RO_FILE_PATH_FUNCS+ # 派生, 跟 :func:`build_filesystem_policy` 里 _record_ro_resource_bind 注册的+ # 集合一一对应。 路径不存在 / 解析失败时只 debug-log 跳过, 跟 build 侧的 warn+ # 是一回事 (build 侧负责报告状态, 展示侧静默)。+ for func in _INTRINSIC_RO_FILE_PATH_FUNCS:+ try:+ raw = func()+ except Exception as exc: # noqa: BLE001+ logger.debug(+ "[sysop_builder] auto view: intrinsic ro path func failed: %s",+ exc,)+ continue+ if raw is None:+ continue+ try:+ resolved = Path(raw).expanduser().resolve()+ except OSError as exc:+ logger.debug(+ "[sysop_builder] auto view: intrinsic ro path %r resolve failed: %s",+ raw, exc,+ )+ continue+ _append_unique(+ deny,+ {"path": str(resolved), "permissions": "0444", "kind": "file"},+ )++ # Built-in skills directory mirrors what :func:`build_filesystem_policy`+ # registers via ``_record_rw_bind``. We surface it under ``allow_write``+ # so ``/sandbox files list`` makes the writable mount visible to+ # operators (otherwise the directory would appear inside the sandbox+ # without any breadcrumb in the file panel). The path resolution here+ # is silent on failure: a dev checkout without ``resources/`` shipped+ # should not raise from a display helper.+ agent_skills = _resolve_agent_skills_dir()+ if agent_skills is not None:+ _append_unique(+ allow,+ {+ "path": str(agent_skills) + "/",+ "permissions": "0777",+ "kind": "directory",+ },+ )return {"allow_write": allow, "deny_write": deny}@@ -754,6 +993,7 @@ def list_effective_sandbox_files(files_runtime: dict[str, Any] | None,*,project_dir: str | Path | None = None,+ is_code_agent: bool = False,) -> dict[str, list[dict[str, str]]]:"""Read-only "what will the sandbox actually allow / deny writes to" view.@@ -778,7 +1018,10 @@ def list_effective_sandbox_files(``{"allow_write": [...], "deny_write": [...]}`` where every entry is``{"path": str, "permissions": str, "kind": "file" | "directory"}``."""- auto = list_auto_managed_sandbox_paths(project_dir=project_dir)+ auto = list_auto_managed_sandbox_paths(+ project_dir=project_dir,+ is_code_agent=is_code_agent,+ )allow = list(auto["allow_write"])deny = list(auto["deny_write"])@@ -812,6 +1055,7 @@ def find_auto_managed_match(path: str,*,project_dir: str | Path | None = None,+ is_code_agent: bool = False,) -> tuple[str, str] | None:"""Return ``(bucket, canonical_path)`` if ``path`` is auto-managed; else ``None``.@@ -834,7 +1078,10 @@ def find_auto_managed_match(target = _resolve_display_path(path)if target is None:return None- auto = list_auto_managed_sandbox_paths(project_dir=project_dir)+ auto = list_auto_managed_sandbox_paths(+ project_dir=project_dir,+ is_code_agent=is_code_agent,+ )for bucket in ("allow_write", "deny_write"):for entry in auto.get(bucket, []):candidate = _resolve_display_path(entry.get("path", ""))