The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: project execution-owned approvals to ACP viewers
Teknium97a24c10b3b8
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex 6fb65bf74fe..4d41bc02a5c 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -30,6 +30,7 @@ class GatewayACPAgent(acp.Agent):self._streamed = {}self._changed = asyncio.Condition()self._failure = None+ self._permissions = {}def on_connect(self, conn):self._conn = conn@@ -95,6 +96,8 @@ class GatewayACPAgent(acp.Agent):if self._conn:for update in _history_replay_updates(snapshot["messages"]):await self._conn.session_update(session_id=session_id, update=update)+ for pending in snapshot.get("prompts", []):+ self._permission(session_id, pending)return snapshotasync def load_session(self, cwd, session_id, mcp_servers=None, **kwargs):@@ -151,6 +154,14 @@ class GatewayACPAgent(acp.Agent):async def _project(self, event):sid, kind, payload = event["session_id"], event.get("type"), event.get("payload", {})aid = event.get("admission_id")+ if kind == "approval.request":+ self._permission(sid, payload)+ return+ if kind == "approval.settled":+ task = self._permissions.pop((sid, payload["prompt_id"], payload["execution_generation"]), None)+ if task:+ task.cancel()+ returnif kind == "message.delta":text = payload.get("text", "")self._streamed[aid] = self._streamed.get(aid, "") + text@@ -168,7 +179,45 @@ class GatewayACPAgent(acp.Agent):self._terminals.pop(next(iter(self._terminals)))self._changed.notify_all()+ def _permission(self, session_id, prompt):+ if prompt.get("kind") != "approval" or self._conn is None:+ return+ key = (session_id, prompt["prompt_id"], prompt["execution_generation"])+ if key not in self._permissions:+ self._permissions[key] = asyncio.create_task(self._answer_permission(session_id, prompt))++ async def _answer_permission(self, session_id, prompt):+ import logging+ from acp.schema import AllowedOutcome+ from acp_adapter.permissions import (+ _build_permission_options, _build_permission_tool_call, _OPTION_ID_TO_HERMES,+ )+ choices = prompt["choices"]+ options = [option for option in _build_permission_options(+ allow_permanent="always" in choices, allow_session="session" in choices)+ if _OPTION_ID_TO_HERMES[option.option_id] in choices]+ try:+ response = await self._conn.request_permission(session_id=session_id,+ tool_call=_build_permission_tool_call(prompt.get("command", ""), prompt.get("description", "")),+ options=options)+ # Transport loss/cancel is not a denial: the canonical waiter belongs+ # to the execution and may still be answered by another viewer.+ if not isinstance(response.outcome, AllowedOutcome):+ return+ if response.outcome.option_id not in {option.option_id for option in options}:+ return+ await self._gateway.rpc("approval.respond", session_id=session_id,+ prompt_id=prompt["prompt_id"], execution_generation=prompt["execution_generation"],+ choice=_OPTION_ID_TO_HERMES[response.outcome.option_id])+ except Exception:+ logging.getLogger(__name__).info("ACP permission viewer detached or control expired")+async def aclose(self):+ for task in self._permissions.values():+ task.cancel()+ if self._permissions:+ await asyncio.gather(*self._permissions.values(), return_exceptions=True)+ self._permissions.clear()if self._event_task:self._event_task.cancel()with suppress(asyncio.CancelledError):diff --git a/tests/acp/test_gateway_sessions.py b/tests/acp/test_gateway_sessions.pyindex 4de57a826ee..d654a49a634 100644--- a/tests/acp/test_gateway_sessions.py+++ b/tests/acp/test_gateway_sessions.py@@ -149,3 +149,53 @@ async def test_acp_transport_shares_canonical_history_and_order(daemon, tmp_pathassert len([e for e in events if e["type"] == "message.complete"]) == 2assert len(model_peer.requests) == 2print("ACP_SHARED_RECEIPT=" + json.dumps({"session_id": sid, "events": events, "messages": snapshot["messages"]}))+++[email protected]_only+async def test_acp_permission_detach_keeps_canonical_waiter(daemon, tmp_path, model_peer):+ import shlex+ from contextlib import suppress+ from hermes_cli.gateway_client import GatewayClientError+ from tests.gateway.fixtures.authority_controls_peer import ModelPeer as ApprovalPeer++ target = tmp_path / "owned-removal"+ target.mkdir()+ (target / "owned.txt").write_text("disposable")+ model_peer.command = "rm -r -- " + shlex.quote(str(target))+ model_peer.RequestHandlerClass = ApprovalPeer+ async with viewer(daemon) as ws:+ created = await ws.rpc("session.create", request_id="acp-permission", source="cli", cwd=str(tmp_path))+ sid = created["session_id"]+ async with editor(daemon, tmp_path) as acp:+ await acp.rpc("initialize", protocolVersion=1, clientCapabilities={})+ assert "result" in await acp.rpc("session/load", cwd=str(tmp_path), sessionId=sid, mcpServers=[])+ prompt_task = asyncio.create_task(acp.rpc("session/prompt", sessionId=sid,+ prompt=[{"type": "text", "text": "Remove the owned fixture"}]))+ try:+ async with asyncio.timeout(15):+ while not any(f.get("method") == "session/request_permission" for f in acp.frames):+ await asyncio.sleep(.05)+ permission = next(f for f in acp.frames if f.get("method") == "session/request_permission")+ assert target.exists()+ snapshot = await ws.rpc("session.resume", session_id=sid)+ pending = snapshot["prompts"][0]+ with pytest.raises(GatewayClientError, match="stale_generation"):+ await ws.rpc("approval.respond", session_id=sid, prompt_id=pending["prompt_id"],+ execution_generation=pending["execution_generation"] + 1, choice="once")+ assert target.exists()+ finally:+ prompt_task.cancel()+ with suppress(asyncio.CancelledError):+ await prompt_task+ assert target.exists(), "Editor detach must not synthesize approval or denial"+ response = await ws.rpc("approval.respond", session_id=sid, prompt_id=pending["prompt_id"],+ execution_generation=pending["execution_generation"], choice="once")+ assert response["status"] == "resolved", response+ async with asyncio.timeout(20):+ while target.exists():+ await asyncio.sleep(.05)+ print("ACP_PERMISSION_RECEIPT=" + json.dumps({"session_id": sid, "permission": permission,+ "stale_generation_rejected": True, "detached_waiter_resolved_by_ws": True,+ "real_owned_deletion": not target.exists()}))