Skip to content

The agent that grows with you

fix: ACP reuses the input identity of an un-acked prompt on retry

Teknium74d084a619b3
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.py
index b19a4404f66..2bec951f5be 100644
--- a/acp_adapter/gateway_server.py
+++ b/acp_adapter/gateway_server.py
@@ -87,6 +87,17 @@ def _slash_command(text):
return command.name if command is not None else None
+def _submit_fingerprint(session_id, text, attachments):
+ """Content identity of one logical prompt: its text and the staged image bytes (staging names
+ are disposable; the authority reconciles a retry by the same digests)."""
+ import hashlib
+ digest = hashlib.sha256(text.encode())
+ for item in attachments:
+ with open(item['path'], 'rb') as staged:
+ digest.update(item['mime'].encode() + b'\0' + hashlib.sha256(staged.read()).digest())
+ return session_id, digest.hexdigest()
+
+
class GatewayACPAgent(acp.Agent):
def __init__(self):
self._conn = None
@@ -111,6 +122,11 @@ class GatewayACPAgent(acp.Agent):
self._permissions = {}
self._admissions = {}
self._submitting = set()
+ # (session, content fingerprint) -> input_id of a submit whose ack never arrived. The
+ # editor's retry of that prompt reuses it, so the authority returns the same admission.
+ self._unacked = {}
+ # Admissions whose message.complete the pump is projecting right now.
+ self._settling = set()
self._pending_cancels = set()
self._tool_args = {}
# Editor-held compression-tip id -> logical session id (see ``_resume``).
@@ -392,17 +408,32 @@ class GatewayACPAgent(acp.Agent):
submit = {'text': text}
if attachments:
submit['attachments'] = attachments
+ retry_key = await asyncio.to_thread(_submit_fingerprint, session_id, text, attachments)
+ input_id = self._unacked.pop(retry_key, None) or uuid.uuid4().hex
self._submitting.add(session_id)
try:
- receipt = await client.rpc("prompt.submit", session_id=session_id,
- input_id=uuid.uuid4().hex, **submit)
- except BaseException:
+ receipt = await client.rpc("prompt.submit", session_id=session_id, input_id=input_id, **submit)
+ except BaseException as exc:
+ from hermes_cli.gateway_client import GatewayRPCError
+ if not isinstance(exc, GatewayRPCError):
+ # Transport loss, timeout or cancel before the ack: the owner may hold this admission.
+ # Keep its identity for the editor's retry of the same prompt (latest 64 kept).
+ self._unacked[retry_key] = input_id
+ while len(self._unacked) > 64:
+ self._unacked.pop(next(iter(self._unacked)))
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 receipt.get("status") == "terminal":
+ # A retry of an un-acked submit whose turn already settled: report that turn once.
+ await self._settled_receipt(client, held_id, session_id, receipt)
+ elif receipt.get("status") == "unknown":
+ # A retry of an un-acked submit the owner lost in a restart: never a second turn.
+ self._admissions.pop(session_id, None)
+ raise GatewayClientError(self._unknown_recovery(session_id, admission_id))
try:
if session_id in self._pending_cancels:
self._pending_cancels.discard(session_id)
@@ -434,6 +465,20 @@ class GatewayACPAgent(acp.Agent):
raise GatewayClientError("admitted_turn_failed")
return PromptResponse(stop_reason="cancelled" if outcome == "cancelled" else "end_turn")
+ async def _settled_receipt(self, client, held_id, session_id, receipt):
+ admission_id = receipt["admission_id"]
+ saved = await client.rpc("prompt.receipt", session_id=session_id, admission_id=admission_id,
+ include_result=True)
+ if admission_id in self._terminals or admission_id in self._settling:
+ return # this connection's pump carried the completion itself
+ text = (saved.get("result") or {}).get("final_response") or ""
+ if text and self._conn:
+ await self._conn.session_update(session_id=held_id, update=acp.update_agent_message_text(text))
+ outcome = {"interrupted": "cancelled"}.get(receipt.get("outcome"), receipt.get("outcome"))
+ async with self._changed:
+ self._terminals[admission_id] = {"outcome": outcome}
+ self._changed.notify_all()
+
def _unknown_recovery(self, session_id, admission_id=None, *, submitted=True):
"""The refusal for a FIFO blocked by a lost turn, naming the existing recovery control.
@@ -545,14 +590,19 @@ class GatewayACPAgent(acp.Agent):
await self._conn.session_update(session_id=editor_id,
update=acp.update_agent_message_text(text + "\n\n"))
elif kind == "message.complete":
- remainder = self._final_remainder(aid, payload)
- if remainder and self._conn:
- await self._conn.session_update(session_id=editor_id, 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()
+ self._settling.add(aid)
+ try:
+ remainder = self._final_remainder(aid, payload)
+ if remainder and self._conn:
+ await self._conn.session_update(session_id=editor_id,
+ 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()
+ finally:
+ self._settling.discard(aid)
def _close_segment(self, aid):
streamed = self._streamed.pop(aid, "")
diff --git a/tests/acp_adapter/test_gateway_submit_retry.py b/tests/acp_adapter/test_gateway_submit_retry.py
new file mode 100644
index 00000000000..19df2f98c38
--- /dev/null
+++ b/tests/acp_adapter/test_gateway_submit_retry.py
@@ -0,0 +1,89 @@
+"""An editor retry of a prompt whose submit ack was lost reuses its identity: one admission, one turn."""
+import asyncio
+from types import SimpleNamespace
+
+import acp
+import pytest
+
+from acp_adapter.gateway_server import GatewayACPAgent
+from gateway.config import GatewayConfig, Platform
+from gateway.session import SessionSource, SessionStore
+from gateway.session_authority import LiveSession, initialize_session_authority
+from gateway.session_controls import AuthorityConnection
+from hermes_cli.gateway_client import GatewayClientError, GatewayRPCError
+from hermes_state_runtime import list_session_admissions
+
+
+class Wire:
+ """The ACP agent's gateway client over a real AuthorityConnection; can lose one submit's ack."""
+
+ def __init__(self, loop):
+ self.loop, self.events, self.serial, self.viewer, self.lose_ack = loop, asyncio.Queue(), 0, None, True
+
+ def write(self, frame): # the authority's transport (may be called off-loop)
+ self.loop.call_soon_threadsafe(self.events.put_nowait, frame)
+ return True
+
+ async def rpc(self, method, **params):
+ self.serial += 1
+ reply = await self.viewer.dispatch({'id': self.serial, 'method': method, 'params': params})
+ if 'error' in reply:
+ raise GatewayRPCError(reply['error'].get('data', {}).get('reason', 'request_failed'))
+ if method == 'prompt.submit' and self.lose_ack:
+ self.lose_ack = False
+ raise GatewayClientError('Gateway disconnected; turn outcome is unknown.')
+ return reply['result']
+
+
[email protected]('settled_before_retry', [False, True])
+async def test_retry_after_lost_submit_ack_is_one_admission(tmp_path, monkeypatch, settled_before_retry):
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ executed = []
+
+ async def answer(event):
+ from gateway.session_results import execution_result
+ executed.append(event.text)
+ execution_result.get()['result'] = {'final_response': 'ACK_' + event.text, 'completed': True, 'messages': []}
+ return 'ACK_' + event.text
+
+ runner = SimpleNamespace(_session_db=store._db, session_store=store, _draining=False,
+ _handle_message=answer, _adapter_for_source=lambda source: None)
+ store._db.create_session('s', source='telegram')
+ authority = await initialize_session_authority(runner, profile_id='p', instance_id='owner')
+ authority.sessions['s'] = LiveSession(SessionSource(platform=Platform.TELEGRAM, chat_id='retry'), 's')
+ wire = Wire(asyncio.get_running_loop())
+ wire.viewer = AuthorityConnection(authority, wire, {'user_id': 'editor'})
+ agent = GatewayACPAgent()
+ agent._gateway = wire
+ agent._conn = SimpleNamespace(updates=[])
+
+ async def session_update(session_id, update):
+ agent._conn.updates.append(update.content.text)
+ agent._conn.session_update = session_update
+ agent._snapshots['s'] = await wire.rpc('session.resume', session_id='s')
+ agent._event_task = asyncio.create_task(agent._events())
+ schedule = authority._schedule
+ try:
+ if not settled_before_retry:
+ authority._schedule = lambda ref: None # the lost turn is still queued at retry time
+ with pytest.raises(GatewayClientError, match='outcome is unknown'):
+ await agent.prompt([acp.text_block('same words')], 's')
+ authority._schedule = schedule
+ if settled_before_retry:
+ async with asyncio.timeout(5):
+ while 'ACK_same words' not in agent._conn.updates:
+ await asyncio.sleep(0.01)
+ response = await asyncio.wait_for(agent.prompt([acp.text_block('same words')], 's'), 5)
+ assert response.stop_reason == 'end_turn'
+ rows = list_session_admissions(authority.db, session_id='s', pending_only=False)
+ assert len(rows) == 1 and executed == ['same words']
+ assert agent._conn.updates.count('ACK_same words') == 1
+ # A different prompt is new work with a fresh identity.
+ await asyncio.wait_for(agent.prompt([acp.text_block('other words')], 's'), 5)
+ assert len(list_session_admissions(authority.db, session_id='s', pending_only=False)) == 2
+ finally:
+ agent._event_task.cancel()
+ await wire.viewer.close()
+ store.close_all_db_handles()