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(cli): persist trusted directories and merge into request params
haowenzhong1d228026f1b96
diff --git a/jiuwenswarm/cli/chat.py b/jiuwenswarm/cli/chat.pyindex a00988c899..2089ffac04 100644--- a/jiuwenswarm/cli/chat.py+++ b/jiuwenswarm/cli/chat.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport argparseimport asyncioimport datetime+import jsonimport loggingimport osimport signal@@ -25,6 +26,142 @@ from jiuwenswarm.cli.render import HumanRenderer, JsonRenderer, JsonlRendererlogger = logging.getLogger(__name__)+# ── Trusted-directory persistence (local, no server/harness changes) ───++_STATE_FILE = Path.home() / ".jiuwenswarm" / "cli_trusted_dirs_state.json"+++def _load_state() -> dict[str, bool]:+ """Load per-directory prompt state. {dir_path: keep_bool}."""+ if _STATE_FILE.exists():+ try:+ return json.loads(_STATE_FILE.read_text(encoding="utf-8"))+ except ValueError:+ pass+ return {}+++def _save_state(state: dict[str, bool]) -> None:+ _STATE_FILE.parent.mkdir(parents=True, exist_ok=True)+ _STATE_FILE.write_text(json.dumps(state, indent=2), encoding="utf-8")+++def _get_persisted_external_dirs() -> list[str]:+ """Read config.yaml for external_directory entries with value 'allow' (excluding '*' wildcard)."""+ from jiuwenswarm.common.config import CONFIG_YAML_PATH, load_yaml_round_trip++ cfg_path = Path(CONFIG_YAML_PATH) if not isinstance(CONFIG_YAML_PATH, Path) else CONFIG_YAML_PATH+ if not cfg_path.exists():+ return []+ try:+ data = load_yaml_round_trip(cfg_path)+ except Exception:+ return []+ if not isinstance(data, dict):+ return []+ perms = data.get("permissions")+ if not isinstance(perms, dict):+ return []+ ext = perms.get("external_directory")+ if not isinstance(ext, dict):+ return []+ result = []+ for k, v in ext.items():+ if str(k) != "*" and str(v) == "allow":+ result.append(str(k))+ return result+++def _remove_dir_from_config(dir_path: str) -> bool:+ """Remove a single directory entry from config.yaml's external_directory."""+ from jiuwenswarm.common.config import CONFIG_YAML_PATH, load_yaml_round_trip, dump_yaml_round_trip++ cfg_path = Path(CONFIG_YAML_PATH) if not isinstance(CONFIG_YAML_PATH, Path) else CONFIG_YAML_PATH+ if not cfg_path.exists():+ return False+ try:+ data = load_yaml_round_trip(cfg_path)+ except Exception:+ return False+ if not isinstance(data, dict):+ return False+ perms = data.get("permissions")+ if not isinstance(perms, dict):+ return False+ ext = perms.get("external_directory")+ if not isinstance(ext, dict):+ return False++ target = dir_path.rstrip("/")+ key_to_remove = None+ for key in list(ext.keys()):+ if str(key).rstrip("/") == target:+ key_to_remove = key+ break+ if key_to_remove is None:+ return False+ del ext[key_to_remove]+ try:+ dump_yaml_round_trip(cfg_path, data)+ except Exception:+ return False+ return True+++async def _persist_trusted_dirs(client: GatewayClient, trusted_dirs: list[str]) -> None:+ """Tell the agent-server to persist each trusted directory via ``command.add_dir``."""+ failed: list[str] = []+ for d in trusted_dirs:+ resolved = str(Path(d).resolve())+ try:+ await client.send_request({+ "type": "req",+ "id": f"add_dir-{uuid_module.uuid4().hex[:8]}",+ "method": "command.add_dir",+ "is_stream": False,+ "params": {"path": resolved, "remember": True},+ })+ except Exception:+ logger.warning("Failed to persist trusted directory: %s", resolved, exc_info=True)+ failed.append(resolved)+ if failed:+ write_stderr(+ "Warning: could not persist the following trusted directories:\n "+ + "\n ".join(failed)+ + "\n"+ + "The agent-server may not support command.add_dir.\n"+ )+++def _prompt_and_cleanup_dirs() -> None:+ """Check for newly persisted dirs and ask user whether to keep each one.++ Only called from the REPL loop (interactive TTY).+ """+ if not sys.stdin.isatty():+ return++ persisted = _get_persisted_external_dirs()+ state = _load_state()+ new_dirs = [d for d in persisted if d not in state]++ for d in sorted(new_dirs):+ write_stderr(f"\nNew workspace added: {d}\n")+ try:+ answer = input("Keep using this workspace? [Y/n]: ").strip().lower()+ except EOFError:+ answer = "y"++ keep = answer not in ("n", "no")+ state[d] = keep+ _save_state(state)++ if not keep:+ if _remove_dir_from_config(d):+ write_stderr(f"Workspace removed: {d}\n")+ else:+ write_stderr(f"Failed to remove workspace: {d}\n")+MODE_ALIASES: dict[str, str] = {"agent": "agent.plan","fast": "agent.fast",@@ -161,6 +298,13 @@ def _build_request(args: argparse.Namespace, prompt: str) -> dict:else:trusted_dirs = [str(Path(d).resolve()) for d in trusted_dirs]+ # Merge persisted external_directory allow entries into trusted_dirs+ # so that RuntimePromptRail can inject them into the system prompt.+ persisted = _get_persisted_external_dirs()+ for pd in persisted:+ if pd not in trusted_dirs:+ trusted_dirs.append(pd)+return {"type": "req","id": f"chat-{uuid_module.uuid4().hex[:12]}",@@ -343,14 +487,16 @@ async def _run_interactive_loop(return 1continue- # Sleep woke up before recv — loop back and re-check flags- if recv_task not in done:- continue-try:data = recv_task.result()- except ConnectionError:- return 0+ except OSError:+ logger.warning("WebSocket connection lost — the Gateway may have closed the connection", exc_info=True)+ write_stderr("Connection lost. Use --session to re-connect or retry.\n")+ return 4+ except Exception:+ logger.warning("Unexpected error while receiving", exc_info=True)+ write_stderr("Error receiving response. Check ~/.jiuwenswarm/agent/.logs/full.log\n")+ return 5except KeyboardInterrupt:if _force_exit:return 130@@ -396,29 +542,23 @@ async def _run_interactive_loop(elif kind == "interactive":renderer.clear_loading()if sys.stdin.isatty():- source = str(payload.get("source") or "").strip()- request_id = str(payload.get("request_id") or "").strip()- questions = payload.get("questions") or []-- # Collect all options across questions for input mapping- all_options: list[dict] = []- # Display question(s) and options- if isinstance(questions, list) and questions:- for q in questions:- header = q.get("header", "Input needed")- question_text = q.get("question", "")- options = q.get("options") or []- write_stderr(f"\n[{header}] {question_text}\n")- if isinstance(options, list) and options:- for i, opt in enumerate(options, 1):- label = opt.get("label", "")- desc = opt.get("description", "")- write_stderr(- f" {i}. {label}"- + (f" — {desc}" if desc else "")- + "\n"- )- all_options.append(opt)+ request_id = payload.get("request_id", "")+ source = payload.get("source", "")+ options = payload.get("options", [])+ all_options: list[dict[str, Any]] = [opt for opt in options if isinstance(opt, dict)]++ if options:+ write_stderr(+ f"\n[{event_type}] "+ f"{payload.get('question') or payload.get('message', 'Input needed')}\n"+ )+ for idx, opt in enumerate(all_options, 1):+ label = opt.get("label") or opt.get("value") or "?"+ desc = opt.get("description", "")+ if desc:+ write_stderr(f" {idx}. {label} — {desc}\n")+ else:+ write_stderr(f" {idx}. {label}\n")else:write_stderr(f"\n[{event_type}] "@@ -660,6 +800,12 @@ async def _run_chat(request = _build_request(args, prompt)+ # Persist explicitly-provided trusted dirs after building the request+ # so _build_request still sees the original trusted_dirs for the prompt.+ if getattr(args, "trusted_dir", None):+ await _persist_trusted_dirs(client, args.trusted_dir)+ args.trusted_dir = None # prevent re-persistence on subsequent REPL turns+try:if args.jsonl:renderer: JsonlRenderer | JsonRenderer | HumanRenderer = JsonlRenderer()@@ -704,6 +850,10 @@ def run_chat(args: argparse.Namespace) -> int:if error is not None:return error+ # Check for newly persisted dirs before sending the message,+ # so the user gets a chance to clean up from previous sessions.+ _prompt_and_cleanup_dirs()+return asyncio.run(_run_chat(args, prompt))@@ -734,6 +884,7 @@ def _run_repl(args: argparse.Namespace) -> int:exit_code = 0try:while True:+ _prompt_and_cleanup_dirs()try:line = input("> ")except EOFError:diff --git a/jiuwenswarm/cli/gateway_client.py b/jiuwenswarm/cli/gateway_client.pyindex 898b5b05cc..bce03fe3a6 100644--- a/jiuwenswarm/cli/gateway_client.py+++ b/jiuwenswarm/cli/gateway_client.py@@ -14,10 +14,22 @@ logger = logging.getLogger(__name__)def _connect_ws(url: str):try:from websockets.legacy.client import connect as legacy_connect- return legacy_connect(url, close_timeout=2.0, max_size=8 * 2**20)+ return legacy_connect(+ url,+ close_timeout=2.0,+ max_size=8 * 2**20,+ ping_interval=20,+ ping_timeout=60,+ )except ImportError:import websockets- return websockets.connect(url, close_timeout=2.0, max_size=8 * 2**20)+ return websockets.connect(+ url,+ close_timeout=2.0,+ max_size=8 * 2**20,+ ping_interval=20,+ ping_timeout=60,+ )class GatewayClient:@@ -29,6 +41,11 @@ class GatewayClient:def url(self) -> str:return self._url+ @property+ def is_open(self) -> bool:+ """True if the internal WebSocket connection is active (not None)."""+ return self._ws is not None+async def connect(self) -> None:self._ws = await _connect_ws(self._url)@@ -63,14 +80,28 @@ class GatewayClient:await self._ws.send(json.dumps(frame, ensure_ascii=False))async def recv(self) -> dict[str, Any]:- raw = await self._ws.recv()+ try:+ raw = await self._ws.recv()+ except (OSError, EOFError):+ raise ConnectionError("WebSocket connection lost") from None+ except Exception as exc:+ # websockets.ConnectionClosed inherits from AssertionError,+ # not OSError/ConnectionError. Convert to ConnectionError so+ # callers (chat._run_interactive_loop) catch it uniformly.+ cls_name = type(exc).__name__+ if "ConnectionClosed" in cls_name:+ raise ConnectionError("WebSocket connection closed by peer") from None+ raisereturn json.loads(raw)async def close(self) -> None:if self._ws is not None:ws = self._wsself._ws = None- await ws.close()+ try:+ await ws.close()+ except Exception:+ logger.debug("[GatewayClient] error closing websocket", exc_info=True)def set_mock_ws(self, ws: Any) -> None:self._ws = wsdiff --git a/tests/unit_tests/cli/test_chat.py b/tests/unit_tests/cli/test_chat.pyindex 4947825d4c..5929b5e28a 100644--- a/tests/unit_tests/cli/test_chat.py+++ b/tests/unit_tests/cli/test_chat.py@@ -9,6 +9,8 @@ import asyncioimport ioimport jsonimport os+import tempfile+from pathlib import Pathfrom unittest.mock import patchimport pytest@@ -19,6 +21,10 @@ from jiuwenswarm.cli.chat import (_build_default_gateway_url,_build_request,_generate_session_id,+ _get_persisted_external_dirs,+ _load_state,+ _remove_dir_from_config,+ _save_state,_validate_args,build_parser,resolve_mode,@@ -173,6 +179,10 @@ class TestBuildRequest:@staticmethoddef test_with_trusted_dirs(monkeypatch):monkeypatch.setattr(os, "getcwd", lambda: "/cwd")+ monkeypatch.setattr(+ "jiuwenswarm.cli.chat._get_persisted_external_dirs",+ lambda: [],+ )args = argparse.Namespace(mode="code.normal",session=None,@@ -781,7 +791,7 @@ class TestInteractiveLoop:"trusted_dirs": ["/tmp"]},}code = await _run_interactive_loop(client, renderer, request)- assert code == 0+ assert code == 4@pytest.mark.asyncioasync def test_processing_status_restarts_spinner(self):@@ -917,3 +927,127 @@ class TestSpinner:assert r.loading is Falser.ensure_loading()assert r.loading is True+++class TestTrustedDirsState:+ """Tests for _load_state / _save_state."""++ @staticmethod+ def test_load_state_missing_file(monkeypatch, tmp_path):+ state_file = tmp_path / "nonexistent.json"+ monkeypatch.setattr("jiuwenswarm.cli.chat._STATE_FILE", state_file)+ assert _load_state() == {}++ @staticmethod+ def test_save_and_load_state(monkeypatch, tmp_path):+ state_file = tmp_path / "state.json"+ monkeypatch.setattr("jiuwenswarm.cli.chat._STATE_FILE", state_file)+ _save_state({"/dir1": True, "/dir2": False})+ assert state_file.exists()+ loaded = _load_state()+ assert loaded == {"/dir1": True, "/dir2": False}++ @staticmethod+ def test_load_state_corrupted_file(monkeypatch, tmp_path):+ state_file = tmp_path / "bad.json"+ state_file.write_text("not json", encoding="utf-8")+ monkeypatch.setattr("jiuwenswarm.cli.chat._STATE_FILE", state_file)+ assert _load_state() == {}+++class TestExternalDirs:+ """Tests for _get_persisted_external_dirs / _remove_dir_from_config."""++ @staticmethod+ def test_get_persisted_external_dirs_empty(monkeypatch, tmp_path):+ cfg_path = tmp_path / "config.yaml"+ from ruamel.yaml import YAML+ yaml = YAML()+ yaml.dump({"permissions": {"external_directory": {"*": "ask"}}}, cfg_path)+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", cfg_path)+ assert _get_persisted_external_dirs() == []++ @staticmethod+ def test_get_persisted_external_dirs_with_allows(monkeypatch, tmp_path):+ cfg_path = tmp_path / "config.yaml"+ from ruamel.yaml import YAML+ yaml = YAML()+ yaml.dump(+ {+ "permissions": {+ "external_directory": {+ "*": "deny",+ "/Users/hwz/mcore/foo": "allow",+ "/tmp/bar": "deny",+ "/opt/baz": "allow",+ }+ }+ },+ cfg_path,+ )+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", cfg_path)+ dirs = _get_persisted_external_dirs()+ assert "/Users/hwz/mcore/foo" in dirs+ assert "/opt/baz" in dirs+ assert "/tmp/bar" not in dirs+ assert "*" not in dirs+ assert len(dirs) == 2++ @staticmethod+ def test_remove_dir_from_config(monkeypatch, tmp_path):+ cfg_path = tmp_path / "config.yaml"+ save_cfg_path = cfg_path+ from ruamel.yaml import YAML+ yaml = YAML()+ yaml.dump(+ {+ "permissions": {+ "external_directory": {+ "*": "ask",+ "/Users/hwz/mcore/foo": "allow",+ }+ }+ },+ cfg_path,+ )+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", save_cfg_path)+ assert _remove_dir_from_config("/Users/hwz/mcore/foo") is True+ assert _get_persisted_external_dirs() == []++ @staticmethod+ def test_remove_dir_from_config_nonexistent(monkeypatch, tmp_path):+ cfg_path = tmp_path / "config.yaml"+ from ruamel.yaml import YAML+ yaml = YAML()+ yaml.dump(+ {"permissions": {"external_directory": {"*": "ask"}}},+ cfg_path,+ )+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", cfg_path)+ assert _remove_dir_from_config("/nonexistent") is False+++class TestGatewayClientClose:+ """Tests for GatewayClient.close() exception handling."""++ @pytest.mark.asyncio+ @staticmethod+ async def test_close_swallows_error():+ client = GatewayClient("ws://127.0.0.1:19001/tui")++ class FakeFailingWs:+ async def close(self):+ raise RuntimeError("connection already closed")++ client.set_mock_ws(FakeFailingWs())+ # Should not raise+ await client.close()+ # Internal ws reference should be cleared+ assert client.is_open is False++ @pytest.mark.asyncio+ @staticmethod+ async def test_close_ws_none():+ client = GatewayClient("ws://127.0.0.1:19001/tui")+ # _ws is None by default+ await client.close() # Should not raise