Skip to content

The agent that grows with you

fix(cli): run classic CLI plugin slash commands in the gateway

unsupportedpastelsb16cd8f66f1f
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 6cf4a26fa5f..06160544721 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -3765,6 +3765,8 @@ export interface CommandsCatalogResult {
skills?: Record<string, SkillCatalogEntry>
skill_count?: number
warning?: string
+ plugin_discovery_error?: string
+ plugin_commands?: Record<string, string>
}
export interface CommandCatalogMeta {
argument_mode?: ArgumentMode | null
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 55ea261ddd0..d072ff5dc4f 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -12026,6 +12026,18 @@
"default": "",
"title": "Warning",
"type": "string"
+ },
+ "plugin_discovery_error": {
+ "default": "",
+ "title": "Plugin Discovery Error",
+ "type": "string"
+ },
+ "plugin_commands": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "title": "Plugin Commands",
+ "type": "object"
}
},
"title": "CommandsCatalogResult",
diff --git a/cli.py b/cli.py
index e0f9be91bb5..087bb1873ba 100644
--- a/cli.py
+++ b/cli.py
@@ -1212,7 +1212,12 @@ class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin,
user_args = cmd_original[len(base_cmd):].strip()
if bare in quick_commands:
return self._run_quick_command(base_cmd, quick_commands[bare], user_args)
- if bare in _get_plugin_cmd_handler_names():
+ from hermes_cli import gateway_plugin_commands
+ try:
+ plugin = gateway_plugin_commands.lookup(self, bare) # the gateway's; None off the gateway
+ except gateway_plugin_commands.CatalogUnavailable:
+ return True # printed; an unreadable catalog never selects a skill, bundle or expansion
+ if 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:
self._run_skill_bundle_command(base_cmd, skill_bundles[base_cmd], user_args)
@@ -1265,8 +1270,10 @@ class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin,
return True
def _run_plugin_slash_command(self, base_cmd: str, user_args: str) -> None:
+ 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
from hermes_cli.plugins import get_plugin_command_handler, resolve_plugin_command_result
-
plugin_handler = get_plugin_command_handler(base_cmd.lstrip("/"))
if not plugin_handler:
return
diff --git a/gateway/run_inbound_hooks.py b/gateway/run_inbound_hooks.py
index 07ffb720407..5614ba5a124 100644
--- a/gateway/run_inbound_hooks.py
+++ b/gateway/run_inbound_hooks.py
@@ -243,23 +243,30 @@ class GatewayInboundHooksMixin:
from hermes_cli.plugins import get_plugin_command_handler
plugin_handler = get_plugin_command_handler(command.replace("_", "-"))
if plugin_handler:
- # The agent-turn path binds HERMES_SESSION_* via _set_session_env; this dispatch
- # sits before it, so a handler reading get_session_env() would see an empty or a
- # foreign (cron agent's os.environ) session (#108698). No session_entry exists yet,
- # so session_key is derived from source. Sync handlers run on the gateway pool
- # (contextvars carried), never the loop thread: blocking I/O there starves the
- # liveness watchdog and the process exits 75 mid-handler (#105279).
- _plugin_context = build_session_context(source, self.config)
- _plugin_context.session_key = self._session_key_for_source(source)
- user_args = event.get_command_args().strip()
- with self._session_env_scope(_plugin_context):
- if asyncio.iscoroutinefunction(plugin_handler):
- result = await plugin_handler(user_args)
- else:
- result = await self._run_in_executor_with_context(plugin_handler, user_args)
- if asyncio.iscoroutine(result):
- result = await result
- return True, str(result) if result else None, command
+ return True, await self._hm_run_plugin_handler(plugin_handler, event, source), command
except Exception as e:
logger.warning("Plugin command dispatch failed: %s", e, exc_info=True)
return False, None, command
+
+ async def _hm_run_plugin_handler(
+ self, plugin_handler, event: MessageEvent, source: SessionSource
+ ) -> Optional[str]:
+ """Run a resolved plugin command handler for *source* → its reply text or None; raises what
+ the handler raises (``gateway/session_commands.py`` resolves the exact registered name)."""
+ # The agent-turn path binds HERMES_SESSION_* via _set_session_env; this dispatch
+ # sits before it, so a handler reading get_session_env() would see an empty or a
+ # foreign (cron agent's os.environ) session (#108698). No session_entry exists yet,
+ # so session_key is derived from source. Sync handlers run on the gateway pool
+ # (contextvars carried), never the loop thread: blocking I/O there starves the
+ # liveness watchdog and the process exits 75 mid-handler (#105279).
+ _plugin_context = build_session_context(source, self.config)
+ _plugin_context.session_key = self._session_key_for_source(source)
+ user_args = event.get_command_args().strip()
+ with self._session_env_scope(_plugin_context):
+ if asyncio.iscoroutinefunction(plugin_handler):
+ result = await plugin_handler(user_args)
+ else:
+ result = await self._run_in_executor_with_context(plugin_handler, user_args)
+ if asyncio.iscoroutine(result):
+ result = await result
+ return str(result) if result else None
diff --git a/gateway/session_commands.py b/gateway/session_commands.py
index e5e24a02d90..d1a3277b21b 100644
--- a/gateway/session_commands.py
+++ b/gateway/session_commands.py
@@ -5,12 +5,15 @@ Executing those here would double-submit and bypass their retry identity.
"""
import asyncio
from contextlib import contextmanager
+import logging
import os
from pathlib import Path
import shlex
from hermes_state_runtime import RuntimeStoreError
+logger = logging.getLogger(__name__)
+
# Reviewed gateway handlers only: listing a command is not permission to run it. Each read was
# run through its real handler against a local session (website/docs/developer-guide/
@@ -123,14 +126,16 @@ def _resolve_alias(name, arg):
def _runner_command(name):
- """``('exec', shell)`` for a ``type: exec`` quick command, ``('plugin', None)`` for a plugin
- slash command, else None (read in the owning profile's scope)."""
+ """``('exec', shell)`` for a ``type: exec`` quick command, ``('plugin', registered)`` for a plugin
+ slash command, else None (read in the owning profile's scope). The exact registered name wins over
+ Telegram's ``_`` -> ``-`` form, as main's CLI looked it up: ``foo_bar`` is its own command."""
from gateway.run import _load_gateway_config
from hermes_cli.plugins import get_plugin_command_handler
entry = (_load_gateway_config().get('quick_commands') or {}).get(name)
if isinstance(entry, dict) and entry.get('type') == 'exec':
return 'exec', str(entry.get('command') or '')
- return ('plugin', None) if get_plugin_command_handler(name.replace('_', '-')) else None
+ return next((('plugin', registered) for registered in dict.fromkeys((name, name.replace('_', '-')))
+ if get_plugin_command_handler(registered)), None)
async def _run_runner_command(runner, live, name, arg, kind, shell):
@@ -153,10 +158,18 @@ async def _run_runner_command(runner, live, name, arg, kind, shell):
raise RuntimeStoreError('cwd_unavailable')
return await runner._hm_run_exec_quick_command(name, shell, cwd=cwd)
# Plugin-only: the runner's quick commands are the launch profile's under multiplex, and this
- # session's own were already resolved above in its profile (``_resolve_alias``/``_runner_command``).
+ # session's own were already resolved above in its profile (``_resolve_alias``/``_runner_command``),
+ # so is the registered name (``shell``) the handler is looked up by.
+ from hermes_cli.plugins import get_plugin_command_handler
+ handler = get_plugin_command_handler(shell)
+ if handler is None:
+ raise RuntimeStoreError('unsupported_command')
event = MessageEvent(text='/' + name + (' ' + arg if arg else ''), source=live.source)
- _handled, output, _command = await runner._hm_dispatch_plugin_command(event, live.source, name)
- return output
+ try:
+ return await runner._hm_run_plugin_handler(handler, event, live.source)
+ except Exception as e: # main's CLI printed it; messaging (run_inbound_hooks) still only logs it
+ logger.warning("Plugin command dispatch failed: %s", e, exc_info=True)
+ return t('cli.plugin.command_error', error=str(e) or type(e).__name__)
def _skill_directive(name, arg, route):
diff --git a/hermes_cli/cli_tui_mixin.py b/hermes_cli/cli_tui_mixin.py
index 83fd1f6f8eb..169d1790b5e 100644
--- a/hermes_cli/cli_tui_mixin.py
+++ b/hermes_cli/cli_tui_mixin.py
@@ -2212,6 +2212,7 @@ class CLITuiMixin:
from cli import _estimate_tui_input_height, get_skill_bundles, get_skill_commands
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.completion import ThreadedCompleter
+ from hermes_cli import gateway_plugin_commands
cli_ref = self
def get_prompt():
@@ -2220,7 +2221,7 @@ class CLITuiMixin:
_completer = SlashCommandCompleter(
skill_commands_provider=lambda: get_skill_commands(),
command_filter=cli_ref._command_available,
- skill_bundles_provider=lambda: get_skill_bundles())
+ skill_bundles_provider=lambda: get_skill_bundles(), plugin_commands_provider=lambda: gateway_plugin_commands.names(cli_ref))
input_area = TextArea(
height=Dimension(min=1, max=8, preferred=1),
prompt=get_prompt,
@@ -2229,10 +2230,9 @@ class CLITuiMixin:
wrap_lines=True,
read_only=Condition(lambda: bool(cli_ref._command_blocks_input)),
history=FileHistory(str(self._history_file)),
- # The completer does blocking work (fuzzy @-file indexing shells out to rg/fd with a
- # 2s timeout; path completion hits os.listdir/stat), so complete_while_typing inline
- # would stall the render loop per keystroke (WSL2/slow FS). ThreadedCompleter moves
- # it off the UI event loop.
+ # The completer does blocking work (fuzzy @-file indexing shells out to rg/fd with a 2s timeout;
+ # path completion hits os.listdir/stat), so complete_while_typing inline would stall the render
+ # loop per keystroke (WSL2/slow FS). ThreadedCompleter moves it off the UI event loop.
completer=ThreadedCompleter(_completer),
complete_while_typing=True,
auto_suggest=SlashCommandAutoSuggest(history_suggest=AutoSuggestFromHistory(), completer=_completer),
diff --git a/hermes_cli/commands_completion.py b/hermes_cli/commands_completion.py
index 9d28d4a8fc9..09bb5ab9e90 100644
--- a/hermes_cli/commands_completion.py
+++ b/hermes_cli/commands_completion.py
@@ -5,6 +5,7 @@ prompt_toolkit-free for the gateway."""
from __future__ import annotations
import functools
+import logging
import os
import shutil
import subprocess
@@ -272,8 +273,10 @@ class SlashCommandCompleter(Completer):
self,
skill_commands_provider: Callable[[], Mapping[str, dict[str, Any]]] | None = None,
command_filter: Callable[[str], bool] | None = None,
- skill_bundles_provider: Callable[[], Mapping[str, dict[str, Any]]] | None = None) -> None:
+ skill_bundles_provider: Callable[[], Mapping[str, dict[str, Any]]] | None = None,
+ plugin_commands_provider: Callable[[], Mapping[str, str] | None] | None = None) -> None:
self._skill_commands_provider = skill_commands_provider
+ self._plugin_commands_provider = plugin_commands_provider
self._command_filter = command_filter
self._skill_bundles_provider = skill_bundles_provider
# Cached project file list for fuzzy @ completions
@@ -456,14 +459,22 @@ class SlashCommandCompleter(Completer):
for cmd, info in self._iter_skill_commands().items():
if cmd[1:].startswith(word):
yield _cmd_completion(cmd[1:], f"⚡ {info.get('description', 'Skill command')}")
+ for cmd_name, desc in self._plugin_commands().items():
+ if cmd_name.startswith(word):
+ yield _cmd_completion(cmd_name, f"🔌 {desc or 'Plugin command'}")
+
+ def _plugin_commands(self) -> Mapping[str, str]:
+ """``{name: description}``: the provider's (the classic CLI asks its gateway), else, when it
+ has none (None), this process's plugin registry."""
try:
- from hermes_cli.plugins import get_plugin_commands
- for cmd_name, cmd_info in get_plugin_commands().items():
- if cmd_name.startswith(word):
- yield _cmd_completion(
- cmd_name, f"🔌 {cmd_info.get('description', 'Plugin command')}")
- except Exception:
- pass
+ found = self._plugin_commands_provider() if self._plugin_commands_provider else None
+ if found is None:
+ from hermes_cli.plugins import get_plugin_commands
+ found = {name: info.get("description", "") for name, info in get_plugin_commands().items()}
+ return found
+ except Exception: # a plugin's registry or the gateway call must never break typing
+ logging.getLogger(__name__).debug("plugin command completion unavailable", exc_info=True)
+ return {}
class SlashCommandAutoSuggest(AutoSuggest):
diff --git a/hermes_cli/gateway_plugin_commands.py b/hermes_cli/gateway_plugin_commands.py
new file mode 100644
index 00000000000..380f79aa2d0
--- /dev/null
+++ b/hermes_cli/gateway_plugin_commands.py
@@ -0,0 +1,115 @@
+"""Plugin slash commands of the classic CLI on the shared gateway (``slash.exec``).
+
+On main a plugin's ``/command`` ran in this process. Rewired, the plugin's hooks, tools and MCP servers
+live in the gateway, so its command runs there too (``gateway/session_commands.py``, the messaging
+gateway's own plugin dispatch): ``ctx.call_mcp`` reaches the servers the gateway connected, and this
+process 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.
+"""
+from __future__ import annotations
+
+from hermes_cli.gateway_client import GatewayClientError
+
+_CATEGORY = "Plugin commands" # tui_gateway/command_discovery.py
+
+
+class CatalogUnavailable(Exception):
+ """The gateway's command list could not be read (already printed): run nothing for this input."""
+
+
+def _boundary(cli, connection):
+ return connection, getattr(connection, "epoch", None), getattr(cli, "session_id", None)
+
+
+def _read(cli, connection):
+ """Fetch the catalog's plugin commands and cache them for the session and gateway life that served
+ them (raises GatewayClientError, also when the gateway reports its plugin discovery failed). The
+ result is published only if neither moved during the call: a reply from epoch E that arrives after
+ a concurrent redial is never relabelled E+1 (``call_tagged``)."""
+ session = getattr(cli, "session_id", None)
+ catalog, epoch = connection.call_tagged("commands.catalog")
+ catalog = catalog or {}
+ if catalog.get("plugin_discovery_error"): # absent on older gateways: today's behaviour
+ raise GatewayClientError(f"plugin command discovery failed: {catalog['plugin_discovery_error']}")
+ listed = catalog.get("plugin_commands")
+ if isinstance(listed, dict): # every plugin command, also one a display row (Ink's /logs) hides
+ found = {str(name).lstrip("/"): str(desc or "") for name, desc in listed.items()}
+ else: # older gateways: the display category
+ found = {}
+ for category in catalog.get("categories") or []:
+ if isinstance(category, dict) and category.get("name") == _CATEGORY:
+ for row in category.get("pairs") or []:
+ if isinstance(row, (list, tuple)) and len(row) == 2 and isinstance(row[0], str):
+ found[row[0].lstrip("/")] = str(row[1] or "")
+ served = (connection, epoch, session)
+ if _boundary(cli, connection) == served:
+ cli._gateway_plugin_commands = (served, found)
+ return found
+
+
+def _cached(cli, connection):
+ if getattr(connection, "closed", False): # hung up: the next call redials, maybe to another life
+ return None
+ boundary, found = getattr(cli, "_gateway_plugin_commands", None) or (None, None)
+ return found if boundary == _boundary(cli, connection) else None
+
+
+def names(cli):
+ """``{name: description}`` of the gateway's plugin commands for completion, or None off the
+ gateway. A failed read degrades quietly to none; dispatch uses :func:`lookup`."""
+ from hermes_cli.gateway_side import connection_for
+ connection = connection_for(cli)
+ if connection is None:
+ return None
+ found = _cached(cli, connection)
+ if found is None:
+ try:
+ found = _read(cli, connection)
+ except GatewayClientError:
+ return {} # not cached: the next read asks again
+ return found
+
+
+def lookup(cli, name):
+ """Whether ``/name`` is one of the gateway's plugin commands; None off the gateway. A name the
+ cached list lacks re-reads it once. A failed read is not evidence the name is no plugin: it is
+ printed and :class:`CatalogUnavailable` raised, so no skill, bundle or expansion stands in."""
+ from hermes_cli.gateway_side import connection_for
+ connection = connection_for(cli)
+ if connection is None:
+ return None
+ found = _cached(cli, connection)
+ if found is not None and name in found:
+ return True
+ try:
+ return name in _read(cli, connection)
+ except GatewayClientError as exc:
+ from cli import _cprint
+ _cprint(f" /{name}: the gateway's command list is unavailable ({exc}); nothing was run.")
+ raise CatalogUnavailable(name) from exc
+
+
+def run(cli, name, arg):
+ """True when the gateway answered ``/name arg`` (the local handler must not run)."""
+ from hermes_cli.gateway_side import connection_for
+ connection = connection_for(cli)
+ if connection is None:
+ return False
+ from cli import _cprint
+ try:
+ reply = connection.call("slash.exec", session_id=cli.session_id, command=name + (" " + arg if arg else ""))
+ except GatewayClientError as exc:
+ _cprint(f" /{name}: {exc}")
+ return True
+ reply = 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.")
+ return True
+ output = str(reply.get("output") or "")
+ if output:
+ _cprint(output)
+ return True
diff --git a/tests/gateway/fixtures/plugin_mcp_daemon.py b/tests/gateway/fixtures/plugin_mcp_daemon.py
new file mode 100644
index 00000000000..7524c29206f
--- /dev/null
+++ b/tests/gateway/fixtures/plugin_mcp_daemon.py
@@ -0,0 +1,31 @@
+"""Test-only: the ordinary daemon with a fake MCP server in its own registry (no MCP SDK, no network).
+
+``probe-mcp`` answers every tool with the call and the pid of the process holding the registry, so a
+test sees that a plugin's ``ctx.call_mcp`` reached THIS gateway's MCP registry.
+"""
+import asyncio
+import json
+import os
+import runpy
+from types import SimpleNamespace
+
+from tools import mcp_tool
+from tools.mcp_tool_loop import _ensure_mcp_loop
+
+
+class _Session:
+ async def call_tool(self, name, arguments=None):
+ text = json.dumps({'tool': name, 'arguments': arguments, 'registry_pid': os.getpid()})
+ return SimpleNamespace(is_error=False, content=[SimpleNamespace(type='text', text=text)],
+ structured_content=None, meta=None)
+
+
+class _Server:
+ def __init__(self):
+ self.session = _Session()
+ self._rpc_lock = asyncio.Lock()
+
+
+_ensure_mcp_loop()
+mcp_tool._servers['probe-mcp'] = _Server()
+runpy.run_module('gateway.run', run_name='__main__')
diff --git a/tests/gateway/test_cli_plugin_command_in_gateway.py b/tests/gateway/test_cli_plugin_command_in_gateway.py
new file mode 100644
index 00000000000..6004f23fa14
--- /dev/null
+++ b/tests/gateway/test_cli_plugin_command_in_gateway.py
@@ -0,0 +1,250 @@
+"""A classic CLI plugin command runs in the gateway and its ``ctx.call_mcp`` reaches the gateway's MCP
+registry (#134889 CLI-13, PLG-7).
+
+A real daemon (``gateway.run``) loads a user plugin whose ``/probe-mcp-status`` calls ``probe-mcp``, a
+fake server in the daemon's own MCP registry (tests/gateway/fixtures/plugin_mcp_daemon.py). The CLI's
+dispatch reads the daemon's ``commands.catalog`` and sends ``slash.exec`` over its websocket, so the
+command goes through ``gateway/session_commands.py`` -> ``_hm_run_plugin_handler``.
+"""
+import asyncio
+from contextlib import asynccontextmanager, contextmanager
+import json
+import os
+from http.server import ThreadingHTTPServer
+from pathlib import Path
+import signal
+import threading
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon, rpc, websocket
+from tests.waiting import wait_until
+
+_PLUGIN = '''import json
+import os
+
+
+def register(ctx):
+ def status(arg):
+ reply = ctx.call_mcp("probe-mcp", "echo", {"text": arg})
+ return "PLUGIN_PID=%d MCP=%s" % (os.getpid(), json.dumps(reply, default=str))
+ ctx.register_command("probe-mcp-status", status, description="Ask the fake MCP server")
+ ctx.register_command("probe_under", lambda arg: "EXACT_UNDERSCORE", description="Exact name")
+ ctx.register_command("probe-under", lambda arg: "HYPHEN_ALIAS", description="Telegram alias form")
+ ctx.register_command("probe_only", lambda arg: "UNDERSCORE_ONLY", description="No hyphen twin")
+
+ def boom(arg):
+ raise RuntimeError("probe handler exploded")
+ ctx.register_command("probe-boom", boom, description="Always fails")
+'''
+# One command per gateway life: A serves /alpha, the restarted B only /beta.
+_LIFE = '''import os
+
+
+def register(ctx):
+ ctx.register_command("NAME", lambda arg: "RAN_NAME PID=%d" % os.getpid(), description="NAME")
+'''
+
+
+@contextmanager
+def _plugin_home(tmp_path, source):
+ """``(root, home, env)``: a profile home with plugin ``probe-cmd`` and a loopback model."""
+ root = Path(__file__).resolve().parents[2]
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ plugin = home / 'plugins' / 'probe-cmd'
+ plugin.mkdir(parents=True)
+ (plugin / 'plugin.yaml').write_text("name: probe-cmd\nversion: '1.0'\n")
+ (plugin / '__init__.py').write_text(source)
+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)
+ peer.requests = []
+ peer.blocked, peer.release = threading.Event(), threading.Event()
+ thread = threading.Thread(target=peer.serve_forever, daemon=True)
+ thread.start()
+ url = f'http://127.0.0.1:{peer.server_port}/v1'
+ (home / 'config.yaml').write_text(json.dumps({
+ 'gateway': {'multiplex_profiles': False},
+ 'model': {'provider': 'custom', 'default': 'plugin-model', 'base_url': url},
+ 'auxiliary': {'title_generation': {'enabled': False}}, 'platform_toolsets': {'cli': []},
+ 'plugins': {'enabled': ['probe-cmd'], 'entries': {'probe-cmd': {'mcp_allowlist': ['probe-mcp']}}},
+ }))
+ env = child_env()
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1',
+ PYTHONDONTWRITEBYTECODE='1')
+ try:
+ yield root, home, env
+ finally:
+ peer.shutdown()
+ peer.server_close()
+ thread.join(timeout=5)
+
+
+def _no_local_plugins(monkeypatch):
+ def no_local_plugin(*_a, **_k):
+ pytest.fail('the CLI process loaded or ran plugin code')
+ for name in ('get_plugin_command_handler', 'discover_plugins', 'get_plugin_commands'):
+ monkeypatch.setattr(f'hermes_cli.plugins.{name}', no_local_plugin)
+
+
+class _Wire:
+ """The CLI connection's ``call`` over the daemon's real websocket, on one loop thread."""
+ closed = final = False
+ epoch = 1
+
+ def __init__(self, home, desc):
+ self.loop = asyncio.new_event_loop()
+ self.thread = threading.Thread(target=self.loop.run_forever, daemon=True)
+ self.thread.start()
+ self.calls = []
+
+ async def _open():
+ return await websocket(home, desc)
+ self.ws = self._run(_open())
+
+ def _run(self, coro):
+ return asyncio.run_coroutine_threadsafe(coro, self.loop).result(60)
+
+ def call(self, method, **params):
+ from hermes_cli.gateway_client import GatewayClientError
+ self.calls.append(method)
+ reply = self._run(rpc(self.ws, method, **params))
+ if 'error' in reply:
+ raise GatewayClientError(str(reply['error'].get('message')))
+ return reply['result']
+
+ def call_tagged(self, method, **params):
+ return self.call(method, **params), self.epoch
+
+ def close(self):
+ self._run(self.ws.close())
+ self.loop.call_soon_threadsafe(self.loop.stop)
+ self.thread.join(timeout=5)
+
+
+def test_cli_plugin_command_runs_in_the_gateway_and_reaches_its_mcp_registry(tmp_path, monkeypatch, capsys):
+ import cli as cli_mod
+ from cli import HermesCLI
+ _no_local_plugins(monkeypatch)
+ monkeypatch.setattr(cli_mod, '_ensure_skill_commands', dict)
+ monkeypatch.setattr(cli_mod, 'get_skill_bundles', dict)
+ work = tmp_path / 'work'
+ work.mkdir()
+ with _plugin_home(tmp_path, _PLUGIN) 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-cli', 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
+ capsys.readouterr()
+ assert c._process_unregistered_slash('/probe-mcp-status Deep Check',
+ '/probe-mcp-status deep check') is True
+ out = capsys.readouterr().out
+ calls = list(wire.calls)
+ typed_outs = {}
+ for typed in ('/probe_under', '/probe_only', '/probe-boom'):
+ assert c._process_unregistered_slash(typed, typed) is True
+ typed_outs[typed] = capsys.readouterr().out
+ finally:
+ wire.close()
+ proc.send_signal(signal.SIGINT)
+ proc.wait(timeout=20)
+ assert calls[-2:] == ['commands.catalog', 'slash.exec'], calls
+ assert 'EXACT_UNDERSCORE' in typed_outs['/probe_under'], typed_outs
+ assert 'UNDERSCORE_ONLY' in typed_outs['/probe_only'], typed_outs
+ # main's local path printed a failing handler's error; the gateway path must not swallow it
+ assert 'Plugin command error: probe handler exploded' in typed_outs['/probe-boom'], typed_outs
+ assert proc.pid != os.getpid()
+ assert f'PLUGIN_PID={proc.pid} ' in out, out # the handler ran in the gateway process
+ mcp = json.loads(json.loads(out.split('MCP=', 1)[1].strip())['result'])
+ assert mcp == {'tool': 'echo', 'arguments': {'text': 'Deep Check'}, 'registry_pid': proc.pid}, out
+
+
+def _dial_running(home):
+ """The production dial pinned to an owner already running (``connect_gateway(endpoint)``), so a
+ redial while none is up fails instead of starting one the test does not own."""
+ from hermes_cli.gateway_client import GatewayClientError, connect_gateway
+ from hermes_cli.gateway_runtime import discover_gateway_endpoint
+
+ @asynccontextmanager
+ async def dial():
+ found = await asyncio.to_thread(discover_gateway_endpoint, home)
+ if found.state != 'ready' or found.endpoint is None:
+ raise GatewayClientError(f'no gateway is serving this home ({found.state})')
+ async with connect_gateway(found.endpoint) as client:
+ yield client
+ return dial
+
+
+def test_a_redial_to_a_restarted_gateway_and_slash_new_reread_the_plugin_commands(tmp_path, monkeypatch, capsys):
+ """The classic CLI's own GatewayConnection and GatewaySessionStore across a real owner restart:
+ gateway A serves /alpha, B (same home and socket) only /beta. A cached /alpha never runs: while no
+ gateway answers it is a named refusal (no same-named skill stands in), on B it is no plugin
+ command. /new through the gateway session store re-reads B's catalog for the new session."""
+ 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)
+ skills, ran_skill = {'/alpha': {'name': 'alpha'}}, []
+ monkeypatch.setattr(cli_mod, '_ensure_skill_commands', lambda: dict(skills))
+ monkeypatch.setattr(cli_mod, 'get_skill_bundles', dict)
+ monkeypatch.setattr(HermesCLI, '_run_skill_slash_command', lambda self, *a: ran_skill.append(a[0]))
+ with _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
+
+ def spy(method, **params):
+ sent.append((method, params.get('session_id')))
+ return real(method, **params)
+ monkeypatch.setattr(conn, 'call_tagged', spy)
+ c = HermesCLI()
+ c.agent, c._session_db, c._gateway_session_open = None, GatewaySessionStore(conn), False
+
+ def typed(text):
+ del sent[:]
+ assert c._process_unregistered_slash(text, text) is True
+ return capsys.readouterr().out, [m for m, _ in sent]
+ try:
+ with daemon(root, home, env, barrier=True, fixture='plugin_mcp_daemon.py') as (a, _desc):
+ c._ensure_gateway_session() # the CLI's startup session.create on A
+ first = c.session_id
+ capsys.readouterr()
+ on_a = typed('/alpha')
+ a.send_signal(signal.SIGINT)
+ a.wait(timeout=20)
+ wait_until(lambda: conn.closed, timeout=20, what='the CLI connection to see gateway A hang up')
+ gone = typed('/alpha')
+ (home / 'plugins' / 'probe-cmd' / '__init__.py').write_text(_LIFE.replace('NAME', 'beta'))
+ skills.clear()
+ with daemon(root, home, env, barrier=False) as (b, _desc):
+ on_b = typed('/beta')
+ epoch_b = conn.epoch
+ stale = typed('/alpha')
+ c.new_session(silent=True)
+ capsys.readouterr()
+ del sent[:]
+ assert c._process_unregistered_slash('/beta', '/beta') is True
+ after_new, new_calls = capsys.readouterr().out, list(sent)
+ b.send_signal(signal.SIGINT)
+ b.wait(timeout=20)
+ finally:
+ conn.close()
+ assert on_a[1] == ['commands.catalog', 'slash.exec'] and f'RAN_alpha PID={a.pid}' in on_a[0], on_a
+ # A hung up and nothing serves the home: the cached /alpha is not sent and the skill does not run
+ assert 'slash.exec' not in gone[1] and "command list is unavailable" in gone[0], gone
+ assert 'nothing was run' in gone[0] and ran_skill == [], (gone, ran_skill)
+ assert epoch_b == 2 and on_b[1] == ['commands.catalog', 'slash.exec'], (epoch_b, on_b)
+ assert f'RAN_beta PID={b.pid}' in on_b[0] and b.pid != a.pid, on_b
+ # B's catalog has no /alpha: one refresh on the miss, never a slash.exec, no plugin output
+ assert stale[1] == ['commands.catalog'] and 'RAN_alpha' not in stale[0], stale
+ assert c.session_id != first and conn.epoch == epoch_b
+ assert new_calls == [('commands.catalog', None), ('slash.exec', c.session_id)], new_calls
+ assert f'RAN_beta PID={b.pid}' in after_new, after_new
diff --git a/tests/hermes_cli/test_gateway_plugin_commands.py b/tests/hermes_cli/test_gateway_plugin_commands.py
new file mode 100644
index 00000000000..2b4c249ca3a
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_plugin_commands.py
@@ -0,0 +1,328 @@
+"""Plugin slash commands typed in the classic CLI run in the gateway (#134889 PLG-7, CLI-13).
+
+The plugin's hooks, tools and MCP servers live in the gateway, so its slash command runs there too
+(``slash.exec``) and ``ctx.call_mcp`` reaches the connected servers. The CLI learns the command names
+from the gateway's ``commands.catalog``: no plugin code is imported or executed in the CLI process.
+"""
+import pytest
+
+import cli as cli_mod
+from cli import HermesCLI
+from hermes_cli.commands_completion import SlashCommandCompleter
+from hermes_cli.gateway_client import GatewayClientError
+
+
+class _Conn:
+ closed = False
+ final = False
+ epoch = 1
+
+ def __init__(self, plugins, reply=None, catalog_error=None):
+ self.calls = []
+ self._plugins = plugins
+ self._reply = reply or {"type": "exec", "output": "mcp says hi"}
+ self.catalog_error = catalog_error
+ self.extra = {} # merged into the catalog reply (e.g. plugin_discovery_error)
+ self.after_catalog = None # runs once the reply exists, before the caller sees it
+
+ def call(self, method, **params):
+ 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)
+ self.closed, self.epoch = False, self.epoch + 1
+ epoch = self.epoch # the socket that carried this request
+ if method == "commands.catalog":
+ if self.catalog_error is not None:
+ raise self.catalog_error
+ rows = [["/" + name, desc] for name, desc in self._plugins.items()]
+ reply = {"pairs": [["/help", "Show help"], *rows],
+ "categories": [{"name": "Session", "pairs": [["/help", "Show help"]]},
+ {"name": "Plugin commands", "pairs": rows}], **self.extra}
+ hook, self.after_catalog = self.after_catalog, None
+ if hook:
+ hook()
+ return reply, epoch
+ if isinstance(self._reply, Exception):
+ raise self._reply
+ return self._reply, epoch
+
+
+def local_plugin_reads(monkeypatch):
+ """Every way the CLI process could load or run plugin code; each records the call."""
+ reads = []
+
+ def recorder(name):
+ def read(*_a, **_k):
+ reads.append(name)
+ return {} if name == "get_plugin_commands" else None
+ return read
+ for name in ("get_plugin_commands", "get_plugin_command_handler", "discover_plugins"):
+ monkeypatch.setattr(f"hermes_cli.plugins.{name}", recorder(name))
+ return reads
+
+
+def _cli(monkeypatch, conn):
+ monkeypatch.setattr("hermes_cli.gateway_side.connection_for", lambda cli: conn)
+ monkeypatch.setattr(cli_mod, "_ensure_skill_commands", dict)
+ monkeypatch.setattr(cli_mod, "get_skill_bundles", dict)
+ c = HermesCLI.__new__(HermesCLI)
+ c.config = {}
+ c.session_id = "local-s"
+ return c
+
+
+def test_plugin_command_runs_in_the_gateway(monkeypatch, capsys, local_plugin_reads):
+ conn = _Conn({"mcp-status": "Ask the MCP server"})
+ c = _cli(monkeypatch, conn)
+ assert c._process_unregistered_slash("/mcp-status Deep Check", "/mcp-status deep check") is True
+ assert ("slash.exec", {"session_id": "local-s", "command": "mcp-status Deep Check"}) in conn.calls
+ assert "mcp says hi" in capsys.readouterr().out
+ assert local_plugin_reads == []
+
+
+def test_gateway_refusal_is_printed_not_run_locally(monkeypatch, capsys, local_plugin_reads):
+ conn = _Conn({"mcp-status": "Ask the MCP server"}, reply=GatewayClientError("permission_denied"))
+ c = _cli(monkeypatch, conn)
+ assert c._process_unregistered_slash("/mcp-status", "/mcp-status") is True
+ assert "permission_denied" in capsys.readouterr().out
+ assert local_plugin_reads == []
+
+
+def test_non_plugin_command_falls_through_without_loading_plugins(monkeypatch, local_plugin_reads):
+ conn = _Conn({"mcp-status": "Ask the MCP server"})
+ c = _cli(monkeypatch, conn)
+ expanded = []
+ monkeypatch.setattr(HermesCLI, "_expand_slash_prefix", lambda self, *a: expanded.append(a) or True)
+ assert c._process_unregistered_slash("/zzz", "/zzz") is True
+ assert expanded and not any(method == "slash.exec" for method, _ in conn.calls)
+ assert local_plugin_reads == []
+
+
+def _catalog_reads(conn):
+ return [m for m, _ in conn.calls].count("commands.catalog")
+
+
+def _execs(conn):
+ return [p["command"] for m, p in conn.calls if m == "slash.exec"]
+
+
+def test_known_plugin_commands_reuse_the_sessions_catalog(monkeypatch, local_plugin_reads):
+ conn = _Conn({"mcp-status": "Ask the MCP server"})
+ c = _cli(monkeypatch, conn)
+ for _ in range(3):
+ c._process_unregistered_slash("/mcp-status", "/mcp-status")
+ assert _catalog_reads(conn) == 1 and _execs(conn) == ["mcp-status"] * 3
+
+
+def test_a_plugin_the_gateway_gained_dispatches_after_one_miss_refresh(monkeypatch, local_plugin_reads):
+ """The same open CLI: a plugin enabled in the gateway after the first read is not 'unknown'."""
+ conn = _Conn({})
+ c = _cli(monkeypatch, conn)
+ expanded = []
+ monkeypatch.setattr(HermesCLI, "_expand_slash_prefix", lambda self, *a: expanded.append(a) or True)
+ c._process_unregistered_slash("/zzz", "/zzz")
+ reads = _catalog_reads(conn)
+ conn._plugins["late-plugin"] = "Enabled after the CLI opened"
+ assert c._process_unregistered_slash("/late-plugin now", "/late-plugin now") is True
+ assert _execs(conn) == ["late-plugin now"]
+ assert _catalog_reads(conn) == reads + 1 # one refresh on the miss, no loop
+ assert len(expanded) == 1 and local_plugin_reads == []
+
+
+def test_an_unknown_command_refreshes_the_catalog_once_then_falls_through(monkeypatch):
+ conn = _Conn({"mcp-status": "Ask the MCP server"})
+ c = _cli(monkeypatch, conn)
+ expanded = []
+ monkeypatch.setattr(HermesCLI, "_expand_slash_prefix", lambda self, *a: expanded.append(a) or True)
+ c._process_unregistered_slash("/mcp-status", "/mcp-status")
+ for submitted in range(1, 4): # each repeat of the unknown name: exactly one read, no retry loop
+ c._process_unregistered_slash("/zzz", "/zzz")
+ assert _catalog_reads(conn) == 1 + submitted and len(expanded) == submitted
+ assert _execs(conn) == ["mcp-status"]
+
+
[email protected]("boundary", ["new_session", "reconnect"])
+def test_a_session_boundary_rereads_the_catalog(monkeypatch, boundary):
+ """/new or resume (a new session id) and a redial to another gateway life re-read the names,
+ so completion also sees a plugin set the gateway changed meanwhile."""
+ from hermes_cli import gateway_plugin_commands
+ conn = _Conn({"old-plugin": "Before"})
+ c = _cli(monkeypatch, conn)
+ assert set(gateway_plugin_commands.names(c) or ()) == {"old-plugin"}
+ conn._plugins = {"new-plugin": "After a gateway restart"}
+ assert set(gateway_plugin_commands.names(c) or ()) == {"old-plugin"} # completion keeps the session's read
+ if boundary == "new_session":
+ c.session_id = "local-s2"
+ else:
+ conn.epoch += 1
+ assert set(gateway_plugin_commands.names(c) or ()) == {"new-plugin"}
+ c._process_unregistered_slash("/new-plugin", "/new-plugin")
+ assert _execs(conn) == ["new-plugin"]
+
+
+def test_a_failed_catalog_read_runs_nothing_else(monkeypatch, capsys, local_plugin_reads):
+ """Not knowing the gateway's plugin commands is not evidence a name is no plugin: a same-named
+ skill or bundle must not run in its place, nor prefix expansion or a local plugin."""
+ conn = _Conn({}, catalog_error=GatewayClientError("gateway restarting"))
+ c = _cli(monkeypatch, conn)
+ ran = []
+ monkeypatch.setattr(cli_mod, "_ensure_skill_commands", lambda: {"/mcp-status": {"name": "mcp-status"}})
+ monkeypatch.setattr(cli_mod, "get_skill_bundles", lambda: {"/mcp-status": {"skills": []}})
+ for name in ("_run_skill_bundle_command", "_run_skill_slash_command", "_expand_slash_prefix"):
+ monkeypatch.setattr(HermesCLI, name, lambda self, *a, _n=name: ran.append(_n) or True)
+ assert c._process_unregistered_slash("/mcp-status", "/mcp-status") is True
+ assert "gateway restarting" in capsys.readouterr().out
+ assert ran == [] and _execs(conn) == [] and local_plugin_reads == []
+
+
+def _colliding_skill_and_bundle(monkeypatch, name):
+ ran = []
+ monkeypatch.setattr(cli_mod, "_ensure_skill_commands", lambda: {f"/{name}": {"name": name}})
+ monkeypatch.setattr(cli_mod, "get_skill_bundles", lambda: {f"/{name}": {"skills": []}})
+ for meth in ("_run_skill_bundle_command", "_run_skill_slash_command", "_expand_slash_prefix"):
+ monkeypatch.setattr(HermesCLI, meth, lambda self, *a, _n=meth: ran.append(_n) or True)
+ return ran
+
+
+def test_a_catalog_whose_plugin_discovery_failed_runs_nothing_else(monkeypatch, capsys, local_plugin_reads):
+ """The gateway answers commands.catalog but says its plugin discovery failed: the missing plugin
+ list is not evidence the name is no plugin, so the colliding skill or bundle must not run."""
+ from hermes_cli import gateway_plugin_commands
+ conn = _Conn({})
+ conn.extra = {"plugin_discovery_error": "boom in register()",
+ "warning": "plugin command discovery unavailable: boom in register()"}
+ c = _cli(monkeypatch, conn)
+ ran = _colliding_skill_and_bundle(monkeypatch, "mcp-status")
+ assert c._process_unregistered_slash("/mcp-status", "/mcp-status") is True
+ assert "boom in register()" in capsys.readouterr().out
+ assert ran == [] and _execs(conn) == [] and local_plugin_reads == []
+ assert gateway_plugin_commands.names(c) == {} # completion degrades quietly
+ assert capsys.readouterr().out == ""
+ conn.extra = {} # discovery recovered: the degraded answer was never cached
+ conn._plugins = {"mcp-status": "Ask the MCP server"}
+ assert c._process_unregistered_slash("/mcp-status", "/mcp-status") is True
+ assert _execs(conn) == ["mcp-status"] and ran == []
+
+
+def test_an_older_gateway_without_the_discovery_field_keeps_todays_behaviour(monkeypatch):
+ conn = _Conn({})
+ conn.extra = {"warning": "skill discovery unavailable: x"} # no plugin_discovery_error key
+ c = _cli(monkeypatch, conn)
+ ran = _colliding_skill_and_bundle(monkeypatch, "probe")
+ assert c._process_unregistered_slash("/probe", "/probe") is True
+ assert ran == ["_run_skill_bundle_command"]
+
+
+def test_a_plugin_command_a_display_entry_hides_still_dispatches(monkeypatch, local_plugin_reads):
+ """Ink's ``/logs`` row hides a plugin's ``/logs`` from the display categories; the catalog's
+ ``plugin_commands`` still names it, and that list routes and completes."""
+ from hermes_cli import gateway_plugin_commands
+ conn = _Conn({})
+ conn.extra = {"plugin_commands": {"logs": "Plugin logs"}}
+ c = _cli(monkeypatch, conn)
+ ran = _colliding_skill_and_bundle(monkeypatch, "logs")
+ assert c._process_unregistered_slash("/logs", "/logs") is True
+ assert _execs(conn) == ["logs"] and ran == [] and local_plugin_reads == []
+ assert gateway_plugin_commands.names(c) == {"logs": "Plugin logs"}
+
+
+def test_a_hung_up_connection_rereads_the_catalog_before_a_cached_name_runs(monkeypatch, local_plugin_reads):
+ """A hung-up connection keeps its epoch until its next call redials, so the cache still matched;
+ the gateway that answers next may have lost the plugin. Its catalog decides, not the stale one."""
+ conn = _Conn({"gone-plugin": "Before the restart"})
+ c = _cli(monkeypatch, conn)
+ c._process_unregistered_slash("/gone-plugin", "/gone-plugin")
+ conn.closed, conn._plugins = True, {} # the gateway restarted without the plugin
+ ran = _colliding_skill_and_bundle(monkeypatch, "gone-plugin")
+ assert c._process_unregistered_slash("/gone-plugin", "/gone-plugin") is True
+ assert _execs(conn) == ["gone-plugin"] and _catalog_reads(conn) == 2
+ assert ran == ["_run_skill_bundle_command"] and local_plugin_reads == []
+
+
+def test_a_reply_that_is_no_plugin_run_is_reported(monkeypatch, capsys):
+ """The gateway lost the plugin between lookup and ``slash.exec`` and answered for a same-named
+ skill (``type: skill``): nothing ran, and the input must not vanish without a word."""
+ conn = _Conn({"gone-plugin": "Before the restart"}, reply={"type": "skill", "message": "skill body"})
+ c = _cli(monkeypatch, conn)
+ assert c._process_unregistered_slash("/gone-plugin", "/gone-plugin") is True
+ out = capsys.readouterr().out
+ assert "/gone-plugin" in out and "nothing was run" in out and "skill body" not in out
+
+
+def test_a_catalog_served_before_a_redial_is_not_cached_as_the_new_lifes(monkeypatch):
+ """Completion worker: the reply comes from epoch E, another caller redials to E+1 before the worker
+ publishes it. The cache must not take E's names as E+1's; the next lookup reads again."""
+ from hermes_cli import gateway_plugin_commands
+ conn = _Conn({"old-plugin": "Served by the old gateway life"})
+ c = _cli(monkeypatch, conn)
+
+ def redial():
+ conn.epoch += 1
+ conn._plugins = {"new-plugin": "Served by the new gateway life"}
+ conn.after_catalog = redial
+ assert set(gateway_plugin_commands.names(c) or ()) == {"old-plugin"} # this caller's own answer
+ assert set(gateway_plugin_commands.names(c) or ()) == {"new-plugin"}
+ assert _catalog_reads(conn) == 2
+ c._process_unregistered_slash("/new-plugin", "/new-plugin")
+ assert _execs(conn) == ["new-plugin"] and _catalog_reads(conn) == 2
+
+
+def test_a_catalog_read_across_a_session_change_is_not_cached_for_the_new_session(monkeypatch):
+ from hermes_cli import gateway_plugin_commands
+ conn = _Conn({"old-plugin": "Before"})
+ c = _cli(monkeypatch, conn)
+
+ def switch():
+ c.session_id = "local-s2"
+ conn._plugins = {"new-plugin": "After"}
+ conn.after_catalog = switch
+ gateway_plugin_commands.names(c)
+ assert set(gateway_plugin_commands.names(c) or ()) == {"new-plugin"}
+ assert _catalog_reads(conn) == 2
+
+
+def test_slash_new_rereads_the_catalog(monkeypatch):
+ """The real /new path (``new_session``), not a hand-set session id. Off a GatewaySessionStore the
+ id is main's local mint; the gateway's session.create path is covered by its own tests."""
+ from hermes_cli import gateway_plugin_commands
+ conn = _Conn({"old-plugin": "Before"})
+ monkeypatch.setattr("hermes_cli.gateway_side.connection_for", lambda cli: conn)
+ c = HermesCLI()
+ c.agent = None
+ assert set(gateway_plugin_commands.names(c) or ()) == {"old-plugin"}
+ conn._plugins = {"new-plugin": "After"}
+ before = c.session_id
+ c.new_session(silent=True)
+ assert c.session_id != before
+ assert set(gateway_plugin_commands.names(c) or ()) == {"new-plugin"}
+ assert _catalog_reads(conn) == 2
+
+
+def test_a_failed_refresh_on_a_miss_runs_nothing_else(monkeypatch, capsys):
+ conn = _Conn({"mcp-status": "Ask the MCP server"})
+ c = _cli(monkeypatch, conn)
+ c._process_unregistered_slash("/mcp-status", "/mcp-status")
+ conn.catalog_error = GatewayClientError("gateway restarting")
+ ran = []
+ monkeypatch.setattr(cli_mod, "_ensure_skill_commands", lambda: {"/probe-skill": {"name": "probe-skill"}})
+ monkeypatch.setattr(HermesCLI, "_run_skill_slash_command", lambda self, *a: ran.append(a))
+ assert c._process_unregistered_slash("/probe-skill", "/probe-skill") is True
+ assert "gateway restarting" in capsys.readouterr().out and ran == []
+
+
+def test_completion_degrades_quietly_when_the_catalog_fails(monkeypatch, capsys):
+ from hermes_cli import gateway_plugin_commands
+ c = _cli(monkeypatch, _Conn({}, catalog_error=GatewayClientError("gateway restarting")))
+ assert gateway_plugin_commands.names(c) == {}
+ assert capsys.readouterr().out == ""
+
+
+def test_completion_lists_the_gateways_plugin_commands(local_plugin_reads):
+ from prompt_toolkit.document import Document
+ completer = SlashCommandCompleter(plugin_commands_provider=lambda: {"mcp-status": "Ask the MCP server"})
+ 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 == []
diff --git a/tests/tui_gateway/test_command_catalog_plugin_discovery.py b/tests/tui_gateway/test_command_catalog_plugin_discovery.py
new file mode 100644
index 00000000000..7723e8bbdb9
--- /dev/null
+++ b/tests/tui_gateway/test_command_catalog_plugin_discovery.py
@@ -0,0 +1,41 @@
+"""``commands.catalog`` says when its plugin discovery failed (#134889 PLG-7, CLI-13).
+
+The catalog degrades per loader, so a plugin discovery failure still answers successfully, with no
+plugin commands. ``plugin_discovery_error`` tells a client that list is unknown rather than empty;
+the classic CLI then refuses dispatch instead of letting a same-named skill or bundle run
+(tests/hermes_cli/test_gateway_plugin_commands.py).
+"""
+from importlib import import_module
+from types import SimpleNamespace
+
+from tui_gateway.command_discovery import command_catalog
+
+
+def _catalog(get_plugin_commands):
+ stubs = {"hermes_cli.plugins": SimpleNamespace(get_plugin_commands=get_plugin_commands),
+ "agent.skill_commands": SimpleNamespace(get_interactive_skill_commands=dict)}
+ return command_catalog(load_cfg=dict, module_loader=lambda name: stubs.get(name) or import_module(name))
+
+
+def test_a_failed_plugin_discovery_is_a_field_not_only_warning_text():
+ def broken():
+ raise RuntimeError("boom in register()")
+ result = _catalog(broken)
+ assert result["plugin_discovery_error"] == "boom in register()"
+ assert "Plugin commands" not in {c["name"] for c in result["categories"]}
+
+
+def test_a_working_plugin_discovery_leaves_the_field_empty():
+ assert _catalog(dict)["plugin_discovery_error"] == ""
+ result = _catalog(lambda: {"probe": {"description": "Probe"}})
+ assert result["plugin_discovery_error"] == ""
+ assert ["/probe", "Probe"] in next(c["pairs"] for c in result["categories"] if c["name"] == "Plugin commands")
+
+
+def test_plugin_commands_lists_names_a_display_entry_hides():
+ """``/logs`` is an Ink display entry, not a built-in, so a plugin may register it; the categories
+ show Ink's row, and ``plugin_commands`` still names the plugin's for routing."""
+ result = _catalog(lambda: {"logs": {"description": "Plugin logs"}, "probe": {"description": "Probe"}})
+ assert result["plugin_commands"] == {"logs": "Plugin logs", "probe": "Probe"}
+ plugin_rows = next(c["pairs"] for c in result["categories"] if c["name"] == "Plugin commands")
+ assert ["/logs", "Plugin logs"] not in plugin_rows
diff --git a/tui_gateway/command_discovery.py b/tui_gateway/command_discovery.py
index 89e1a983e95..497b7c29483 100644
--- a/tui_gateway/command_discovery.py
+++ b/tui_gateway/command_discovery.py
@@ -130,6 +130,7 @@ class _Catalog:
self.canon: dict[str, str] = {}
self.commands: dict[str, dict[str, str | None]] = {}
self.cat_map: dict[str, list[list[str]]] = {} # insertion order = category order
+ self.plugin_commands: dict[str, str] = {} # every plugin command, also those a display row hides
def add(self, key: str, desc: str, cat: str) -> None:
self.canon[key.lower()] = key
@@ -173,9 +174,12 @@ def _catalog_plugin_commands(cat: _Catalog, module_loader) -> None:
cat.cat_map.setdefault("Plugin commands", [])
for pname, info in sorted(plugin_cmds.items()):
key = f"/{pname}"
- if not isinstance(info, dict) or key.lower() in cat.canon:
+ if not isinstance(info, dict):
continue
- cat.add(key, str(info.get("description") or "Plugin command"), "Plugin commands")
+ cat.plugin_commands[pname] = str(info.get("description") or "Plugin command")
+ if key.lower() in cat.canon:
+ continue
+ cat.add(key, cat.plugin_commands[pname], "Plugin commands")
mode = info.get("argument_mode")
if mode not in {"options", "text", "mixed"}:
mode = "text" if str(info.get("args_hint") or "").strip() else None
@@ -202,7 +206,9 @@ def _catalog_skills(cat: _Catalog, skills: dict[str, dict], module_loader) -> st
def command_catalog(load_cfg=None, module_loader=import_module, scope=None) -> dict:
"""Registry-backed slash metadata, categorized, no aliases. Discovery failures land in ``warning``
(skills' message wins, then quick commands', then plugins'); only with no failure does it carry
- the built-in-name collision notice for skills that have no ``/<name>`` (empty when none). Quick
+ the built-in-name collision notice for skills that have no ``/<name>`` (empty when none). A plugin
+ discovery failure is also ``plugin_discovery_error`` (empty when it worked), so a client can tell
+ "no plugin commands" from "plugin commands unknown" without parsing ``warning``. Quick
command, plugin command and skill discovery are all home-keyed, so ``scope`` (a context manager
binding the calling session's profile home and workspace) wraps every loader: project-local skills
register for the repo the session is actually in (#114359), and a profile-routed palette never
@@ -213,7 +219,7 @@ def command_catalog(load_cfg=None, module_loader=import_module, scope=None) -> d
load_cfg = load_config_readonly
cat = _Catalog()
_catalog_registry(cat, module_loader)
- warning = ""
+ warning = plugin_error = ""
skills: dict[str, dict] = {}
# Each loader is a degrade boundary: user config, third-party plugin registration and skill
# files can raise anything, and one failing source must never blank the whole palette.
@@ -227,6 +233,7 @@ def command_catalog(load_cfg=None, module_loader=import_module, scope=None) -> d
_catalog_plugin_commands(cat, module_loader)
except Exception as e:
logger.debug("plugin command discovery failed", exc_info=True)
+ plugin_error = str(e) or type(e).__name__
warning = warning or f"plugin command discovery unavailable: {e}"
try:
collision_note = _catalog_skills(cat, skills, module_loader) # always runs: skills must list even when a loader failed
@@ -239,7 +246,8 @@ def command_catalog(load_cfg=None, module_loader=import_module, scope=None) -> d
"canon": cat.canon,
"commands": cat.commands,
"categories": [{"name": c, "pairs": rows} for c, rows in cat.cat_map.items()],
- "skills": skills, "skill_count": len(skills), "warning": warning}
+ "skills": skills, "skill_count": len(skills), "warning": warning, "plugin_discovery_error": plugin_error,
+ "plugin_commands": cat.plugin_commands}
def slash_completions(text: str = "", scope=None) -> dict:
diff --git a/tui_gateway/contracts/tools_commands.py b/tui_gateway/contracts/tools_commands.py
index 6026b97d65a..7acf9b86f59 100644
--- a/tui_gateway/contracts/tools_commands.py
+++ b/tui_gateway/contracts/tools_commands.py
@@ -237,6 +237,11 @@ class CommandsCatalogResult(Result):
skills: dict[str, SkillCatalogEntry] = Field(default_factory=dict)
skill_count: int = 0
warning: str = ""
+ # Non-empty when plugin command discovery failed: the plugin list is unknown, not empty.
+ plugin_discovery_error: str = ""
+ # Every plugin command (name without ``/`` -> description), also one a display row such as Ink's
+ # ``/logs`` hides from ``categories``: route on this, not on the display list.
+ plugin_commands: dict[str, str] = Field(default_factory=dict)
method("commands.catalog", params=CommandsCatalogParams, result=CommandsCatalogResult,