M0: framing (ndjson + lsp-frame), ACPClient, mock agent fixture, probe script; real claude-code-acp handshake verified

This commit is contained in:
openbot committed 2026-10-06 11:05:40 +08:00
1 parent d96d4f73bb
commit 82c3763e5c
10 files changed
+967 -4

No files matched your search

+158
View File
@@ -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()
+146
View File
@@ -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()
+76
View File
@@ -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]
+29
View File
@@ -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