Skip to content

The agent that grows with you

fix(gateway): terminate replay gaps and retain ACP cancels

Brian Fernstrom37662b16ec96
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.py
index 6e543169e31..432630dd61b 100644
--- a/acp_adapter/gateway_server.py
+++ b/acp_adapter/gateway_server.py
@@ -62,6 +62,8 @@ class GatewayACPAgent(acp.Agent):
self._failure = None
self._permissions = {}
self._admissions = {}
+ self._submitting = set()
+ self._pending_cancels = set()
self._tool_args = {}
from hermes_cli.gateway_mutations import PreparedMutations
self._mutations = PreparedMutations()
@@ -147,12 +149,7 @@ class GatewayACPAgent(acp.Agent):
await self._resume(cwd, session_id, mcp_servers)
return ResumeSessionResponse()
- async def cancel(self, session_id, **kwargs):
- if session_id not in self._snapshots:
- raise GatewayClientError("not_found")
- admission_id = self._admissions.get(session_id)
- if admission_id is None:
- return
+ async def _cancel_admission(self, session_id, admission_id):
client = await self._client()
# 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.
@@ -166,6 +163,16 @@ class GatewayACPAgent(acp.Agent):
await client.rpc("session.interrupt", session_id=session_id,
execution_generation=receipt["execution_generation"])
+ async def cancel(self, session_id, **kwargs):
+ if session_id not in self._snapshots:
+ raise GatewayClientError("not_found")
+ admission_id = self._admissions.get(session_id)
+ if admission_id is None:
+ if session_id in self._submitting:
+ self._pending_cancels.add(session_id)
+ return
+ await self._cancel_admission(session_id, admission_id)
+
async def fork_session(self, cwd, session_id, mcp_servers=None, **kwargs):
from acp.schema import ForkSessionResponse
client = await self._client()
@@ -230,10 +237,20 @@ class GatewayACPAgent(acp.Agent):
submit = {'text': text}
if attachments:
submit['attachments'] = attachments
- receipt = await client.rpc("prompt.submit", session_id=session_id,
- input_id=uuid.uuid4().hex, **submit)
+ self._submitting.add(session_id)
+ try:
+ receipt = await client.rpc("prompt.submit", session_id=session_id,
+ input_id=uuid.uuid4().hex, **submit)
+ except BaseException:
+ self._pending_cancels.discard(session_id)
+ raise
+ finally:
+ self._submitting.discard(session_id)
admission_id = receipt["admission_id"]
self._admissions[session_id] = admission_id
+ if session_id in self._pending_cancels:
+ self._pending_cancels.discard(session_id)
+ await self._cancel_admission(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)
@@ -274,6 +291,8 @@ 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 == "session.replay_gap":
+ raise GatewayClientError("session_replay_gap")
if kind == "approval.request":
self._permission(sid, payload)
return
diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.py
index 85b0793c04a..711d40b04df 100644
--- a/hermes_cli/gateway_chat_view.py
+++ b/hermes_cli/gateway_chat_view.py
@@ -64,6 +64,10 @@ class GatewayChatView:
continue
kind, payload = params.get("type"), params.get("payload", {})
self.generation = params.get("execution_generation", self.generation)
+ if kind == "session.replay_gap":
+ self.failure = GatewayClientError("session_replay_gap")
+ self.changed.set()
+ return
admission = params.get("admission_id") or payload.get("admission_id")
handler = {
"message.delta": self._delta, "message.complete": self._complete,
diff --git a/tests/acp_adapter/test_gateway_cancel_admission.py b/tests/acp_adapter/test_gateway_cancel_admission.py
index e046230495b..ba4badaeb8b 100644
--- a/tests/acp_adapter/test_gateway_cancel_admission.py
+++ b/tests/acp_adapter/test_gateway_cancel_admission.py
@@ -63,6 +63,38 @@ async def test_cancel_interrupts_only_when_our_admission_is_the_one_running():
assert (await settle(agent, task, 'cancelled')).stop_reason == 'cancelled'
+async def test_cancel_during_submit_is_applied_when_admission_id_arrives():
+ agent = agent_with_queued_prompt()
+ submit_started = asyncio.Event()
+ release_submit = asyncio.Event()
+ calls = []
+
+ async def rpc(method, **params):
+ calls.append((method, params))
+ if method == 'prompt.submit':
+ submit_started.set()
+ await release_submit.wait()
+ return {'admission_id': 'ours'}
+ if method == 'prompt.cancel':
+ return {'admission_id': 'ours', 'status': 'terminal', 'outcome': 'cancelled'}
+ return {}
+
+ agent._gateway.rpc.side_effect = rpc
+ task = asyncio.create_task(agent.prompt([TextContentBlock(type='text', text='hello')], 's'))
+ await asyncio.wait_for(submit_started.wait(), 2)
+ await agent.cancel('s')
+ assert [method for method, _ in calls] == ['prompt.submit']
+
+ release_submit.set()
+ for _ in range(20):
+ if any(method == 'prompt.cancel' for method, _ in calls):
+ break
+ await asyncio.sleep(0)
+ assert ('prompt.cancel', {'session_id': 's', 'admission_id': 'ours'}) in calls
+ assert (await settle(agent, task, 'cancelled')).stop_reason == 'cancelled'
+
+
@pytest.mark.asyncio
async def test_cancel_without_an_acp_prompt_leaves_other_surfaces_turn_alone():
agent = agent_with_queued_prompt()
diff --git a/tests/acp_adapter/test_gateway_terminal_projection.py b/tests/acp_adapter/test_gateway_terminal_projection.py
index 3d7a66e9640..ebe27eecd44 100644
--- a/tests/acp_adapter/test_gateway_terminal_projection.py
+++ b/tests/acp_adapter/test_gateway_terminal_projection.py
@@ -44,6 +44,16 @@ async def test_cancelled_admission_suppresses_only_interrupt_metadata(text, visi
assert 'other' in agent._terminals and 'current' not in agent._terminals
+async def test_replay_gap_is_a_recoverable_projection_failure():
+ agent = agent_with_admission()
+ with pytest.raises(GatewayClientError, match='session_replay_gap'):
+ await agent._project({
+ 'session_id': 's', 'type': 'session.replay_gap',
+ 'payload': {'reason': 'subscriber_overflow'},
+ })
+
+
@pytest.mark.asyncio
async def test_failed_admission_raises_without_poisoning_the_next_success():
agent = agent_with_admission()
diff --git a/tests/hermes_cli/test_gateway_chat_failures.py b/tests/hermes_cli/test_gateway_chat_failures.py
index 08994134616..9faccc081b4 100644
--- a/tests/hermes_cli/test_gateway_chat_failures.py
+++ b/tests/hermes_cli/test_gateway_chat_failures.py
@@ -59,6 +59,26 @@ async def test_oneshot_matches_own_terminal_receipt_not_neighbor(capsys):
assert capsys.readouterr().out == "mine\n"
+async def test_oneshot_replay_gap_fails_instead_of_waiting_forever():
+ from hermes_cli.gateway_chat_view import GatewayChatView
+ from hermes_cli.gateway_client import GatewayClientError
+
+ class Peer:
+ events = asyncio.Queue()
+
+ async def rpc(self, method, **params):
+ assert method == "prompt.submit"
+ self.events.put_nowait({"method": "event", "params": {
+ "type": "session.replay_gap", "session_id": "stored",
+ "payload": {"reason": "subscriber_overflow"}}})
+ return {"admission_id": "mine"}
+
+ view = GatewayChatView(Peer(), {"stored_session_id": "stored"}, quiet=True)
+ with pytest.raises(GatewayClientError, match="session_replay_gap"):
+ await asyncio.wait_for(view.run("query", oneshot=True), 2)
+
+
@pytest.mark.asyncio
async def test_oneshot_refuses_unknown_blocked_session_before_submitting(capsys):
"""After a SIGKILL mid-turn the head admission is ``unknown``; a new -q admission would queue