Skip to content

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(team): Agent Teams support communication with third-party agents through ACP client

ray_lea663377aa97d
diff --git a/jiuwenswarm/acp/__init__.py b/jiuwenswarm/acp/__init__.py
new file mode 100644
index 0000000000..f7b73e79d5
--- /dev/null
+++ b/jiuwenswarm/acp/__init__.py
@@ -0,0 +1,7 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""ACP stdio client primitives (talk to external ACP agents as a subprocess)."""
+
+from jiuwenswarm.acp.stdio_client import AcpStdioClient
+
+__all__ = ["AcpStdioClient"]
diff --git a/jiuwenswarm/acp/cli.py b/jiuwenswarm/acp/cli.py
new file mode 100644
index 0000000000..c6b42369ab
--- /dev/null
+++ b/jiuwenswarm/acp/cli.py
@@ -0,0 +1,90 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""CLI smoke test for external ACP agents (stdio), sharing config with acp_chat tool."""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import logging
+import os
+import sys
+
+from jiuwenswarm.acp.stdio_client import AcpStdioClient
+from jiuwenswarm.common.config import get_config
+
+logger = logging.getLogger(__name__)
+
+
+def _get_spec(agent: str) -> dict | None:
+ cfg = get_config()
+ agents = cfg.get("acp_agents")
+ if not isinstance(agents, dict):
+ logger.error("[ERROR] config has no acp_agents.")
+ return None
+ spec = agents.get(agent.strip())
+ if not isinstance(spec, dict):
+ logger.error("[ERROR] unknown acp_agents profile %r.", agent)
+ return None
+ return spec
+
+
+async def _run_once(agent: str, message: str) -> int:
+ spec = _get_spec(agent)
+ if spec is None:
+ return 2
+ command = str(spec.get("command") or "").strip()
+ if not command:
+ logger.error("[ERROR] profile needs command.")
+ return 2
+ raw_args = spec.get("args")
+ args = [str(x) for x in raw_args] if isinstance(raw_args, list) else []
+ cwd = spec.get("cwd")
+ cwd_s: str | None = None
+ if isinstance(cwd, str) and cwd.strip():
+ cwd_s = cwd.strip()
+ env = spec.get("env") if isinstance(spec.get("env"), dict) else None
+
+ client = AcpStdioClient(command, args, cwd=cwd_s, env=env)
+ try:
+ await client.connect()
+ out = await client.chat(message)
+ logger.info("%s", out or "(empty response)")
+ return 0
+ except Exception as exc:
+ logger.error("[ERROR] ACP session failed: %s", exc)
+ return 1
+ finally:
+ _close_timeout = float(os.getenv("ACP_CLI_CLOSE_TIMEOUT_S", "30"))
+ try:
+ await asyncio.wait_for(asyncio.shield(client.close()), timeout=_close_timeout)
+ except Exception as exc:
+ logger.warning("Failed to close ACP client: %s", exc)
+
+
+async def _main_async() -> int:
+ p = argparse.ArgumentParser(description="Smoke-test an acp_agents profile (one-shot subprocess).")
+ p.add_argument("agent", help="Profile key under acp_agents in config.yaml")
+ p.add_argument("message", nargs="?", default="Hello", help="Prompt text")
+ args = p.parse_args()
+ return await _run_once(args.agent, args.message)
+
+
+def main() -> None:
+ logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout)
+ if os.environ.get("JIUWENCLAW_SKIP_DOTENV", "").strip() != "1":
+ try:
+ from dotenv import load_dotenv
+ from jiuwenswarm.common.utils import get_env_file
+
+ load_dotenv(dotenv_path=get_env_file(), override=False)
+ except Exception as exc:
+ logger.debug("Skipping dotenv load: %s", exc)
+ try:
+ sys.exit(asyncio.run(_main_async()))
+ except KeyboardInterrupt:
+ sys.exit(130)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/jiuwenswarm/acp/stdio_client.py b/jiuwenswarm/acp/stdio_client.py
new file mode 100644
index 0000000000..74038dfd4d
--- /dev/null
+++ b/jiuwenswarm/acp/stdio_client.py
@@ -0,0 +1,670 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Minimal ACP JSON-RPC client over subprocess stdin/stdout.
+
+Each message is JSON-RPC over UTF-8. Values may span multiple lines (pretty-printed JSON);
+we buffer stdout and parse with ``json.JSONDecoder.raw_decode``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import os
+import shutil
+import signal
+import sys
+from typing import Any
+
+from jiuwenswarm.acp.subprocess_env import build_acp_subprocess_env
+
+logger = logging.getLogger(__name__)
+
+_DEFAULT_CHAT_TIMEOUT = float(os.getenv("ACP_CHAT_TIMEOUT", "600"))
+_DEBUG_CHAT = os.getenv("ACP_CHAT_DEBUG", "").strip().lower() in ("1", "true", "yes")
+_JSON_DECODER = json.JSONDecoder()
+_MAX_STDOUT_BUFFER = int(os.getenv("ACP_CHAT_MAX_PARSE_BUFFER_BYTES", str(24 * 1024 * 1024)))
+_STDOUT_READ_CHUNK = int(os.getenv("ACP_CHAT_STDOUT_READ_CHUNK", str(65536)))
+_CLOSE_STDIN_WAIT_S = float(os.getenv("ACP_CLOSE_STDIN_WAIT_S", "4"))
+_CLOSE_TERM_WAIT_S = float(os.getenv("ACP_CLOSE_TERM_WAIT_S", "5"))
+_CLOSE_KILL_WAIT_S = float(os.getenv("ACP_CLOSE_KILL_WAIT_S", "8"))
+_CLOSE_STDERR_JOIN_S = float(os.getenv("ACP_CLOSE_STDERR_JOIN_S", "3"))
+_CLOSE_DRAIN_PIPE_S = float(os.getenv("ACP_CLOSE_DRAIN_PIPE_S", "3"))
+_KILL_PG = sys.platform != "win32" and os.getenv("ACP_KILL_PROCESS_GROUP", "true").strip().lower() in (
+ "1",
+ "true",
+ "yes",
+)
+
+# When true (default), auto-answer session/request_permission so headless Codex does not stall.
+_AUTO_APPROVE = os.getenv("ACP_AUTO_APPROVE_PERMISSIONS", "true").strip().lower() in (
+ "1",
+ "true",
+ "yes",
+)
+
+
+def _jsonrpc_error_message(err: Any) -> str:
+ """Human-readable ACP JSON-RPC error for logs and RuntimeError messages."""
+ if not isinstance(err, dict):
+ return f"ACP JSON-RPC error: {err}"
+ code = err.get("code")
+ message = err.get("message")
+ data = err.get("data")
+ parts: list[str] = []
+ if code is not None:
+ parts.append(str(code))
+ if message:
+ parts.append(str(message))
+ if data is not None:
+ parts.append(f"data={data!r}")
+ return "ACP JSON-RPC error: " + (" ".join(parts) if parts else repr(err))
+
+
+def _consume_one_json(buffer: str) -> tuple[Any | None, str]:
+ """Parse one JSON value from the start of *buffer* if complete; otherwise (None, *buffer*).
+
+ Leading whitespace is dropped from the consumed prefix; remainder retains extra data
+ after the parsed value for the next call.
+ """
+ s = buffer.lstrip()
+ if not s:
+ return None, buffer
+ if len(s) > _MAX_STDOUT_BUFFER:
+ raise RuntimeError(f"ACP stdout parse buffer exceeds {_MAX_STDOUT_BUFFER} bytes")
+ try:
+ obj, idx = _JSON_DECODER.raw_decode(s)
+ rest = s[idx:].lstrip("\r\n\t ")
+ return obj, rest
+ except json.JSONDecodeError:
+ return None, buffer
+
+
+def _is_peer_jsonrpc_request(msg: dict[str, Any]) -> bool:
+ """True if peer sent a JSON-RPC request (expects a response line on stdin).
+
+ Responses carry ``result``/``error``. Notifications omit ``id`` or use notifications only.
+ """
+ if msg.get("jsonrpc") != "2.0":
+ return False
+ if not isinstance(msg.get("method"), str):
+ return False
+ if msg.get("id") is None:
+ return False
+ if "result" in msg or "error" in msg:
+ return False
+ return True
+
+
+def _extract_session_update_text(msg: dict[str, Any]) -> str:
+ if msg.get("method") != "session/update":
+ return ""
+ params = msg.get("params")
+ if not isinstance(params, dict):
+ return ""
+ update = params.get("update")
+ if not isinstance(update, dict):
+ return ""
+ content = update.get("content")
+ if not isinstance(content, dict):
+ return ""
+ if content.get("type") == "text":
+ return str(content.get("text") or "")
+ return ""
+
+
+def _merge_env(profile_env: dict[str, Any] | None) -> dict[str, str]:
+ return build_acp_subprocess_env(profile_env)
+
+
+def _resolve_spawn_command(command: str) -> str:
+ """Resolve Windows command shims like npx.cmd when shell=False."""
+ cmd = (command or "").strip()
+ if sys.platform != "win32" or not cmd:
+ return cmd
+ if any(sep in cmd for sep in ("/", "\\")) or os.path.splitext(cmd)[1]:
+ return cmd
+ for candidate in (cmd, f"{cmd}.cmd", f"{cmd}.exe", f"{cmd}.bat"):
+ resolved = shutil.which(candidate)
+ if resolved:
+ return resolved
+ return cmd
+
+
+def _resolved_session_root(client_cwd: str | None) -> str:
+ if client_cwd and client_cwd.strip():
+ return os.path.realpath(os.path.abspath(os.path.expanduser(client_cwd.strip())))
+ return os.path.realpath(os.getcwd())
+
+
+def _resolved_path_inside_root(session_root: str, path_in: Any) -> str | None:
+ if not isinstance(path_in, str) or not path_in.strip():
+ return None
+ try:
+ cand = os.path.realpath(os.path.abspath(os.path.expanduser(path_in.strip())))
+ except OSError:
+ return None
+ if cand == session_root:
+ return cand
+ if not cand.startswith(session_root + os.sep):
+ return None
+ return cand
+
+
+def _slice_file_lines(text: str, line_raw: Any, limit_raw: Any) -> str:
+ lines = text.splitlines(True)
+ try:
+ line_no = max(1, int(line_raw)) if line_raw is not None else 1
+ except (TypeError, ValueError):
+ line_no = 1
+ start = max(0, line_no - 1)
+ try:
+ lim = int(limit_raw) if limit_raw is not None else None
+ except (TypeError, ValueError):
+ lim = None
+ if lim is not None and lim > 0:
+ return "".join(lines[start:start + lim])
+ return "".join(lines[start:])
+
+
+async def _bounded_drain_reader(stream: asyncio.StreamReader | None, seconds: float) -> None:
+ """Read until EOF or *seconds* elapse — ``StreamReader.read`` can block indefinitely without this."""
+ if stream is None or seconds <= 0:
+ return
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + seconds
+ try:
+ while loop.time() < deadline:
+ try:
+ blob = await asyncio.wait_for(stream.read(_STDOUT_READ_CHUNK),
+ timeout=max(0.05, deadline - loop.time()))
+ except asyncio.TimeoutError:
+ break
+ except Exception as exc:
+ logger.debug("drain reader stopped on read error: %s", exc)
+ break
+ if not blob:
+ break
+ except Exception as exc:
+ logger.debug("drain reader stopped: %s", exc)
+
+
+def _signal_process_leader(proc: asyncio.subprocess.Process, *, brutal: bool) -> None:
+ """Signal the managed subprocess (and its POSIX process group when configured)."""
+ if proc.pid is None:
+ return
+ if sys.platform != "win32":
+ sig = signal.SIGKILL if brutal else signal.SIGTERM
+ if _KILL_PG:
+ try:
+ os.killpg(proc.pid, sig)
+ return
+ except OSError as exc:
+ logger.debug("killpg(%s) skipped: %s", proc.pid, exc)
+ try:
+ proc.send_signal(sig)
+ except ProcessLookupError as exc:
+ logger.debug("send_signal(%s) skipped: %s", proc.pid, exc)
+ return
+ try:
+ if brutal:
+ proc.kill()
+ else:
+ proc.terminate()
+ except ProcessLookupError as exc:
+ logger.debug("signal process skipped: %s", exc)
+
+
+class AcpStdioClient:
+ """Spawn an ACP-compatible agent and exchange JSON-RPC 2.0 over subprocess stdio."""
+
+ def __init__(
+ self,
+ command: str,
+ args: list[str] | None = None,
+ cwd: str | None = None,
+ env: dict[str, Any] | None = None,
+ ) -> None:
+ self._command = (command or "").strip()
+ self._args = list(args or [])
+ self._cwd = cwd if cwd else None
+ self._env = _merge_env(env)
+ self._proc: asyncio.subprocess.Process | None = None
+ self._session_id: str | None = None
+ self._next_rpc_id = 1
+ self._stderr_task: asyncio.Task[None] | None = None
+ self._closed = False
+ self._stdout_buf = ""
+
+ async def _send_json_rpc_response(
+ self,
+ req_id: Any,
+ *,
+ result: Any | None = None,
+ error: Any | None = None,
+ ) -> None:
+ body: dict[str, Any] = {"jsonrpc": "2.0", "id": req_id}
+ if error is not None:
+ body["error"] = error
+ else:
+ body["result"] = result
+ line = json.dumps(body, ensure_ascii=False) + "\n"
+ self._proc.stdin.write(line.encode("utf-8"))
+ await self._proc.stdin.drain()
+
+ async def _handle_peer_request(self, msg: dict[str, Any]) -> None:
+ """Respond to outbound JSON-RPC from the spawned agent so it does not block."""
+ req_id = msg.get("id")
+ method = str(msg.get("method") or "").strip()
+
+ # Align with Gateway permission outcome parsing (see interrupt_helpers permiss flow).
+ if method == "session/request_permission":
+ if _AUTO_APPROVE:
+ await self._send_json_rpc_response(
+ req_id,
+ result={
+ "outcome": {
+ "outcome": "selected",
+ "optionId": "allow-once",
+ }
+ },
+ )
+ logger.info(
+ "[AcpStdioClient] replied to session/request_permission id=%s (allow-once)",
+ req_id,
+ )
+ else:
+ await self._send_json_rpc_response(
+ req_id,
+ result={"outcome": {"outcome": "cancelled"}},
+ )
+ logger.info(
+ "[AcpStdioClient] replied to session/request_permission id=%s (cancelled)",
+ req_id,
+ )
+ return
+
+ if method == "fs/read_text_file":
+ params = msg.get("params")
+ if not isinstance(params, dict):
+ await self._send_json_rpc_response(
+ req_id,
+ error={"code": -32602, "message": "invalid fs/read_text_file params"},
+ )
+ return
+ raw_path = params.get("path")
+ root = _resolved_session_root(self._cwd)
+ abs_path = _resolved_path_inside_root(root, raw_path)
+ if abs_path is None:
+ await self._send_json_rpc_response(
+ req_id,
+ error={"code": -32001, "message": "path denied or invalid"},
+ )
+ return
+
+ def _load() -> str:
+ with open(abs_path, encoding="utf-8", errors="replace") as fh:
+ return fh.read()
+
+ try:
+ full = await asyncio.to_thread(_load)
+ except FileNotFoundError:
+ await self._send_json_rpc_response(
+ req_id,
+ error={"code": -32002, "message": "ENOENT"},
+ )
+ return
+ except OSError as exc:
+ await self._send_json_rpc_response(
+ req_id,
+ error={"code": -32000, "message": str(exc) or "read failed"},
+ )
+ return
+ chunk = _slice_file_lines(full, params.get("line"), params.get("limit"))
+ await self._send_json_rpc_response(req_id, result={"content": chunk})
+ if _DEBUG_CHAT:
+ logger.info("[AcpStdioClient] fs/read_text_file ok path=%s bytes=%s", abs_path, len(chunk))
+ return
+
+ if method == "fs/write_text_file":
+ params = msg.get("params")
+ if not isinstance(params, dict):
+ await self._send_json_rpc_response(
+ req_id,
+ error={"code": -32602, "message": "invalid fs/write_text_file params"},
+ )
+ return
+ raw_path = params.get("path")
+ root = _resolved_session_root(self._cwd)
+ abs_path = _resolved_path_inside_root(root, raw_path)
+ if abs_path is None:
+ await self._send_json_rpc_response(
+ req_id,
+ error={"code": -32001, "message": "path denied or invalid"},
+ )
+ return
+ wcontent = params.get("content")
+ if wcontent is None:
+ wbody = ""
+ elif isinstance(wcontent, str):
+ wbody = wcontent
+ else:
+ wbody = str(wcontent)
+
+ def _save() -> None:
+ os.makedirs(os.path.dirname(abs_path) or ".", exist_ok=True)
+ with open(abs_path, "w", encoding="utf-8") as fh:
+ fh.write(wbody)
+
+ try:
+ await asyncio.to_thread(_save)
+ except OSError as exc:
+ await self._send_json_rpc_response(
+ req_id,
+ error={"code": -32000, "message": str(exc) or "write failed"},
+ )
+ return
+ await self._send_json_rpc_response(req_id, result=None)
+ if _DEBUG_CHAT:
+ logger.info("[AcpStdioClient] fs/write_text_file ok path=%s", abs_path)
+ return
+
+ # Minimal stub so agent can progress; callers may tighten per Agent.
+ logger.warning("[AcpStdioClient] unhandled peer request method=%s id=%s — error reply", method, req_id)
+ await self._send_json_rpc_response(
+ req_id,
+ error={"code": -32601, "message": f"stdio ACP client: unsupported method {method}"},
+ )
+
+ @property
+ def session_id(self) -> str | None:
+ return self._session_id
+
+ @property
+ def is_connected(self) -> bool:
+ if self._closed or self._proc is None:
+ return False
+ rc = self._proc.returncode
+ return rc is None
+
+ def _next_id(self) -> int:
+ rid = self._next_rpc_id
+ self._next_rpc_id += 1
+ return rid
+
+ async def _drain_stderr(self) -> None:
+ while True:
+ line = await self._proc.stderr.readline()
+ if not line:
+ break
+ try:
+ txt = line.decode("utf-8", errors="replace").rstrip()
+ if txt:
+ if _DEBUG_CHAT:
+ logger.info("[acp-agent stderr] %s", txt)
+ else:
+ logger.debug("[acp-agent stderr] %s", txt)
+ except Exception as exc:
+ logger.debug("failed to decode stderr line: %s", exc)
+
+ async def _read_one_message(self, timeout: float) -> dict[str, Any] | None:
+ deadline = asyncio.get_event_loop().time() + timeout
+ while True:
+ while True:
+ try:
+ obj, self._stdout_buf = _consume_one_json(self._stdout_buf)
+ except RuntimeError as exc:
+ logger.error("%s", exc)
+ raise
+ if obj is None:
+ break
+ if not isinstance(obj, dict):
+ logger.warning("[AcpStdioClient] dropping non-object JSON-RPC message: %s", type(obj).__name__)
+ continue
+ if _DEBUG_CHAT:
+ logger.info(
+ "[AcpStdioClient] rx keys=%s id=%s method=%s",
+ list(obj.keys()),
+ obj.get("id"),
+ obj.get("method"),
+ )
+ return obj
+
+ now = asyncio.get_event_loop().time()
+ if now >= deadline:
+ return None
+ remain = max(0.1, deadline - now)
+ try:
+ chunk = await asyncio.wait_for(
+ self._proc.stdout.read(_STDOUT_READ_CHUNK),
+ timeout=remain,
+ )
+ except asyncio.TimeoutError:
+ continue
+ if not chunk:
+ if self._stdout_buf.strip():
+ logger.warning(
+ "[AcpStdioClient] EOF while partial JSON buffered (%s bytes)",
+ len(self._stdout_buf),
+ )
+ return None
+ self._stdout_buf += chunk.decode("utf-8", errors="replace")
+
+ async def _rpc_call(
+ self,
+ method: str,
+ params: dict[str, Any],
+ *,
+ timeout: float = 120.0,
+ ) -> Any:
+ rid = self._next_id()
+ payload = {"jsonrpc": "2.0", "id": rid, "method": method, "params": params}
+ line = json.dumps(payload, ensure_ascii=False) + "\n"
+ self._proc.stdin.write(line.encode("utf-8"))
+ await self._proc.stdin.drain()
+
+ deadline = asyncio.get_event_loop().time() + timeout
+ while True:
+ remain = max(0.1, deadline - asyncio.get_event_loop().time())
+ msg = await self._read_one_message(remain)
+ if msg is None:
+ proc = self._proc
+ if proc is not None and proc.returncode is not None:
+ raise RuntimeError(
+ f"ACP agent process exited ({proc.returncode}) while waiting for {method}."
+ )
+ raise RuntimeError(f"ACP agent closed stream or timed out waiting for {method} response")
+ if msg.get("method") == "session/update":
+ continue
+ if _is_peer_jsonrpc_request(msg):
+ await self._handle_peer_request(msg)
+ continue
+ if str(msg.get("id")) == str(rid):
+ if "error" in msg:
+ raise RuntimeError(_jsonrpc_error_message(msg["error"]))
+ return msg.get("result")
+
+ async def connect(self) -> None:
+ if self._closed:
+ raise RuntimeError("AcpStdioClient is closed")
+ if not self._command:
+ raise ValueError("ACP agent command is empty")
+
+ self._stdout_buf = ""
+
+ spawn_kw: dict[str, Any] = {}
+ if _KILL_PG:
+ spawn_kw["start_new_session"] = True
+
+ self._proc = await asyncio.create_subprocess_exec(
+ _resolve_spawn_command(self._command),
+ *self._args,
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ cwd=self._cwd,
+ env=self._env,
+ **spawn_kw,
+ )
+ self._stderr_task = asyncio.create_task(self._drain_stderr())
+
+ await self._rpc_call(
+ "initialize",
+ {
+ "protocolVersion": 1,
+ # Advertise FS so Agents (e.g. Codex ACP) can complete tool turns; omit terminal — unsupported here.
+ "clientCapabilities": {
+ "fs": {"readTextFile": True, "writeTextFile": True},
+ "terminal": False,
+ },
+ "clientInfo": {"name": "jiuwenswarm", "version": "0.1"},
+ },
+ timeout=120.0,
+ )
+
+ session_cwd = (
+ os.path.abspath(os.path.expanduser(self._cwd))
+ if self._cwd
+ else os.getcwd()
+ )
+ # Codex ACP expects cwd + mcpServers (see agent deserialization errors).
+ new_params: dict[str, Any] = {
+ "cwd": session_cwd,
+ "mcpServers": [],
+ }
+ result = await self._rpc_call("session/new", new_params, timeout=60.0)
+ if not isinstance(result, dict):
+ raise RuntimeError(f"session/new: unexpected result: {result!r}")
+ sid = str(result.get("sessionId") or result.get("session_id") or "").strip()
+ if not sid:
+ raise RuntimeError(f"session/new: missing sessionId in {result!r}")
+ self._session_id = sid
+ logger.info("[AcpStdioClient] connected sessionId=%s", self._session_id)
+
+ async def chat(self, message: str, *, timeout: float | None = None) -> str:
+ if self._closed:
+ raise RuntimeError("AcpStdioClient is closed")
+ if not self._proc or not self._session_id:
+ raise RuntimeError("not connected; call connect() first")
+
+ t_out = timeout if timeout is not None else _DEFAULT_CHAT_TIMEOUT
+ rid = self._next_id()
+ params = {
+ "sessionId": self._session_id,
+ "prompt": [{"type": "text", "text": message}],
+ }
+ payload = {"jsonrpc": "2.0", "id": rid, "method": "session/prompt", "params": params}
+ line = json.dumps(payload, ensure_ascii=False) + "\n"
+ self._proc.stdin.write(line.encode("utf-8"))
+ await self._proc.stdin.drain()
+
+ parts: list[str] = []
+ deadline = asyncio.get_event_loop().time() + t_out
+
+ while True:
+ remain = max(0.1, deadline - asyncio.get_event_loop().time())
+ msg = await self._read_one_message(remain)
+ if msg is None:
+ proc = self._proc
+ if proc is not None and proc.returncode is not None:
+ raise RuntimeError(
+ "ACP agent process exited"
+ f" ({proc.returncode}) before completing session/prompt; check stderr/logs and API auth."
+ )
+ raise RuntimeError("timed out or EOF waiting for session/prompt completion")
+
+ if msg.get("method") == "session/update":
+ chunk = _extract_session_update_text(msg)
+ if chunk:
+ parts.append(chunk)
+ continue
+
+ if _is_peer_jsonrpc_request(msg):
+ await self._handle_peer_request(msg)
+ continue
+
+ if str(msg.get("id")) == str(rid):
+ if "error" in msg:
+ raise RuntimeError(_jsonrpc_error_message(msg["error"]))
+ return "".join(parts).strip() or _result_text_fallback(msg.get("result"))
+
+ logger.debug("[AcpStdioClient] ignoring unrelated message keys=%s", list(msg.keys()))
+
+ async def aclose(self) -> None:
+ await self.close()
+
+ async def close(self) -> None:
+ self._closed = True
+ proc = self._proc
+ self._proc = None
+ stderr_task = self._stderr_task
+ self._stderr_task = None
+ self._session_id = None
+
+ if proc is None:
+ if stderr_task:
+ stderr_task.cancel()
+ try:
+ await stderr_task
+ except asyncio.CancelledError as exc:
+ logger.debug("stderr task cancelled during close: %s", exc)
+ return
+
+ if proc.stdin is not None:
+ try:
+ closing = getattr(proc.stdin, "is_closing", None)
+ if not (callable(closing) and closing()):
+ proc.stdin.close()
+ try:
+ await asyncio.wait_for(proc.stdin.wait_closed(), timeout=_CLOSE_STDIN_WAIT_S)
+ except asyncio.TimeoutError as exc:
+ logger.debug("stdin wait_closed timed out after %ss: %s", _CLOSE_STDIN_WAIT_S, exc)
+ except OSError as exc:
+ logger.debug("closing stdin failed: %s", exc)
+ except RuntimeError as exc:
+ logger.debug("closing stdin failed: %s", exc)
+
+ if proc.returncode is None:
+ try:
+ _signal_process_leader(proc, brutal=False)
+ await asyncio.wait_for(proc.wait(), timeout=_CLOSE_TERM_WAIT_S)
+ except asyncio.TimeoutError as exc:
+ logger.debug("process wait (TERM) timed out after %ss: %s", _CLOSE_TERM_WAIT_S, exc)
+ except Exception as exc:
+ logger.debug("process wait (TERM) failed: %s", exc)
+
+ if proc.returncode is None:
+ try:
+ _signal_process_leader(proc, brutal=True)
+ await asyncio.wait_for(proc.wait(), timeout=_CLOSE_KILL_WAIT_S)
+ except Exception as exc:
+ logger.debug("process wait (KILL) failed: %s", exc)
+
+ if stderr_task:
+ try:
+ await asyncio.wait_for(stderr_task, timeout=_CLOSE_STDERR_JOIN_S)
+ except (asyncio.TimeoutError, asyncio.CancelledError) as exc:
+ logger.debug("stderr task join timed out or cancelled: %s", exc)
+ stderr_task.cancel()
+ try:
+ await stderr_task
+ except asyncio.CancelledError as cancel_exc:
+ logger.debug("stderr task cancelled after join timeout: %s", cancel_exc)
+ except Exception as join_exc:
+ logger.debug("stderr task failed after join timeout: %s", join_exc)
+
+ await _bounded_drain_reader(proc.stdout, _CLOSE_DRAIN_PIPE_S)
+ await _bounded_drain_reader(proc.stderr, _CLOSE_DRAIN_PIPE_S)
+
+ await asyncio.sleep(0)
+
+
+def _result_text_fallback(result: Any) -> str:
+ if result is None:
+ return ""
+ if isinstance(result, dict):
+ # Some agents may only return stopReason
+ sr = result.get("stopReason") or result.get("stop_reason")
+ return str(sr) if sr else json.dumps(result, ensure_ascii=False)
+ return str(result)
diff --git a/jiuwenswarm/acp/subprocess_env.py b/jiuwenswarm/acp/subprocess_env.py
new file mode 100644
index 0000000000..74f45a3376
--- /dev/null
+++ b/jiuwenswarm/acp/subprocess_env.py
@@ -0,0 +1,56 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Build subprocess environment for external ACP agents (Codex CLI, etc.).
+
+Secrets and proxy settings come only from ``acp_agents.<profile>.env`` in
+config.yaml (supports ``${VAR}`` placeholders via :func:`resolve_env_vars`).
+They are not inherited from the parent process and are not read from workspace
+``config/.env``. PATH, HOME, and other system variables still come from
+``os.environ``.
+"""
+
+from __future__ import annotations
+
+import os
+from typing import Any
+
+from jiuwenswarm.common.config import resolve_env_vars
+
+# Never inherit these from the parent; only acp_agents.<profile>.env.
+_PROFILE_SCOPED_KEYS = frozenset(
+ {
+ "OPENAI_API_KEY",
+ "OPENAI_ORGANIZATION",
+ "OPENAI_PROJECT",
+ "HTTPS_PROXY",
+ "HTTP_PROXY",
+ "ALL_PROXY",
+ "NO_PROXY",
+ }
+)
+
+
+def build_acp_subprocess_env(profile_env: dict[str, Any] | None = None) -> dict[str, str]:
+ """Environment for ``asyncio.create_subprocess_exec(..., env=...)``.
+
+ Layering:
+ 1. ``os.environ`` minus :data:`_PROFILE_SCOPED_KEYS` (PATH, HOME, locale, …)
+ 2. ``profile_env`` from ``acp_agents.<name>.env`` (after ``${VAR}`` resolution)
+ """
+ env: dict[str, str] = {
+ str(k): str(v)
+ for k, v in os.environ.items()
+ if str(k) not in _PROFILE_SCOPED_KEYS
+ }
+
+ if profile_env:
+ resolved = resolve_env_vars(dict(profile_env))
+ for key, val in resolved.items():
+ if val is None:
+ continue
+ sk = str(key)
+ sv = str(val).strip()
+ if sv:
+ env[sk] = sv
+
+ return env
diff --git a/jiuwenswarm/agents/harness/common/tools/acp_chat/__init__.py b/jiuwenswarm/agents/harness/common/tools/acp_chat/__init__.py
new file mode 100644
index 0000000000..06f4d0cd12
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/tools/acp_chat/__init__.py
@@ -0,0 +1,7 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""External ACP agent chat tool (stdio subprocess)."""
+
+from jiuwenswarm.agents.harness.common.tools.acp_chat.tool import acp_chat
+
+__all__ = ["acp_chat"]
diff --git a/jiuwenswarm/agents/harness/common/tools/acp_chat/tool.py b/jiuwenswarm/agents/harness/common/tools/acp_chat/tool.py
new file mode 100644
index 0000000000..f642ff01ab
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/tools/acp_chat/tool.py
@@ -0,0 +1,124 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Tool: forward a prompt to an external ACP agent (stdio) configured in config.yaml."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from typing import Any
+
+from openjiuwen.core.foundation.tool import tool
+
+from jiuwenswarm.acp.stdio_client import AcpStdioClient
+from jiuwenswarm.common.config import get_config
+
+logger = logging.getLogger(__name__)
+
+_clients: dict[str, AcpStdioClient] = {}
+_locks: dict[str, asyncio.Lock] = {}
+
+
+def _profile_lock(name: str) -> asyncio.Lock:
+ if name not in _locks:
+ _locks[name] = asyncio.Lock()
+ return _locks[name]
+
+
+def _load_profile(agent: str) -> dict[str, Any]:
+ cfg = get_config()
+ agents = cfg.get("acp_agents")
+ if not isinstance(agents, dict):
+ raise ValueError("config has no acp_agents mapping")
+ spec = agents.get(str(agent).strip())
+ if not isinstance(spec, dict):
+ raise ValueError(
+ f"unknown acp_agents profile {agent!r}; define it under acp_agents in config.yaml"
+ )
+ return spec
+
+
+async def _close_profile_unlocked(profile: str) -> None:
+ client = _clients.pop(profile, None)
+ if client is not None:
+ try:
+ await client.close()
+ except Exception as exc:
+ logger.warning("[acp_chat] close profile=%s failed: %s", profile, exc)
+
+
+async def _get_or_create_client(profile: str, new_session: bool) -> AcpStdioClient:
+ spec = _load_profile(profile)
+
+ if new_session:
+ await _close_profile_unlocked(profile)
+
+ if profile in _clients:
+ existing = _clients[profile]
+ if existing.is_connected:
+ return existing
+ await _close_profile_unlocked(profile)
+
+ command = str(spec.get("command") or "").strip()
+ if not command:
+ raise ValueError("acp_agents profile needs non-empty command")
+
+ raw_args = spec.get("args")
+ args: list[str]
+ if raw_args is None:
+ args = []
+ elif isinstance(raw_args, list):
+ args = [str(x) for x in raw_args]
+ else:
+ raise ValueError("acp_agents.args must be a list of strings")
+
+ cwd = spec.get("cwd")
+ cwd_s: str | None
+ if cwd is None or (isinstance(cwd, str) and not cwd.strip()):
+ cwd_s = None
+ elif isinstance(cwd, str):
+ cwd_s = cwd.strip()
+ else:
+ cwd_s = None
+
+ env = spec.get("env")
+ if env is not None and not isinstance(env, dict):
+ raise ValueError("acp_agents.env must be a map of strings")
+
+ client = AcpStdioClient(command, args, cwd=cwd_s, env=env if isinstance(env, dict) else None)
+ await client.connect()
+ _clients[profile] = client
+ return client
+
+
+@tool(
+ name="acp_chat",
+ description=(
+ "Send a user message to an external ACP-compatible agent subprocess defined in "
+ "config.yaml under acp_agents.<name> (command + args). Use for Codex CLI, Gemini CLI, "
+ "or any other stdio ACP agent. Parameter agent is the profile key, message is the prompt. "
+ "Set new_session=true to restart the subprocess and ACP session for that profile."
+ ),
+)
+async def acp_chat(
+ agent: str,
+ message: str,
+ new_session: bool = False,
+) -> str:
+ profile = (agent or "").strip()
+ text = (message or "").strip()
+ if not profile:
+ return "[ERROR] agent (profile name) is required."
+ if not text:
+ return "[ERROR] message is empty."
+
+ lock = _profile_lock(profile)
+ async with lock:
+ try:
+ client = await _get_or_create_client(profile, new_session=new_session)
+ out = await client.chat(text)
+ return out or "(empty response from external ACP agent)"
+ except Exception as exc:
+ logger.exception("[acp_chat] profile=%s failed", profile)
+ await _close_profile_unlocked(profile)
+ return f"[ERROR] acp_chat failed: {exc}"
diff --git a/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py b/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py
index 03ee5ef408..09138eb923 100644
--- a/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py
+++ b/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py
@@ -121,6 +121,7 @@ TOOL_WHITELIST = frozenset({
"skill_toolkit",
"enter_worktree",
"exit_worktree",
+ "acp_chat",
})
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index fd1fd20ada..3027487ce3 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -167,6 +167,15 @@ models:
model_config_obj:
temperature: 0.95
+# 外接 ACP Agent(stdio),供工具 acp_chat 使用。按需取消注释并填写;command/args 可指向任意兼容 ACP 的包(与 VS Code formulahendry.acp-client 预置列表一致)。
+acp_agents:
+ codex:
+ command: npx
+ args: ["@zed-industries/codex-acp@latest"]
+ cwd:
+ env:
+ OPENAI_API_KEY: ${OPENAI_API_KEY} # 仅由此 env 注入子进程(不读 workspace .env / 父进程)
+
telemetry:
enabled: false # 总开关(环境变量 OTEL_ENABLED 优先)
exporter: otlp # otlp / console / none
@@ -506,6 +515,7 @@ permissions:
cron_delete_job: allow
cron_toggle_job: allow
cron_preview_job: allow
+ acp_chat: ask
rules:
- id: shell_allow_dir
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index 736dbba52b..bd82301448 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -56,6 +56,7 @@ from jiuwenswarm.agents.harness.common.rails import (
)
from jiuwenswarm.agents.harness.common.memory.config import get_memory_mode
from jiuwenswarm.agents.harness.common.tools import SkillToolkit
+from jiuwenswarm.agents.harness.common.tools.acp_chat import acp_chat
from jiuwenswarm.common.config import get_config
from jiuwenswarm.common.utils import get_agent_workspace_dir
@@ -86,6 +87,7 @@ _TOOL_BUILD_NAMES: dict[str, str] = {
"web_paid_search": "_build_paid_search_tool",
"user_todos": "_build_user_todos_tool",
"skill_toolkit": "_build_skill_toolkit",
+ "acp_chat": "_build_acp_chat_tool",
}
@@ -890,6 +892,14 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):
logger.warning("[JiuwenClawCodeAdapter] skill_toolkit build failed: %s", exc)
return None
+ def _build_acp_chat_tool(self, agent_id: str) -> Any | None:
+ """Register acp_chat when at least one external ACP profile is configured."""
+ acp_cfg = get_config().get("acp_agents")
+ if not isinstance(acp_cfg, dict) or not acp_cfg:
+ logger.info("[JiuwenClawCodeAdapter] acp_chat skipped: no acp_agents configured")
+ return None
+ return acp_chat
+
def merge_member_mcp_configs(self, agent: Any, config_base: dict[str, Any]) -> int:
"""Merge enabled code-mode MCP configs into a team member agent."""
deep_config = getattr(agent, "deep_config", None)
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 58f3e17eaf..fcc26d0654 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -158,6 +158,7 @@ from jiuwenswarm.agents.harness.common.tools import SendFileToolkit, SkillToolki
from jiuwenswarm.agents.harness.common.tools.wiki_tools import wiki_ingest, wiki_query, wiki_lint
from jiuwenswarm.agents.harness.common.tools.acp_output_tools import get_tools as get_acp_output_tools
from jiuwenswarm.agents.harness.common.tools.multi_session_toolkits import MultiSessionToolkit
+from jiuwenswarm.agents.harness.common.tools.acp_chat import acp_chat
from jiuwenswarm.agents.harness.common.tools.xiaoyi_phone_tools import (
get_user_location,
create_note,
@@ -2336,6 +2337,17 @@ class JiuWenClawDeepAdapter:
except Exception as exc:
logger.warning("[JiuWenClawDeepAdapter] skill tools registration failed: %s", exc)
+ # acp_chat: forward prompts to external stdio ACP agents (see acp_agents in config.yaml)
+ try:
+ acp_cfg = get_config().get("acp_agents")
+ if isinstance(acp_cfg, dict) and acp_cfg:
+ if not Runner.resource_mgr.get_tool(acp_chat.card.id):
+ Runner.resource_mgr.add_tool(acp_chat)
+ tool_cards.append(acp_chat.card)
+ logger.info("[JiuWenClawDeepAdapter] acp_chat tool registered")
+ except Exception as exc:
+ logger.warning("[JiuWenClawDeepAdapter] acp_chat registration failed: %s", exc)
+
return tool_cards
def _build_cron_tools(self) -> list[Any]:
diff --git a/pyproject.toml b/pyproject.toml
index 0c82b151ed..e126743649 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -75,6 +75,7 @@ jiuwenswarm-init = "jiuwenswarm.init_workspace:main"
jiuwenswarm-desktop = "jiuwenswarm.channels.desktop.desktop_app:main"
jiuwenswarm-tui = "jiuwenswarm.channels.acp.app_acp:main"
jiuwenswarm-acp = "jiuwenswarm.gateway.channel_manager.protocol.acp.acp_connect:main"
+jiuwenswarm-acp-chat = "jiuwenswarm.acp.cli:main"
jiuwenbox = "jiuwenbox.cli.jiuwenbox:main"
jiuwenbox-server = "jiuwenbox.server.launcher:main"
diff --git a/tests/system_tests/test_acp_stdio_client_st.py b/tests/system_tests/test_acp_stdio_client_st.py
new file mode 100644
index 0000000000..3bb01eabb7
--- /dev/null
+++ b/tests/system_tests/test_acp_stdio_client_st.py
@@ -0,0 +1,270 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""System tests for jiuwenswarm.acp (stdio client + CLI smoke entry).
+
+Writes an inline fake ACP agent script to *tmp_path* per test (no Codex CLI / API keys).
+Modes: echo | error | permission | fs_read
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+from textwrap import dedent
+
+import pytest
+
+from jiuwenswarm.acp.cli import _get_spec, _run_once
+from jiuwenswarm.acp.stdio_client import AcpStdioClient
+
+pytestmark = pytest.mark.system
+
+_FAKE_AGENT_SOURCE = dedent(
+ '''
+ import json
+ import sys
+
+ _SESSION_ID = "st-fake-session"
+ _MODE = (sys.argv[1] if len(sys.argv) > 1 else "echo").strip().lower()
+ _FS_TARGET = "st_file.txt"
+
+
+ def _read_one():
+ buf = ""
+ dec = json.JSONDecoder()
+ while True:
+ chunk = sys.stdin.read(1)
+ if not chunk:
+ return None
+ buf += chunk
+ stripped = buf.lstrip()
+ if not stripped:
+ continue
+ try:
+ obj, idx = dec.raw_decode(stripped)
+ consumed = len(buf) - len(stripped) + idx
+ buf = buf[consumed:]
+ return obj if isinstance(obj, dict) else None
+ except json.JSONDecodeError:
+ if len(buf) > 1024 * 1024:
+ return None
+
+
+ def _write(obj):
+ sys.stdout.write(json.dumps(obj, ensure_ascii=False) + "\\n")
+ sys.stdout.flush()
+
+
+ def _wait_response(expected_id):
+ while True:
+ msg = _read_one()
+ if msg is None:
+ return None
+ if str(msg.get("id")) == str(expected_id):
+ return msg
+
+
+ def _handle_prompt(req_id, text):
+ if _MODE == "error":
+ _write({"jsonrpc": "2.0", "id": req_id, "error": {"code": -32603, "message": "agent failed"}})
+ return
+
+ if _MODE == "permission":
+ perm_id = "perm-st-1"
+ _write({
+ "jsonrpc": "2.0",
+ "id": perm_id,
+ "method": "session/request_permission",
+ "params": {
+ "sessionId": _SESSION_ID,
+ "toolCall": {"toolCallId": "tc-1", "title": "run test"},
+ "options": [{"optionId": "allow-once", "kind": "allow"}],
+ },
+ })
+ reply = _wait_response(perm_id)
+ if reply is None or "error" in reply:
+ _write({
+ "jsonrpc": "2.0",
+ "id": req_id,
+ "error": {"code": -32000, "message": "permission handshake failed"},
+ })
+ return
+
+ body_text = text
+ if _MODE == "fs_read":
+ fs_id = "fs-st-1"
+ _write({
+ "jsonrpc": "2.0",
+ "id": fs_id,
+ "method": "fs/read_text_file",
+ "params": {"path": _FS_TARGET},
+ })
+ reply = _wait_response(fs_id)
+ if reply is None or "error" in reply:
+ _write({
+ "jsonrpc": "2.0",
+ "id": req_id,
+ "error": {"code": -32000, "message": "fs read handshake failed"},
+ })
+ return
+ result = reply.get("result")
+ body_text = str(result.get("content") or "") if isinstance(result, dict) else ""
+
+ if _MODE == "echo":
+ body_text = f"echo:{text}"
+ elif _MODE == "permission":
+ body_text = f"after-perm:{text}"
+
+ _write({
+ "jsonrpc": "2.0",
+ "method": "session/update",
+ "params": {
+ "sessionId": _SESSION_ID,
+ "update": {
+ "sessionUpdate": "agent_message_chunk",
+ "content": {"type": "text", "text": body_text},
+ },
+ },
+ })
+ _write({"jsonrpc": "2.0", "id": req_id, "result": {"stopReason": "end_turn"}})
+
+
+ while True:
+ msg = _read_one()
+ if msg is None:
+ break
+ req_id = msg.get("id")
+ method = str(msg.get("method") or "")
+
+ if method == "initialize":
+ _write({"jsonrpc": "2.0", "id": req_id, "result": {"protocolVersion": 1}})
+ elif method == "session/new":
+ _write({"jsonrpc": "2.0", "id": req_id, "result": {"sessionId": _SESSION_ID}})
+ elif method == "session/prompt":
+ params = msg.get("params") if isinstance(msg.get("params"), dict) else {}
+ prompt = params.get("prompt")
+ text = ""
+ if isinstance(prompt, list) and prompt:
+ first = prompt[0]
+ if isinstance(first, dict):
+ text = str(first.get("text") or "")
+ _handle_prompt(req_id, text)
+ elif req_id is not None:
+ _write({
+ "jsonrpc": "2.0",
+ "id": req_id,
+ "error": {"code": -32601, "message": f"method not found: {method}"},
+ })
+ '''
+).strip()
+
+
+def fake_agent_script(tmp_path: Path) -> Path:
+ script = tmp_path / "fake_acp_agent.py"
+ script.write_text(_FAKE_AGENT_SOURCE, encoding="utf-8")
+ return script
+
+
+def _profile(script: Path, *modes: str) -> dict:
+ return {"command": sys.executable, "args": [str(script), *modes]}
+
+
+def fake_acp_profile(fake_agent_script: Path) -> dict:
+ return _profile(fake_agent_script, "echo")
+
+
+async def test_stdio_client_connect_and_chat_with_fake_agent(fake_acp_profile: dict) -> None:
+ client = AcpStdioClient(fake_acp_profile["command"], fake_acp_profile["args"])
+ try:
+ await client.connect()
+ assert client.session_id == "st-fake-session"
+ out = await client.chat("hello st")
+ assert out == "echo:hello st"
+ finally:
+ await client.close()
+
+
+async def test_stdio_client_chat_raises_on_jsonrpc_error(fake_agent_script: Path) -> None:
+ prof = _profile(fake_agent_script, "error")
+ client = AcpStdioClient(prof["command"], prof["args"])
+ try:
+ await client.connect()
+ with pytest.raises(RuntimeError, match=r"ACP JSON-RPC error:.*agent failed"):
+ await client.chat("trigger error")
+ finally:
+ await client.close()
+
+
+async def test_stdio_client_auto_approves_permission_and_completes_chat(
+ fake_agent_script: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("ACP_AUTO_APPROVE_PERMISSIONS", "true")
+ prof = _profile(fake_agent_script, "permission")
+ client = AcpStdioClient(prof["command"], prof["args"])
+ try:
+ await client.connect()
+ out = await client.chat("need perm")
+ assert out == "after-perm:need perm"
+ finally:
+ await client.close()
+
+
+async def test_stdio_client_fs_read_text_file_via_peer_request(
+ fake_agent_script: Path,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ target = tmp_path / "st_file.txt"
+ target.write_text("file-content-xyz\n", encoding="utf-8")
+ monkeypatch.chdir(tmp_path)
+
+ prof = _profile(fake_agent_script, "fs_read")
+ client = AcpStdioClient(prof["command"], prof["args"], cwd=str(tmp_path))
+ try:
+ await client.connect()
+ out = await client.chat("read file")
+ assert out == "file-content-xyz"
+ finally:
+ await client.close()
+
+
+async def test_cli_run_once_uses_config_profile(monkeypatch: pytest.MonkeyPatch, fake_acp_profile: dict) -> None:
+ monkeypatch.setattr(
+ "jiuwenswarm.acp.cli.get_config",
+ lambda: {"acp_agents": {"fake": fake_acp_profile}},
+ )
+
+ code = await _run_once("fake", "ping")
+
+ assert code == 0
+
+
+async def test_cli_run_once_returns_1_on_chat_failure(
+ monkeypatch: pytest.MonkeyPatch,
+ fake_agent_script: Path,
+) -> None:
+ prof = _profile(fake_agent_script, "error")
+ monkeypatch.setattr(
+ "jiuwenswarm.acp.cli.get_config",
+ lambda: {"acp_agents": {"fake": prof}},
+ )
+
+ assert await _run_once("fake", "trigger error") == 1
+
+
+def test_get_spec_returns_none_when_profile_missing(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ "jiuwenswarm.acp.cli.get_config",
+ lambda: {"acp_agents": {}},
+ )
+
+ assert _get_spec("missing") is None
diff --git a/tests/unit_tests/acp/test_stdio_client_helpers.py b/tests/unit_tests/acp/test_stdio_client_helpers.py
new file mode 100644
index 0000000000..473cc2f7eb
--- /dev/null
+++ b/tests/unit_tests/acp/test_stdio_client_helpers.py
@@ -0,0 +1,40 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+from jiuwenswarm.acp.stdio_client import _consume_one_json, _extract_session_update_text
+
+
+def test_consume_one_json_multiline_whitespace_between():
+ buf = '{"a": 1}\n\n{"jsonrpc":"2.0","id":1}\n'
+ first, buf2 = _consume_one_json(buf)
+ assert first == {"a": 1}
+ second, buf3 = _consume_one_json(buf2)
+ assert second == {"jsonrpc": "2.0", "id": 1}
+ assert buf3 == ""
+
+
+def test_consume_one_json_incomplete_then_complete():
+ part1 = '{\n "method":'
+ obj, tail = _consume_one_json(part1)
+ assert obj is None and tail == part1
+ buf = part1 + ' "session/update"\n}\n{"x":true}'
+ obj, tail = _consume_one_json(buf)
+ assert obj == {"method": "session/update"}
+ obj2, tail2 = _consume_one_json(tail)
+ assert obj2 == {"x": True}
+ assert tail2 == ""
+
+
+def test_extract_session_update_text_accepts_nested_update():
+ msg = {
+ "jsonrpc": "2.0",
+ "method": "session/update",
+ "params": {
+ "sessionId": "s1",
+ "update": {
+ "sessionUpdate": "agent_message_chunk",
+ "messageId": "m1",
+ "content": {"type": "text", "text": "hello"},
+ },
+ },
+ }
+ assert _extract_session_update_text(msg) == "hello"
diff --git a/tests/unit_tests/acp/test_subprocess_env.py b/tests/unit_tests/acp/test_subprocess_env.py
new file mode 100644
index 0000000000..8dcbfbb66e
--- /dev/null
+++ b/tests/unit_tests/acp/test_subprocess_env.py
@@ -0,0 +1,49 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+from __future__ import annotations
+
+import pytest
+
+from jiuwenswarm.acp.subprocess_env import build_acp_subprocess_env
+
+
+def test_parent_openai_key_is_not_inherited(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-stale-parent")
+ monkeypatch.setenv("PATH", "/usr/bin")
+
+ env = build_acp_subprocess_env(None)
+
+ assert "OPENAI_API_KEY" not in env
+ assert env["PATH"] == "/usr/bin"
+
+
+def test_profile_env_supplies_scoped_keys(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-stale-parent")
+
+ env = build_acp_subprocess_env({"OPENAI_API_KEY": "sk-from-profile"})
+
+ assert env["OPENAI_API_KEY"] == "sk-from-profile"
+
+
+def test_profile_env_resolves_placeholder(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-resolved-at-spawn")
+
+ env = build_acp_subprocess_env({"OPENAI_API_KEY": "${OPENAI_API_KEY}"})
+
+ assert env["OPENAI_API_KEY"] == "sk-resolved-at-spawn"
+
+
+def test_empty_profile_env_has_no_scoped_keys(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+
+ env = build_acp_subprocess_env(None)
+
+ assert "OPENAI_API_KEY" not in env
+
+
+def test_non_scoped_keys_still_from_parent(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("CUSTOM_FLAG", "parent-value")
+
+ env = build_acp_subprocess_env(None)
+
+ assert env["CUSTOM_FLAG"] == "parent-value"
diff --git a/tests/unit_tests/agentserver/test_code_adapter_acp_chat_tool.py b/tests/unit_tests/agentserver/test_code_adapter_acp_chat_tool.py
new file mode 100644
index 0000000000..926aef77c7
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_code_adapter_acp_chat_tool.py
@@ -0,0 +1,54 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Unit tests for CodeAdapter ACP tool registration."""
+
+from types import SimpleNamespace
+
+from jiuwenswarm.server.runtime.agent_adapter.interface_code import JiuwenClawCodeAdapter
+
+
+class _FakeResourceMgr:
+ def __init__(self) -> None:
+ self._tools: dict[str, object] = {}
+
+ def get_tool(self, tool_id: str) -> object | None:
+ return self._tools.get(tool_id)
+
+ def add_tool(self, tool: object) -> None:
+ self._tools[tool.card.id] = tool
+
+
+def test_code_adapter_builds_acp_chat_when_profile_configured(monkeypatch):
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_code.get_config",
+ lambda: {
+ "acp_agents": {"codex": {"command": "npx", "args": []}},
+ "modes": {"code": {"tools": ["acp_chat"]}},
+ },
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_code.Runner",
+ SimpleNamespace(resource_mgr=_FakeResourceMgr()),
+ )
+
+ cards = JiuwenClawCodeAdapter().build_code_tool_cards("agent-id")
+
+ assert [card.name for card in cards] == ["acp_chat"]
+
+
+def test_code_adapter_skips_acp_chat_without_profiles(monkeypatch):
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_code.get_config",
+ lambda: {
+ "acp_agents": {},
+ "modes": {"code": {"tools": ["acp_chat"]}},
+ },
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_code.Runner",
+ SimpleNamespace(resource_mgr=_FakeResourceMgr()),
+ )
+
+ cards = JiuwenClawCodeAdapter().build_code_tool_cards("agent-id")
+
+ assert cards == []
diff --git a/tests/unit_tests/agentserver/test_team_runtime_inheritance.py b/tests/unit_tests/agentserver/test_team_runtime_inheritance.py
index 56aa345e22..7b0a92b8a9 100644
--- a/tests/unit_tests/agentserver/test_team_runtime_inheritance.py
+++ b/tests/unit_tests/agentserver/test_team_runtime_inheritance.py
@@ -45,6 +45,7 @@ def test_filter_inheritable_ability_cards_includes_extended_claw_tools():
_make_tool_card("audio_metadata"),
_make_tool_card("user_todos"),
_make_tool_card("task_tool"),
+ _make_tool_card("acp_chat"),
_make_tool_card("send_file_to_user"),
]
)
@@ -53,6 +54,7 @@ def test_filter_inheritable_ability_cards_includes_extended_claw_tools():
inherited = filter_inheritable_ability_cards(main_agent)
inherited_names = {card.name for card in inherited}
+ assert "acp_chat" in inherited_names
assert "visual_question_answering" in inherited_names
assert "audio_question_answering" in inherited_names
assert "audio_metadata" in inherited_names