The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): recover viewers blocked behind unknown execution
David Dudok de Witb660815f86a7
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex 2ff8b8e58b5..89ac8053422 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -270,6 +270,8 @@ class GatewayACPAgent(acp.Agent):held_id, session_id = session_id, self._aliases.get(session_id, session_id)if session_id not in self._snapshots:raise GatewayClientError("not_found")+ if self._has_unknown(session_id):+ raise GatewayClientError("unknown_execution")from acp_adapter.content import _content_blocks_to_openai_user_contenttext, attachments = _stage_user_content(_content_blocks_to_openai_user_content(prompt))if text.lstrip().startswith('/') and not attachments:@@ -308,9 +310,14 @@ class GatewayACPAgent(acp.Agent):self._pending_cancels.discard(session_id)await self._cancel_admission(session_id, 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+ await self._changed.wait_for(lambda: admission_id in self._terminals or self._failure is not None+ or self._blocked_admission(session_id, admission_id))+ # A successor's unknown state cannot replace our committed terminal result.+ if admission_id not in self._terminals:+ if self._failure:+ raise self._failure+ raise GatewayClientError("unknown_execution: do not resend accepted input; "+ "resolve the lost turn before continuing")terminal = self._terminals.pop(admission_id)finally:# Do not let one prompt tear down a newer mapping if the session has@@ -322,6 +329,15 @@ class GatewayACPAgent(acp.Agent):raise GatewayClientError("admitted_turn_failed")return PromptResponse(stop_reason="cancelled" if outcome == "cancelled" else "end_turn")+ def _has_unknown(self, session_id):+ return any(row.get("status") == "unknown"+ for row in self._snapshots[session_id].get("pending", []))++ def _blocked_admission(self, session_id, admission_id):+ return self._has_unknown(session_id) and any(+ row.get("admission_id") == admission_id and row.get("status") in {"queued", "unknown"}+ for row in self._snapshots[session_id].get("pending", []))+async def _events(self):try:while True:@@ -353,6 +369,12 @@ class GatewayACPAgent(acp.Agent):kind, payload = event.get("type"), event.get("payload", {})sid, editor_id = event["session_id"], self._editor_id(event["session_id"])aid = event.get("admission_id")+ if kind == "session.info":+ if sid in self._snapshots and "pending" in payload:+ async with self._changed:+ self._snapshots[sid]["pending"] = payload["pending"]+ self._changed.notify_all()+ returnif kind == "session.replay_gap":raise GatewayClientError("session_replay_gap")if kind in {"approval.request", "clarify.request"}:diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.pyindex 9a0014122ed..46ffc43aa43 100644--- a/hermes_cli/gateway_chat_view.py+++ b/hermes_cli/gateway_chat_view.py@@ -12,6 +12,7 @@ logger = logging.getLogger(__name__)_BLOCKING_CONTROL_EVENTS = frozenset({"approval.request", "approval.settled", "clarify.request", "clarify.settled",+ "session.info",})@@ -80,7 +81,7 @@ class GatewayChatView:returnadmission = params.get("admission_id") or payload.get("admission_id")if self.finite and kind in _BLOCKING_CONTROL_EVENTS:- # Approval/clarification gates block the session FIFO, not merely one+ # Gates and unknown executions block the session FIFO, not merely one# admission's output. Track them even when another admission owns the# event so a queued one-shot can detach instead of waiting forever.self._dispatch_event(kind, admission, payload)@@ -103,10 +104,15 @@ class GatewayChatView:"tool.start": self._tool_start, "tool.complete": self._tool_complete,"approval.request": self._request, "clarify.request": self._request,"approval.settled": self._settled, "clarify.settled": self._settled,+ "session.info": self._session_info,}.get(kind)if handler:handler(admission, payload)+ def _session_info(self, admission, payload):+ self.pending = payload.get("pending", self.pending)+ self.generation = payload.get("execution_generation", self.generation)+def _tool_start(self, admission, payload):# Deltas before a tool call are interim commentary the final reply does not repeat;# close that segment so `_complete` measures only the final's own stream.@@ -294,6 +300,11 @@ class GatewayChatView:self.changed.clear()if self.failure:raise self.failure+ if self.unknown_admissions() and any(+ row["admission_id"] == admission and row["status"] in {"queued", "unknown"}+ for row in self.pending):+ return self._detach("Unknown execution blocks this session; your accepted input is retained. "+ "Resume interactively to resolve the lost turn; do not resend the input.")if self.prompts:return self._detach("Input required; detached without cancelling. Resume this session interactively.")await self.changed.wait()diff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.pyindex f45c51cc86f..866c033867b 100644--- a/hermes_cli/gateway_client.py+++ b/hermes_cli/gateway_client.py@@ -31,6 +31,7 @@ class GatewayClient:await self.readerasync def _read(self):+ from websockets.exceptions import ConnectionClosedtry:async for raw in self.websocket:frame = json.loads(raw)@@ -46,10 +47,11 @@ class GatewayClient:future.set_result(frame.get("result", {}))elif "method" in frame:self.events.put_nowait(frame)- except (OSError, ValueError, asyncio.QueueFull):+ except (ConnectionClosed, OSError, ValueError, asyncio.QueueFull):passfinally:- error = GatewayClientError("Gateway disconnected; accepted work was not cancelled. Resume the printed session ID.")+ error = GatewayClientError("Gateway disconnected; turn outcome is unknown. "+ "Resume the printed session ID to check whether it completed or was interrupted; do not resend the work.")for future in self.pending.values():if not future.done():future.set_exception(error)diff --git a/tests/acp_adapter/test_adversarial_clarify_disconnect.py b/tests/acp_adapter/test_adversarial_clarify_disconnect.pynew file mode 100644index 00000000000..b9d7ddea920--- /dev/null+++ b/tests/acp_adapter/test_adversarial_clarify_disconnect.py@@ -0,0 +1,21 @@+"""A detached ACP question viewer cannot answer for another viewer."""+import asyncio+from unittest.mock import AsyncMock++import pytest++from acp_adapter.gateway_server import GatewayACPAgent++[email protected]('kind', ['approval', 'clarify'])+async def test_editor_transport_exception_leaves_shared_question_unanswered(kind):+ agent = GatewayACPAgent()+ agent._conn = AsyncMock()+ agent._conn.request_permission.side_effect = RuntimeError('editor transport detached')+ agent._gateway = AsyncMock()+ agent._permission('s', {'kind': kind, 'prompt_id': 'question', 'execution_generation': 2,+ 'question': 'Which target?', 'command': 'build', 'choices': ['once']})+ await asyncio.gather(*agent._permissions.values())+ agent._gateway.rpc.assert_not_awaited()+ assert agent._failure is Nonediff --git a/tests/acp_adapter/test_adversarial_client_session_identity.py b/tests/acp_adapter/test_adversarial_client_session_identity.pynew file mode 100644index 00000000000..2bae953435b--- /dev/null+++ b/tests/acp_adapter/test_adversarial_client_session_identity.py@@ -0,0 +1,17 @@+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock+import acp+import pytest+from acp_adapter.gateway_server import GatewayACPAgent++async def test_compression_preview_addresses_the_editor_retained_physical_alias():+ agent = GatewayACPAgent()+ agent._conn = AsyncMock()+ gateway = AsyncMock()+ agent._client = AsyncMock(return_value=gateway)+ agent._aliases['editor-tip'] = 'logical-root'+ agent._snapshots['logical-root'] = {}+ agent._mutations = SimpleNamespace(apply=AsyncMock(return_value={'status': 'preview', 'lines': ['retained 10 rows']}), acknowledge=Mock())+ await agent.prompt([acp.text_block('/compress --preview')], 'editor-tip')+ assert agent._conn.session_update.await_args.kwargs['session_id'] == 'editor-tip'diff --git a/tests/acp_adapter/test_adversarial_unknown_follower.py b/tests/acp_adapter/test_adversarial_unknown_follower.pynew file mode 100644index 00000000000..e441939dafc--- /dev/null+++ b/tests/acp_adapter/test_adversarial_unknown_follower.py@@ -0,0 +1,40 @@+"""Terminal results cannot be replaced by a successor's unknown queue state."""+import asyncio+from unittest.mock import AsyncMock++import acp+import pytest++from acp_adapter.gateway_server import GatewayACPAgent++[email protected]('before_ack', [False, True])+async def test_successor_unknown_does_not_overwrite_completed_editor_prompt(before_ack):+ agent = GatewayACPAgent()+ agent._gateway = AsyncMock()+ agent._snapshots['s'] = {}++ async def publish_buffered_events():+ await agent._project({'session_id': 's', 'type': 'message.complete', 'admission_id': 'ours',+ 'payload': {'outcome': 'completed', 'text': 'done'}})+ # Both events may be buffered before the prompt coroutine wakes; only+ # the successor has become unknown, not the completed prompt.+ await agent._project({'session_id': 's', 'type': 'session.info',+ 'payload': {'pending': [{'admission_id': 'next', 'status': 'unknown'}]}})++ async def submit(method, **params):+ assert method == 'prompt.submit'+ if before_ack:+ await publish_buffered_events()+ return {'admission_id': 'ours'}++ agent._gateway.rpc.side_effect = submit+ submitted = asyncio.create_task(agent.prompt([acp.text_block('our work')], 's'))+ if not before_ack:+ await asyncio.sleep(0)+ assert agent._admissions['s'] == 'ours'+ await publish_buffered_events()+ response = await asyncio.wait_for(submitted, 5)+ assert response.stop_reason == 'end_turn'+ agent._gateway.rpc.assert_awaited_once()diff --git a/tests/acp_adapter/test_gateway_queued_unknown.py b/tests/acp_adapter/test_gateway_queued_unknown.pynew file mode 100644index 00000000000..7234f319599--- /dev/null+++ b/tests/acp_adapter/test_gateway_queued_unknown.py@@ -0,0 +1,51 @@+"""Editor prompts fail recoverably when their FIFO becomes unknown."""+import asyncio+from unittest.mock import AsyncMock++import acp+import pytest++from acp_adapter.gateway_server import GatewayACPAgent+from hermes_cli.gateway_client import GatewayClientError++[email protected]('before_ack', [False, True])+async def test_editor_follower_reports_unknown_without_poisoning_other_sessions(before_ack):+ agent = GatewayACPAgent()+ agent._gateway = AsyncMock()+ agent._snapshots['s'] = {}+ agent._snapshots['other'] = {}+ unknown = {'session_id': 's', 'type': 'session.info', 'payload': {'pending': [+ {'admission_id': 'head', 'status': 'unknown'}, {'admission_id': 'ours', 'status': 'queued'}]}}++ async def submit(method, **params):+ assert method == 'prompt.submit'+ if params['session_id'] == 'other':+ await agent._project({'session_id': 'other', 'type': 'message.complete',+ 'admission_id': 'other-turn', 'payload': {'outcome': 'completed'}})+ return {'admission_id': 'other-turn'}+ if before_ack:+ await agent._project(unknown)+ return {'admission_id': 'ours'}++ agent._gateway.rpc.side_effect = submit+ submitted = asyncio.create_task(agent.prompt([acp.text_block('queued')], 's'))+ if not before_ack:+ await asyncio.sleep(0)+ await agent._project(unknown)+ with pytest.raises(GatewayClientError, match='unknown_execution: do not resend accepted input'):+ await asyncio.wait_for(submitted, 5)+ agent._gateway.rpc.assert_awaited_once()+ assert agent._failure is None+ assert (await agent.prompt([acp.text_block('independent')], 'other')).stop_reason == 'end_turn'+++async def test_editor_refuses_new_prompt_until_lost_turn_is_resolved():+ agent = GatewayACPAgent()+ agent._gateway = AsyncMock()+ agent._snapshots['s'] = {'pending': [{'admission_id': 'lost', 'status': 'unknown'}]}+ with pytest.raises(GatewayClientError, match='unknown_execution'):+ await asyncio.wait_for(agent.prompt([acp.text_block('new input')], 's'), 5)+ agent._gateway.rpc.assert_not_awaited()diff --git a/tests/hermes_cli/test_gateway_disconnect_outcome.py b/tests/hermes_cli/test_gateway_disconnect_outcome.pynew file mode 100644index 00000000000..4cefc9729d9--- /dev/null+++ b/tests/hermes_cli/test_gateway_disconnect_outcome.py@@ -0,0 +1,25 @@+"""Expected keepalive close preserves an honest unknown outcome and no task traceback."""+import asyncio++import pytest+from websockets.exceptions import ConnectionClosedError++from hermes_cli.gateway_client import GatewayClient, GatewayClientError+++async def test_keepalive_close_releases_waiters_without_unhandled_reader_exception():+ class Disconnected:+ def __aiter__(self):+ return self++ async def __anext__(self):+ raise ConnectionClosedError(None, None)++ client = GatewayClient(Disconnected())+ pending = asyncio.get_running_loop().create_future()+ client.pending[1] = pending+ await client._read()+ with pytest.raises(GatewayClientError, match='outcome is unknown'):+ await pending+ assert 'do not resend' in str(await client.events.get())diff --git a/tests/hermes_cli/test_gateway_queued_unknown.py b/tests/hermes_cli/test_gateway_queued_unknown.pynew file mode 100644index 00000000000..d6eff384ef8--- /dev/null+++ b/tests/hermes_cli/test_gateway_queued_unknown.py@@ -0,0 +1,70 @@+"""A finite queued viewer detaches when its predecessor becomes unknown."""+import asyncio+import json++import pytest++from hermes_cli.gateway_chat_view import GatewayChatView++[email protected]('before_ack', [False, True])[email protected]('stream_json', [False, True])+async def test_finite_follower_does_not_wait_forever_after_worker_loss(before_ack, stream_json, capsys):+ from hermes_cli.stream_json import StreamJsonEmitter++ rendered = asyncio.Event()++ class Events(asyncio.Queue):+ async def get(self):+ event = await super().get()+ rendered.set()+ return event++ class Peer:+ events = Events()+ calls = []++ async def rpc(self, method, **params):+ self.calls.append((method, params))+ assert method == 'prompt.submit'+ self.events.put_nowait({'method': 'event', 'params': {'session_id': 's',+ 'type': 'session.info', 'admission_id': 'predecessor', 'payload': {'pending': [+ {'admission_id': 'predecessor', 'status': 'unknown'},+ {'admission_id': 'ours', 'status': 'queued'}]}}})+ if before_ack:+ await rendered.wait()+ return {'admission_id': 'ours'}++ peer = Peer()+ emitter = StreamJsonEmitter(model='m', session_id='s') if stream_json else None+ view = GatewayChatView(peer, {'stored_session_id': 's'}, quiet=True, emitter=emitter)+ assert await asyncio.wait_for(view.run('queued', oneshot=True), 5) == 3+ assert len(peer.calls) == 1+ assert peer.calls[0][1]['text'] == 'queued'+ output = capsys.readouterr()+ assert 'accepted input is retained' in output.err and 'do not resend' in output.err+ if stream_json:+ records = [json.loads(line) for line in output.out.splitlines()]+ assert records[-1]['type'] == 'result' and records[-1]['exit_code'] == 3+++async def test_successor_unknown_does_not_replace_completed_prompt():+ class Peer:+ events = asyncio.Queue()++ async def rpc(self, method, **params):+ if method == 'prompt.receipt':+ return {'result': {'completed': True}}+ assert method == 'prompt.submit'+ for kind, admission, payload in [+ ('message.complete', 'ours', {'outcome': 'completed', 'text': 'done'}),+ ('session.info', 'next', {'pending': [{'admission_id': 'next', 'status': 'unknown'}]}),+ ]:+ self.events.put_nowait({'method': 'event', 'params': {'session_id': 's',+ 'type': kind, 'admission_id': admission, 'payload': payload}})+ return {'admission_id': 'ours'}++ view = GatewayChatView(Peer(), {'stored_session_id': 's'}, quiet=True)+ assert await asyncio.wait_for(view.run('work', oneshot=True), 5) == 0diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.mdindex d59a9e5aaa2..9f7b9f5c172 100644--- a/website/docs/developer-guide/gateway-internals.md+++ b/website/docs/developer-guide/gateway-internals.md@@ -223,6 +223,10 @@ Canonical wire models live in `tui_gateway/contracts/canonical*.py` and generate`CanonicalRpcMethods` plus the OpenRPC `x-canonical-methods` catalog, separatelyfrom the standalone protocol. Both parameters and successful results are checked.+ACP and finite CLI viewers detach with an explicit recovery notice if an accepted+input becomes blocked behind an unknown execution. The accepted input remains+queued: resolve the lost turn before continuing, rather than resending it.+## Private native HTTP authenticationThe authoritative daemon accepts a **fresh, one-use HTTP grant per request** fromdiff --git a/website/docs/user-guide/cli.md b/website/docs/user-guide/cli.mdindex a61f03f603d..79ea5f3c31d 100644--- a/website/docs/user-guide/cli.md+++ b/website/docs/user-guide/cli.md@@ -150,6 +150,11 @@ for the exact supported subset and trust boundary.`hermes chat` (and the bare `hermes` prompt when `display.interface` is `cli`) no longer runs the agent inside your terminal process. It discovers or starts the profile's gateway (`hermes gateway ensure`), creates or resumes the session there, and attaches over the gateway's local WebSocket — the same session a Desktop window, the TUI, or a Telegram topic can open at the same time. Closing the terminal detaches (`Detached; accepted work continues at the gateway.`); it does not cancel the turn. Your working directory, `--model`, `--provider`, `--reasoning`, `--toolsets`, `--max-turns`, `--ignore-rules`, `--base-url`/`--api-key`, and `--safe-mode`/`--ignore-user-config` are frozen into the session at creation and cannot be changed by `--resume`. `--resume <id-or-title>` and `-c <title>` name the session; the gateway resolves the title (exact id first, then the latest `"<title> #N"` continuation, followed to its live tip) among the sessions you may read, and reports `No session found matching '…'` (exit 1) otherwise. `-c <title> --create-if-missing` creates a session with that title when none exists and resumes it when one does, so programmatic callers (Bot Mode's `Bot Chat` turns) get a deterministic thread. Options that only make sense for an in-process agent — `--image`, `--skills`, `--worktree`, `--checkpoints`, `--yolo`, `--pass-session-id`, bare `--continue` (no name), `--create-if-missing` without `-c <name>`, `--run-budget`, `--verbose`, `--compact`, `--list-tools`, `--list-toolsets`, and `--resume latest` — are refused up front (`Unsupported gateway CLI options: …`, exit 2); the refusal lists, per flag, where that capability lives now (the TUI flag, the `config.yaml` key, or the `hermes` subcommand), and nothing falls back to a local agent. A `--safe-mode` / `--ignore-user-config` launch reads no profile default model, so it must name one; the refusal prints a complete example such as `hermes chat --safe-mode --provider openrouter --model anthropic/claude-sonnet-4 -q "hello"`. In this mode the slash surface is `/stop`, `/approve <id> <choice>`, `/answer <id> <text>`, `/discard <admission_id>`, `/branch [title]`, `/model <model> [--provider name]`, `/compress [here [N] | <focus>] [--preview]`, `/help` and `/quit`; other slash commands print `Unsupported gateway CLI command; use /help.` Use the TUI (`hermes --tui`) for the full slash registry.:::+If a running turn loses its owner while your finite CLI query is queued, the CLI+exits with code `3`. Your accepted input stays queued. Resume the printed session+interactively, inspect the unknown turn, and use `/discard <admission_id>` to+acknowledge it before continuing. Do not resend the queued input.+<img className="docs-terminal-figure" src="/docs/img/docs/cli-layout.svg" alt="Stylized preview of the Hermes CLI layout showing the banner, conversation area, and fixed input prompt." /><p className="docs-figure-caption">The Hermes CLI banner, conversation stream, and fixed input prompt rendered as a stable docs figure instead of fragile text art.</p>