The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(acp): session/cancel cancels the ACP-owned admission, not another surface's turn
teknium1fca061e94e73
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex 7c56ad110ce..66050ac1376 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -61,6 +61,8 @@ class GatewayACPAgent(acp.Agent):self._changed = asyncio.Condition()self._failure = Noneself._permissions = {}+ self._admissions = {}+ self._tool_args = {}from hermes_cli.gateway_mutations import PreparedMutationsself._mutations = PreparedMutations()@@ -145,12 +147,23 @@ class GatewayACPAgent(acp.Agent):return ResumeSessionResponse()async def cancel(self, session_id, **kwargs):- snapshot = self._snapshots.get(session_id)- if snapshot is None:+ if session_id not in self._snapshots:raise GatewayClientError("not_found")+ admission_id = self._admissions.get(session_id)+ if admission_id is None:+ returnclient = await self._client()- await client.rpc("session.interrupt", session_id=session_id,- execution_generation=snapshot["execution_generation"])+ # Cancel our own admission; another surface's running turn is not ours to+ # interrupt. Only when our admission is the one executing do we interrupt.+ try:+ await client.rpc("prompt.cancel", session_id=session_id, admission_id=admission_id)+ except GatewayClientError as exc:+ if str(exc) != "stale_generation":+ raise+ receipt = await client.rpc("prompt.receipt", session_id=session_id, admission_id=admission_id)+ if receipt["status"] == "started":+ await client.rpc("session.interrupt", session_id=session_id,+ execution_generation=receipt["execution_generation"])async def fork_session(self, cwd, session_id, mcp_servers=None, **kwargs):from acp.schema import ForkSessionResponse@@ -214,11 +227,15 @@ class GatewayACPAgent(acp.Agent):receipt = await client.rpc("prompt.submit", session_id=session_id,input_id=uuid.uuid4().hex, **submit)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- terminal = self._terminals.pop(admission_id)+ self._admissions[session_id] = admission_id+ try:+ 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+ terminal = self._terminals.pop(admission_id)+ finally:+ self._admissions.pop(session_id, None)outcome = terminal.get("outcome")if outcome == "failed":raise GatewayClientError("admitted_turn_failed")@@ -259,6 +276,25 @@ class GatewayACPAgent(acp.Agent):if task:task.cancel()return+ # In-process turns publish ``tool_name``; managed workers publish ``name``.+ tool_name = payload.get("tool_name") or payload.get("name") or "tool"+ if kind == "tool.start":+ from acp_adapter.tools import build_tool_start, coerce_tool_args+ args = coerce_tool_args(payload.get("args"))+ self._tool_args[(sid, payload["tool_call_id"])] = (tool_name, args)+ if self._conn:+ await self._conn.session_update(session_id=sid,+ update=build_tool_start(payload["tool_call_id"], tool_name, args))+ return+ if kind == "tool.complete":+ from acp_adapter.tools import build_tool_complete+ name, args = self._tool_args.pop((sid, payload["tool_call_id"]), (tool_name, {}))+ result = payload.get("result")+ if self._conn:+ await self._conn.session_update(session_id=sid, update=build_tool_complete(+ payload["tool_call_id"], name, result=result if isinstance(result, str) else None,+ function_args=args))+ returnif kind == "message.delta":text = payload.get("text", "")self._streamed[aid] = self._streamed.get(aid, "") + textdiff --git a/tests/acp/test_gateway_cancel_admission.py b/tests/acp/test_gateway_cancel_admission.pynew file mode 100644index 00000000000..e046230495b--- /dev/null+++ b/tests/acp/test_gateway_cancel_admission.py@@ -0,0 +1,70 @@+"""session/cancel cancels the ACP-owned admission, never another surface's running turn."""+import asyncio+from unittest.mock import AsyncMock++import pytest+from acp.schema import TextContentBlock++from acp_adapter.gateway_server import GatewayACPAgent+from hermes_cli.gateway_client import GatewayClientError+++def agent_with_queued_prompt():+ agent = GatewayACPAgent()+ # Another viewer's turn is executing under generation 7 when we are queued.+ agent._snapshots['s'] = {'execution_generation': 7}+ agent._gateway = AsyncMock()+ agent._conn = AsyncMock()+ return agent+++async def queued(agent):+ agent._gateway.rpc.return_value = {'admission_id': 'ours'}+ task = asyncio.create_task(agent.prompt([TextContentBlock(type='text', text='hello')], 's'))+ await asyncio.sleep(0)+ assert not task.done()+ agent._gateway.rpc.reset_mock()+ return task+++async def settle(agent, task, outcome):+ await agent._project({'session_id': 's', 'type': 'message.complete', 'admission_id': 'ours',+ 'payload': {'outcome': outcome, 'text': ''}})+ return await asyncio.wait_for(task, 2)+++async def test_cancel_targets_queued_acp_admission_not_the_running_generation():+ agent = agent_with_queued_prompt()+ task = await queued(agent)+ agent._gateway.rpc.return_value = {'admission_id': 'ours', 'status': 'terminal', 'outcome': 'cancelled'}+ await agent.cancel('s')+ methods = [call.args[0] for call in agent._gateway.rpc.await_args_list]+ assert methods == ['prompt.cancel']+ assert agent._gateway.rpc.await_args.kwargs == {'session_id': 's', 'admission_id': 'ours'}+ assert (await settle(agent, task, 'cancelled')).stop_reason == 'cancelled'+++async def test_cancel_interrupts_only_when_our_admission_is_the_one_running():+ agent = agent_with_queued_prompt()+ task = await queued(agent)++ async def rpc(method, **params):+ if method == 'prompt.cancel':+ raise GatewayClientError('stale_generation')+ if method == 'prompt.receipt':+ return {'admission_id': 'ours', 'status': 'started', 'execution_generation': 8}+ return {}+ agent._gateway.rpc.side_effect = rpc+ await agent.cancel('s')+ calls = {call.args[0]: call.kwargs for call in agent._gateway.rpc.await_args_list}+ assert calls['session.interrupt'] == {'session_id': 's', 'execution_generation': 8}+ assert (await settle(agent, task, 'cancelled')).stop_reason == 'cancelled'+++async def test_cancel_without_an_acp_prompt_leaves_other_surfaces_turn_alone():+ agent = agent_with_queued_prompt()+ await agent.cancel('s')+ agent._gateway.rpc.assert_not_awaited()