The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): wait for a gateway plugin command's reply as long as its handler runs
unsupportedpastels25c47f2abbc6
diff --git a/hermes_cli/cli_tui_mixin.py b/hermes_cli/cli_tui_mixin.pyindex 169d1790b5e..912367a5343 100644--- a/hermes_cli/cli_tui_mixin.py+++ b/hermes_cli/cli_tui_mixin.py@@ -918,7 +918,7 @@ class CLITuiMixin:def _tui_cancel_foreground_ui(self, event, *, closers) -> bool:"""Close the first active foreground UI (slash-confirm / picker / palette); True if any."""for state_attr, close in closers:- if getattr(self, state_attr):+ if getattr(self, state_attr, None):close()event.app.current_buffer.reset()event.app.invalidate()@@ -951,16 +951,16 @@ class CLITuiMixin:event.app.exit()def _tui_handle_ctrl_c(self, event):- """Ctrl+C priority: cancel voice recording → cancel foreground UI/overlay prompt →- clear a typed draft, even mid-run (a correction must never kill the turn) → interrupt- the running agent → force exit (second press within 2s) → when idle and empty, exit."""+ """Ctrl+C priority: cancel voice recording → cancel foreground UI/overlay prompt or the wait for a+ gateway plugin command → clear a typed draft, even mid-run (a correction must never kill the turn)+ → interrupt the running agent → force exit (second press within 2s) → when idle and empty, exit."""now = time.time()if self._tui_cancel_voice_recording(event):returnif self._tui_cancel_foreground_ui(event, closers=(("_slash_confirm_state", lambda: self._submit_slash_confirm_response("cancel")),- ("_model_picker_state", self._close_model_picker),- ("_command_palette_state", self._close_command_palette))):+ ("_model_picker_state", self._close_model_picker), ("_command_palette_state", self._close_command_palette),+ ("_plugin_command_wait", lambda: self._plugin_command_wait.set()))):returnoverlay_cleared = self._tui_clear_blocking_overlays(event)if overlay_cleared and not (self._agent_running and self.agent):diff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.pyindex 1b38e53e7aa..2bc7852e8c4 100644--- a/hermes_cli/gateway_client.py+++ b/hermes_cli/gateway_client.py@@ -135,14 +135,16 @@ class GatewayClient:async def rpc(self, method, *, _timeout=None, **params):"""Send one request and await its answer; ``_timeout`` (seconds, never sent on the wire)- overrides ``DEFAULT_RPC_TIMEOUT`` for a verb that legitimately takes longer."""+ overrides ``DEFAULT_RPC_TIMEOUT`` for a verb that legitimately takes longer (``math.inf``: no+ deadline; the answer, a hang-up or the caller's cancel ends the wait)."""self.sequence += 1rid = self.sequencefuture = asyncio.get_running_loop().create_future()self.pending[rid] = futuretry:await self.websocket.send(json.dumps({"jsonrpc": "2.0", "id": rid, "method": method, "params": params}))- return await asyncio.wait_for(future, DEFAULT_RPC_TIMEOUT if _timeout is None else _timeout)+ budget = DEFAULT_RPC_TIMEOUT if _timeout is None else _timeout+ return await asyncio.wait_for(future, None if budget == float("inf") else budget)finally:self.pending.pop(rid, None)diff --git a/hermes_cli/gateway_connection.py b/hermes_cli/gateway_connection.pyindex 85e3de71611..31138eb8c57 100644--- a/hermes_cli/gateway_connection.py+++ b/hermes_cli/gateway_connection.py@@ -28,6 +28,10 @@ NOT_SENT = "Gateway disconnected before the request was sent; nothing was sent."_GONE = frozenset({"not_found", "permission_denied", "profile_mismatch"})+class CallStopped(GatewayClientError):+ """The caller stopped waiting (:meth:`GatewayConnection.call_until`); the request was sent."""++def lost_before(frame, epoch) -> bool:"""``frame`` is a transport error from a connection older than ``epoch``: a reconnect replaced it,so it is no outcome of anything submitted on ``epoch``."""@@ -289,9 +293,8 @@ class GatewayConnection:def call(self, method, *, timeout=None, **params):return self.call_tagged(method, timeout=timeout, **params)[0]- def call_tagged(self, method, *, timeout=None, **params):- """``(result, epoch)``: the epoch of the socket that carried the request, so work it admitted- is tied to that gateway life even if another caller redials before this one reads ``epoch``."""+ def _send(self, method, budget, params):+ """``(future, epoch)`` of one request sent on the live socket (see :meth:`call_tagged`)."""if self._thread is not None and threading.current_thread() is self._thread:raise RuntimeError("GatewayConnection.call() on the gateway loop thread would deadlock")self.start()@@ -299,8 +302,29 @@ class GatewayConnection:if live is None or loop is None:raise GatewayClientError(NOT_SENT)client, epoch = live+ return asyncio.run_coroutine_threadsafe(client.rpc(method, _timeout=budget, **params), loop), epoch++ def call_until(self, method, wake, **params):+ """``call`` with no answer deadline, for a verb that lasts as long as the work it runs (a plugin+ command's handler). Waits for the answer or the transport's error, unless *wake* (a+ ``threading.Event``, e.g. set by Ctrl+C) is set first: then raises :class:`CallStopped`; the+ request was sent and its work goes on, but its answer is dropped."""+ future, _epoch = self._send(method, float("inf"), params)+ future.add_done_callback(lambda _done: wake.set())+ try:+ wake.wait()+ finally:+ if not future.done():+ future.cancel()+ if future.cancelled():+ raise CallStopped(method)+ return future.result()++ def call_tagged(self, method, *, timeout=None, **params):+ """``(result, epoch)``: the epoch of the socket that carried the request, so work it admitted+ is tied to that gateway life even if another caller redials before this one reads ``epoch``."""budget = DEFAULT_RPC_TIMEOUT if timeout is None else timeout- future = asyncio.run_coroutine_threadsafe(client.rpc(method, _timeout=budget, **params), loop)+ future, epoch = self._send(method, budget, params)try:return future.result(budget + 5), epochexcept TimeoutError as exc:diff --git a/hermes_cli/gateway_plugin_commands.py b/hermes_cli/gateway_plugin_commands.pyindex 6057c9a61df..f6ae4ceb694 100644--- a/hermes_cli/gateway_plugin_commands.py+++ b/hermes_cli/gateway_plugin_commands.py@@ -13,11 +13,15 @@ them, not because there are none: it is treated as a failed read and never cache"""from __future__ import annotations+import threading+from hermes_cli.gateway_client import GatewayClientError_CATEGORY = "Plugin commands" # tui_gateway/command_discovery.pyGONE = object() # run(): the gateway no longer has the command; the caller dispatches the name again_GONE_LINE = " /{}: the gateway no longer has this plugin command; nothing was run."+_STOPPED_LINE = (" /{}: stopped waiting. The command keeps running in the gateway and its reply will not be shown;"+ " the next gateway request from this CLI waits until it finishes.")class CatalogUnavailable(Exception):@@ -107,8 +111,17 @@ def run(cli, name, arg):return Falsefrom cli import _cprintfrom hermes_cli.gateway_client import GatewayRPCError+ from hermes_cli.gateway_connection import CallStopped+ # No answer deadline: main's CLI waited for the handler, which may wait minutes (ctx.call_mcp).+ wake = cli._plugin_command_wait = threading.Event() # set by Ctrl+C (cli_tui_mixin)try:- reply = connection.call("slash.exec", session_id=cli.session_id, command=name + (" " + arg if arg else ""))+ reply = connection.call_until("slash.exec", wake, session_id=cli.session_id,+ command=name + (" " + arg if arg else ""))+ except (CallStopped, KeyboardInterrupt) as exc:+ _cprint(_STOPPED_LINE.format(name))+ if isinstance(exc, KeyboardInterrupt):+ raise+ return Trueexcept GatewayRPCError as exc:if str(exc) != "unsupported_command":_cprint(f" /{name}: {exc}")@@ -117,6 +130,8 @@ def run(cli, name, arg):except GatewayClientError as exc:_cprint(f" /{name}: {exc}")return True+ finally:+ cli._plugin_command_wait = Nonereply = reply or {}if reply.get("type", "exec") != "exec": # it lost the plugin since lookup: a refusal or skill replyif _dropped(cli, connection, name):diff --git a/tests/gateway/test_cli_plugin_command_in_gateway.py b/tests/gateway/test_cli_plugin_command_in_gateway.pyindex afdaaf6a70b..b14be2e60b5 100644--- a/tests/gateway/test_cli_plugin_command_in_gateway.py+++ b/tests/gateway/test_cli_plugin_command_in_gateway.py@@ -126,6 +126,9 @@ class _Wire:def call_tagged(self, method, **params):return self.call(method, **params), self.epoch+ def call_until(self, method, _wake, **params):+ return self.call(method, **params)+def close(self):self._run(self.ws.close())self.loop.call_soon_threadsafe(self.loop.stop)@@ -212,12 +215,17 @@ def test_a_redial_to_a_restarted_gateway_and_slash_new_reread_the_plugin_commandwith _plugin_home(tmp_path, _LIFE.replace('NAME', 'alpha')) as (root, home, env):monkeypatch.setenv('HERMES_HOME', str(home))conn = GatewayConnection(connect=_dial_running(home))- sent, real = [], conn.call_tagged+ sent, real, real_until = [], conn.call_tagged, conn.call_untildef spy(method, **params):sent.append((method, params.get('session_id')))return real(method, **params)++ def spy_until(method, wake, **params): # slash.exec: no answer deadline+ sent.append((method, params.get('session_id')))+ return real_until(method, wake, **params)monkeypatch.setattr(conn, 'call_tagged', spy)+ monkeypatch.setattr(conn, 'call_until', spy_until)c = HermesCLI()c.agent, c._session_db, c._gateway_session_open = None, GatewaySessionStore(conn), False@@ -336,3 +344,97 @@ def test_a_command_a_plugin_reload_removed_is_dispatched_again(tmp_path, monkeypassert after[0][1] == ['slash.exec', 'commands.catalog'] and ran_skill == ['/pptwin', '/pptwin'], afterassert f'PIDPROBE PID={proc.pid}' in after[1][0], after # still the plugin's, in the gatewayassert 'slash.exec' not in after[2][1] and 'PLUGIN_TWIN' not in after[2][0], after+++# /ppslow blocks on the FIFO GATE until the test writes a note; MARKS/started-<arg> and+# MARKS/done-<arg> show when the handler started and finished in the gateway.+_SLOW = '''import os+++def register(ctx):+ def slow(arg):+ open(os.path.join(MARKS, "started-" + arg), "w").close()+ with open(GATE) as gate:+ note = gate.read()+ open(os.path.join(MARKS, "done-" + arg), "w").close()+ return "SLOW_DONE %s %s" % (arg, note)+ ctx.register_command("ppslow", slow, description="Waits for the test")+ ctx.register_command("ppquick", lambda arg: "QUICK_DONE", description="Answers at once")+'''+++def _typed_in_thread(c, text):+ thread = threading.Thread(target=c._process_unregistered_slash, args=(text, text.lower()), daemon=True)+ thread.start()+ return thread+++def _release(gate, note):+ with open(gate, 'w') as pipe: # blocks until the handler opened its end+ pipe.write(note)++[email protected]("linux")+def test_a_plugin_command_outliving_the_rpc_limit_prints_its_reply_and_ctrl_c_stops_the_wait(+ tmp_path, monkeypatch, capsys):+ """Main's CLI ran the handler itself and waited for it. Through the gateway the CLI waits for the+ reply as long as the handler runs, not the 30 s RPC budget (injected here as 0, so a request on+ that budget gives up at once). Ctrl+C stops the wait with a line saying what happens next: the+ handler finishes in the gateway, its reply is dropped, and the connection keeps working once it+ has (the socket answers in order)."""+ import cli as cli_mod+ from types import SimpleNamespace+ from prompt_toolkit.buffer import Buffer+ from cli import HermesCLI+ from hermes_cli import gateway_plugin_commands+ from hermes_cli.gateway_connection import GatewayConnection+ from hermes_cli.gateway_session_store import GatewaySessionStore+ _no_local_plugins(monkeypatch)+ monkeypatch.setattr(cli_mod, '_ensure_skill_commands', dict)+ monkeypatch.setattr(cli_mod, 'get_skill_bundles', dict)+ gate, marks = tmp_path / 'gate', tmp_path / 'marks'+ os.mkfifo(gate)+ marks.mkdir()+ source = _SLOW.replace('GATE', repr(str(gate))).replace('MARKS', repr(str(marks)))+ with _plugin_home(tmp_path, source) as (root, home, env):+ monkeypatch.setenv('HERMES_HOME', str(home))+ conn = GatewayConnection(connect=_dial_running(home))+ c = HermesCLI()+ c.agent, c._session_db, c._gateway_session_open = None, GatewaySessionStore(conn), False+ try:+ with daemon(root, home, env, barrier=True, fixture='plugin_mcp_daemon.py') as (proc, _desc):+ c._ensure_gateway_session()+ assert 'ppslow' in (gateway_plugin_commands.names(c) or {}) # cached: no catalog read below+ monkeypatch.setattr('hermes_cli.gateway_connection.DEFAULT_RPC_TIMEOUT', 0)+ capsys.readouterr()+ waiting = _typed_in_thread(c, '/ppslow long')+ wait_until(lambda: (marks / 'started-long').exists(), timeout=30, what='the handler to start')+ _release(gate, 'released')+ waiting.join(60)+ long_out = capsys.readouterr().out+ assert not waiting.is_alive()+ assert 'SLOW_DONE long released' in long_out, long_out+ assert 'did not answer' not in long_out, long_out++ stopped = _typed_in_thread(c, '/ppslow stop')+ wait_until(lambda: (marks / 'started-stop').exists(), timeout=30, what='the handler to start')+ app = SimpleNamespace(current_buffer=Buffer(), invalidate=lambda: None,+ exit=lambda: setattr(c, '_should_exit', True))+ c._tui_handle_ctrl_c(SimpleNamespace(app=app)) # the classic TUI's Ctrl+C binding+ stopped.join(60)+ stop_out = capsys.readouterr().out+ stop_alive, should_exit = stopped.is_alive(), c._should_exit+ # The socket answers its requests in order (tui_gateway/ws.py), so the next one waits+ # for the stopped handler: let it finish before typing again.+ _release(gate, 'late')+ wait_until(lambda: (marks / 'done-stop').exists(), timeout=30, what='the handler to finish')+ assert c._process_unregistered_slash('/ppquick', '/ppquick') is True+ after_out = capsys.readouterr().out+ proc.send_signal(signal.SIGINT)+ proc.wait(timeout=20)+ finally:+ conn.close()+ assert not stop_alive and not should_exit, (stop_alive, should_exit)+ assert 'stopped waiting' in stop_out and 'keeps running in the gateway' in stop_out, stop_out+ assert 'SLOW_DONE' not in stop_out, stop_out+ assert 'QUICK_DONE' in after_out and 'SLOW_DONE' not in after_out, after_out # the late reply is droppeddiff --git a/tests/hermes_cli/test_gateway_plugin_commands.py b/tests/hermes_cli/test_gateway_plugin_commands.pyindex 35efdf50b3e..56a5624267d 100644--- a/tests/hermes_cli/test_gateway_plugin_commands.py+++ b/tests/hermes_cli/test_gateway_plugin_commands.py@@ -28,6 +28,9 @@ class _Conn:def call(self, method, **params):return self.call_tagged(method, **params)[0]+ def call_until(self, method, _wake, **params): # slash.exec: no answer deadline+ return self.call_tagged(method, **params)[0]+def call_tagged(self, method, **params):self.calls.append((method, params))if self.closed: # a hung-up connection redials on its next call (gateway_connection)