The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): dispatch a plugin command again once a gateway reload dropped it
unsupportedpastels247ce9eedc76
diff --git a/cli.py b/cli.pyindex 087bb1873ba..fef3a45a7db 100644--- a/cli.py+++ b/cli.py@@ -1217,13 +1217,16 @@ class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin,plugin = gateway_plugin_commands.lookup(self, bare) # the gateway's; None off the gatewayexcept gateway_plugin_commands.CatalogUnavailable:return True # printed; an unreadable catalog never selects a skill, bundle or expansion+ gone = Falseif plugin or (plugin is None and bare in _get_plugin_cmd_handler_names()):- self._run_plugin_slash_command(base_cmd, user_args)- elif base_cmd in skill_bundles:+ gone = self._run_plugin_slash_command(base_cmd, user_args) is gateway_plugin_commands.GONE+ if not gone:+ return True+ if base_cmd in skill_bundles: # also a name a gateway plugin reload just dropped (GONE)self._run_skill_bundle_command(base_cmd, skill_bundles[base_cmd], user_args)elif base_cmd in skill_commands:self._run_skill_slash_command(base_cmd, skill_commands[base_cmd], user_args)- else:+ elif not (gone and gateway_plugin_commands.report_gone(bare, skill_commands, skill_bundles)):return self._expand_slash_prefix(cmd_original, cmd_lower, skill_commands, skill_bundles)return True@@ -1269,10 +1272,11 @@ class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin,self._console_print(f"[bold red]{_t('cli.quick.error', error=str(e))}[/]")return True- def _run_plugin_slash_command(self, base_cmd: str, user_args: str) -> None:+ def _run_plugin_slash_command(self, base_cmd: str, user_args: str):from hermes_cli import gateway_plugin_commands- if gateway_plugin_commands.run(self, base_cmd.lstrip("/"), user_args):- return # ran beside the plugin's hooks, tools and MCP servers in the gateway+ answered = gateway_plugin_commands.run(self, base_cmd.lstrip("/"), user_args)+ if answered:+ return answered # ran beside the plugin's hooks, tools and MCP servers in the gateway, or GONEfrom hermes_cli.plugins import get_plugin_command_handler, resolve_plugin_command_resultplugin_handler = get_plugin_command_handler(base_cmd.lstrip("/"))if not plugin_handler:diff --git a/hermes_cli/gateway_plugin_commands.py b/hermes_cli/gateway_plugin_commands.pyindex 380f79aa2d0..6057c9a61df 100644--- a/hermes_cli/gateway_plugin_commands.py+++ b/hermes_cli/gateway_plugin_commands.py@@ -5,16 +5,19 @@ live in the gateway, so its command runs there too (``gateway/session_commands.pgateway's own plugin dispatch): ``ctx.call_mcp`` reaches the servers the gateway connected, and thisprocess never imports the plugin to run it. The names come from the gateway's ``commands.catalog``,read once per session and gateway life (``/new``, resume and a redial read again) and again once when-a typed name misses, so a plugin the gateway enabled since still dispatches. A catalog whose-``plugin_discovery_error`` is set lists no plugins because the gateway could not load them, not-because there are none: it is treated as a failed read and never cached. Off the gateway (tests,-the TUI slash worker's shadow CLI) main's dispatch applies.+a typed name misses, so a plugin the gateway enabled since still dispatches; a cached name a plugin+reload dropped since is re-read once when the gateway refuses it, then dispatched again (:data:`GONE`).+A catalog whose ``plugin_discovery_error`` is set lists no plugins because the gateway could not load+them, not because there are none: it is treated as a failed read and never cached. Off the gateway+(tests, the TUI slash worker's shadow CLI) main's dispatch applies."""from __future__ import annotationsfrom 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."class CatalogUnavailable(Exception):@@ -94,22 +97,54 @@ def lookup(cli, name):def run(cli, name, arg):- """True when the gateway answered ``/name arg`` (the local handler must not run)."""+ """True when the gateway answered ``/name arg`` (the local handler must not run); :data:`GONE`+ when it no longer has that plugin command and a fresh catalog read agrees (a plugin reload, e.g.+ ``hermes plugins disable``, dropped it in this session and gateway life, which no cache boundary+ sees): nothing ran, and the caller dispatches the name again (bundle, skill, prefix)."""from hermes_cli.gateway_side import connection_forconnection = connection_for(cli)if connection is None:return Falsefrom cli import _cprint+ from hermes_cli.gateway_client import GatewayRPCErrortry:reply = connection.call("slash.exec", session_id=cli.session_id, command=name + (" " + arg if arg else ""))+ except GatewayRPCError as exc:+ if str(exc) != "unsupported_command":+ _cprint(f" /{name}: {exc}")+ return True+ reply = {"type": "unsupported"}except GatewayClientError as exc:_cprint(f" /{name}: {exc}")return Truereply = reply or {}- if reply.get("type", "exec") != "exec": # it lost the plugin since lookup: a skill/prompt reply- _cprint(f" /{name}: the gateway no longer has this plugin command; nothing was run.")+ if reply.get("type", "exec") != "exec": # it lost the plugin since lookup: a refusal or skill reply+ if _dropped(cli, connection, name):+ return GONE+ _cprint(_GONE_LINE.format(name))return Trueoutput = str(reply.get("output") or "")if output:_cprint(output)return True+++def _dropped(cli, connection, name):+ """Whether the gateway's catalog, read again with the cached copy dropped, no longer lists+ ``name`` (a failed read: not known, so False)."""+ cli._gateway_plugin_commands = None+ try:+ return name not in _read(cli, connection)+ except GatewayClientError:+ return False+++def report_gone(name, *known):+ """Print that ``/name`` is no longer a plugin command, unless one of the built-in commands or a+ ``known`` skill or bundle name starts with it (then prefix expansion decides); True when printed."""+ from hermes_cli.commands import COMMANDS+ if any(key.startswith("/" + name) for group in (COMMANDS, *known) for key in group):+ return False+ from cli import _cprint+ _cprint(_GONE_LINE.format(name))+ return Truediff --git a/tests/gateway/test_cli_plugin_command_in_gateway.py b/tests/gateway/test_cli_plugin_command_in_gateway.pyindex 6004f23fa14..3417da1c5eb 100644--- a/tests/gateway/test_cli_plugin_command_in_gateway.py+++ b/tests/gateway/test_cli_plugin_command_in_gateway.py@@ -107,11 +107,11 @@ class _Wire:return asyncio.run_coroutine_threadsafe(coro, self.loop).result(60)def call(self, method, **params):- from hermes_cli.gateway_client import GatewayClientError+ from hermes_cli.gateway_client import GatewayRPCErrorself.calls.append(method)reply = self._run(rpc(self.ws, method, **params))- if 'error' in reply:- raise GatewayClientError(str(reply['error'].get('message')))+ if 'error' in reply: # an owner refusal, as gateway_client raises it+ raise GatewayRPCError(str(reply['error'].get('message')), reply['error'].get('code'))return reply['result']def call_tagged(self, method, **params):@@ -248,3 +248,78 @@ def test_a_redial_to_a_restarted_gateway_and_slash_new_reread_the_plugin_commandassert c.session_id != first and conn.epoch == epoch_bassert new_calls == [('commands.catalog', None), ('slash.exec', c.session_id)], new_callsassert f'RAN_beta PID={b.pid}' in after_new, after_new+++# /pidprobe stays; /pptwin shares its name with a skill. ``TWIN`` is dropped to stop registering it.+_RELOADED = '''import os+++def register(ctx):+ ctx.register_command("pidprobe", lambda arg: "PIDPROBE PID=%d" % os.getpid(), description="Probe")+ TWIN+'''+_TWIN = 'ctx.register_command("pptwin", lambda arg: "PLUGIN_TWIN", description="Shadows a skill")'++[email protected]("linux")[email protected]("unload", ["disable", "stop_registering"])+def test_a_command_a_plugin_reload_removed_is_dispatched_again(tmp_path, monkeypatch, capsys, unload):+ """The open CLI cached the session's catalog; then the running gateway reloads its plugins (what+ ``hermes plugins disable`` asks for) without the command, in the same session and gateway life.+ The cached name gets ``unsupported_command`` from ``slash.exec`` once: the CLI re-reads the catalog+ and dispatches the name again, so a same-named skill runs, and a name nothing else matches gets+ the "no longer has this plugin command" line, never the raw code, on that try or a later one."""+ import cli as cli_mod+ from cli import HermesCLI+ from gateway.control_socket import reload_gateway_plugins+ _no_local_plugins(monkeypatch)+ ran_skill = []+ monkeypatch.setattr(cli_mod, '_ensure_skill_commands', lambda: {'/pptwin': {'name': 'pptwin'}})+ monkeypatch.setattr(cli_mod, 'get_skill_bundles', dict)+ monkeypatch.setattr(HermesCLI, '_run_skill_slash_command', lambda self, *a: ran_skill.append(a[0]))+ work = tmp_path / 'work'+ work.mkdir()+ with _plugin_home(tmp_path, _RELOADED.replace('TWIN', _TWIN)) as (root, home, env):+ with daemon(root, home, env, barrier=True, fixture='plugin_mcp_daemon.py') as (proc, desc):+ wire = _Wire(home, desc)+ try:+ sid = wire.call('session.create', request_id='plugin-reload', source='cli', toolsets=[],+ cwd=str(work))['session_id']+ monkeypatch.setattr('hermes_cli.gateway_side.connection_for', lambda _cli: wire)+ c = HermesCLI.__new__(HermesCLI)+ c.config, c.session_id = {}, sid++ def typed(text):+ del wire.calls[:]+ assert c._process_unregistered_slash(text, text) is True+ return capsys.readouterr().out, list(wire.calls)+ capsys.readouterr()+ before = typed('/pidprobe'), typed('/pptwin')+ if unload == 'disable':+ config = json.loads((home / 'config.yaml').read_text())+ config['plugins'].update(enabled=[], disabled=['probe-cmd'])+ (home / 'config.yaml').write_text(json.dumps(config))+ else:+ (home / 'plugins' / 'probe-cmd' / '__init__.py').write_text(_RELOADED.replace('TWIN', 'pass'))+ answer = reload_gateway_plugins(home)+ order = ('/pidprobe', '/pptwin', '/pidprobe') if unload == 'disable' else ('/pptwin', '/pidprobe', '/pptwin')+ after = [typed(text) for text in order]+ finally:+ wire.close()+ proc.send_signal(signal.SIGINT)+ proc.wait(timeout=20)+ assert f'PIDPROBE PID={proc.pid}' in before[0][0] and 'PLUGIN_TWIN' in before[1][0], before+ assert (answer or {}).get('reloaded') is True, answer+ assert not any('unsupported_command' in out for out, _ in after), after+ if unload == 'disable':+ # the cached /pidprobe: refused once, one re-read, the existing line; nothing else ran+ assert after[0][1] == ['slash.exec', 'commands.catalog'], after[0]+ assert 'no longer has this plugin command' in after[0][0] and 'PIDPROBE' not in after[0][0], after[0]+ # the re-read is the session's catalog now: the skill runs without asking the gateway to exec+ assert 'slash.exec' not in after[1][1] and 'slash.exec' not in after[2][1], after+ assert ran_skill == ['/pptwin'] and 'PIDPROBE' not in after[2][0], (ran_skill, after)+ else:+ # the cached /pptwin: refused once, one re-read, then the same-named skill runs+ assert after[0][1] == ['slash.exec', 'commands.catalog'] and ran_skill == ['/pptwin', '/pptwin'], after+ assert f'PIDPROBE PID={proc.pid}' in after[1][0], after # still the plugin's, in the gateway+ assert 'slash.exec' not in after[2][1] and 'PLUGIN_TWIN' not in after[2][0], afterdiff --git a/tests/hermes_cli/test_gateway_plugin_commands.py b/tests/hermes_cli/test_gateway_plugin_commands.pyindex 2b4c249ca3a..35efdf50b3e 100644--- a/tests/hermes_cli/test_gateway_plugin_commands.py+++ b/tests/hermes_cli/test_gateway_plugin_commands.py@@ -326,3 +326,51 @@ def test_completion_lists_the_gateways_plugin_commands(local_plugin_reads):found = {c.text: c.display_meta_text for c in completer.get_completions(Document("/mcp"), None)}assert any("mcp-status" in text for text in found)assert local_plugin_reads == []+++def _unloaded_since_the_cached_read(monkeypatch, name):+ """The CLI ran ``/name`` and cached the catalog; then a gateway plugin reload dropped it (same+ session, same gateway life), so ``slash.exec`` refuses it as the gateway does."""+ from hermes_cli.gateway_client import GatewayRPCError+ conn = _Conn({name: "Before the reload"})+ c = _cli(monkeypatch, conn)+ c._process_unregistered_slash(f"/{name}", f"/{name}")+ conn._plugins, conn._reply = {}, GatewayRPCError("unsupported_command")+ return conn, c+++def test_a_command_a_reload_unloaded_is_named_not_the_raw_refusal(monkeypatch, capsys, local_plugin_reads):+ conn, c = _unloaded_since_the_cached_read(monkeypatch, "gone-plugin")+ capsys.readouterr()+ assert c._process_unregistered_slash("/gone-plugin", "/gone-plugin") is True+ out = capsys.readouterr().out+ assert "no longer has this plugin command" in out and "unsupported_command" not in out, out+ assert _execs(conn) == ["gone-plugin"] * 2 and _catalog_reads(conn) == 2 # one re-read, no retry+ expanded = []+ monkeypatch.setattr(HermesCLI, "_expand_slash_prefix", lambda self, *a: expanded.append(a) or True)+ c._process_unregistered_slash("/gone-plugin", "/gone-plugin") # the cache is fresh: never sent+ assert _execs(conn) == ["gone-plugin"] * 2 and len(expanded) == 1 and local_plugin_reads == []+++def test_a_same_named_skill_runs_once_a_reload_unloaded_the_plugin_command(monkeypatch, capsys):+ conn, c = _unloaded_since_the_cached_read(monkeypatch, "pptwin")+ ran = []+ monkeypatch.setattr(cli_mod, "_ensure_skill_commands", lambda: {"/pptwin": {"name": "pptwin"}})+ monkeypatch.setattr(HermesCLI, "_run_skill_slash_command", lambda self, *a: ran.append(a[0]))+ capsys.readouterr()+ for _ in range(2):+ assert c._process_unregistered_slash("/pptwin", "/pptwin") is True+ assert ran == ["/pptwin", "/pptwin"] and "unsupported_command" not in capsys.readouterr().out+ assert _execs(conn) == ["pptwin"] * 2 # the first run and the one refusal; the skill follows+++def test_a_skill_reply_for_an_unloaded_plugin_command_runs_the_skill_here(monkeypatch, capsys):+ """The gateway answers the dropped name for its own same-named skill (``type: skill``): the+ re-read shows no plugin command, so the CLI's skill dispatch runs it, as for a refusal."""+ conn, c = _unloaded_since_the_cached_read(monkeypatch, "pptwin")+ conn._reply = {"type": "skill", "name": "pptwin", "message": "skill body"}+ ran = []+ monkeypatch.setattr(cli_mod, "_ensure_skill_commands", lambda: {"/pptwin": {"name": "pptwin"}})+ monkeypatch.setattr(HermesCLI, "_run_skill_slash_command", lambda self, *a: ran.append(a[0]))+ assert c._process_unregistered_slash("/pptwin", "/pptwin") is True+ assert ran == ["/pptwin"] and "nothing was run" not in capsys.readouterr().out