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(agentserver): validate chat work mode
guozirui1d1c4807711b6
diff --git a/docs/en/SlashCommands.md b/docs/en/SlashCommands.mdindex 271f585c61..4a1a6c4c15 100644--- a/docs/en/SlashCommands.md+++ b/docs/en/SlashCommands.md@@ -696,7 +696,7 @@ Enter / leave jiuwenbox sandbox mode and tune its runtime policy. Calls `command- **Nested paths**: Supported: parent allow + child deny (e.g. allow `/tmp`, deny `/tmp/secret`). Not supported: child allow + parent deny (parent deny wins); the server rejects such configs.- **Effective write policy**: `files.allow_write` / `files.deny_write` in the status panel show the merged view of auto-managed and user-configured entries, each labeled `(rw)` or `(ro)`.- **preserve_file_sharing_mode**: Controlled by jiuwenswarm config, not by `/sandbox`. Only `mount` is supported: intrinsic files and `project_dir` are bind-mounted into the sandbox and `project_dir/config/config.yaml` is explicitly added to `deny_write`. Writing any other value into config.yaml is rejected by the server.-- **excluded_commands**: Match the full command string (not just `argv[0]`); a match makes that tool call run on the host, effectively granting the command's side effects to the local environment.+- **excluded_commands**: `fnmatch` per simple-command leaf (full leaf text or command name). All matches → whole command on host; none → whole command in sandbox; mixed leaves → local bash orchestrates and wraps remote leaves with `jiuwenbox sandbox exec` (CLI required).- **Add / remove are strict**: `exclude add` rejects a pattern that is already in the list; `exclude remove` rejects a pattern that is not in the list. `files allow|deny` rejects a path that is already in the same bucket, and rejects a path that exists in the opposite bucket (allow vs deny conflict) — run `files remove` first if you want to flip it. `files remove` rejects paths that have no matching user-configured entry.- **enable / disable**: Triggers an agent rebuild. The response lists `rebuilt_modes` (typically `agent.*` / `code.*`) and the jiuwenbox endpoint.diff --git "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md" "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"index 09ea59712a..be401848a6 100644--- "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"+++ "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"@@ -711,7 +711,7 @@- **嵌套路径**:支持「父 allow + 子 deny」(例如 allow `/tmp`、deny `/tmp/secret`);不支持「子 allow + 父 deny」(父 deny 会覆盖子 allow),服务端会拒绝此类配置。- **生效写入策略**:状态面板里的 `files.allow_write` / `files.deny_write` 是 auto-managed 与 user-configured 合并后的视图,每条路径显示 `(rw)` 或 `(ro)`。- **preserve_file_sharing_mode**:由 jiuwenswarm 配置决定,不通过 `/sandbox` 切换。仅支持 `mount`:intrinsic 文件与 `project_dir` 通过 bind mount 注入沙箱,`project_dir/config/config.yaml` 会显式加进 `deny_write`;yaml 里写入其它值会被服务端拒绝。-- **excluded_commands**:按完整命令字符串匹配(不是只看 `argv[0]`),命中后该次调用穿透到本地,相当于把对应命令的副作用授权给本地环境。+- **excluded_commands**:按 simple-command 叶子做 fnmatch(可匹配完整叶子文本或命令名)。全命中则整条本地;全未命中则整条沙箱;混合命中时由本地 bash 编排,远端段走 `jiuwenbox sandbox exec`(需宿主 CLI)。- **add / remove 的去重与冲突**:`exclude add` 在已存在同名 pattern 时报错;`exclude remove` 在不存在该 pattern 时报错。`files allow|deny` 在同一 bucket 已有同 path 时报错,在对侧 bucket(allow vs deny)已登记同 path 时也报错,需要先 `files remove` 再 add;`files remove` 在用户配置里找不到该 path 时报错。- **enable / disable**:会触发 agent 重建,响应里会列出 `rebuilt_modes`(典型 `agent.*` / `code.*`)和 jiuwenbox 端点。diff --git "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md" "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"index 1efe91130a..6be7080e98 100644--- "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"+++ "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"@@ -473,7 +473,7 @@ jiuwenswarm-tui --session "$(printf 'a%.0s' {1..200})" # 超 128 → 长度超- `landlock` — jiuwenbox Landlock 支持情况(`supported` + `compatibility`)。- `files.allow_write` / `files.deny_write` — 生效(auto-managed ∪ user-configured,去重)的写入策略,显示 `(rw)` / `(ro)`。- 自动配置路径:当前工作路径。`preserve_file_sharing_mode` 仅支持 `mount`。-- `excluded_commands` 的匹配:按完整命令字符串匹配,不仅看 `argv[0]`;写 glob 时要把参数也覆盖进去(例如 `"git *"` 而不是 `git`)。本质等同于沙箱穿透口,不要对 `rm -rf` / `curl` 这类高风险命令使用。+- `excluded_commands` 的匹配:按 simple-command 叶子做 fnmatch;写 glob 时建议覆盖参数(例如 `"git *"`)。混合管道会本地/远端拆分执行,不安全结构则整条进沙箱。本质仍是沙箱穿透口,不要对 `rm -rf` / `curl` 这类高风险命令使用。- add / remove 严格校验:`exclude add` 已存在 pattern、`exclude remove` 不存在 pattern 都会报错;`files allow|deny` 在同 bucket 已有 path 或对侧 bucket 已有 path(allow/deny 冲突)会报错,先 `files remove` 再 add;`files remove` 没匹配到也会报错。避免"看起来执行了实际什么也没改"。- 写入策略:`allow` / `deny` 控制写访问(rw/ro),不是 Unix 八进制权限;支持「父 allow + 子 deny」,不支持「子 allow + 父 deny」。- 示例:`/sandbox enable`、`/sandbox status`、`/sandbox files allow ./tmp/`、`/sandbox exclude add "git *"`。diff --git a/jiuwenbox/README.md b/jiuwenbox/README.mdindex 51bcf96b45..351dbd27f4 100644--- a/jiuwenbox/README.md+++ b/jiuwenbox/README.md@@ -597,7 +597,7 @@ Field reference:| `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` | `mount` | Intrinsic files (`AGENT.md` etc.) and `project_dir` are bind-mounted, with `project_dir/config/config.yaml` auto-added to `deny_write`. Writing any other value is rejected. || `sandbox.enabled` | bool | `false` | When true, agent rebuilds route tools through the sandbox provider; toggled by `/sandbox enable`. |-| `sandbox.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.excluded_commands` | list[str] | `[]` | Shell globs matched per **simple-command leaf**. All matches → whole command on host; no matches → whole command in sandbox; mixed → local bash orchestrates control flow and wraps remote leaves with `jiuwenbox sandbox exec` (CLI required). Unsafe mixed forms run the whole original command 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` command reference](../docs/en/SlashCommands.md). |### Two typical deployment shapesdiff --git a/jiuwenbox/README_CN.md b/jiuwenbox/README_CN.mdindex f8f598fcf9..679faeef89 100644--- a/jiuwenbox/README_CN.md+++ b/jiuwenbox/README_CN.md@@ -564,7 +564,7 @@ sandbox:| `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` | `mount` | intrinsic 文件(`AGENT.md` 等)与 `project_dir` 通过 bind mount 注入沙箱,`project_dir/config/config.yaml` 自动加进 `deny_write`。 写入其它值会被服务端拒绝 || `sandbox.enabled` | bool | `false` | 启用后 agent 在重建时会切到 sandbox provider;可用 `/sandbox enable` 触发 |-| `sandbox.excluded_commands` | list[str] | `[]` | shell glob 列表;按**整条命令字符串**匹配,命中后该次调用穿透到本地 |+| `sandbox.excluded_commands` | list[str] | `[]` | shell glob 列表;按 **simple-command 叶子**匹配。全命中→整条本地;全未命中→整条沙箱;混合→本地 bash 编排并用 `jiuwenbox sandbox exec` 包装远端段(需安装 CLI)。不安全的混合形态不改写,整条进沙箱 || `sandbox.fallback_on_failure` | bool | `false` | jiuwenbox exec 异常(连接失败、daemon 不可用等)时回退宿主机本地执行;沙箱内命令非零 exit 不回退 || `sandbox.files.allow` / `sandbox.files.deny` | list | `[]` | 用户额外配置的写入策略;最终生效集合是 `auto_managed ∪ user_configured`,详见 [`/sandbox` 命令说明](../docs/zh/Slash命令表.md) |diff --git a/jiuwenswarm/server/handlers/_default.py b/jiuwenswarm/server/handlers/_default.pyindex e04c608764..6b4a1a3d83 100644--- a/jiuwenswarm/server/handlers/_default.py+++ b/jiuwenswarm/server/handlers/_default.py@@ -334,6 +334,25 @@ async def _prepare_code_mode_chat_turn(and isinstance(params.get("answers"), list)and bool(str(params.get("request_id") or "").strip()))+ from jiuwenswarm.server.runtime.session.work_mode import (+ resolve_request_work_mode,+ )++ request_work_mode, work_mode_error = resolve_request_work_mode(+ params,+ request.channel_id or "web",+ )+ if work_mode_error is not None:+ raw_work_mode = params.get("work_mode")+ logger.warning(+ "[_prepare_code_mode_chat_turn] invalid work_mode=%r for channel=%s "+ "session=%s",+ raw_work_mode,+ request.channel_id,+ request.session_id,+ )+ raise ValueError(f"invalid work_mode: {raw_work_mode!r}")+runtime_work_mode = Nonesid = str(request.session_id or "").strip()sessions_root = _sessions_dir_for_request(request)@@ -378,26 +397,20 @@ async def _prepare_code_mode_chat_turn(}:runtime_work_mode = stored_work_mode.strip().lower()if runtime_work_mode is None:- request_work_mode = params.get("work_mode")- if isinstance(request_work_mode, str) and request_work_mode.strip().lower() in {- "code",- "work",- }:- runtime_work_mode = request_work_mode.strip().lower()- else:- from jiuwenswarm.server.runtime.session.work_mode import (- default_work_mode_for_channel,- )-- channel_id_for_default = request.channel_id or "web"- runtime_work_mode = default_work_mode_for_channel(channel_id_for_default)+ runtime_work_mode = request_work_mode+ raw_work_mode = params.get("work_mode")+ if raw_work_mode is None or (+ isinstance(raw_work_mode, str) and not raw_work_mode.strip()+ ):logger.warning("[_prepare_code_mode_chat_turn] work_mode missing in both session ""metadata and request params; defaulting to %r for channel=%s session=%s",runtime_work_mode,- channel_id_for_default,+ request.channel_id or "web",request.session_id,)+ if runtime_work_mode is None:+ raise RuntimeError("work_mode resolution returned no value")params["work_mode"] = runtime_work_mode# An explicit/hydrated concrete mode is the stronger routing identity.# A stale session work_mode (OfficeClaw historically initialized it asdiff --git a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py b/tests/unit_tests/agentserver/test_plan_mode_orchestration.pyindex af6763b57c..9fb61f7e3e 100644--- a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py+++ b/tests/unit_tests/agentserver/test_plan_mode_orchestration.py@@ -188,6 +188,61 @@ async def test_prepare_chat_defaults_missing_e2a_work_mode() -> None:)+async def test_prepare_chat_defaults_missing_web_work_mode() -> None:+ agent = MagicMock()+ manager = MagicMock()+ manager.get_agent = AsyncMock(return_value=agent)+ manager.wait_for_session_prewarm = AsyncMock()+ server = AgentWebSocketServer.__new__(AgentWebSocketServer)+ server._agent_manager = manager+ request = _chat_request("sess_web_default", mode="agent")+ request.channel_id = "web"++ with patch(+ "jiuwenswarm.server.runtime.session.session_metadata.get_session_metadata",+ return_value={},+ ):+ mode, sub_mode, resolved_agent = await _default._prepare_code_mode_chat_turn(+ _default_ctx(server, request),+ request,+ "web",+ sync_metadata=False,+ )++ assert (mode, sub_mode, resolved_agent) == ("agent", None, agent)+ assert request.params["work_mode"] == "work"++[email protected]("invalid_work_mode", ["invalid", 123])+async def test_prepare_chat_rejects_invalid_work_mode(invalid_work_mode: object) -> None:+ manager = MagicMock()+ manager.get_agent = AsyncMock()+ manager.wait_for_session_prewarm = AsyncMock()+ server = AgentWebSocketServer.__new__(AgentWebSocketServer)+ server._agent_manager = manager+ request = _chat_request(+ "sess_invalid_work_mode",+ mode="agent",+ extra_params={"work_mode": invalid_work_mode},+ )++ with patch(+ "jiuwenswarm.server.runtime.session.session_metadata.get_session_metadata",+ return_value={"work_mode": "work"},+ ), pytest.raises(ValueError, match="invalid work_mode"):+ await _default._prepare_code_mode_chat_turn(+ _default_ctx(server, request),+ request,+ "web",+ sync_metadata=False,+ )++ assert request.params["work_mode"] == invalid_work_mode+ manager.get_agent.assert_not_awaited()++@pytest.mark.asyncioasync def test_prepare_team_chat_turn_propagates_locked_project_dir() -> None:"""The session-locked project dir reaches TeamSpec request metadata.