Skip to content

The agent that grows with you

feat: share authenticated canonical slash discovery with legacy catalogs

Tekniumfcf50e03c3b2
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index aacfd650aab..fe9755a566d 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -32,6 +32,7 @@ class AuthorityConnection:
params = request.get('params') or {}
ref = SessionRef(self.actor.profile_id, params.get('session_id', ''))
handlers = {'session.create': self.create, 'ping': self.ping, 'runtime.describe': self.describe,
+ 'commands.catalog': self.command_catalog, 'complete.slash': self.slash_completions,
'session.list': self.list_sessions, 'session.info': self.info,
'session.mutate': self.mutate,
'setup.status': self.setup_status, 'setup.runtime_check': self.setup_runtime_check,
@@ -51,6 +52,14 @@ class AuthorityConnection:
return {'jsonrpc': '2.0', 'id': rid, 'error': {
'code': 5001, 'message': 'storage_unavailable', 'data': {'reason': 'storage_unavailable'}}}
+ async def command_catalog(self, ref, params):
+ from gateway.session_discovery import discover_commands
+ return await discover_commands(self.authority, self.actor, params)
+
+ async def slash_completions(self, ref, params):
+ from gateway.session_discovery import discover_commands
+ return await discover_commands(self.authority, self.actor, params, completion=True)
+
async def setup_status(self, ref, params):
from gateway.session_readiness import readiness
return await readiness(self.authority, self.actor, params, runtime=False)
diff --git a/gateway/session_discovery.py b/gateway/session_discovery.py
new file mode 100644
index 00000000000..fd0074bf1e3
--- /dev/null
+++ b/gateway/session_discovery.py
@@ -0,0 +1,26 @@
+"""Authenticated, profile-bound discovery without legacy execution dispatch."""
+import asyncio
+from pathlib import Path
+
+from hermes_state_runtime import RuntimeStoreError
+
+
+async def discover_commands(authority, actor, params, *, completion=False):
+ if 'session:read' not in actor.capabilities or actor.profile_id != authority.profile_id:
+ raise RuntimeStoreError('permission_denied')
+ allowed = {'profile', 'text', 'session_id'} if completion else {'profile'}
+ if (not isinstance(params, dict) or set(params) - allowed
+ or any(not isinstance(value, str) for value in params.values())):
+ raise RuntimeStoreError('invalid_params')
+
+ def discover():
+ from hermes_cli.profiles import profile_matches_home
+ home = Path(authority.profile_id)
+ if params.get('profile') and not profile_matches_home(params['profile'], home):
+ raise RuntimeStoreError('profile_mismatch')
+ from gateway.run import _profile_runtime_scope
+ from tui_gateway.command_discovery import command_catalog, slash_completions
+ with _profile_runtime_scope(home):
+ return slash_completions(params.get('text', '')) if completion else command_catalog()
+
+ return await asyncio.to_thread(discover)
diff --git a/tests/gateway/test_command_discovery.py b/tests/gateway/test_command_discovery.py
index 98c944c3f58..15f0c6adeb1 100644
--- a/tests/gateway/test_command_discovery.py
+++ b/tests/gateway/test_command_discovery.py
@@ -50,16 +50,6 @@ requests = json.loads(sys.argv[1])
results = [server._methods[method](i, params)['result'] for i, (method, params) in enumerate(requests)]
sys.__stdout__.write(json.dumps(results) + '\\n')
'''
- legacy = subprocess.run([sys.executable, '-c', legacy_code, json.dumps(requests)],
- cwd=root, env=env, stdin=subprocess.DEVNULL,
- capture_output=True, text=True, timeout=45)
- assert legacy.returncode == 0, legacy.stderr
- expected = json.loads(legacy.stdout.splitlines()[-1])
- pairs = dict(expected[0]['pairs'])
- for name in ('/probe-skill', '/probe-quick', '/probe-plugin'):
- assert name in pairs, (name, expected[0]['warning'])
- assert {'probe-skill', 'probe-plugin'} <= {
- row['text'].strip().lstrip('/') for row in expected[2]['items']}
async def probe(descriptor):
url = descriptor['api_origin'].replace('http:', 'ws:') + '/api/ws'
@@ -103,6 +93,17 @@ sys.__stdout__.write(json.dumps(results) + '\\n')
time.sleep(.1)
log.seek(0)
assert descriptor.get('state') == 'ready', (descriptor, log.read())
+ # Ordinary startup syncs bundled skills; compare both transports on that same snapshot.
+ legacy = subprocess.run([sys.executable, '-c', legacy_code, json.dumps(requests)],
+ cwd=root, env=env, stdin=subprocess.DEVNULL,
+ capture_output=True, text=True, timeout=45)
+ assert legacy.returncode == 0, legacy.stderr
+ expected = json.loads(legacy.stdout.splitlines()[-1])
+ pairs = dict(expected[0]['pairs'])
+ for name in ('/probe-skill', '/probe-quick', '/probe-plugin'):
+ assert name in pairs, (name, expected[0]['warning'])
+ assert {'probe-skill', 'probe-plugin'} <= {
+ row['text'].strip().lstrip('/') for row in expected[2]['items']}
receipt = asyncio.run(probe(descriptor))
process.send_signal(signal.SIGINT)
assert process.wait(timeout=20) == 0
diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.py
index 1450910bd42..332a917e601 100644
--- a/tests/test_tui_gateway_server.py
+++ b/tests/test_tui_gateway_server.py
@@ -9240,8 +9240,7 @@ def _slash_skill_fixtures(monkeypatch):
usage = {"work": 297, "research": 84, "clean": 12}
monkeypatch.setattr(
- server,
- "_skill_usage_lookup",
+ "tui_gateway.command_discovery._skill_usage_lookup",
lambda: (
lambda name: usage.get(name, 0),
lambda name: "bundled" if name.startswith("unused-") else "local",
@@ -11326,8 +11325,7 @@ def test_commands_catalog_ranks_skill_commands_by_recorded_usage(monkeypatch):
opened outranks the one they invoke daily.
"""
monkeypatch.setattr(
- server,
- "_skill_usage_lookup",
+ "tui_gateway.command_discovery._skill_usage_lookup",
lambda: (
lambda name: {"research": 60, "work": 172}.get(name, 0),
lambda name: "bundled" if name == "research-paper-writing" else "local",
diff --git a/tests/tui_gateway/test_slash_fuzzy.py b/tests/tui_gateway/test_slash_fuzzy.py
index 287019d91bd..55fd0abc125 100644
--- a/tests/tui_gateway/test_slash_fuzzy.py
+++ b/tests/tui_gateway/test_slash_fuzzy.py
@@ -7,7 +7,7 @@ lookup: skill rows sort by fuzzy score first, then usage, then name.
import math
-from tui_gateway.server import _rank_slash_completions
+from tui_gateway.command_discovery import _rank_slash_completions
from tui_gateway.slash_fuzzy import (
fuzzy_rank_slash_items,
normalize_slash_search_query,
diff --git a/tui_gateway/AGENTS.md b/tui_gateway/AGENTS.md
index d4181645bd1..d48c5b18b52 100644
--- a/tui_gateway/AGENTS.md
+++ b/tui_gateway/AGENTS.md
@@ -72,10 +72,19 @@ retains its legacy unscoped contract.
`command.dispatch` fallback, which the gateway resolves into a skill / alias / exec directive
(a skill command resolves to `{type: "skill", message}` and is submitted as a normal prompt).
-`commands.catalog` (empty-query list) and `complete.slash` (typed-query completions) already include
-built-ins, user `quick_commands`, AND skill-derived commands (`scan_skill_commands()` /
-`get_skill_commands()`) — clients do not need a new RPC to see skills. The command definitions
-themselves come from `hermes_cli/commands.py` (`hermes_cli/AGENTS.md`).
+`commands.catalog` (empty-query list) includes built-ins, user `quick_commands`, plugin commands,
+and skill-derived commands. `complete.slash` uses the existing CLI completer (registry, plugins,
+skills/bundles, argument completions); quick commands remain catalog-only. Shared data builders
+live in `tui_gateway/command_discovery.py`, without importing the legacy server. Definitions
+come from `hermes_cli/commands.py` (`hermes_cli/AGENTS.md`).
+
+The canonical gateway exposes the same two discovery RPCs through `gateway/session_discovery.py`.
+It requires authenticated `session:read` capability and the authority's exact profile before any
+discovery. An optional named `profile` must resolve to that same home; a foreign selector returns
+`profile_mismatch`. Discovery runs off-loop in the authority's profile scope, without creating a
+legacy session or execution runtime. Catalog warnings, categories, aliases, desktop metadata,
+skill usage/origin, and completion replacement offsets retain their legacy shapes. Discovery is
+not an assertion that every listed slash execution command is implemented by the canonical RPCs.
## Dev commands
diff --git a/tui_gateway/command_discovery.py b/tui_gateway/command_discovery.py
new file mode 100644
index 00000000000..8e00db90e6e
--- /dev/null
+++ b/tui_gateway/command_discovery.py
@@ -0,0 +1,258 @@
+"""Shared slash discovery data; no server import or session execution runtime.
+
+Transport wrappers own authentication and profile binding before calling these
+builders. Keep the legacy catalog and completion semantics identical here.
+"""
+import contextlib
+from importlib import import_module
+import logging
+
+logger = logging.getLogger(__name__)
+
+_TUI_HIDDEN: frozenset[str] = frozenset({"sethome", "set-home", "commands", "approve", "deny"})
+
+_TUI_EXTRA: list[tuple[str, str, str]] = [
+ ("/density", "Toggle compact display mode", "TUI"),
+ ("/logs", "Show recent gateway log lines", "TUI"),
+ ("/mouse", "Set mouse tracking preset [on|off|toggle|wheel|buttons|all]", "TUI"),
+ ("/sessions", "Switch between live TUI sessions", "TUI"),
+]
+
+_SLASH_EXTRAS = [
+ ("/density", "Toggle compact display mode"), ("/details", "Control agent detail visibility"),
+ ("/logs", "Show recent gateway log lines"),
+ ("/mouse", "Set mouse tracking preset [on|off|toggle|wheel|buttons|all]")]
+
+
+def _item(text: str, meta: str, display: str | None = None) -> dict:
+ return {"text": text, "display": display if display is not None else text, "meta": meta}
+
+
+def _skill_usage_lookup():
+ """``(usage, origin)`` callables for the skill catalog: activity count (use + view + patch) and
+ "hub" / "bundled" / "local" (``/api/skills`` ``provenance``, "local" spelled "agent"). Failure → 0 / "local"."""
+ try:
+ from tools.skill_usage import (
+ _read_bundled_manifest_names, _read_hub_installed_names, activity_count, load_usage)
+ records, bundled, hub = load_usage(), _read_bundled_manifest_names(), _read_hub_installed_names()
+ except Exception as e:
+ logger.debug("skill usage lookup unavailable: %s", e)
+ return (lambda _name: 0), (lambda _name: "local")
+
+ def usage(name: str) -> int:
+ with contextlib.suppress(Exception):
+ return activity_count(records.get(name) or {})
+ return 0
+
+ def origin(name: str) -> str:
+ return "hub" if name in hub else "bundled" if name in bundled else "local"
+ return usage, origin
+
+
+_SLASH_COMPLETION_LIMIT = 30
+
+
+def _rank_slash_completions(items: list[dict], usage, origin_of, *, browsing: bool, score_of=None) -> list[dict]:
+ """Registry commands keep their order; only skills reorder: fuzzy ``score_of`` first, then most-used, then
+ A-Z. The limit is spent PER KIND (a flat cut on a large install offered no skill at all). ``browsing``
+ (bare ``/``) drops never-used bundled skills as noise; a typed query is SEARCHING — nothing pruned, only reordered."""
+ def name_of(item: dict) -> str:
+ return str(item.get("text", "")).strip().lstrip("/").lower()
+ commands = [item for item in items if item.get("kind") != "skill"]
+ skills = [item for item in items if item.get("kind") == "skill"]
+ if browsing:
+ skills = [item for item in skills if origin_of(name_of(item)) != "bundled" or usage(name_of(item)) > 0]
+ skills.sort(key=lambda item: (
+ *(() if score_of is None else (score_of(item),)), -usage(name_of(item)), name_of(item)))
+ return commands[:_SLASH_COMPLETION_LIMIT] + skills[:_SLASH_COMPLETION_LIMIT]
+
+
+_DETAILS_SECTIONS = ("thinking", "tools", "subagents", "activity")
+_DETAILS_MODES = ("hidden", "collapsed", "expanded")
+
+
+def _details_root_meta(candidate: str) -> str:
+ if candidate in _DETAILS_SECTIONS:
+ return "section override"
+ return "cycle global mode" if candidate == "cycle" else "global mode"
+
+
+def _details_completions(text: str) -> list[dict] | None:
+ """Argument completions for ``/details [section] [mode]``; None when ``text`` is not that command."""
+ if not text.lower().startswith("/details"):
+ return None
+ stripped = text.strip()
+ if stripped and not "/details".startswith(stripped.lower().split()[0]):
+ return None
+ body = text[len("/details") :].removeprefix(" ")
+ parts = body.split()
+ trailing = text.endswith(" ")
+ root_candidates = (*_DETAILS_MODES, "cycle", *_DETAILS_SECTIONS)
+ if not body or (not parts and trailing):
+ lead = "" if trailing else " "
+ return [_item(f"{lead}{c}", _details_root_meta(c)) for c in root_candidates]
+ if len(parts) == 1 and not trailing:
+ prefix = parts[0].lower()
+ return [_item(c, _details_root_meta(c)) for c in root_candidates if c.startswith(prefix) and c != prefix]
+ section = parts[0].lower() if parts else ""
+ if section not in _DETAILS_SECTIONS:
+ return []
+
+ def section_meta(candidate: str) -> str:
+ return f"clear {section} override" if candidate == "reset" else f"set {section}"
+ mode_candidates = (*_DETAILS_MODES, "reset")
+ if len(parts) == 1: # trailing space after the section
+ return [_item(c, section_meta(c)) for c in mode_candidates]
+ if len(parts) == 2 and not trailing:
+ prefix = parts[1].lower()
+ return [_item(c, section_meta(c)) for c in mode_candidates if c.startswith(prefix) and c != prefix]
+ return []
+
+
+class _Catalog:
+ """Accumulator for commands.catalog: ``pairs`` (every [key, desc]), ``canon`` (lowercase
+ key/alias → canonical key), ``commands`` (key → desktop meta) and ordered categories."""
+
+ def __init__(self) -> None:
+ self.pairs: list[list[str]] = []
+ 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
+
+ def add(self, key: str, desc: str, cat: str) -> None:
+ self.canon[key.lower()] = key
+ self.pairs.append([key, desc])
+ self.cat_map.setdefault(cat, []).append([key, desc])
+
+
+def _catalog_registry(cat: _Catalog, module_loader) -> None:
+ commands = module_loader("hermes_cli.commands")
+ for cmd in commands.COMMAND_REGISTRY:
+ meta = commands.command_desktop_meta(cmd)
+ cat.commands.update({f"/{key}": dict(meta) for key in (cmd.name, *cmd.aliases)})
+ if cmd.name in _TUI_HIDDEN or cmd.gateway_only:
+ continue
+ cat.add(f"/{cmd.name}", commands._build_description(cmd), cmd.category)
+ for a in cmd.aliases:
+ cat.canon[f"/{a}".lower()] = f"/{cmd.name}"
+ for name, desc, category in _TUI_EXTRA:
+ # Registry command/alias wins over a colliding TUI extra (e.g. /compact, /sessions).
+ if name.lower() not in cat.canon:
+ cat.add(name, desc, category)
+
+
+def _catalog_quick_commands(cat: _Catalog, load_cfg) -> None:
+ qcmds = load_cfg().get("quick_commands", {}) or {}
+ if not (isinstance(qcmds, dict) and qcmds):
+ return
+ cat.cat_map.setdefault("User commands", []) # category exists even when every entry is malformed
+ for qname, qc in sorted(qcmds.items()):
+ if not isinstance(qc, dict):
+ continue
+ qtype = qc.get("type", "")
+ default_desc = {"exec": f"exec: {qc.get('command', '')}", "alias": f"alias → {qc.get('target', '')}"}
+ desc = str(qc.get("description") or default_desc.get(qtype, qtype or "quick command"))
+ cat.add(f"/{qname}", desc, "User commands")
+
+
+def _catalog_plugin_commands(cat: _Catalog, module_loader) -> None:
+ plugin_cmds = module_loader("hermes_cli.plugins").get_plugin_commands() or {}
+ if plugin_cmds:
+ 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:
+ continue
+ cat.add(key, str(info.get("description") or "Plugin command"), "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
+ cat.commands[key] = {"argument_mode": mode, "desktop": None}
+
+
+def _catalog_skills(cat: _Catalog, skills: dict[str, dict], module_loader) -> None:
+ """Append skill pairs and fill ``skills`` = ``{key: {usage, origin}}`` (every consumer ranks by them)."""
+ usage, origin_of = _skill_usage_lookup()
+ for k, info in sorted(module_loader("agent.skill_commands").scan_skill_commands().items()):
+ cat.pairs.append([k, str(info.get("description", "Skill"))])
+ name = str(info.get("name") or k.lstrip("/"))
+ skills[k] = {"usage": usage(name), "origin": origin_of(name)}
+
+
+def command_catalog(load_cfg=None, module_loader=import_module) -> dict:
+ """Registry-backed slash metadata, categorized, no aliases. Discovery failures land in ``warning``
+ (skills' message wins, then quick commands', then plugins')."""
+ if load_cfg is None:
+ from hermes_cli.config import load_config_readonly
+ load_cfg = load_config_readonly
+ cat = _Catalog()
+ _catalog_registry(cat, module_loader)
+ warning = ""
+ try:
+ _catalog_quick_commands(cat, load_cfg)
+ except Exception as e:
+ warning = f"quick_commands discovery unavailable: {e}"
+ try:
+ _catalog_plugin_commands(cat, module_loader)
+ except Exception as e:
+ warning = warning or f"plugin command discovery unavailable: {e}"
+ skills: dict[str, dict] = {}
+ try:
+ _catalog_skills(cat, skills, module_loader)
+ except Exception as e:
+ warning = f"skill discovery unavailable: {e}"
+ return {
+ "pairs": cat.pairs, "sub": {k: v[:] for k, v in module_loader("hermes_cli.commands").SUBCOMMANDS.items()},
+ "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}
+
+
+def slash_completions(text: str = "") -> dict:
+ if not text.startswith("/"):
+ return {"items": []}
+ from hermes_cli.commands_completion import SlashCommandCompleter
+ from prompt_toolkit.document import Document
+ from prompt_toolkit.formatted_text import to_plain_text
+ from agent.skill_commands import get_skill_commands
+ from agent.skill_bundles import get_skill_bundles
+ completer = SlashCommandCompleter(
+ skill_commands_provider=lambda: get_skill_commands(), skill_bundles_provider=lambda: get_skill_bundles())
+ # `kind` reaches the TUI as data (from the providers, not sniffed from ⚡/▣ glyphs):
+ # skills/bundles are the only completions for an inline `/skill` typed mid-message.
+ skill_names = {key.lstrip("/").lower() for key in (*get_skill_commands(), *get_skill_bundles())}
+
+ def to_items(doc: Document) -> list[dict]:
+ # display/display_meta are FormattedText; the TUI contract is a plain string
+ # (the raw list trips Ink's row layout into 1-char truncation).
+ return [
+ {
+ "text": c.text, "display": to_plain_text(c.display) if c.display else c.text,
+ "meta": to_plain_text(c.display_meta) if c.display_meta else "",
+ "kind": "skill" if c.text.strip().lstrip("/").lower() in skill_names else "command"}
+ for c in completer.get_completions(doc, None)]
+ items = to_items(Document(text, len(text)))
+ # Rank + bound while a `/token` is under the cursor (the one stage skills are
+ # offered at); an argument stage (`/personality `) keeps its command's order.
+ if text.rsplit(" ", 1)[-1].startswith("/"):
+ score_of = None
+ # Command-token stage: the completer only emits name-prefix matches, so merge in
+ # catalog entries whose name SUBSTRING or DESCRIPTION words match (name outranks description).
+ if " " not in text and len(text) > 1:
+ from tui_gateway.slash_fuzzy import fuzzy_rank_slash_items, normalize_slash_search_query
+ items, score_of = fuzzy_rank_slash_items(
+ items, to_items(Document("/", 1)), normalize_slash_search_query(text))
+ usage, origin_of = _skill_usage_lookup()
+ items = _rank_slash_completions(items, usage, origin_of, browsing=text == "/", score_of=score_of)
+ else:
+ items = items[:_SLASH_COMPLETION_LIMIT]
+ text_lower = text.lower()
+ for extra_text, extra_meta in _SLASH_EXTRAS:
+ if extra_text.startswith(text_lower) and not any(item["text"] == extra_text for item in items):
+ items.append({**_item(extra_text, extra_meta), "kind": "command"})
+ if (details_items := _details_completions(text)) is not None:
+ return {"items": details_items, "replace_from": text.rfind(" ") + 1 if " " in text else len(text)}
+ return {"items": items, "replace_from": text.rfind(" ") + 1 if " " in text else 1}
+
+
diff --git a/tui_gateway/methods_complete.py b/tui_gateway/methods_complete.py
index a7e5decc116..9b1b2c5cca9 100644
--- a/tui_gateway/methods_complete.py
+++ b/tui_gateway/methods_complete.py
@@ -14,12 +14,6 @@ _BUILTIN_AT_PREFIXES = frozenset({"file", "folder", "url", "git", "diff", "stage
_AT_DIRECTIVE_HINTS = [
("@diff", "git diff"), ("@staged", "staged diff"), ("@file:", "attach file"),
("@folder:", "attach folder"), ("@url:", "fetch url"), ("@git:", "git log")]
-_SLASH_EXTRAS = [
- ("/density", "Toggle compact display mode"), ("/details", "Control agent detail visibility"),
- ("/logs", "Show recent gateway log lines"),
- ("/mouse", "Set mouse tracking preset [on|off|toggle|wheel|buttons|all]")]
-
-
def _item(text: str, meta: str, display: str | None = None) -> dict:
return {"text": text, "display": display if display is not None else text, "meta": meta}
@@ -223,51 +217,8 @@ def _(rid, params: dict) -> dict:
@method("complete.slash")
@_catch(5020)
def _(rid, params: dict) -> dict:
- text = params.get("text", "")
- if not text.startswith("/"):
- return _ok(rid, {"items": []})
- from hermes_cli.commands_completion import SlashCommandCompleter
- from prompt_toolkit.document import Document
- from prompt_toolkit.formatted_text import to_plain_text
- from agent.skill_commands import get_skill_commands
- from agent.skill_bundles import get_skill_bundles
- completer = SlashCommandCompleter(
- skill_commands_provider=lambda: get_skill_commands(), skill_bundles_provider=lambda: get_skill_bundles())
- # `kind` reaches the TUI as data (from the providers, not sniffed from ⚡/▣ glyphs):
- # skills/bundles are the only completions for an inline `/skill` typed mid-message.
- skill_names = {key.lstrip("/").lower() for key in (*get_skill_commands(), *get_skill_bundles())}
-
- def to_items(doc: Document) -> list[dict]:
- # display/display_meta are FormattedText; the TUI contract is a plain string
- # (the raw list trips Ink's row layout into 1-char truncation).
- return [
- {
- "text": c.text, "display": to_plain_text(c.display) if c.display else c.text,
- "meta": to_plain_text(c.display_meta) if c.display_meta else "",
- "kind": "skill" if c.text.strip().lstrip("/").lower() in skill_names else "command"}
- for c in completer.get_completions(doc, None)]
- items = to_items(Document(text, len(text)))
- # Rank + bound while a `/token` is under the cursor (the one stage skills are
- # offered at); an argument stage (`/personality `) keeps its command's order.
- if text.rsplit(" ", 1)[-1].startswith("/"):
- score_of = None
- # Command-token stage: the completer only emits name-prefix matches, so merge in
- # catalog entries whose name SUBSTRING or DESCRIPTION words match (name outranks description).
- if " " not in text and len(text) > 1:
- from tui_gateway.slash_fuzzy import fuzzy_rank_slash_items, normalize_slash_search_query
- items, score_of = fuzzy_rank_slash_items(
- items, to_items(Document("/", 1)), normalize_slash_search_query(text))
- usage, origin_of = _skill_usage_lookup()
- items = _rank_slash_completions(items, usage, origin_of, browsing=text == "/", score_of=score_of)
- else:
- items = items[:_SLASH_COMPLETION_LIMIT]
- text_lower = text.lower()
- for extra_text, extra_meta in _SLASH_EXTRAS:
- if extra_text.startswith(text_lower) and not any(item["text"] == extra_text for item in items):
- items.append({**_item(extra_text, extra_meta), "kind": "command"})
- if (details_items := _details_completions(text)) is not None:
- return _ok(rid, {"items": details_items, "replace_from": text.rfind(" ") + 1 if " " in text else len(text)})
- return _ok(rid, {"items": items, "replace_from": text.rfind(" ") + 1 if " " in text else 1})
+ from tui_gateway.command_discovery import slash_completions
+ return _ok(rid, slash_completions(params.get("text", "")))
def _session_agent(params: dict):
diff --git a/tui_gateway/methods_complete_helpers.py b/tui_gateway/methods_complete_helpers.py
index b4ea31533ae..a9fb4b6a6d6 100644
--- a/tui_gateway/methods_complete_helpers.py
+++ b/tui_gateway/methods_complete_helpers.py
@@ -120,48 +120,6 @@ def _abs_completion_prefix_exists(path_part: str) -> bool:
return False
-_DETAILS_SECTIONS = ("thinking", "tools", "subagents", "activity")
-_DETAILS_MODES = ("hidden", "collapsed", "expanded")
-
-
-def _details_root_meta(candidate: str) -> str:
- if candidate in _DETAILS_SECTIONS:
- return "section override"
- return "cycle global mode" if candidate == "cycle" else "global mode"
-
-
-def _details_completions(text: str) -> list[dict] | None:
- """Argument completions for ``/details [section] [mode]``; None when ``text`` is not that command."""
- if not text.lower().startswith("/details"):
- return None
- stripped = text.strip()
- if stripped and not "/details".startswith(stripped.lower().split()[0]):
- return None
- body = text[len("/details") :].removeprefix(" ")
- parts = body.split()
- trailing = text.endswith(" ")
- root_candidates = (*_DETAILS_MODES, "cycle", *_DETAILS_SECTIONS)
- if not body or (not parts and trailing):
- lead = "" if trailing else " "
- return [_item(f"{lead}{c}", _details_root_meta(c)) for c in root_candidates]
- if len(parts) == 1 and not trailing:
- prefix = parts[0].lower()
- return [_item(c, _details_root_meta(c)) for c in root_candidates if c.startswith(prefix) and c != prefix]
- section = parts[0].lower() if parts else ""
- if section not in _DETAILS_SECTIONS:
- return []
-
- def section_meta(candidate: str) -> str:
- return f"clear {section} override" if candidate == "reset" else f"set {section}"
- mode_candidates = (*_DETAILS_MODES, "reset")
- if len(parts) == 1: # trailing space after the section
- return [_item(c, section_meta(c)) for c in mode_candidates]
- if len(parts) == 2 and not trailing:
- prefix = parts[1].lower()
- return [_item(c, section_meta(c)) for c in mode_candidates if c.startswith(prefix) and c != prefix]
- return []
-
-
def _model_picker_context(agent):
"""Layer live session state onto config without losing custom identity."""
from hermes_cli.inventory import load_picker_context
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index ed57a1f51eb..ef6c7d8e6f1 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -329,102 +329,10 @@ def _(rid, params: dict) -> dict:
# ─── Command catalog / dispatch ──────────────────────────────────────────────
-class _Catalog:
- """Accumulator for commands.catalog: ``pairs`` (every [key, desc]), ``canon`` (lowercase
- key/alias → canonical key), ``commands`` (key → desktop meta) and ordered categories."""
-
- def __init__(self) -> None:
- self.pairs: list[list[str]] = []
- 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
-
- def add(self, key: str, desc: str, cat: str) -> None:
- self.canon[key.lower()] = key
- self.pairs.append([key, desc])
- self.cat_map.setdefault(cat, []).append([key, desc])
-
-
-def _catalog_registry(cat: _Catalog) -> None:
- commands = _tools_mod("hermes_cli.commands")
- for cmd in commands.COMMAND_REGISTRY:
- meta = commands.command_desktop_meta(cmd)
- cat.commands.update({f"/{key}": dict(meta) for key in (cmd.name, *cmd.aliases)})
- if cmd.name in _TUI_HIDDEN or cmd.gateway_only:
- continue
- cat.add(f"/{cmd.name}", commands._build_description(cmd), cmd.category)
- for a in cmd.aliases:
- cat.canon[f"/{a}".lower()] = f"/{cmd.name}"
- for name, desc, category in _TUI_EXTRA:
- # Registry command/alias wins over a colliding TUI extra (e.g. /compact, /sessions).
- if name.lower() not in cat.canon:
- cat.add(name, desc, category)
-
-
-def _catalog_quick_commands(cat: _Catalog) -> None:
- qcmds = _load_cfg().get("quick_commands", {}) or {}
- if not (isinstance(qcmds, dict) and qcmds):
- return
- cat.cat_map.setdefault("User commands", []) # category exists even when every entry is malformed
- for qname, qc in sorted(qcmds.items()):
- if not isinstance(qc, dict):
- continue
- qtype = qc.get("type", "")
- default_desc = {"exec": f"exec: {qc.get('command', '')}", "alias": f"alias → {qc.get('target', '')}"}
- desc = str(qc.get("description") or default_desc.get(qtype, qtype or "quick command"))
- cat.add(f"/{qname}", desc, "User commands")
-
-
-def _catalog_plugin_commands(cat: _Catalog) -> None:
- plugin_cmds = _tools_mod("hermes_cli.plugins").get_plugin_commands() or {}
- if plugin_cmds:
- 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:
- continue
- cat.add(key, str(info.get("description") or "Plugin command"), "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
- cat.commands[key] = {"argument_mode": mode, "desktop": None}
-
-
-def _catalog_skills(cat: _Catalog, skills: dict[str, dict]) -> None:
- """Append skill pairs and fill ``skills`` = ``{key: {usage, origin}}`` (every consumer ranks by them)."""
- usage, origin_of = _skill_usage_lookup()
- for k, info in sorted(_tools_mod("agent.skill_commands").scan_skill_commands().items()):
- cat.pairs.append([k, str(info.get("description", "Skill"))])
- name = str(info.get("name") or k.lstrip("/"))
- skills[k] = {"usage": usage(name), "origin": origin_of(name)}
-
-
@_rpc("commands.catalog", 5020)
def _(rid, params: dict) -> dict:
- """Registry-backed slash metadata, categorized, no aliases. Discovery failures land in ``warning``
- (skills' message wins, then quick commands', then plugins')."""
- cat = _Catalog()
- _catalog_registry(cat)
- warning = ""
- try:
- _catalog_quick_commands(cat)
- except Exception as e:
- warning = f"quick_commands discovery unavailable: {e}"
- try:
- _catalog_plugin_commands(cat)
- except Exception as e:
- warning = warning or f"plugin command discovery unavailable: {e}"
- skills: dict[str, dict] = {}
- try:
- _catalog_skills(cat, skills)
- except Exception as e:
- warning = f"skill discovery unavailable: {e}"
- return _ok(rid, {
- "pairs": cat.pairs, "sub": {k: v[:] for k, v in _tools_mod("hermes_cli.commands").SUBCOMMANDS.items()},
- "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})
+ from tui_gateway.command_discovery import command_catalog
+ return _ok(rid, command_catalog(_load_cfg, _tools_mod))
@method("cli.exec")
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 80d3fb46abc..7c16789375b 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -1862,15 +1862,6 @@ def _finish_reload(rid, params: dict, *, coalesced: bool) -> dict:
return _ok(rid, {"status": "reloaded", "loaded_rev": _mcp_reload_loaded_rev, **({"coalesced": True} if coalesced else {})})
-_TUI_HIDDEN: frozenset[str] = frozenset({"sethome", "set-home", "commands", "approve", "deny"})
-
-_TUI_EXTRA: list[tuple[str, str, str]] = [
- ("/density", "Toggle compact display mode", "TUI"),
- ("/logs", "Show recent gateway log lines", "TUI"),
- ("/mouse", "Set mouse tracking preset [on|off|toggle|wheel|buttons|all]", "TUI"),
- ("/sessions", "Switch between live TUI sessions", "TUI"),
-]
-
# Commands that queue onto _pending_input in the CLI; the slash worker has no reader for that queue, so
# slash.exec routes them to command.dispatch instead.
_PENDING_INPUT_COMMANDS: frozenset[str] = frozenset({
@@ -1881,45 +1872,6 @@ _PENDING_INPUT_COMMANDS: frozenset[str] = frozenset({
_WORKER_BLOCKED_COMMANDS: frozenset[str] = frozenset({"snapshot", "snap"})
-def _skill_usage_lookup():
- """``(usage, origin)`` callables for the skill catalog: activity count (use + view + patch) and
- "hub" / "bundled" / "local" (``/api/skills`` ``provenance``, "local" spelled "agent"). Failure → 0 / "local"."""
- try:
- from tools.skill_usage import (
- _read_bundled_manifest_names, _read_hub_installed_names, activity_count, load_usage)
- records, bundled, hub = load_usage(), _read_bundled_manifest_names(), _read_hub_installed_names()
- except Exception as e:
- logger.debug("skill usage lookup unavailable: %s", e)
- return (lambda _name: 0), (lambda _name: "local")
-
- def usage(name: str) -> int:
- with contextlib.suppress(Exception):
- return activity_count(records.get(name) or {})
- return 0
-
- def origin(name: str) -> str:
- return "hub" if name in hub else "bundled" if name in bundled else "local"
- return usage, origin
-
-
-_SLASH_COMPLETION_LIMIT = 30
-
-
-def _rank_slash_completions(items: list[dict], usage, origin_of, *, browsing: bool, score_of=None) -> list[dict]:
- """Registry commands keep their order; only skills reorder: fuzzy ``score_of`` first, then most-used, then
- A-Z. The limit is spent PER KIND (a flat cut on a large install offered no skill at all). ``browsing``
- (bare ``/``) drops never-used bundled skills as noise; a typed query is SEARCHING — nothing pruned, only reordered."""
- def name_of(item: dict) -> str:
- return str(item.get("text", "")).strip().lstrip("/").lower()
- commands = [item for item in items if item.get("kind") != "skill"]
- skills = [item for item in items if item.get("kind") == "skill"]
- if browsing:
- skills = [item for item in skills if origin_of(name_of(item)) != "bundled" or usage(name_of(item)) > 0]
- skills.sort(key=lambda item: (
- *(() if score_of is None else (score_of(item),)), -usage(name_of(item)), name_of(item)))
- return commands[:_SLASH_COMPLETION_LIMIT] + skills[:_SLASH_COMPLETION_LIMIT]
-
-
# argv shapes that must not run headless in the gateway process → user hint.
_CLI_EXEC_BLOCKED = {
("setup",): "`hermes setup` needs a full terminal — run it outside the TUI",