JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(acp): harden E2A envelope path for headless clients
openJiuwen-botd31df0288fde
diff --git a/docs/en/E2A-protocol.md b/docs/en/E2A-protocol.mdindex 4c11d07353..9898b1f09a 100644--- a/docs/en/E2A-protocol.md+++ b/docs/en/E2A-protocol.md@@ -280,6 +280,52 @@ After parse: `channel`=`feishu`, `method`=`chat.send`, `timestamp` normalized toAfter `merge_params_to_acp_prompt`, `params` gains a `prompt` equivalent to `content_blocks` if there was no `prompt` before.+### 11.6 `session/prompt` + per-request `workspace_dir`++External clients (IDE plugins, headless evaluators, MCP drivers) can+scope one prompt's filesystem root to a per-invocation directory by+passing `workspace_dir` in `params`. The AgentServer resolves the path,+creates it on demand (`mkdir -p`), and threads the absolute path through+to `init_cwd(cwd=workspace_dir, workspace=workspace_dir)` so openjiuwen's+per-task `CwdState` ContextVar is reseeded for the duration of the+prompt. Both layers get the override:++- **`get_cwd()`** returns the scratch dir, so tools resolving relative+ paths land there.+- **`get_workspace()`** also returns the scratch dir, so+ `fs_operation`'s sandbox enforcement (which gates absolute-path writes+ by workspace membership) accepts writes anywhere under it.++Memory files, `.workspace`, and other artifact-root consumers therefore+land under the scratch dir for that request — useful for hermetic+evaluators that want one fresh slate per task. Long-lived agents whose+memory must persist should *not* pass `workspace_dir`; they fall back to+the agent's instance-level workspace as before.++Precedence and behavior:++- **Precedence:** when `workspace_dir` is set and `mkdir` succeeds, it+ wins over `params.cwd`. When `workspace_dir` is set but `mkdir` fails+ (e.g. permission denied), the request degrades to `params.cwd` (if+ any), then to the agent's global default; a warning is logged.+- **Path form:** absolute paths are recommended. Relative paths are+ resolved against the AgentServer process cwd, not the client's.++```json+{+ "method": "session/prompt",+ "session_id": "s1",+ "jsonrpc_id": 1,+ "params": {+ "content": "Create the project under datautils-project/",+ "workspace_dir": "/tmp/eval-task-42"+ }+}+```++`jiuwenswarm-tui` (the ACP stdio bridge) exposes this as+`--workspace-dir <path>`.+---## 12. E2A response protocol (`E2AResponse`)@@ -376,6 +422,21 @@ Runtime list: **`constants.E2A_RESPONSE_KINDS`**; **`body`** is a **dict**. NormCross-reference: request log normalization in **`E2A-AgentRequest-log-migration.md`**; response logging can adopt the same single-line JSON convention later.+### 12.9 Streaming `chat.error` carries `error_type`++When the inner agent loop raises, the streaming aggregator emits a+`chat.error` event whose payload carries the originating exception class.+Consumers can group failures structurally instead of regexing the message+string.++```json+{"event_type":"chat.error","error":"rate limited (429)","error_type":"RateLimitError"}+```++The same `error_type` field appears at the top level of the persisted+`history.json` record. Cancellation (`asyncio.CancelledError`) propagates+as cancellation rather than being classified as a `chat.error`.+---## 13. Security notesdiff --git a/jiuwenswarm/channels/acp/app_acp.py b/jiuwenswarm/channels/acp/app_acp.pyindex fbf490dad4..dd536f0fd8 100644--- a/jiuwenswarm/channels/acp/app_acp.py+++ b/jiuwenswarm/channels/acp/app_acp.py@@ -54,6 +54,17 @@ def _build_parser() -> argparse.ArgumentParser:default="acp_cli_session",help="ACP 请求使用的 session_id。",)+ acp_parser.add_argument(+ "--workspace-dir",+ default=None,+ help=(+ "Per-request scratch directory. The AgentServer mkdir-p's it and "+ "scopes the agent's cwd (via openjiuwen's CwdState ContextVar) "+ "to the path for the duration of the prompt, so filesystem/shell "+ "tools resolve relative paths against it. See E2A-protocol.md "+ "section 11.6."+ ),+ )acp_parser.add_argument("args",nargs=argparse.REMAINDER,@@ -69,9 +80,13 @@ def run_acp(args: argparse.Namespace) -> int:return 2request_id = f"acp_cli_{uuid.uuid4().hex[:12]}"+ params: dict = {"content": prompt}+ workspace_dir = getattr(args, "workspace_dir", None)+ if workspace_dir:+ params["workspace_dir"] = str(workspace_dir)env = envelope_from_acp_jsonrpc(method="session/prompt",- params={"content": prompt},+ params=params,jsonrpc_id=request_id,session_id=str(args.session_id or "acp_cli_session"),channel="acp",@@ -130,6 +145,12 @@ def run_acp(args: argparse.Namespace) -> int:"id": resp.jsonrpc_id,"result": resp.body,}+ # The gateway may remap the client-supplied session_id to an+ # internal id. Surface that resolved id so callers can locate+ # the written history.json.+ if isinstance(final_rpc.get("result"), dict):+ if not final_rpc["result"].get("session_id") and resp.session_id:+ final_rpc["result"]["session_id"] = resp.session_idbreakfinally:if proc.poll() is None:diff --git a/jiuwenswarm/gateway/channel_manager/protocol/acp/acp_connect.py b/jiuwenswarm/gateway/channel_manager/protocol/acp/acp_connect.pyindex 42dc1ea04e..985fa616f6 100644--- a/jiuwenswarm/gateway/channel_manager/protocol/acp/acp_connect.py+++ b/jiuwenswarm/gateway/channel_manager/protocol/acp/acp_connect.py@@ -801,6 +801,15 @@ class AcpChannel(BaseChannel):response_mode="e2a",session_id=msg.session_id,)+ # Mirror the JSON-RPC session/prompt path (line ~1168): register the+ # session→request mapping so gateway events (_message_from_gateway_event)+ # can resolve their request_id and emit responses. Without this,+ # streaming events on the envelope path are silently dropped and the+ # channel hangs waiting for a final frame that never arrives. Scope+ # this to session/prompt only -- non-prompt envelopes (session/cancel,+ # session/load, etc.) must not clobber an in-flight prompt's mapping.+ if msg.session_id and env.method == "session/prompt":+ self._active_prompt_request_by_session[msg.session_id] = msg.idawait self._dispatch_message(msg)diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex addaee78b2..f64ccc458f 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -15,6 +15,7 @@ import jsonimport loggingimport reimport time+from pathlib import Pathfrom typing import Any, AsyncIterator, Tuplefrom datetime import datetime, timedelta, timezone@@ -481,6 +482,29 @@ class JiuWenSwarm:"context": {"extra": {"cron": cron}},}+ # Per-request workspace_dir scopes one prompt's cwd to the given+ # directory; threaded into inputs["cwd"] which downstream init_cwd+ # installs onto openjiuwen's CwdState ContextVar. See E2A-protocol.md+ # section 11.6 for the wire contract and precedence rules.+ workspace_dir = request.params.get("workspace_dir")+ if isinstance(workspace_dir, str) and workspace_dir.strip():+ expanded = Path(workspace_dir).expanduser().resolve()+ try:+ expanded.mkdir(parents=True, exist_ok=True)+ except OSError as exc:+ logger.warning(+ "[JiuWenClaw] workspace_dir %s mkdir failed (%s); "+ "request falls back to params.cwd or the global default",+ workspace_dir, exc,+ )+ else:+ # Scope BOTH cwd and workspace so the agent's tools (which+ # read get_cwd() for relative-path resolution) AND its+ # fs_operation sandbox (which gates absolute-path writes by+ # workspace membership) agree on the per-request root.+ inputs["cwd"] = str(expanded)+ inputs["workspace_dir"] = str(expanded)+# 返回原始 query(未经 build_user_prompt 包装)# Team 模式需要使用原始 query,而不是 JSON 包装后的 promptreturn inputs, memory_mode, query@@ -1089,6 +1113,17 @@ class JiuWenSwarm:if isinstance(data, asyncio.CancelledError):logger.info("[JiuWenSwarm] 流式处理被中断: request_id=%s", rid)raise data+ # Surface exception class so consumers can classify+ # failures structurally instead of regexing the message.+ error_type = (+ type(data).__name__ if isinstance(data, BaseException) else ""+ )+ error_payload: dict[str, Any] = {+ "event_type": "chat.error",+ "error": str(data),+ }+ if error_type:+ error_payload["error_type"] = error_typeappend_history_record(session_id=session_id,request_id=rid,@@ -1098,11 +1133,12 @@ class JiuWenSwarm:content=str(data),timestamp=time.time(),mode=request.params.get("mode", "unknown"),+ extra={"error_type": error_type} if error_type else None,)yield AgentResponseChunk(request_id=rid,channel_id=cid,- payload={"event_type": "chat.error", "error": str(data)},+ payload=error_payload,is_complete=False,)else:diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex cf45102d51..a63479c1de 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -3507,9 +3507,20 @@ class JiuWenSwarmDeepAdapter:if self._instance.deep_config is not None:self._instance.deep_config.language = resolved_language- def _seed_runtime_cwd(self, cwd: str | None = None) -> None:- """Seed Core's CwdState holder from the request/runtime cwd."""- workspace_root = str(self._workspace_dir or self._project_dir or os.getcwd())+ def _seed_runtime_cwd(+ self, cwd: str | None = None, workspace: str | None = None+ ) -> None:+ """Seed Core's CwdState holder from the request/runtime cwd.++ ``workspace``: optional per-request workspace override. When set,+ becomes the workspace anchor for tools that read ``get_workspace()``+ (notably ``fs_operation``'s sandbox enforcement, which gates+ absolute-path writes by membership in the workspace tree). When+ unset, falls back to the agent's instance-level workspace.+ """+ workspace_root = str(+ workspace or self._workspace_dir or self._project_dir or os.getcwd()+ )runtime_cwd = str(cwd or "").strip()if not runtime_cwd or not os.path.isdir(runtime_cwd):runtime_cwd = str(self._project_dir or "").strip()@@ -3528,6 +3539,7 @@ class JiuWenSwarmDeepAdapter:request_metadata: dict[str, Any] | None = Nonetrusted_dirs: list[str] | None = Nonecwd: str | None = None+ workspace: str | None = Noneproject_dir: str | None = Noneasync def _update_runtime_config(self, runtime_config: "_RuntimeConfig") -> None:@@ -3539,7 +3551,8 @@ class JiuWenSwarmDeepAdapter:runtime_config.cwdor runtime_config.project_diror self._project_dir- or self._workspace_dir+ or self._workspace_dir,+ workspace=runtime_config.workspace,)resolved_language = self._resolve_runtime_language()resolved_channel = (@@ -5060,6 +5073,7 @@ class JiuWenSwarmDeepAdapter:request_metadata=request.metadata,trusted_dirs=inputs.get("trusted_dirs"),cwd=inputs.get("cwd"),+ workspace=inputs.get("workspace_dir"),project_dir=inputs.get("project_dir"),))@@ -5287,6 +5301,7 @@ class JiuWenSwarmDeepAdapter:request_metadata=request.metadata,trusted_dirs=inputs.get("trusted_dirs"),cwd=inputs.get("cwd"),+ workspace=inputs.get("workspace_dir"),project_dir=inputs.get("project_dir"),))@@ -5510,7 +5525,11 @@ class JiuWenSwarmDeepAdapter:yield AgentResponseChunk(request_id=rid,channel_id=cid,- payload={"event_type": "chat.error", "error": str(exc)},+ payload={+ "event_type": "chat.error",+ "error": str(exc),+ "error_type": type(exc).__name__,+ },is_complete=False,)finally:diff --git a/tests/unit/agentserver/test_interface_chat_error.py b/tests/unit/agentserver/test_interface_chat_error.pynew file mode 100644index 0000000000..2d72f0270e--- /dev/null+++ b/tests/unit/agentserver/test_interface_chat_error.py@@ -0,0 +1,214 @@+"""Regression test for chat.error stream events carrying ``error_type``.++The streaming error aggregator in ``JiuWenClaw.process_message_stream``+classifies the exception class on each chat.error event so that downstream+consumers (log indexers, dashboards, external evaluators) can group failures+without regexing the message text. This pins the contract on both the+yielded ``AgentResponseChunk`` and the persisted history record.+"""+from __future__ import annotations++import asyncio+import json+from pathlib import Path+from typing import Any, AsyncIterator, List++import pytest++from jiuwenswarm.server.runtime.agent_adapter import interface as interface_module+from jiuwenswarm.server.runtime.agent_adapter.interface import JiuWenClaw+from jiuwenswarm.common.schema.agent import AgentRequest, AgentResponseChunk+++class _RaisingStream:+ def __init__(self, exc: BaseException) -> None:+ self._exc = exc++ def __aiter__(self) -> "_RaisingStream":+ return self++ async def __anext__(self) -> AgentResponseChunk:+ raise self._exc+++class _RaisingAdapter:+ """Fake AgentAdapter whose stream impl raises immediately."""++ def __init__(self, exc: BaseException) -> None:+ self._exc = exc++ async def create_instance(self, config: dict[str, Any] | None = None) -> None:+ return None++ async def reload_agent_config(self, *_args: Any, **_kwargs: Any) -> None:+ return None++ async def process_message_impl(self, *_args: Any, **_kwargs: Any) -> Any:+ raise self._exc++ def process_message_stream_impl(+ self, _request: AgentRequest, _inputs: dict[str, Any]+ ) -> AsyncIterator[AgentResponseChunk]:+ return _RaisingStream(self._exc)++ async def process_interrupt(self, *_args: Any, **_kwargs: Any) -> Any:+ return None++ async def handle_user_answer(self, *_args: Any, **_kwargs: Any) -> Any:+ return None++ async def handle_heartbeat(self, *_args: Any, **_kwargs: Any) -> Any:+ return None+++def _patch_facade(+ monkeypatch: pytest.MonkeyPatch,+ facade: JiuWenClaw,+ adapter: _RaisingAdapter,+ recorded: List[dict[str, Any]],+) -> None:+ monkeypatch.setattr(facade, "_adapter", adapter)+ monkeypatch.setattr(facade, "_sdk_name", "harness")++ def _capture_history(**kwargs: Any) -> None:+ recorded.append(kwargs)++ monkeypatch.setattr(interface_module, "append_history_record", _capture_history)+ monkeypatch.setattr(interface_module, "get_config", lambda: {"preferred_language": "zh"})+ monkeypatch.setattr(interface_module, "get_memory_mode", lambda _cfg: "off")+ # Bypass the user prompt builder; the test only cares about the error+ # aggregator after the inner stream raises.+ monkeypatch.setattr(interface_module, "build_user_prompt", lambda q, **_kw: q)+++async def test_chat_error_chunk_includes_error_type(monkeypatch: pytest.MonkeyPatch) -> None:+ facade = JiuWenClaw()+ adapter = _RaisingAdapter(ValueError("boom from agent"))+ history: List[dict[str, Any]] = []+ _patch_facade(monkeypatch, facade, adapter, history)++ request = AgentRequest(+ request_id="req-err-1",+ channel_id="acp",+ session_id="acp_test_sess",+ params={"query": "hello", "mode": "agent.plan"},+ )++ chunks: List[AgentResponseChunk] = []+ async for chunk in facade.process_message_stream(request):+ chunks.append(chunk)++ error_chunks = [+ c for c in chunks+ if isinstance(c.payload, dict) and c.payload.get("event_type") == "chat.error"+ ]+ assert len(error_chunks) == 1, f"expected 1 chat.error chunk, got {len(error_chunks)}"+ payload = error_chunks[0].payload+ assert payload["error_type"] == "ValueError"+ assert "boom from agent" in payload["error"]+++async def test_chat_error_history_record_carries_error_type(monkeypatch: pytest.MonkeyPatch) -> None:+ facade = JiuWenClaw()+ adapter = _RaisingAdapter(RuntimeError("rate limited"))+ history: List[dict[str, Any]] = []+ _patch_facade(monkeypatch, facade, adapter, history)++ request = AgentRequest(+ request_id="req-err-2",+ channel_id="acp",+ session_id="acp_test_sess",+ params={"query": "hi", "mode": "agent.plan"},+ )+ async for _chunk in facade.process_message_stream(request):+ pass++ error_records = [+ r for r in history if r.get("event_type") == "chat.error"+ ]+ assert len(error_records) == 1+ extra = error_records[0].get("extra")+ assert isinstance(extra, dict)+ assert extra.get("error_type") == "RuntimeError"+++async def test_chat_error_history_record_persists_error_type_at_top_level(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ # Pin that append_history_record flattens extra["error_type"] to the+ # persisted record's top level.+ from jiuwenswarm.server.runtime.session import session_history+ from jiuwenswarm.server.runtime.session import session_metadata++ facade = JiuWenClaw()+ adapter = _RaisingAdapter(LookupError("token bucket exhausted"))+ monkeypatch.setattr(facade, "_adapter", adapter)+ monkeypatch.setattr(facade, "_sdk_name", "harness")++ # Redirect session_history's sessions dir into the tempdir; do NOT mock+ # append_history_record itself — we want the real flatten-and-write path.+ # session_metadata.py imports get_agent_sessions_dir into its own module+ # namespace and is invoked transitively by append_history_record, so it+ # needs the same redirect or it writes metadata.json to the real+ # ~/.jiuwenswarm sessions dir.+ sessions_root = tmp_path / "sessions"+ sessions_root.mkdir()+ monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: sessions_root)+ monkeypatch.setattr(session_metadata, "get_agent_sessions_dir", lambda: sessions_root)+ monkeypatch.setattr(interface_module, "get_config", lambda: {"preferred_language": "zh"})+ monkeypatch.setattr(interface_module, "get_memory_mode", lambda _cfg: "off")+ monkeypatch.setattr(interface_module, "build_user_prompt", lambda q, **_kw: q)++ sid = "tempsess1"+ request = AgentRequest(+ request_id="req-err-disk",+ channel_id="acp",+ session_id=sid,+ params={"query": "hi", "mode": "agent.plan"},+ )+ async for _chunk in facade.process_message_stream(request):+ pass++ history_file = sessions_root / sid / "history.json"+ chat_errors: list[dict[str, Any]] = []+ for _ in range(50):+ if history_file.exists():+ persisted = json.loads(history_file.read_text(encoding="utf-8"))+ chat_errors = [r for r in persisted if r.get("event_type") == "chat.error"]+ if chat_errors:+ break+ await asyncio.sleep(0.02)++ assert history_file.exists(), f"history.json not written at {history_file}"+ assert len(chat_errors) == 1+ # The doc claims this field is at the top level (not nested under+ # event_payload or extra). Pin it.+ assert chat_errors[0].get("error_type") == "LookupError"+++async def test_cancelled_error_propagates_without_chat_error_chunk(monkeypatch: pytest.MonkeyPatch) -> None:+ # asyncio.CancelledError must propagate as cancellation, not be classified+ # and yielded as a chat.error event.+ facade = JiuWenClaw()+ adapter = _RaisingAdapter(asyncio.CancelledError())+ history: List[dict[str, Any]] = []+ _patch_facade(monkeypatch, facade, adapter, history)++ request = AgentRequest(+ request_id="req-cancel",+ channel_id="acp",+ session_id="acp_test_sess",+ params={"query": "hi", "mode": "agent.plan"},+ )++ with pytest.raises(asyncio.CancelledError):+ async for _chunk in facade.process_message_stream(request):+ pass++ # No history record for cancellation+ assert not [r for r in history if r.get("event_type") == "chat.error"]diff --git a/tests/unit/channel/test_acp_channel_envelope_path.py b/tests/unit/channel/test_acp_channel_envelope_path.pynew file mode 100644index 0000000000..e103c35e16--- /dev/null+++ b/tests/unit/channel/test_acp_channel_envelope_path.py@@ -0,0 +1,119 @@+"""Regression test for envelope-path session→request mapping.++The JSON-RPC `session/prompt` handler registers+``_active_prompt_request_by_session[session_id] = msg.id`` so that+``_message_from_gateway_event`` can route streamed events back to the+originating prompt request. The envelope path used by ``app_cli`` (and+any external stdio driver speaking E2AEnvelope) historically forgot+that registration -- the channel would then drop every gateway event+and the client's ``proc.stdout`` reader would hang waiting for a final+frame that never arrives.++This test pins the contract: after ``_handle_raw_line`` processes an+envelope with ``session_id``, the mapping must be populated.+"""+from __future__ import annotations++import json+from typing import Any++import pytest++from jiuwenswarm.gateway.channel_manager.protocol.acp.acp_connect import (+ AcpChannel,+ AcpChannelConfig,+)+++class _NoopBus:+ @staticmethod+ async def publish_user_messages(_msg: Any) -> None:+ return None+++def _build_channel() -> AcpChannel:+ return AcpChannel(+ AcpChannelConfig(+ enabled=True,+ channel_id="acp",+ default_session_id="acp_cli_session",+ metadata={},+ ),+ router=_NoopBus(),+ gateway_url=None,+ )+++def _envelope(session_id: str, *, request_id: str = "req-1") -> str:+ """Minimal session/prompt envelope as written to acp_channel stdin."""+ return json.dumps({+ "protocol_version": "1.0",+ "request_id": request_id,+ "method": "session/prompt",+ "params": {"content": "hi"},+ "channel": "acp",+ "session_id": session_id,+ "is_stream": True,+ "jsonrpc_id": request_id,+ })+++async def _noop_dispatch(_msg: Any) -> None:+ return None+++async def _handle_envelope_line(channel: AcpChannel, line: str) -> None:+ handler = getattr(channel, "_handle_raw_line")+ await handler(line)+++def _mapped_request_id(channel: AcpChannel, session_id: str) -> str | None:+ mapping = getattr(channel, "_active_prompt_request_by_session")+ value = mapping.get(session_id)+ return value if isinstance(value, str) else None+++def _has_request_context(channel: AcpChannel, request_id: str) -> bool:+ request_ctx = getattr(channel, "_request_ctx")+ return request_id in request_ctx+++async def test_handle_raw_line_registers_session_to_request_mapping(monkeypatch: pytest.MonkeyPatch) -> None:+ channel = _build_channel()+ # Skip dispatch (no gateway available in unit tests); we only care about+ # what state `_handle_raw_line` itself leaves behind.+ monkeypatch.setattr(channel, "_dispatch_message", _noop_dispatch)++ sid = "session-xyz"+ await _handle_envelope_line(channel, _envelope(sid))++ mapped_request_id = _mapped_request_id(channel, sid)+ assert mapped_request_id is not None, (+ "envelope path must register session→request mapping so gateway events"+ " can be routed back to the originating prompt"+ )+ assert _has_request_context(channel, mapped_request_id)+++async def test_handle_raw_line_skips_mapping_when_session_id_missing(monkeypatch: pytest.MonkeyPatch) -> None:+ # Envelope with missing session_id falls back to the channel default.+ channel = _build_channel()+ monkeypatch.setattr(channel, "_dispatch_message", _noop_dispatch)++ env = json.dumps({+ "protocol_version": "1.0",+ "request_id": "req-2",+ "method": "session/prompt",+ "params": {"content": "hi"},+ "channel": "acp",+ # session_id intentionally absent — _envelope_to_message falls back+ # to channel default+ "is_stream": True,+ "jsonrpc_id": "req-2",+ })+ await _handle_envelope_line(channel, env)+ # Default session id from config (not None), so mapping IS populated.+ # The contract is "if msg.session_id, register" — falsy session_id skips.+ assert _mapped_request_id(channel, "acp_cli_session") is not Nonediff --git a/tests/unit_tests/agentserver/test_agentserver_modes.py b/tests/unit_tests/agentserver/test_agentserver_modes.pyindex cddef84abe..651721c979 100644--- a/tests/unit_tests/agentserver/test_agentserver_modes.py+++ b/tests/unit_tests/agentserver/test_agentserver_modes.py@@ -355,6 +355,152 @@ def test_deep_adapter_routes_team_simplify_answer_by_evolution_meta(monkeypatch)assert calls == [("approve_simplify", "evolve_simplify_team123")]+def test_build_inputs_threads_workspace_dir_into_cwd(monkeypatch, tmp_path):+ """``params.workspace_dir`` scopes a single prompt's cwd AND workspace to+ the supplied directory and creates it on demand. Threaded into BOTH+ ``inputs["cwd"]`` (so tools that read ``get_cwd()`` resolve relative paths+ against it) and ``inputs["workspace_dir"]`` (so the deep adapter forwards+ it as the workspace override on ``init_cwd``, which controls+ ``fs_operation``'s sandbox enforcement for absolute-path writes). Used by+ external drivers (IDE plugins, headless evaluators) that allocate a+ per-invocation scratch dir.+ """+ from jiuwenswarm.server.runtime.agent_adapter import interface as interface_module++ class FakeSkillManager:+ def __init__(self, workspace_dir=None):+ self.workspace_dir = workspace_dir+ self.hook = None++ def set_skillnet_install_complete_hook(self, hook):+ self.hook = hook++ class FakeSessionManager:+ @staticmethod+ def get_session_id(session_id):+ return session_id or "default"++ async def submit_and_wait(self, _session_id, task_func):+ return await task_func()++ class FakeAdapter:+ def __init__(self):+ self.seen_inputs = None+ self.skill_manager = None++ def set_skill_manager(self, skill_manager):+ self.skill_manager = skill_manager++ async def handle_heartbeat(self, _request):+ return None++ async def process_message_impl(self, request, inputs):+ self.seen_inputs = inputs+ return AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ payload={"content": "ok"},+ )++ fake_adapter = FakeAdapter()++ monkeypatch.setattr(interface_module, "get_config", lambda: {"preferred_language": "zh"})+ monkeypatch.setattr(interface_module, "get_memory_mode", lambda _config: "disabled")+ monkeypatch.setattr(interface_module, "SkillManager", FakeSkillManager)+ monkeypatch.setattr(interface_module, "SessionManager", FakeSessionManager)+ monkeypatch.setattr(interface_module, "append_history_record", lambda **_kwargs: None)+ monkeypatch.setattr(interface_module, "resolve_sdk_choice", lambda: "harness")+ monkeypatch.setattr(interface_module, "create_adapter", lambda _sdk, mode="agent": fake_adapter)++ scratch = tmp_path / "scoped-run-001" # does NOT exist yet+ assert not scratch.exists()++ request = AgentRequest(+ request_id="req-ws",+ channel_id="acp",+ session_id="acp_session",+ params={"query": "hello", "workspace_dir": str(scratch)},+ )++ asyncio.run(interface_module.JiuWenClaw().process_message(request))++ inputs = fake_adapter.seen_inputs+ # Path is resolved (symlinks followed, absolute form) before threading.+ resolved = str(scratch.resolve())+ assert inputs["cwd"] == resolved, "workspace_dir must thread into inputs.cwd"+ assert inputs["workspace_dir"] == resolved, (+ "workspace_dir must also thread into inputs.workspace_dir so the deep "+ "adapter forwards it as the workspace override on init_cwd"+ )+ assert scratch.is_dir(), "_build_inputs must mkdir the scratch dir"+++def test_build_inputs_omits_cwd_when_workspace_dir_unset(monkeypatch):+ """When ``params.workspace_dir`` is absent or empty, ``_build_inputs``+ does not overwrite ``inputs.cwd`` -- letting the explicit ``params.cwd``+ (or the downstream default) win.+ """+ from jiuwenswarm.server.runtime.agent_adapter import interface as interface_module++ class FakeSkillManager:+ def __init__(self, workspace_dir=None):+ self.workspace_dir = workspace_dir+ self.hook = None++ def set_skillnet_install_complete_hook(self, hook):+ self.hook = hook++ class FakeSessionManager:+ @staticmethod+ def get_session_id(session_id):+ return session_id or "default"++ async def submit_and_wait(self, _session_id, task_func):+ return await task_func()++ class FakeAdapter:+ def __init__(self):+ self.seen_inputs = None+ self.skill_manager = None++ def set_skill_manager(self, skill_manager):+ self.skill_manager = skill_manager++ async def handle_heartbeat(self, _request):+ return None++ async def process_message_impl(self, request, inputs):+ self.seen_inputs = inputs+ return AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ payload={"content": "ok"},+ )++ fake_adapter = FakeAdapter()++ monkeypatch.setattr(interface_module, "get_config", lambda: {"preferred_language": "zh"})+ monkeypatch.setattr(interface_module, "get_memory_mode", lambda _config: "disabled")+ monkeypatch.setattr(interface_module, "SkillManager", FakeSkillManager)+ monkeypatch.setattr(interface_module, "SessionManager", FakeSessionManager)+ monkeypatch.setattr(interface_module, "append_history_record", lambda **_kwargs: None)+ monkeypatch.setattr(interface_module, "resolve_sdk_choice", lambda: "harness")+ monkeypatch.setattr(interface_module, "create_adapter", lambda _sdk, mode="agent": fake_adapter)++ request = AgentRequest(+ request_id="req-nows",+ channel_id="acp",+ session_id="acp_session",+ params={"query": "hello", "cwd": "/tmp/explicit-cwd"}, # no workspace_dir+ )++ asyncio.run(interface_module.JiuWenClaw().process_message(request))++ inputs = fake_adapter.seen_inputs+ # params.cwd is preserved untouched+ assert inputs["cwd"] == "/tmp/explicit-cwd"++def test_handle_stream_accepts_team_mode_without_sub_mode(monkeypatch):class FakeAgent:def __init__(self):