Skip to content

The agent that grows with you

fix(cli): run a gateway plugin command on a socket of its own

unsupportedpastels06111d20fdc5
diff --git a/hermes_cli/gateway_connection.py b/hermes_cli/gateway_connection.py
index 31138eb8c57..fe823acb9c7 100644
--- a/hermes_cli/gateway_connection.py
+++ b/hermes_cli/gateway_connection.py
@@ -114,6 +114,8 @@ class GatewayConnection:
# waiter or the frame comes first, so an answer faster than the verb's reply is kept.
self._side: dict[str, queue.Queue] = {}
self._side_lock = threading.Lock()
+ # The wake events of :meth:`call_until` commands in flight, each on its own socket.
+ self._commands: set[threading.Event] = set()
@classmethod
def shared(cls):
@@ -264,6 +266,9 @@ class GatewayConnection:
def close(self):
self._detached = True
+ with self._side_lock:
+ for wake in self._commands: # their sockets close too
+ wake.set()
loop, stop = self.loop, self._stop
if loop is not None and stop is not None and not self.closed:
try:
@@ -306,19 +311,63 @@ class GatewayConnection:
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())
+ command's handler), on a socket of its own to this connection's gateway: the gateway answers a
+ socket's requests one at a time, in arrival order (``tui_gateway/ws.py``), so a handler still
+ running never holds this connection's reads, prompts and interrupts. One dial and one send,
+ never retried. Waits for the answer or the transport's error, unless *wake* (a
+ ``threading.Event``, set by Ctrl+C or :meth:`close`) is set first: then raises
+ :class:`CallStopped`; the request was sent and its work goes on, but its answer is dropped. The
+ socket closes on any of these, and its thread is gone before this returns."""
+ import concurrent.futures
+ from agent.memory_provider import spawn_context_thread
+ if self._thread is not None and threading.current_thread() is self._thread:
+ raise RuntimeError("GatewayConnection.call_until() on the gateway loop thread would deadlock")
+ self.start() # this viewer's gateway, dialled (or redialled after a hang-up) as for any call
+ if self.final:
+ raise GatewayClientError(NOT_SENT)
+ answer, sent = concurrent.futures.Future(), threading.Event()
+ answer.add_done_callback(lambda _done: wake.set())
+ thread = spawn_context_thread(lambda: asyncio.run(self._command(method, params, wake, answer, sent)),
+ name="hermes-gateway-command")
+ with self._side_lock:
+ self._commands.add(wake)
+ thread.start()
try:
wake.wait()
finally:
- if not future.done():
- future.cancel()
- if future.cancelled():
+ wake.set() # also on KeyboardInterrupt: the socket closes
+ thread.join(10)
+ with self._side_lock:
+ self._commands.discard(wake)
+ if answer.done():
+ return answer.result()
+ if sent.is_set():
raise CallStopped(method)
- return future.result()
+ raise GatewayClientError(NOT_SENT)
+
+ async def _command(self, method, params, wake, answer, sent):
+ """The command socket of :meth:`call_until`: dial, send once, settle ``answer`` with the reply or
+ the transport's error; a set ``wake`` without an answer cancels the dial or the wait."""
+ connect = self._connect
+ if connect is None:
+ from hermes_cli.gateway_client import connect_gateway
+ connect = connect_gateway
+ task = asyncio.current_task()
+ stop = asyncio.ensure_future(asyncio.to_thread(wake.wait))
+ stop.add_done_callback(lambda _stop: answer.done() or task.cancel())
+ try:
+ async with connect() as client:
+ sent.set() # from here the request may have reached the gateway: never sent again
+ answer.set_result(await client.rpc(method, _timeout=float("inf"), **params))
+ except asyncio.CancelledError:
+ pass
+ except Exception as exc: # health: allow BLE001 -- every transport failure is the caller's error
+ if not isinstance(exc, GatewayClientError):
+ exc = GatewayClientError(DISCONNECTED if sent.is_set() else NOT_SENT)
+ answer.set_exception(exc)
+ finally:
+ wake.set() # ends the watcher above
+ await asyncio.gather(stop, return_exceptions=True)
def call_tagged(self, method, *, timeout=None, **params):
"""``(result, epoch)``: the epoch of the socket that carried the request, so work it admitted
diff --git a/hermes_cli/gateway_plugin_commands.py b/hermes_cli/gateway_plugin_commands.py
index f6ae4ceb694..3f0c9de2539 100644
--- a/hermes_cli/gateway_plugin_commands.py
+++ b/hermes_cli/gateway_plugin_commands.py
@@ -20,8 +20,7 @@ from hermes_cli.gateway_client import GatewayClientError
_CATEGORY = "Plugin commands" # tui_gateway/command_discovery.py
GONE = 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.")
+_STOPPED_LINE = " /{}: stopped waiting. The command keeps running in the gateway and its reply will not be shown."
class CatalogUnavailable(Exception):
@@ -112,7 +111,8 @@ def run(cli, name, arg):
from cli import _cprint
from 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).
+ # No answer deadline: main's CLI waited for the handler, which may wait minutes (ctx.call_mcp). On
+ # a socket of its own, so the session's prompts and interrupts never queue behind it.
wake = cli._plugin_command_wait = threading.Event() # set by Ctrl+C (cli_tui_mixin)
try:
reply = connection.call_until("slash.exec", wake, session_id=cli.session_id,
diff --git a/tests/gateway/test_cli_plugin_command_in_gateway.py b/tests/gateway/test_cli_plugin_command_in_gateway.py
index f69cf6dd017..f1dfc42c65f 100644
--- a/tests/gateway/test_cli_plugin_command_in_gateway.py
+++ b/tests/gateway/test_cli_plugin_command_in_gateway.py
@@ -445,8 +445,7 @@ def test_a_plugin_command_outliving_the_rpc_limit_prints_its_reply_and_ctrl_c_st
"""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)."""
+ handler finishes in the gateway and its reply is dropped, while the next command already runs."""
import cli as cli_mod
from types import SimpleNamespace
from prompt_toolkit.buffer import Buffer
@@ -489,12 +488,11 @@ def test_a_plugin_command_outliving_the_rpc_limit_prints_its_reply_and_ctrl_c_st
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')
+ # The stopped handler ran on a socket of its own: the next command does not wait for it.
assert c._process_unregistered_slash('/ppquick', '/ppquick') is True
after_out = capsys.readouterr().out
+ _release(gate, 'late')
+ wait_until(lambda: (marks / 'done-stop').exists(), timeout=30, what='the handler to finish')
proc.send_signal(signal.SIGINT)
proc.wait(timeout=20)
finally:
diff --git a/tests/gateway/test_cli_plugin_command_own_socket.py b/tests/gateway/test_cli_plugin_command_own_socket.py
new file mode 100644
index 00000000000..7d1bdc33f10
--- /dev/null
+++ b/tests/gateway/test_cli_plugin_command_own_socket.py
@@ -0,0 +1,160 @@
+"""A classic CLI plugin command never holds the CLI's own gateway connection (#134889 PLG-7).
+
+The gateway answers one socket's requests one at a time, in arrival order (``tui_gateway/ws.py``
+``_dispatch_loop``), and a plugin handler may run for minutes. So ``slash.exec`` for a plugin command
+goes over a socket of its own to the same gateway, for the same session: while the handler runs, even
+after Ctrl+C stopped the wait, the CLI's reads, prompt admissions and interrupts are answered at once.
+Main's CLI ran the handler itself, without occupying any gateway connection.
+"""
+import os
+import signal
+import threading
+from types import SimpleNamespace
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import Model, daemon
+from tests.gateway.test_cli_plugin_command_in_gateway import (
+ _SLOW, _dial_running, _no_local_plugins, _plugin_home, _release, _typed_in_thread,
+)
+from tests.waiting import wait_until
+
+# The command socket's thread (hermes_cli/gateway_connection.py); none may outlive its command.
+_COMMAND_THREAD = 'hermes-gateway-command'
+
+
+def _command_threads():
+ return [thread for thread in threading.enumerate() if thread.name == _COMMAND_THREAD]
+
+
+def _cli(monkeypatch, home):
+ """``(cli, connection)``: a classic CLI on its own production connection to ``home``."""
+ import cli as cli_mod
+ from cli import HermesCLI
+ 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)
+ 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
+ return c, conn
+
+
+def _slow_source(tmp_path):
+ gate, marks = tmp_path / 'gate', tmp_path / 'marks'
+ os.mkfifo(gate)
+ marks.mkdir()
+ return gate, marks, _SLOW.replace('GATE', repr(str(gate))).replace('MARKS', repr(str(marks)))
+
+
+def _ctrl_c(c):
+ """The classic TUI's Ctrl+C binding, with an empty draft."""
+ from prompt_toolkit.buffer import Buffer
+ app = SimpleNamespace(current_buffer=Buffer(), invalidate=lambda: None,
+ exit=lambda: setattr(c, '_should_exit', True))
+ c._tui_handle_ctrl_c(SimpleNamespace(app=app))
+
+
+def test_a_stopped_plugin_command_leaves_the_cli_connection_free(tmp_path, monkeypatch, capsys):
+ """Ctrl+C stops the wait while the handler stays blocked in the gateway. Before it is released, the
+ CLI's connection answers a prompt admission, a receipt read and the interrupt of that turn, in
+ order. Released, the handler's late reply is never shown and no command socket or pending
+ request is left."""
+ from hermes_cli import gateway_plugin_commands
+ from hermes_cli.gateway_client import GatewayClientError
+ models, model_post = [], Model.do_POST
+
+ def seen_post(handler): # the loopback model server, to hold and release the admitted turn
+ models.append(handler.server)
+ model_post(handler)
+ monkeypatch.setattr(Model, 'do_POST', seen_post)
+ gate, marks, source = _slow_source(tmp_path)
+ outcomes = {}
+
+ def step(name, method, **params): # the primary connection's ordinary call, its default budget
+ try:
+ outcomes[name] = conn.call(method, **params)
+ except GatewayClientError as exc:
+ outcomes[name] = exc
+ return outcomes[name]
+ with _plugin_home(tmp_path, source) as (root, home, env):
+ c, conn = _cli(monkeypatch, home)
+ try:
+ with daemon(root, home, env, barrier=True, fixture='plugin_mcp_daemon.py') as (proc, _desc):
+ c._ensure_gateway_session()
+ sid = c.session_id
+ assert 'ppslow' in (gateway_plugin_commands.names(c) or {}) # cached: no catalog read below
+ capsys.readouterr()
+ stopped = _typed_in_thread(c, '/ppslow held')
+ wait_until(lambda: (marks / 'started-held').exists(), timeout=30, what='the handler to start')
+ _ctrl_c(c)
+ stopped.join(60)
+ stop_out, stop_alive = capsys.readouterr().out, stopped.is_alive()
+ try:
+ receipt = step('submit', 'prompt.submit', session_id=sid, submission_id='held-turn',
+ text='BLOCK_STARTED')
+ if isinstance(receipt, dict):
+ wait_until(lambda: models and models[-1].blocked.is_set(), timeout=60,
+ what='the admitted turn to reach the model')
+ read = step('read', 'prompt.receipt', session_id=sid, admission_id=receipt['admission_id'])
+ if isinstance(read, dict):
+ step('interrupt', 'session.interrupt', session_id=sid,
+ execution_generation=read['execution_generation'])
+ handler_held = not (marks / 'done-held').exists()
+ finally:
+ for model in models:
+ model.release.set()
+ _release(gate, 'late')
+ wait_until(lambda: (marks / 'done-held').exists(), timeout=30, what='the handler to finish')
+ after = c._process_unregistered_slash('/ppquick', '/ppquick'), capsys.readouterr().out
+ wait_until(lambda: not _command_threads(), timeout=30, what='the command sockets to close')
+ pending = dict(conn.client.pending) if conn.client is not None else {}
+ proc.send_signal(signal.SIGINT)
+ proc.wait(timeout=20)
+ finally:
+ conn.close()
+ assert not stop_alive and not c._should_exit, (stop_alive, c._should_exit)
+ assert 'stopped waiting' in stop_out and 'keeps running in the gateway' in stop_out, stop_out
+ # answered while the stopped handler was still blocked in the gateway
+ assert handler_held, 'the handler finished before the requests were answered'
+ assert isinstance(outcomes.get('submit'), dict), outcomes
+ assert outcomes['submit']['status'] in {'queued', 'started'}, outcomes
+ assert isinstance(outcomes.get('read'), dict) and outcomes['read']['status'] == 'started', outcomes
+ assert isinstance(outcomes.get('interrupt'), dict), outcomes
+ assert after[0] is True and 'QUICK_DONE' in after[1] and 'SLOW_DONE' not in after[1], after
+ assert pending == {}, pending
+
+
+def test_a_gateway_hang_up_during_a_plugin_command_ends_the_wait_and_leaves_nothing_pending(
+ tmp_path, monkeypatch, capsys):
+ """The gateway dies while the handler runs: the wait ends with the transport's error (the command
+ is not sent again), and no command socket, thread or pending request is left."""
+ _gate, marks, source = _slow_source(tmp_path)
+ with _plugin_home(tmp_path, source) as (root, home, env):
+ c, conn = _cli(monkeypatch, home)
+ try:
+ with daemon(root, home, env, barrier=True, fixture='plugin_mcp_daemon.py') as (proc, _desc):
+ c._ensure_gateway_session()
+ from hermes_cli import gateway_plugin_commands
+ assert 'ppslow' in (gateway_plugin_commands.names(c) or {})
+ capsys.readouterr()
+ waiting = _typed_in_thread(c, '/ppslow hangup')
+ wait_until(lambda: (marks / 'started-hangup').exists(), timeout=30, what='the handler to start')
+ proc.kill()
+ proc.wait(timeout=20)
+ waiting.join(60)
+ out, alive = capsys.readouterr().out, waiting.is_alive()
+ wait_until(lambda: not _command_threads(), timeout=30, what='the command socket to close')
+ pending = dict(conn.client.pending) if conn.client is not None else {}
+ finally:
+ conn.close()
+ assert not alive, 'the wait outlived the gateway'
+ assert '/ppslow: Gateway disconnected' in out and 'stopped waiting' not in out, out
+ assert out.count('/ppslow') == 1 and 'SLOW_DONE' not in out, out
+ wait = getattr(c, '_plugin_command_wait', None)
+ assert wait is None and pending == {}, (wait, pending)
diff --git a/tests/hermes_cli/test_gateway_connection_command_socket.py b/tests/hermes_cli/test_gateway_connection_command_socket.py
new file mode 100644
index 00000000000..f21a342ee5b
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_connection_command_socket.py
@@ -0,0 +1,111 @@
+"""``GatewayConnection.call_until`` sends its one request on a socket of its own (#134889 PLG-7): never
+on the viewer's socket, never twice, and the socket is closed on the reply, on Ctrl+C (``wake``), on
+``close()`` (CLI exit) and when the dial fails."""
+import asyncio
+from contextlib import asynccontextmanager
+import threading
+
+import pytest
+
+from hermes_cli.gateway_client import GatewayClientError
+from hermes_cli.gateway_connection import CallStopped, GatewayConnection
+
+
+class _Client:
+ def __init__(self, hold, sent):
+ self.events = asyncio.Queue()
+ self.calls, self.closed, self.hold, self.sent = [], False, hold, sent
+
+ async def rpc(self, method, *, _timeout=None, **params):
+ self.calls.append((method, params, _timeout))
+ self.sent.set()
+ if self.hold:
+ await asyncio.Event().wait() # a handler that never returns; only a cancel ends it
+ return {'type': 'exec', 'output': 'done'}
+
+
+class _Gateway:
+ """Every dial gets a new client: the first is the viewer's, the next ones command sockets."""
+ def __init__(self, hold=False, refuse_commands=False):
+ self.clients, self.hold, self.refuse = [], hold, refuse_commands
+ self.command_sent = threading.Event()
+
+ @asynccontextmanager
+ async def dial(self):
+ if self.refuse and self.clients:
+ raise GatewayClientError('Gateway connection failed; no local fallback')
+ command = bool(self.clients)
+ client = _Client(self.hold and command, self.command_sent if command else threading.Event())
+ self.clients.append(client)
+ try:
+ yield client
+ finally:
+ client.closed = True
+
+
+def _threads():
+ return [t for t in threading.enumerate() if t.name == 'hermes-gateway-command']
+
+
+def _waiting(conn, wake):
+ """``call_until`` on a thread: ``(thread, outcome)``, the outcome filled when it returns."""
+ outcome = {}
+
+ def run():
+ try:
+ outcome['reply'] = conn.call_until('slash.exec', wake, session_id='s', command='slow')
+ except GatewayClientError as exc:
+ outcome['error'] = exc
+ thread = threading.Thread(target=run, daemon=True)
+ thread.start()
+ return thread, outcome
+
+
+def test_the_reply_comes_over_a_socket_of_its_own_that_then_closes():
+ gateway = _Gateway()
+ conn = GatewayConnection(connect=gateway.dial)
+ try:
+ reply = conn.call_until('slash.exec', threading.Event(), session_id='s', command='quick')
+ viewer, command = gateway.clients
+ assert reply == {'type': 'exec', 'output': 'done'}
+ assert viewer.calls == [] and not viewer.closed # the viewer's socket stays free and open
+ assert command.calls == [('slash.exec', {'session_id': 's', 'command': 'quick'}, float('inf'))]
+ assert command.closed and not _threads() and not conn._commands
+ finally:
+ conn.close()
+
+
[email protected]('stop', ['ctrl_c', 'close'])
+def test_a_stopped_wait_closes_the_command_socket_and_never_sends_again(stop):
+ gateway = _Gateway(hold=True)
+ conn = GatewayConnection(connect=gateway.dial)
+ conn.start(5)
+ wake = threading.Event()
+ thread, outcome = _waiting(conn, wake)
+ try:
+ assert gateway.command_sent.wait(10)
+ if stop == 'ctrl_c':
+ wake.set()
+ else: # CLI exit
+ conn.close()
+ thread.join(10)
+ finally:
+ conn.close()
+ assert not thread.is_alive()
+ assert isinstance(outcome.get('error'), CallStopped), outcome
+ viewer, command = gateway.clients
+ assert viewer.calls == [] and len(command.calls) == 1 and command.closed
+ assert not _threads() and not conn._commands
+
+
+def test_a_failed_command_dial_sends_nothing_and_is_not_retried():
+ gateway = _Gateway(refuse_commands=True)
+ conn = GatewayConnection(connect=gateway.dial)
+ try:
+ with pytest.raises(GatewayClientError, match='connection failed') as raised:
+ conn.call_until('slash.exec', threading.Event(), session_id='s', command='x')
+ assert not isinstance(raised.value, CallStopped)
+ assert len(gateway.clients) == 1 and gateway.clients[0].calls == []
+ assert not _threads() and not conn._commands
+ finally:
+ conn.close()
diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.md
index 290fc600b37..c11198d5792 100644
--- a/website/docs/user-guide/features/plugins.md
+++ b/website/docs/user-guide/features/plugins.md
@@ -127,7 +127,7 @@ A `/command` registered with `ctx.register_command()` runs in the gateway proces
- **Read the session's working directory with `agent.runtime_cwd.resolve_agent_cwd()`**, not `os.getcwd()`, which is the gateway's own directory. The gateway pins the session's directory while the handler runs.
- **Read session identity with `gateway.session_context.get_session_env("HERMES_SESSION_PLATFORM")`** (and the other `HERMES_SESSION_*` names, such as `HERMES_SESSION_ID` and `HERMES_SESSION_KEY`), not `os.environ`. These values are bound per session around the handler, so a background job the handler starts records the session as its parent.
-The classic CLI waits for the reply for as long as the handler runs. Ctrl+C stops the wait, not the handler: the handler finishes in the gateway, its reply is not shown, and the CLI's next gateway request waits until the handler returns.
+The classic CLI waits for the reply for as long as the handler runs. Ctrl+C stops the wait, not the handler: the handler finishes in the gateway and its reply is not shown. The command runs over its own connection to the gateway, so the session's prompts, interrupts and other commands are not held up while it runs.
See [Register slash commands](../../developer-guide/plugins/index.md#register-slash-commands).
:::