Skip to content

The agent that grows with you

feat: attach ACP transport to canonical session execution

Teknium8dd92a30b6b5
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.py
index 25deec81a62..6fb65bf74fe 100644
--- a/acp_adapter/gateway_server.py
+++ b/acp_adapter/gateway_server.py
@@ -2,14 +2,19 @@
from __future__ import annotations
import asyncio
+from contextlib import suppress
import uuid
import acp
-from acp.schema import NewSessionResponse
+from acp.schema import (
+ AgentCapabilities, Implementation, InitializeResponse, LoadSessionResponse,
+ NewSessionResponse, PromptCapabilities, PromptResponse, ResumeSessionResponse,
+ SessionCapabilities, SessionResumeCapabilities,
+)
from hermes_cli.gateway_client import GatewayClientError, connect_gateway
from hermes_constants import get_hermes_home
-from acp_adapter.session import _translate_acp_cwd
+from acp_adapter.session import _translate_acp_cwd, _normalize_cwd_for_compare
class GatewayACPAgent(acp.Agent):
@@ -20,10 +25,29 @@ class GatewayACPAgent(acp.Agent):
self._connect_lock = asyncio.Lock()
self._home = get_hermes_home().resolve()
self._snapshots = {}
+ self._event_task = None
+ self._terminals = {}
+ self._streamed = {}
+ self._changed = asyncio.Condition()
+ self._failure = None
def on_connect(self, conn):
self._conn = conn
+ async def initialize(self, **kwargs):
+ from hermes_cli import __version__
+ from acp_adapter.auth import build_auth_methods
+ return InitializeResponse(protocol_version=acp.PROTOCOL_VERSION,
+ agent_info=Implementation(name="hermes-agent", version=__version__),
+ agent_capabilities=AgentCapabilities(load_session=True,
+ prompt_capabilities=PromptCapabilities(image=False),
+ session_capabilities=SessionCapabilities(resume=SessionResumeCapabilities())),
+ auth_methods=build_auth_methods())
+
+ async def authenticate(self, method_id, **kwargs):
+ from acp_adapter.server import HermesACPAgent
+ return await HermesACPAgent.authenticate(self, method_id, **kwargs)
+
async def _client(self):
async with self._connect_lock:
if self._gateway is None:
@@ -37,6 +61,9 @@ class GatewayACPAgent(acp.Agent):
await connection.__aexit__(None, None, None)
raise
self._connection, self._gateway = connection, gateway
+ self._event_task = asyncio.create_task(self._events())
+ if self._failure:
+ raise self._failure
return self._gateway
async def new_session(self, cwd, mcp_servers=None, **kwargs):
@@ -45,10 +72,108 @@ class GatewayACPAgent(acp.Agent):
if ("acp" not in descriptor.get("session_create", {}).get("sources", [])
or "acp-editor-policy-v1" not in descriptor.get("capabilities", [])):
raise GatewayClientError("acp_policy_unavailable")
- # This is a closed, server-validated launch envelope, not a CLI relabel.
snapshot = await client.rpc("session.create", request_id=uuid.uuid4().hex,
source="acp", cwd=_translate_acp_cwd(cwd),
editor={"mcp_servers": [s.model_dump(by_alias=True) for s in mcp_servers or []],
"edit_approval_policy": "ask"})
self._snapshots[snapshot["session_id"]] = snapshot
return NewSessionResponse(session_id=snapshot["session_id"])
+
+ async def _resume(self, cwd, session_id, mcp_servers):
+ if mcp_servers:
+ raise GatewayClientError("acp_mcp_policy_unavailable")
+ client = await self._client()
+ info = await client.rpc("session.info", session_id=session_id)
+ if "cwd" in info and _normalize_cwd_for_compare(info["cwd"]) != _normalize_cwd_for_compare(_translate_acp_cwd(cwd)):
+ raise GatewayClientError("cwd_policy_conflict")
+ if "cwd" not in info and self._conn:
+ await self._conn.session_update(session_id=session_id, update=acp.update_agent_message_text(
+ "Attached to the gateway's existing session policy; editor cwd is not applied.\n"))
+ snapshot = await client.rpc("session.resume", session_id=session_id)
+ self._snapshots[session_id] = snapshot
+ from acp_adapter.server import _history_replay_updates
+ if self._conn:
+ for update in _history_replay_updates(snapshot["messages"]):
+ await self._conn.session_update(session_id=session_id, update=update)
+ return snapshot
+
+ async def load_session(self, cwd, session_id, mcp_servers=None, **kwargs):
+ await self._resume(cwd, session_id, mcp_servers)
+ return LoadSessionResponse()
+
+ async def resume_session(self, cwd, session_id, mcp_servers=None, **kwargs):
+ await self._resume(cwd, session_id, mcp_servers)
+ return ResumeSessionResponse()
+
+ async def prompt(self, prompt, session_id, **kwargs):
+ if session_id not in self._snapshots:
+ raise GatewayClientError("not_found")
+ if any(getattr(block, "type", None) != "text" for block in prompt):
+ raise GatewayClientError("acp_content_unavailable")
+ text = "\n".join(block.text for block in prompt)
+ if text.lstrip().startswith("/"):
+ raise GatewayClientError("acp_command_unavailable")
+ client = await self._client()
+ receipt = await client.rpc("prompt.submit", session_id=session_id,
+ input_id=uuid.uuid4().hex, text=text)
+ admission_id = receipt["admission_id"]
+ async with self._changed:
+ await self._changed.wait_for(lambda: admission_id in self._terminals or self._failure is not None)
+ if self._failure:
+ raise self._failure
+ self._terminals.pop(admission_id)
+ return PromptResponse(stop_reason="end_turn")
+
+ async def _events(self):
+ try:
+ while True:
+ frame = await self._gateway.events.get()
+ if isinstance(frame, Exception):
+ raise frame
+ event = frame.get("params", {})
+ sid = event.get("session_id")
+ snapshot = self._snapshots.get(sid)
+ if snapshot is None:
+ continue
+ epoch, seq = event.get("replay_epoch"), event.get("seq", 0)
+ if epoch == snapshot.get("replay_epoch") and seq <= snapshot.get("last_sequence", 0):
+ continue
+ snapshot.update(replay_epoch=epoch, last_sequence=seq,
+ execution_generation=event.get("execution_generation", snapshot.get("execution_generation")))
+ await self._project(event)
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc:
+ async with self._changed:
+ self._failure = exc
+ self._changed.notify_all()
+
+ async def _project(self, event):
+ sid, kind, payload = event["session_id"], event.get("type"), event.get("payload", {})
+ aid = event.get("admission_id")
+ if kind == "message.delta":
+ text = payload.get("text", "")
+ self._streamed[aid] = self._streamed.get(aid, "") + text
+ if text and self._conn:
+ await self._conn.session_update(session_id=sid, update=acp.update_agent_message_text(text))
+ elif kind == "message.complete":
+ text = payload.get("text", "")
+ prefix = self._streamed.pop(aid, "")
+ remainder = text[len(prefix):] if text.startswith(prefix) else text
+ if remainder and self._conn:
+ await self._conn.session_update(session_id=sid, update=acp.update_agent_message_text(remainder))
+ async with self._changed:
+ self._terminals[aid] = payload
+ if len(self._terminals) > 256:
+ self._terminals.pop(next(iter(self._terminals)))
+ self._changed.notify_all()
+
+ async def aclose(self):
+ if self._event_task:
+ self._event_task.cancel()
+ with suppress(asyncio.CancelledError):
+ await self._event_task
+ if self._connection:
+ await self._connection.__aexit__(None, None, None)
+ self._connection = None
+ self._gateway = None
diff --git a/tests/acp/test_gateway_sessions.py b/tests/acp/test_gateway_sessions.py
new file mode 100644
index 00000000000..4de57a826ee
--- /dev/null
+++ b/tests/acp/test_gateway_sessions.py
@@ -0,0 +1,151 @@
+"""Actual ACP stdio and WS clients against an ordinary isolated gateway."""
+import asyncio
+from contextlib import asynccontextmanager
+import json
+import os
+from pathlib import Path
+import signal
+import subprocess
+import sys
+import time
+
+import pytest
+from websockets.asyncio.client import connect
+
+from hermes_cli.gateway_client import GatewayClient
+from tests.gateway.test_normal_runtime_boot import control, model_peer # noqa: F401
+
+
+def daemon(tmp_path, model_peer):
+ home = tmp_path / "state"
+ home.mkdir(mode=0o700)
+ user = tmp_path / "user"
+ user.mkdir()
+ root = Path(__file__).resolve().parents[2]
+ model_url = f"http://127.0.0.1:{model_peer.server_port}/v1"
+ (home / "config.yaml").write_text(json.dumps({
+ "gateway": {"multiplex_profiles": False},
+ "approvals": {"mode": "manual", "timeout": 60},
+ "model": {"provider": "custom", "default": "local-wire-stub", "base_url": model_url},
+ "auxiliary": {"title_generation": {"enabled": False}},
+ }))
+ env = {k: os.environ[k] for k in ("PATH", "LANG", "TZ") if k in os.environ}
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),
+ PYTHONPATH=str(root), PYTHONUNBUFFERED="1",
+ OPENAI_API_KEY="loopback-only", OPENAI_BASE_URL=model_url,
+ HERMES_ACP_SKIP_CONFIGURED_MCP="1")
+ log_path = tmp_path / "gateway.log"
+ with log_path.open("w") as log:
+ process = subprocess.Popen([sys.executable, "-m", "gateway.run"], cwd=root, env=env,
+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)
+ try:
+ deadline = time.monotonic() + 40
+ descriptor = {}
+ while process.poll() is None and time.monotonic() < deadline:
+ try:
+ descriptor = control(home, "identify")
+ if descriptor.get("state") == "ready":
+ break
+ except (OSError, ValueError):
+ pass
+ time.sleep(.1)
+ assert descriptor.get("state") == "ready", log_path.read_text()
+ yield home, descriptor, env, root
+ finally:
+ if process.poll() is None:
+ process.send_signal(signal.SIGINT)
+ try:
+ process.wait(timeout=20)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=5)
+
+
+@asynccontextmanager
+async def viewer(daemon):
+ home, descriptor, _, _ = daemon
+ grant = control(home, "session-ticket", {"profile_id": str(home),
+ "instance_id": descriptor["instance_id"], "purpose": "interactive"})
+ url = descriptor["api_origin"].replace("http:", "ws:") + "/api/ws"
+ async with connect(url, subprotocols=["hermes-gateway-v1", "hermes-gateway-ticket." + grant["ticket"]]) as ws:
+ async with GatewayClient(ws) as client:
+ yield client
+
+
+class ACPPeer:
+ def __init__(self, process):
+ self.process = process
+ self.frames = []
+ self.requests = {}
+ self.serial = 0
+ self.reader = asyncio.create_task(self.read())
+
+ async def read(self):
+ while line := await self.process.stdout.readline():
+ frame = json.loads(line)
+ self.frames.append(frame)
+ future = self.requests.get(frame.get("id"))
+ if future and ("result" in frame or "error" in frame):
+ future.set_result(frame)
+
+ async def rpc(self, method, **params):
+ self.serial += 1
+ rid = self.serial
+ future = asyncio.get_running_loop().create_future()
+ self.requests[rid] = future
+ self.process.stdin.write(json.dumps({"jsonrpc": "2.0", "id": rid, "method": method, "params": params}).encode() + b"\n")
+ await self.process.stdin.drain()
+ return await asyncio.wait_for(future, 40)
+
+
+@asynccontextmanager
+async def editor(daemon, tmp_path):
+ _, _, env, root = daemon
+ with (tmp_path / "acp.log").open("w") as log:
+ process = await asyncio.create_subprocess_exec(sys.executable, "-m", "acp_adapter.entry",
+ cwd=root, env=env, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=log)
+ peer = ACPPeer(process)
+ try:
+ yield peer
+ finally:
+ process.stdin.close()
+ try:
+ await asyncio.wait_for(process.wait(), 5)
+ except asyncio.TimeoutError:
+ process.kill()
+ await process.wait()
+ await peer.reader
+
+
+async def test_acp_transport_shares_canonical_history_and_order(daemon, tmp_path, model_peer):
+ async with viewer(daemon) as ws:
+ created = await ws.rpc("session.create", request_id="shared-acp", source="cli", cwd=str(tmp_path))
+ sid = created["session_id"]
+ async with editor(daemon, tmp_path) as acp:
+ init = await acp.rpc("initialize", protocolVersion=1, clientCapabilities={})
+ assert "result" in init, init
+ loaded = await acp.rpc("session/load", cwd=str(tmp_path), sessionId=sid, mcpServers=[])
+ assert "result" in loaded, loaded
+ reply = await acp.rpc("session/prompt", sessionId=sid, prompt=[{"type": "text", "text": "WS_SHARED ACP"}])
+ assert reply.get("result", {}).get("stopReason") == "end_turn", reply
+ assert "LOCAL_ACK_WS_SHARED" in json.dumps(acp.frames)
+ accepted = await ws.rpc("prompt.submit", session_id=sid, input_id="after-acp-disconnect", text="WS_SHARED WS")
+ async with asyncio.timeout(30):
+ while True:
+ receipt = await ws.rpc("prompt.receipt", session_id=sid, admission_id=accepted["admission_id"])
+ if receipt["status"] == "terminal":
+ assert receipt["outcome"] == "completed", receipt
+ break
+ await asyncio.sleep(.05)
+ snapshot = await ws.rpc("session.resume", session_id=sid)
+ assert "WS_SHARED ACP" in json.dumps(snapshot["messages"])
+ assert "WS_SHARED WS" in json.dumps(snapshot["messages"])
+ replay = await ws.rpc("session.events.since", session_id=sid, replay_epoch=created["replay_epoch"], last_sequence=0)
+ events = replay["events"]
+ assert [e["seq"] for e in events] == sorted({e["seq"] for e in events})
+ assert len([e for e in events if e["type"] == "message.complete"]) == 2
+ assert len(model_peer.requests) == 2
+ print("ACP_SHARED_RECEIPT=" + json.dumps({"session_id": sid, "events": events, "messages": snapshot["messages"]}))