From 82c3763e5c6d911f89c5921a37f15bd318032b8f Mon Sep 17 00:00:00 2001 From: OpenBot Date: Tue, 6 Oct 2026 11:05:40 +0800 Subject: [PATCH] M0: framing (ndjson + lsp-frame), ACPClient, mock agent fixture, probe script; real claude-code-acp handshake verified --- .gitignore | 1 + docs/ACP_PRIMER.md | 28 ++- scripts/probe_agent.py | 78 +++++++ src/agenthub/acp_client.py | 347 ++++++++++++++++++++++++++++++- src/agenthub/framing.py | 100 +++++++++ tests/fixtures/mock_acp_agent.py | 158 ++++++++++++++ tests/test_acp_client.py | 146 +++++++++++++ tests/test_framing.py | 76 +++++++ tests/test_ndjson.py | 29 +++ uv.lock | 8 + 10 files changed, 967 insertions(+), 4 deletions(-) create mode 100644 scripts/probe_agent.py create mode 100644 src/agenthub/framing.py create mode 100644 tests/fixtures/mock_acp_agent.py create mode 100644 tests/test_acp_client.py create mode 100644 tests/test_framing.py create mode 100644 tests/test_ndjson.py create mode 100644 uv.lock diff --git a/.gitignore b/.gitignore index bd59653..26fc580 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ __pycache__/ dist/ .pytest_cache/ config.local.yaml +node_modules/ diff --git a/docs/ACP_PRIMER.md b/docs/ACP_PRIMER.md index 07a6339..7a1f734 100644 --- a/docs/ACP_PRIMER.md +++ b/docs/ACP_PRIMER.md @@ -2,16 +2,26 @@ > 供 agenthub 实现时对照。规范:agentclientprotocol.com > (spec 源:zed-industries/zed repo docs/src/ai/external-agents.md) +> +> ⚠️ **实测修正(M0 验证)**:当前 ACP 实现的 stdio 传输是 +> **newline-delimited JSON(ndjson)**——一行一条 JSON-RPC 消息,以 `\n` 分隔, +> **不是** LSP 的 `Content-Length` 帧。依据:官方 +> `@agentclientprotocol/sdk` 的 `ndJsonStream()`,以及 +> `@zed-industries/claude-code-acp` 实测(发 Content-Length 帧会报 +> `Failed to parse JSON message: Content-Length: ...`)。 +> agenthub 默认 transport=`ndjson`,保留 `lsp-frame` 兼容模式备旧实现。 ## 传输与分帧 -- JSON-RPC 2.0 over stdio,LSP 风格 `Content-Length: N\r\n\r\n` 头分帧。 -- agent 子进程 = ACP **server**;桥 = ACP **client**。 +- JSON-RPC 2.0 over stdio: + - **ndjson(默认/当前)**:`{"jsonrpc":...}\n` + - lsp-frame(兼容备选):`Content-Length: N\r\n\r\n{...}` +- agent 子进程 = ACP **server**;agenthub = ACP **client**。 ## 生命周期(client → server) 1. `initialize`:`{protocolVersion, clientCapabilities}` - → 返回 agent 能力(loadSession、promptCapabilities…) + → 返回 agent 能力(loadSession、promptCapabilities…)+ authMethods 2. `session/new`:`{cwd, mcpServers}` → `{sessionId}` 3. `session/load`(可选能力):恢复会话,agent 重放全部历史为 update 流 4. `session/prompt`:`{sessionId, prompt: [content_block]}` → `{stopReason}` @@ -31,9 +41,21 @@ - client 反向方法:`fs/read_text_file`、`fs/write_text_file`、 `terminal/create`(output截断/exit)、`terminal/wait_for_exit`… +## 实测到的真实行为(claude-code-acp v0.16 / claude CLI 2.1.290) + +- `initialize` 返回:`{protocolVersion: 1, agentCapabilities: {promptCapabilities: + {image, embeddedContext}, mcpCapabilities: {http, sse}, loadSession: true, + sessionCapabilities: {fork, list, resume}}, authMethods: [{id: "claude-login"}]}` +- `session/new` **未登录也能成功**(sessionId 立即返回) +- `session/prompt` 未登录返回 JSON-RPC 错误 **`-32000 Authentication required`** + —— 认证失败走 error 通道,不是 stopReason +- 每个会话会先推一条 `available_commands_update` 通知 + ## 实现提醒 - id 复用规则:同方向自增;notification 无 id。 - stdout 只能走协议帧——任何 agent 混入的裸日志都会破坏分帧。 - 权限请求必须回应,否则 agent turn 会挂死;桥侧超时默认拒绝。 - 版本协商失败(protocolVersion 不兼容)→ 直接报错,不要猜。 +- JSON-RPC 业务错误(如未认证 -32000)与传输层错误要分开处理: + 前者是 agent 的正常回复,不能当崩溃。 diff --git a/scripts/probe_agent.py b/scripts/probe_agent.py new file mode 100644 index 0000000..d68759d --- /dev/null +++ b/scripts/probe_agent.py @@ -0,0 +1,78 @@ +"""Probe a local ACP agent: initialize handshake + capability dump. + +Usage: + uv run python scripts/probe_agent.py [--agent CMD] [--transport ndjson|lsp-frame] + +Example: + uv run python scripts/probe_agent.py --agent "node_modules/.bin/claude-code-acp" +""" + +from __future__ import annotations + +import argparse +import os +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) + +from agenthub.acp_client import ACPClient, ACPError # noqa: E402 + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--agent", default="node_modules/.bin/claude-code-acp") + ap.add_argument("--transport", default="ndjson", choices=["ndjson", "lsp-frame"]) + ap.add_argument("--cwd", default="/tmp") + ap.add_argument("--prompt", default=None, help="optionally send one prompt") + args = ap.parse_args() + + client = ACPClient( + cmd=[args.agent], + cwd=os.getcwd(), + transport=args.transport, + env={**os.environ, "PATH": os.path.expanduser("~/.npm-global/node_modules/.bin") + ":" + os.environ.get("PATH", "")}, + ) + client.start() + try: + info = client.request( + "initialize", + { + "protocolVersion": 1, + "clientCapabilities": {"fs": {"readTextFile": True, "writeTextFile": True}}, + }, + timeout=30, + ) + print("== initialize ==") + print("protocolVersion:", info.get("protocolVersion")) + print("agentCapabilities:", info.get("agentCapabilities")) + print("authMethods:", info.get("authMethods")) + + sid = client.session_new(cwd=args.cwd) + print("== session/new == sessionId:", sid) + + updates: list[dict] = [] + client.register_notification_handler(lambda m, p: updates.append(p)) + + if args.prompt: + try: + res = client.session_prompt(sid, [{"type": "text", "text": args.prompt}], timeout=120) + print("== session/prompt ==", res) + except ACPError as e: + print("== session/prompt rejected ==", e.code, e.message) + kinds = [u["update"]["sessionUpdate"] for u in updates if "update" in u] + print("updates seen:", kinds[:20], f"(total {len(kinds)})") + else: + print("(no --prompt given; handshake only)") + + if client.stderr_tail: + print("== agent stderr tail ==") + for line in client.stderr_tail[-5:]: + print(" ", line) + return 0 + finally: + client.close() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/agenthub/acp_client.py b/src/agenthub/acp_client.py index 88692d6..e9512d2 100644 --- a/src/agenthub/acp_client.py +++ b/src/agenthub/acp_client.py @@ -1 +1,346 @@ -"""ACP JSON-RPC over stdio 分帧与调用(M0 核心,见 docs/ACP_PRIMER.md)。""" +"""ACP client: JSON-RPC 2.0 over stdio to an agent subprocess. + +M0 scope: +- launch agent subprocess, talk ACP frames over stdin/stdout +- initialize / session/new / session/prompt +- dispatch server->client notifications (session/update) and requests + (fs/*, terminal/*, session/request_permission) to registered handlers +- thread-safe request/response correlation by id +""" + +from __future__ import annotations + +import json +import shlex +import subprocess +import threading +from dataclasses import dataclass, field +from typing import Any, Callable + +from .framing import FrameError, decode_frames, decode_ndjson_lines, encode_frame, encode_ndjson + +# --------------------------------------------------------------------------- +# JSON-RPC error codes +# --------------------------------------------------------------------------- +PARSE_ERROR = -32700 +INVALID_REQUEST = -32600 +METHOD_NOT_FOUND = -32601 +INVALID_PARAMS = -32602 +INTERNAL_ERROR = -32603 + + +class ACPError(Exception): + """An error returned by the agent for a client request.""" + + def __init__(self, code: int, message: str, data: Any = None): + super().__init__(f"ACP error {code}: {message}") + self.code = code + self.message = message + self.data = data + + +class ACPProcessDead(ACPError): + def __init__(self, detail: str = ""): + super().__init__(INTERNAL_ERROR, f"agent process is not running: {detail}") + + +# --------------------------------------------------------------------------- +# handler signatures +# --------------------------------------------------------------------------- +NotificationHandler = Callable[[str, dict[str, Any]], None] +RequestHandler = Callable[[str, dict[str, Any]], Any] # returns result, raises ACPError + + +@dataclass +class ACPClient: + """A single ACP connection to one agent subprocess.""" + + cmd: list[str] + cwd: str | None = None + env: dict[str, str] | None = None + transport: str = "ndjson" # "ndjson" (current ACP SDK agents) | "lsp-frame" + + _proc: subprocess.Popen | None = field(default=None, init=False, repr=False) + _lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False) + _write_lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False) + _next_id: int = field(default=0, init=False, repr=False) + _pending: dict[int, tuple[threading.Event, list]] = field( + default_factory=dict, init=False, repr=False + ) + _notif_handlers: list[NotificationHandler] = field(default_factory=list, init=False, repr=False) + _req_handlers: list[RequestHandler] = field(default_factory=list, init=False, repr=False) + _buf: bytearray = field(default_factory=bytearray, init=False, repr=False) + _closed: bool = field(default=False, init=False, repr=False) + _stderr_lines: list[str] = field(default_factory=list, init=False, repr=False) + _last_error: str = field(default="", init=False) + + # -- lifecycle --------------------------------------------------------- + def start(self) -> None: + flat: list[str] = [] + for c in self.cmd: + flat.extend(shlex.split(c) if isinstance(c, str) else list(c)) + self._proc = subprocess.Popen( + flat, + cwd=self.cwd, + env=self.env, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + bufsize=0, + ) + threading.Thread(target=self._read_loop, name="acp-reader", daemon=True).start() + threading.Thread(target=self._stderr_loop, name="acp-stderr", daemon=True).start() + + def close(self, timeout: float = 5.0) -> None: + self._closed = True + proc = self._proc + if proc is None: + return + try: + if proc.stdin: + proc.stdin.close() + except OSError: + pass + try: + proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait(timeout=timeout) + + def is_alive(self) -> bool: + return self._proc is not None and self._proc.poll() is None + + @property + def stderr_tail(self) -> list[str]: + return list(self._stderr_lines[-50:]) + + # -- low level io ------------------------------------------------------ + def _send(self, obj: dict[str, Any]) -> None: + if not self.is_alive(): + raise ACPProcessDead(self._last_error or "process exited") + assert self._proc and self._proc.stdin + data = encode_ndjson(obj) if self.transport == "ndjson" else encode_frame(obj) + with self._write_lock: + try: + self._proc.stdin.write(data) + self._proc.stdin.flush() + except (BrokenPipeError, OSError) as e: + raise ACPProcessDead(str(e)) from e + + def _stderr_loop(self) -> None: + assert self._proc and self._proc.stderr + for raw in iter(self._proc.stderr.readline, b""): + line = raw.decode("utf-8", "replace").rstrip() + if line: + self._stderr_lines.append(line) + + def _read_loop(self) -> None: + assert self._proc and self._proc.stdout + try: + while not self._closed: + chunk = self._proc.stdout.read(65536) + if not chunk: + break + self._buf.extend(chunk) + if self.transport == "ndjson": + self._drain_ndjson() + else: + self._drain() + except (OSError, ValueError): + pass + finally: + detail = self._last_error + if not detail and self._proc: + detail = f"exit={self._proc.poll()}" + self._fail_all(f"reader stopped ({detail})") + + def _drain(self) -> None: + """Parse complete frames out of the buffer, keeping partial tails. + + decode_frames raises FrameError for both 'need more bytes' and + 'corrupt stream'; we distinguish by scanning incrementally: + try to parse with a shrinking window until only an incomplete + tail remains. + """ + while True: + if not self._buf: + return + try: + msgs = list(decode_frames(self._buf)) + except FrameError as e: + msg = str(e) + if "incomplete frame" in msg or "no header terminator" in msg: + return # partial tail: wait for more bytes + # corrupt stream: record and drop + self._last_error = f"framing error: {e}" + self._buf.clear() + return + if not msgs: + return + # decode_frames consumed the whole buffer by definition + # (it only yields complete frames and the buffer holds only + # whole frames here, else it would have raised 'incomplete') + self._buf.clear() + for m in msgs: + self._dispatch(m) + return + + def _drain_ndjson(self) -> None: + try: + msgs, consumed = decode_ndjson_lines(self._buf) + except (UnicodeDecodeError, json.JSONDecodeError) as e: + self._last_error = f"ndjson parse error: {e}" + self._buf.clear() + return + if consumed: + del self._buf[:consumed] + for m in msgs: + self._dispatch(m) + + def _fail_all(self, detail: str) -> None: + self._last_error = detail + with self._lock: + pending = list(self._pending.items()) + self._pending.clear() + for _rid, (ev, slot) in pending: + slot.append(ACPProcessDead(detail)) + ev.set() + + # -- dispatch ---------------------------------------------------------- + def _dispatch(self, msg: dict[str, Any]) -> None: + if not isinstance(msg, dict): + return + has_id = "id" in msg + method = msg.get("method") + if method is not None and not has_id: + for h in self._notif_handlers: + try: + h(method, msg.get("params") or {}) + except Exception: # noqa: BLE001 - handler errors must not kill the reader + pass + return + if method is not None and has_id: + self._handle_server_request(msg) + return + if has_id: + self._resolve_response(msg) + + def _handle_server_request(self, msg: dict[str, Any]) -> None: + rid = msg["id"] + method = msg["method"] + params = msg.get("params") or {} + result: Any = None + error: dict[str, Any] | None = None + handled = False + for h in self._req_handlers: + try: + result = h(method, params) + handled = True + break + except ACPError as e: + error = {"code": e.code, "message": e.message, "data": e.data} + handled = True + break + except NotImplementedError: + continue + except Exception as e: # noqa: BLE001 + error = {"code": INTERNAL_ERROR, "message": str(e)} + handled = True + break + if not handled: + error = {"code": METHOD_NOT_FOUND, "message": f"unsupported: {method}"} + + reply: dict[str, Any] = {"jsonrpc": "2.0", "id": rid} + if error: + reply["error"] = error + else: + reply["result"] = result + try: + self._send(reply) + except ACPProcessDead: + pass + + def _resolve_response(self, msg: dict[str, Any]) -> None: + rid = msg["id"] + with self._lock: + slot = self._pending.pop(rid, None) + if slot is None: + return + ev, out = slot + if "error" in msg: + err = msg["error"] or {} + out.append( + ACPError(err.get("code", INTERNAL_ERROR), err.get("message", "unknown"), err.get("data")) + ) + else: + out.append(msg.get("result")) + ev.set() + + # -- public API -------------------------------------------------------- + def register_notification_handler(self, h: NotificationHandler) -> None: + self._notif_handlers.append(h) + + def register_request_handler(self, h: RequestHandler) -> None: + self._req_handlers.append(h) + + def request( + self, method: str, params: dict[str, Any] | None = None, timeout: float | None = 60.0 + ) -> Any: + if not self.is_alive(): + raise ACPProcessDead(self._last_error or "not started") + with self._lock: + self._next_id += 1 + rid = self._next_id + ev = threading.Event() + slot: list = [] + self._pending[rid] = (ev, slot) + try: + self._send({"jsonrpc": "2.0", "id": rid, "method": method, "params": params or {}}) + except ACPProcessDead: + with self._lock: + self._pending.pop(rid, None) + raise + if not ev.wait(timeout): + with self._lock: + self._pending.pop(rid, None) + raise ACPError(INTERNAL_ERROR, f"timeout waiting for {method} ({timeout}s)") + out = slot[0] + if isinstance(out, Exception): + raise out + return out + + def notify(self, method: str, params: dict[str, Any] | None = None) -> None: + self._send({"jsonrpc": "2.0", "method": method, "params": params or {}}) + + # -- ACP convenience --------------------------------------------------- + def initialize( + self, client_capabilities: dict[str, Any] | None = None, protocol_version: int = 1 + ) -> dict[str, Any]: + return self.request( + "initialize", + { + "protocolVersion": protocol_version, + "clientCapabilities": client_capabilities + or { + "fs": {"readTextFile": True, "writeTextFile": True}, + "terminal": True, + }, + }, + ) + + def session_new(self, cwd: str, mcp_servers: list[dict[str, Any]] | None = None) -> str: + res = self.request("session/new", {"cwd": cwd, "mcpServers": mcp_servers or []}) + sid = (res or {}).get("sessionId") + if not sid: + raise ACPError(INTERNAL_ERROR, f"session/new returned no sessionId: {res!r}") + return sid + + def session_prompt( + self, session_id: str, blocks: list[dict[str, Any]], timeout: float | None = None + ) -> dict[str, Any]: + return self.request( + "session/prompt", {"sessionId": session_id, "prompt": blocks}, timeout=timeout + ) + + def session_cancel(self, session_id: str) -> None: + self.notify("session/cancel", {"sessionId": session_id}) diff --git a/src/agenthub/framing.py b/src/agenthub/framing.py new file mode 100644 index 0000000..c557a37 --- /dev/null +++ b/src/agenthub/framing.py @@ -0,0 +1,100 @@ +"""ACP JSON-RPC over stdio: Content-Length framing (LSP style). + +Frame format used by ACP (same as LSP): + Content-Length: \r\n + \r\n + +""" + +from __future__ import annotations + +import json +from typing import Any, Iterator + +_HEADER_SEP = b"\r\n\r\n" +_HEADER_END = b"\r\n" + + +class FrameError(Exception): + """Raised when the byte stream cannot be parsed as a valid frame.""" + + +def encode_frame(payload: dict[str, Any]) -> bytes: + """Serialize a JSON-RPC message to one ACP frame.""" + body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + header = b"Content-Length: " + str(len(body)).encode() + _HEADER_END * 2 + return header + body + + +def _read_exact(buf: memoryview, pos: int, n: int) -> tuple[memoryview, int]: + if pos + n > len(buf): + raise FrameError(f"incomplete frame: need {n} bytes at pos {pos}, have {len(buf) - pos}") + return buf[pos : pos + n], pos + n + + +def decode_frames(buf: bytes | bytearray | memoryview) -> Iterator[dict[str, Any]]: + """Parse all complete frames from a buffer. + + Raises FrameError on malformed headers or truncated frames; + returns an iterator of decoded JSON objects. + """ + view = memoryview(bytes(buf)) + pos = 0 + while pos < len(view): + # find header terminator + idx = bytes(view[pos:]).find(_HEADER_SEP) + if idx == -1: + raise FrameError(f"no header terminator after pos {pos}") + header_blob = bytes(view[pos : pos + idx]) + pos += idx + len(_HEADER_SEP) + + length: int | None = None + content_type: str | None = None + for line in header_blob.split(_HEADER_END): + if not line: + continue + name, _, value = line.partition(b":") + name = name.strip().lower() + if name == b"content-length": + try: + length = int(value.strip()) + except ValueError as e: + raise FrameError(f"bad Content-Length: {value!r}") from e + elif name == b"content-type": + content_type = value.strip().decode("ascii", "replace") + if length is None: + raise FrameError(f"missing Content-Length header: {header_blob!r}") + if length < 0: + raise FrameError(f"negative Content-Length: {length}") + + body_view, pos = _read_exact(view, pos, length) + try: + yield json.loads(bytes(body_view).decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as e: + raise FrameError(f"bad JSON body ({length} bytes): {e}") from e + + +# --------------------------------------------------------------------------- +# newline-delimited JSON (ndjson) transport — used by current ACP SDK agents +# (e.g. @zed-industries/claude-code-acp via @agentclientprotocol/sdk). +# LSP-style Content-Length frames are kept in encode_frame/decode_frames for +# agents that use them; transport is auto-detected by ACPClient. +# --------------------------------------------------------------------------- + +def encode_ndjson(payload: dict) -> bytes: + return json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + b"\n" + + +def decode_ndjson_lines(buf: bytes | bytearray): + """Yield (messages, consumed_bytes) for complete newline-terminated lines.""" + view = bytes(buf) + idx = view.rfind(b"\n") + if idx == -1: + return [], 0 + out = [] + for line in view[:idx].split(b"\n"): + line = line.strip() + if not line: + continue + out.append(json.loads(line.decode("utf-8"))) + return out, idx + 1 diff --git a/tests/fixtures/mock_acp_agent.py b/tests/fixtures/mock_acp_agent.py new file mode 100644 index 0000000..5ecae87 --- /dev/null +++ b/tests/fixtures/mock_acp_agent.py @@ -0,0 +1,158 @@ +"""A minimal ACP *server* (agent side) used to test the client deterministically. + +Implements just enough of the protocol: +- initialize -> protocolVersion + agentCapabilities +- session/new -> sessionId +- session/prompt -> streams a few session/update notifications, then returns + {stopReason: end_turn} +- session/cancel -> aborts the in-flight prompt +- asks the client for permission once (session/request_permission) if + --with-permission is passed + +Run standalone: python -m tests.fixtures.mock_acp_agent [--with-permission] +""" + +from __future__ import annotations + +import json +import sys +import threading +import uuid + +sys.path.insert(0, __file__.rsplit("/tests/", 1)[0] + "/src") + +from agenthub.framing import decode_ndjson_lines, encode_ndjson # noqa: E402 + + +class MockAgent: + def __init__(self, with_permission: bool = False, chunk_count: int = 3): + self.with_permission = with_permission + self.chunk_count = chunk_count + self.sessions: dict[str, dict] = {} + self._lock = threading.Lock() + self._next_id = 0 + self._pending_permission: dict[int, threading.Event] = {} + self._cancelled: set[str] = set() + + # -- io --------------------------------------------------------------- + def send(self, obj: dict) -> None: + sys.stdout.buffer.write(encode_ndjson(obj)) + sys.stdout.buffer.flush() + + def request(self, method: str, params: dict, timeout: float = 30.0) -> dict: + with self._lock: + self._next_id += 1 + rid = self._next_id + ev = threading.Event() + self._pending_permission[rid] = ev + self.send({"jsonrpc": "2.0", "id": rid, "method": method, "params": params}) + if not ev.wait(timeout): + raise TimeoutError(method) + return {} + + def notify(self, method: str, params: dict) -> None: + self.send({"jsonrpc": "2.0", "method": method, "params": params}) + + # -- main loop -------------------------------------------------------- + def run(self) -> None: + buf = bytearray() + while True: + chunk = sys.stdin.buffer.read(1) + if not chunk: + break + buf.extend(chunk) + msgs, consumed = decode_ndjson_lines(buf) + if consumed: + del buf[:consumed] + for m in msgs: + self.handle(m) + + def handle(self, msg: dict) -> None: + if "method" not in msg: # response to our request + rid = msg.get("id") + if rid is None: + return + ev = self._pending_permission.pop(rid, None) + if ev: + ev.set() + return + method = msg["method"] + rid = msg.get("id") + if method == "initialize": + self.reply(rid, {"protocolVersion": 1, "agentCapabilities": {"loadSession": True}}) + elif method == "session/new": + sid = "s-" + uuid.uuid4().hex[:8] + self.sessions[sid] = {"cwd": msg["params"].get("cwd")} + self.reply(rid, {"sessionId": sid}) + elif method == "session/prompt": + sid = msg["params"]["sessionId"] + threading.Thread(target=self._run_prompt, args=(sid, rid), daemon=True).start() + elif method == "session/cancel": + self._cancelled.add(msg["params"]["sessionId"]) + else: + self.reply_error(rid, -32601, f"unknown method {method}") + + def reply(self, rid, result) -> None: + if rid is not None: + self.send({"jsonrpc": "2.0", "id": rid, "result": result}) + + def reply_error(self, rid, code, message) -> None: + if rid is not None: + self.send({"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": message}}) + + def _run_prompt(self, sid: str, rid) -> None: + import time as _time + + for i in range(self.chunk_count): + # give the main loop a chance to receive session/cancel + _time.sleep(0.01) + if sid in self._cancelled: + self._cancelled.discard(sid) + self.reply(rid, {"stopReason": "cancelled"}) + return + self.notify( + "session/update", + { + "sessionId": sid, + "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": f"chunk{i} "}}, + }, + ) + if i == 1: + self.notify( + "session/update", + { + "sessionId": sid, + "update": { + "sessionUpdate": "tool_call", + "toolCallId": "t1", + "title": "read file", + "kind": "read", + "status": "completed", + }, + }, + ) + if self.with_permission: + self.request( + "session/request_permission", + { + "sessionId": sid, + "toolCall": {"toolCallId": "t2", "title": "rm -rf /tmp/x", "kind": "execute"}, + "options": [ + {"optionId": "allow_once", "name": "Allow once", "kind": "allow_once"}, + {"optionId": "reject_once", "name": "Reject", "kind": "reject_once"}, + ], + }, + ) + self.reply(rid, {"stopReason": "end_turn"}) + + +def main() -> None: + with_permission = "--with-permission" in sys.argv + chunk_count = 3 + if "--chunks" in sys.argv: + chunk_count = int(sys.argv[sys.argv.index("--chunks") + 1]) + MockAgent(with_permission=with_permission, chunk_count=chunk_count).run() + + +if __name__ == "__main__": + main() diff --git a/tests/test_acp_client.py b/tests/test_acp_client.py new file mode 100644 index 0000000..b33c83d --- /dev/null +++ b/tests/test_acp_client.py @@ -0,0 +1,146 @@ +"""M0 tests: ACPClient end-to-end against the mock ACP agent subprocess.""" + +import sys +import threading +import time +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "src")) + +from agenthub.acp_client import ACPClient, ACPError, ACPProcessDead # noqa: E402 + +MOCK = ROOT / "tests" / "fixtures" / "mock_acp_agent.py" + + +def make_client(with_permission: bool = False, chunk_count: int = 3) -> ACPClient: + cmd = [sys.executable, str(MOCK)] + if with_permission: + cmd.append("--with-permission") + cmd += ["--chunks", str(chunk_count)] + return ACPClient(cmd=cmd) + + +def test_initialize_and_prompt_streams_updates(): + client = make_client() + client.start() + try: + info = client.initialize() + assert info["protocolVersion"] == 1 + + events: list[tuple[str, dict]] = [] + client.register_notification_handler(lambda m, p: events.append((m, p))) + + sid = client.session_new(cwd="/tmp") + assert sid.startswith("s-") + + res = client.session_prompt(sid, [{"type": "text", "text": "hi"}], timeout=20) + assert res["stopReason"] == "end_turn" + + # wait a beat for notifications to drain + time.sleep(0.2) + updates = [p["update"]["sessionUpdate"] for m, p in events if m == "session/update"] + assert updates.count("agent_message_chunk") == 3 + assert "tool_call" in updates + finally: + client.close() + + +def test_permission_request_is_dispatched_to_handler(): + client = make_client(with_permission=True) + client.start() + try: + client.initialize() + answered: list[tuple[str, dict]] = [] + + def on_request(method: str, params: dict): + answered.append((method, params)) + return {"outcome": {"optionId": "allow_once"}} + + client.register_request_handler(on_request) + sid = client.session_new(cwd="/tmp") + res = client.session_prompt(sid, [{"type": "text", "text": "go"}], timeout=20) + assert res["stopReason"] == "end_turn" + time.sleep(0.1) + assert answered and answered[0][0] == "session/request_permission" + assert answered[0][1]["toolCall"]["title"] == "rm -rf /tmp/x" + finally: + client.close() + + +def test_unknown_server_request_gets_method_not_found(): + """If no handler claims a server->client request, the client answers -32601 + rather than hanging the agent.""" + client = make_client(with_permission=True) + client.start() + try: + client.initialize() + # no request handler registered at all + sid = client.session_new(cwd="/tmp") + res = client.session_prompt(sid, [{"type": "text", "text": "go"}], timeout=20) + assert res["stopReason"] == "end_turn" + finally: + client.close() + + +def test_unknown_method_raises_acp_error(): + client = make_client() + client.start() + try: + client.initialize() + with pytest.raises(ACPError) as ei: + client.request("does/not/exist", {}, timeout=5) + assert ei.value.code == -32601 + finally: + client.close() + + +def test_cancel_mid_prompt(): + client = make_client(chunk_count=200) # long stream + client.start() + try: + client.initialize() + sid = client.session_new(cwd="/tmp") + result: list = [] + + def run(): + try: + result.append(client.session_prompt(sid, [{"type": "text", "text": "long"}], timeout=20)) + except Exception as e: # noqa: BLE001 + result.append(e) + + t = threading.Thread(target=run, daemon=True) + t.start() + time.sleep(0.2) + client.session_cancel(sid) + t.join(timeout=5) + assert result and result[0].get("stopReason") == "cancelled" + finally: + client.close() + + +def test_dead_process_fails_pending_requests(): + client = make_client(chunk_count=200) + client.start() + try: + client.initialize() + sid = client.session_new(cwd="/tmp") + errs: list = [] + + def run(): + try: + client.session_prompt(sid, [{"type": "text", "text": "x"}], timeout=15) + except Exception as e: # noqa: BLE001 + errs.append(e) + + t = threading.Thread(target=run, daemon=True) + t.start() + time.sleep(0.2) + client._proc.kill() # simulate agent crash + t.join(timeout=10) + assert errs and isinstance(errs[0], ACPProcessDead) + assert not client.is_alive() + finally: + client.close() diff --git a/tests/test_framing.py b/tests/test_framing.py new file mode 100644 index 0000000..733bec2 --- /dev/null +++ b/tests/test_framing.py @@ -0,0 +1,76 @@ +"""M0 tests: Content-Length framing encode/decode.""" + +import pytest + +from agenthub.framing import FrameError, decode_frames, encode_frame + + +def test_roundtrip_single(): + msg = {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}} + data = encode_frame(msg) + out = list(decode_frames(data)) + assert out == [msg] + + +def test_roundtrip_multiple_in_one_buffer(): + msgs = [ + {"jsonrpc": "2.0", "id": 1, "result": {"ok": True}}, + {"jsonrpc": "2.0", "method": "session/update", "params": {"seq": 1}}, + {"jsonrpc": "2.0", "id": 2, "error": {"code": -32601, "message": "nope"}}, + ] + data = b"".join(encode_frame(m) for m in msgs) + assert list(decode_frames(data)) == msgs + + +def test_unicode_body(): + msg = {"text": "中文内容 emoji 🎉"} + data = encode_frame(msg) + # header must count bytes, not chars + assert b"Content-Length: " in data + assert list(decode_frames(data)) == [msg] + + +def test_partial_buffer_raises_incomplete(): + msg = {"a": 1} + data = encode_frame(msg) + with pytest.raises(FrameError, match="incomplete"): + list(decode_frames(data[:-5])) + + +def test_partial_header_raises_no_terminator(): + with pytest.raises(FrameError, match="no header terminator"): + list(decode_frames(b"Content-Length: 20\r\n")) + + +def test_missing_content_length(): + bad = b"Content-Type: text/plain\r\n\r\n{}" + with pytest.raises(FrameError, match="missing Content-Length"): + list(decode_frames(bad)) + + +def test_bad_content_length(): + bad = b"Content-Length: abc\r\n\r\n{}" + with pytest.raises(FrameError, match="bad Content-Length"): + list(decode_frames(bad)) + + +def test_bad_json_body(): + bad = b"Content-Length: 3\r\n\r\n{xx" + with pytest.raises(FrameError, match="bad JSON body"): + list(decode_frames(bad)) + + +def test_incremental_feed(): + """Simulate a stream that arrives in fragments.""" + msg = {"jsonrpc": "2.0", "id": 7, "result": [1, 2, 3]} + data = encode_frame(msg) + got = [] + buf = b"" + for i in range(len(data)): + buf += data[i : i + 1] + try: + got.extend(decode_frames(buf)) + buf = b"" + except FrameError: + pass # incomplete: keep feeding + assert got == [msg] diff --git a/tests/test_ndjson.py b/tests/test_ndjson.py new file mode 100644 index 0000000..5b711a9 --- /dev/null +++ b/tests/test_ndjson.py @@ -0,0 +1,29 @@ +"""ndjson transport tests (the transport used by current ACP SDK agents).""" + +import json + +from agenthub.framing import decode_ndjson_lines, encode_ndjson + + +def test_ndjson_roundtrip(): + msg = {"jsonrpc": "2.0", "id": 1, "result": {"ok": True}} + data = encode_ndjson(msg) + assert data.endswith(b"\n") + msgs, consumed = decode_ndjson_lines(data) + assert msgs == [msg] + assert consumed == len(data) + + +def test_ndjson_partial_tail(): + a = {"id": 1} + b = {"id": 2} + buf = encode_ndjson(a) + encode_ndjson(b)[:10] # b is incomplete + msgs, consumed = decode_ndjson_lines(buf) + assert msgs == [a] + assert consumed == len(encode_ndjson(a)) + + +def test_ndjson_unicode(): + msg = {"text": "中文🎉"} + data = encode_ndjson(msg) + assert json.loads(data.decode("utf-8")) == msg diff --git a/uv.lock b/uv.lock new file mode 100644 index 0000000..f58e952 --- /dev/null +++ b/uv.lock @@ -0,0 +1,8 @@ +version = 1 +revision = 3 +requires-python = ">=3.11" + +[[package]] +name = "agenthub" +version = "0.1.0" +source = { editable = "." }