Skip to content

The agent that grows with you

refactor(hermes_cli): compact commands registry helpers; share gateway-availability filter in commands_platforms

Tekniume2ad0c08442c
diff --git a/hermes_cli/commands.py b/hermes_cli/commands.py
index 516312039c3..e0986ecb02f 100644
--- a/hermes_cli/commands.py
+++ b/hermes_cli/commands.py
@@ -1,11 +1,8 @@
-"""Slash command definitions and autocomplete for the Hermes CLI.
+"""Slash command registry for the Hermes CLI and gateway.
-Central registry for all slash commands. Every consumer -- CLI help, gateway
-dispatch, Telegram BotCommands, Slack subcommand mapping, autocomplete --
-derives its data from ``COMMAND_REGISTRY``.
-
-To add a command: add a ``CommandDef`` entry to ``COMMAND_REGISTRY``.
-To add an alias: set ``aliases=("short",)`` on the existing ``CommandDef``.
+Every consumer -- CLI help, gateway dispatch, Telegram BotCommands, Slack
+subcommand mapping, autocomplete -- derives from ``COMMAND_REGISTRY``. To add a
+command, append a ``CommandDef``; to add an alias, set ``aliases=("short",)``.
"""
from __future__ import annotations
@@ -20,9 +17,6 @@ from hermes_constants import INDICATOR_STYLES
logger = logging.getLogger(__name__)
-# ---------------------------------------------------------------------------
-# CommandDef dataclass
-# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class CommandDef:
@@ -36,42 +30,27 @@ class CommandDef:
subcommands: tuple[str, ...] = () # tab-completable subcommands
cli_only: bool = False # only available in CLI
gateway_only: bool = False # only available in gateway/messaging
- gateway_config_gate: str | None = None # config dotpath; when truthy, overrides cli_only for gateway
- # Mid-run (agent busy) gateway behavior, driving the Guard-2 dispatcher in
- # gateway/run.py (_dispatch_busy_slash_command):
- # "dispatch" — run while busy (normal handler, or the
- # mid-run variant named by ``busy_handler``).
- # "reject" — refuse mid-run; generic "Agent is running"
- # catch-all unless ``busy_handler`` names a
- # command-specific reject message.
- # "interrupt_then_dispatch" — interrupt the agent first (/stop, /new,
- # /reset); Guard 1 (platforms/base.py) routes
- # these via is_interrupt_then_dispatch().
+ gateway_config_gate: str | None = None # config dotpath; truthy overrides cli_only for gateway
+ # Mid-run (agent busy) gateway behavior for gateway/run.py's Guard-2 dispatcher:
+ # "dispatch" — run while busy (normal handler, or the mid-run
+ # variant named by ``busy_handler``).
+ # "reject" — refuse mid-run; generic "Agent is running" unless
+ # ``busy_handler`` names a specific reject message.
+ # "interrupt_then_dispatch" — interrupt the agent first (/stop, /new, /reset);
+ # Guard 1 (platforms/base.py) routes these.
busy_policy: str = "reject"
- # Key of a special mid-run handler in gateway/run.py's Guard-2 table for
- # commands whose busy behavior differs from their normal handler.
- busy_handler: str | None = None
- # Key in ``hermes_cli.slash_exec.EXECUTORS`` — a pure formatter producing
- # the surface-independent core text; surfaces apply only their decoration.
- # A string key (not a callable) keeps this module import-light for the
- # gateway (no prompt_toolkit, no executor dependencies).
+ busy_handler: str | None = None # key of a special mid-run handler in Guard-2 table
+ # Key in ``hermes_cli.slash_exec.EXECUTORS`` (pure formatter of the core text). A
+ # string key, not a callable, keeps this module import-light for the gateway.
execute: str | None = None
- # Desktop composer: ``options`` | ``text`` | ``mixed``. ``None`` is inferred.
- argument_mode: str | None = None
- # Desktop availability. ``None`` = offered; ``hidden`` = runs but stays out
- # of the popover; otherwise a reason (terminal / messaging / settings / …).
+ argument_mode: str | None = None # desktop composer: options|text|mixed; None inferred
+ # Desktop availability: None = offered; "hidden" = runs but out of the popover;
+ # otherwise a reason (terminal / messaging / settings / …).
desktop: str | None = None
-# Valid values for CommandDef.busy_policy (see field docs above).
-VALID_BUSY_POLICIES: frozenset[str] = frozenset(
- {"dispatch", "reject", "interrupt_then_dispatch"}
-)
-
+VALID_BUSY_POLICIES: frozenset[str] = frozenset({"dispatch", "reject", "interrupt_then_dispatch"})
-# ---------------------------------------------------------------------------
-# Central registry -- single source of truth
-# ---------------------------------------------------------------------------
COMMAND_REGISTRY: list[CommandDef] = [
# Session
@@ -347,9 +326,8 @@ COMMAND_REGISTRY: list[CommandDef] = [
]
-# Used only to distinguish ``mixed`` (subcommands plus free-text) from
-# ``options`` (subcommand list only). A bare ``args_hint`` with no
-# subcommands is always ``text`` — do not add tokens here for that path.
+# Distinguishes ``mixed`` (subcommands plus free-text) from ``options``. A bare
+# ``args_hint`` with no subcommands is always ``text`` — no tokens needed for that.
_PROSE_HINTS = ("<prompt>", "[text", "instructions", "[interval]", "<what")
@@ -358,13 +336,10 @@ def infer_argument_mode(cmd: CommandDef) -> str | None:
if cmd.argument_mode in {"options", "text", "mixed"}:
return cmd.argument_mode
hint = (cmd.args_hint or "").strip()
- if cmd.subcommands and hint and any(token in hint.lower() for token in _PROSE_HINTS):
- return "mixed"
if cmd.subcommands:
- return "options"
- if hint:
- return "text"
- return None
+ prose = hint and any(token in hint.lower() for token in _PROSE_HINTS)
+ return "mixed" if prose else "options"
+ return "text" if hint else None
def command_desktop_meta(cmd: CommandDef) -> dict[str, str | None]:
@@ -372,47 +347,36 @@ def command_desktop_meta(cmd: CommandDef) -> dict[str, str | None]:
return {"argument_mode": infer_argument_mode(cmd), "desktop": cmd.desktop}
-# ---------------------------------------------------------------------------
-# Derived lookups -- rebuilt once at import time, refreshed by rebuild_lookups()
-# ---------------------------------------------------------------------------
-
-def _build_command_lookup() -> dict[str, CommandDef]:
- """Map every name and alias to its CommandDef."""
- lookup: dict[str, CommandDef] = {}
- for cmd in COMMAND_REGISTRY:
- lookup[cmd.name] = cmd
- for alias in cmd.aliases:
- lookup[alias] = cmd
- return lookup
-
+# --- Derived lookups (built once at import) ---------------------------------
-_COMMAND_LOOKUP: dict[str, CommandDef] = _build_command_lookup()
+# Every name and alias -> its CommandDef.
+_COMMAND_LOOKUP: dict[str, CommandDef] = {
+ key: cmd for cmd in COMMAND_REGISTRY for key in (cmd.name, *cmd.aliases)
+}
def resolve_command(name: str) -> CommandDef | None:
- """Resolve a command name or alias to its CommandDef.
-
- Accepts names with or without the leading slash.
- """
+ """Resolve a command name or alias (leading slash optional) to its CommandDef."""
return _COMMAND_LOOKUP.get(name.lower().lstrip("/"))
def _build_description(cmd: CommandDef) -> str:
"""Build a CLI-facing description string including usage hint."""
- if cmd.args_hint:
- return f"{cmd.description} (usage: /{cmd.name} {cmd.args_hint})"
- return cmd.description
+ if not cmd.args_hint:
+ return cmd.description
+ return f"{cmd.description} (usage: /{cmd.name} {cmd.args_hint})"
# Backwards-compatible flat dict ("/command" -> description) and the same
# grouped by category. Both exclude gateway_only commands.
COMMANDS: dict[str, str] = {}
COMMANDS_BY_CATEGORY: dict[str, dict[str, str]] = {}
-# Subcommands lookup: "/cmd" -> ["sub1", "sub2", ...]
-SUBCOMMANDS: dict[str, list[str]] = {}
+# Subcommands lookup: "/cmd" -> ["sub1", ...]; explicit ``subcommands`` first (in
+# registry order), then pipe patterns in args_hint ("[on|off|status]") as fallback.
+SUBCOMMANDS: dict[str, list[str]] = {
+ f"/{_cmd.name}": list(_cmd.subcommands) for _cmd in COMMAND_REGISTRY if _cmd.subcommands
+}
for _cmd in COMMAND_REGISTRY:
- if _cmd.subcommands:
- SUBCOMMANDS[f"/{_cmd.name}"] = list(_cmd.subcommands)
if _cmd.gateway_only:
continue
_entries = {f"/{_cmd.name}": _build_description(_cmd)}
@@ -421,6 +385,12 @@ for _cmd in COMMAND_REGISTRY:
COMMANDS.update(_entries)
COMMANDS_BY_CATEGORY.setdefault(_cmd.category, {}).update(_entries)
+_PIPE_SUBS_RE = re.compile(r"[a-z]+(?:\|[a-z]+)+")
+for _cmd in COMMAND_REGISTRY:
+ _m = _PIPE_SUBS_RE.search(_cmd.args_hint) if _cmd.args_hint else None
+ if _m and f"/{_cmd.name}" not in SUBCOMMANDS:
+ SUBCOMMANDS[f"/{_cmd.name}"] = _m.group(0).split("|")
+
# /help renderer sub-groups for the ~46-command "Session" category. Category
# itself is load-bearing for gateway help, so commands are not re-tagged;
@@ -436,21 +406,7 @@ HELP_SESSION_SUBGROUPS: dict[str, tuple[str, ...]] = {
),
}
-# Fallback: derive subcommands from pipe patterns in args_hint ("[on|off|status]")
-# for commands without an explicit ``subcommands`` field.
-_PIPE_SUBS_RE = re.compile(r"[a-z]+(?:\|[a-z]+)+")
-for _cmd in COMMAND_REGISTRY:
- key = f"/{_cmd.name}"
- if key in SUBCOMMANDS or not _cmd.args_hint:
- continue
- m = _PIPE_SUBS_RE.search(_cmd.args_hint)
- if m:
- SUBCOMMANDS[key] = m.group(0).split("|")
-
-
-# ---------------------------------------------------------------------------
-# Gateway helpers
-# ---------------------------------------------------------------------------
+# --- Gateway helpers --------------------------------------------------------
# All names + aliases the gateway dispatches. Config-gated commands are
# included; their handler checks the gate at runtime.
@@ -463,12 +419,8 @@ GATEWAY_KNOWN_COMMANDS: frozenset[str] = frozenset(
def is_gateway_known_command(name: str | None) -> bool:
- """Return True if ``name`` is a built-in or plugin gateway slash command.
-
- Plugin commands are looked up lazily so importing this module never forces
- plugin discovery. Gateway code uses this to decide whether to emit
- ``command:<name>`` hooks — plugins get the same lifecycle events as built-ins.
- """
+ """True if ``name`` is a built-in or plugin gateway slash command (plugins looked
+ up lazily); decides whether the gateway emits ``command:<name>`` hooks."""
if not name:
return False
return name in GATEWAY_KNOWN_COMMANDS or any(
@@ -485,32 +437,26 @@ ACTIVE_SESSION_BYPASS_COMMANDS: frozenset[str] = frozenset(
def is_interrupt_then_dispatch(command_name: str | None) -> bool:
- """True when *command_name* (or alias) has busy_policy "interrupt_then_dispatch".
-
- Guard 1 (gateway/platforms/base.py) routes these through the cancel-handoff
- path that serializes cancellation + runner response + pending drain.
- """
- if not command_name:
- return False
- cmd = resolve_command(command_name)
+ """True when *command_name* (or alias) has busy_policy "interrupt_then_dispatch";
+ Guard 1 (gateway/platforms/base.py) routes these through the cancel-handoff path."""
+ cmd = resolve_command(command_name) if command_name else None
return cmd is not None and cmd.busy_policy == "interrupt_then_dispatch"
def should_bypass_active_session(command_name: str | None) -> bool:
- """Return True for any resolvable slash command.
-
- Every recognized slash command is dispatched mid-run — either by its
- Level-2 handler in gateway/run.py or by the "busy — wait or /stop first"
- catch-all — never queued: gateway.run's safety net discards command text
- that reaches the pending queue, so a queued mid-run /model would interrupt
- the agent AND vanish with a zero-char response.
- ACTIVE_SESSION_BYPASS_COMMANDS is the subset with explicit handlers.
+ """True for any resolvable slash command.
+
+ Every recognized command is dispatched mid-run (by its Guard-2 handler or the
+ "busy — wait or /stop first" catch-all), never queued: gateway.run's safety net
+ discards command text reaching the pending queue, so a queued /model would
+ interrupt the agent AND vanish with a zero-char response.
"""
return resolve_command(command_name) is not None if command_name else False
def _resolve_config_gates() -> set[str]:
- """Return canonical names of commands whose ``gateway_config_gate`` dotpath is truthy in config.yaml (empty set on any error)."""
+ """Canonical names of commands whose ``gateway_config_gate`` dotpath is truthy in
+ config.yaml (empty set on any error)."""
gated = [c for c in COMMAND_REGISTRY if c.gateway_config_gate]
if not gated:
return set()
@@ -519,32 +465,31 @@ def _resolve_config_gates() -> set[str]:
cfg = read_raw_config()
except Exception:
return set()
- result: set[str] = set()
- for cmd in gated:
+
+ def _lookup(dotpath: str) -> Any:
val: Any = cfg
- for key in cmd.gateway_config_gate.split("."):
- if isinstance(val, dict):
- val = val.get(key)
- else:
- val = None
- break
- if is_truthy_value(val, default=False):
- result.add(cmd.name)
- return result
+ for key in dotpath.split("."):
+ if not isinstance(val, dict):
+ return None
+ val = val.get(key)
+ return val
+ return {
+ cmd.name for cmd in gated
+ if is_truthy_value(_lookup(cmd.gateway_config_gate), default=False)
+ }
-def _is_gateway_available(cmd: CommandDef, config_overrides: set[str] | None = None) -> bool:
- """True if *cmd* appears in gateway surfaces: not ``cli_only``, or its config gate is truthy.
- Pass *config_overrides* from ``_resolve_config_gates()`` to avoid
- re-reading config per command.
- """
+def _is_gateway_available(cmd: CommandDef, config_overrides: set[str] | None = None) -> bool:
+ """True if *cmd* appears in gateway surfaces: not ``cli_only``, or its config gate
+ is truthy. Pass *config_overrides* from ``_resolve_config_gates()`` to avoid
+ re-reading config per command."""
if not cmd.cli_only:
return True
- if cmd.gateway_config_gate:
- overrides = config_overrides if config_overrides is not None else _resolve_config_gates()
- return cmd.name in overrides
- return False
+ if not cmd.gateway_config_gate:
+ return False
+ overrides = config_overrides if config_overrides is not None else _resolve_config_gates()
+ return cmd.name in overrides
def gateway_help_lines() -> list[str]:
@@ -555,53 +500,38 @@ def gateway_help_lines() -> list[str]:
if not _is_gateway_available(cmd, overrides):
continue
args = f" {cmd.args_hint}" if cmd.args_hint else ""
- alias_parts: list[str] = []
- for a in cmd.aliases:
- # Skip internal aliases like reload_mcp (underscore variant)
- if a.replace("-", "_") == cmd.name.replace("-", "_") and a != cmd.name:
- continue
- alias_parts.append(f"`/{a}`")
+ # Skip internal aliases like reload_mcp (underscore variant of the name).
+ alias_parts = [
+ f"`/{a}`" for a in cmd.aliases
+ if not (a.replace("-", "_") == cmd.name.replace("-", "_") and a != cmd.name)
+ ]
alias_note = f" (alias: {', '.join(alias_parts)})" if alias_parts else ""
lines.append(f"`/{cmd.name}{args}` -- {cmd.description}{alias_note}")
return lines
def _iter_plugin_command_entries() -> list[tuple[str, str, str]]:
- """Return (name, description, args_hint) tuples for all plugin slash commands.
-
- Registered via :func:`hermes_cli.plugins.PluginContext.register_command`;
- surfaced like ``CommandDef`` entries (Telegram menu, Slack ``/hermes``
- map, Discord picker). Lookup is lazy so importing this module never
- forces plugin discovery (filesystem scans, env-dependent behavior).
- """
+ """(name, description, args_hint) for plugin slash commands registered via
+ ``PluginContext.register_command``; surfaced like ``CommandDef`` entries. Lazy so
+ importing this module never forces plugin discovery."""
try:
from hermes_cli.plugins import get_plugin_commands
- except Exception:
- return []
- try:
commands = get_plugin_commands() or {}
except Exception:
return []
- entries: list[tuple[str, str, str]] = []
- for name, meta in commands.items():
- if not isinstance(name, str) or not isinstance(meta, dict):
- continue
- description = str(meta.get("description") or f"Run /{name}")
- args_hint = str(meta.get("args_hint") or "").strip()
- entries.append((name, description, args_hint))
- return entries
-
-
-
-
-# ---------------------------------------------------------------------------
-# Lazy re-exports (PEP 562) of the extracted modules
-# ---------------------------------------------------------------------------
-# Platform derivations and the prompt_toolkit completer live in sibling
-# modules; their names stay importable from here so every existing
-# ``from hermes_cli.commands import X`` and ``patch("hermes_cli.commands.X")``
-# keeps working. Resolving lazily keeps this registry module import-light for
-# the gateway (no prompt_toolkit, no skill/plugin discovery at import time).
+ return [
+ (name, str(meta.get("description") or f"Run /{name}"),
+ str(meta.get("args_hint") or "").strip())
+ for name, meta in commands.items()
+ if isinstance(name, str) and isinstance(meta, dict)
+ ]
+
+
+# --- Lazy re-exports (PEP 562) ----------------------------------------------
+# Platform derivations and the prompt_toolkit completer live in sibling modules;
+# their names stay importable from here so ``from hermes_cli.commands import X``
+# and ``patch("hermes_cli.commands.X")`` keep working, while this registry module
+# stays import-light for the gateway (no prompt_toolkit, no plugin discovery).
_LAZY_EXPORTS: dict[str, str] = {
name: "hermes_cli.commands_platforms"
for name in (
@@ -625,5 +555,4 @@ def __getattr__(name: str):
if module is None:
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
import importlib
-
return getattr(importlib.import_module(module), name)
diff --git a/hermes_cli/commands_platforms.py b/hermes_cli/commands_platforms.py
index 6c1d679815f..0460529eddc 100644
--- a/hermes_cli/commands_platforms.py
+++ b/hermes_cli/commands_platforms.py
@@ -1,6 +1,6 @@
"""Gateway platform command derivations (Telegram / Discord / Slack) from ``COMMAND_REGISTRY``.
-Extracted from :mod:`hermes_cli.commands`, which re-exports every name here so
+:mod:`hermes_cli.commands` lazily re-exports every name here, so
``from hermes_cli.commands import telegram_menu_commands`` keeps working.
"""
@@ -21,20 +21,26 @@ from hermes_cli.commands import (
# Logger name parity with the origin module (tests capture "hermes_cli.commands").
logger = logging.getLogger("hermes_cli.commands")
-_CMD_NAME_LIMIT = 32
-"""Max command name length shared by Telegram and Discord."""
+_CMD_NAME_LIMIT = 32 # max command name length shared by Telegram and Discord
_TG_INVALID_CHARS = re.compile(r"[^a-z0-9_]")
_TG_MULTI_UNDERSCORE = re.compile(r"_{2,}")
+def _gateway_available_commands() -> list:
+ """Registry entries visible on gateway surfaces (config gates read once)."""
+ overrides = _resolve_config_gates()
+ return [cmd for cmd in COMMAND_REGISTRY if _is_gateway_available(cmd, overrides)]
+
+
def _requires_argument(args_hint: str) -> bool:
"""True when selecting a command without text would be incomplete."""
return args_hint.strip().startswith("<")
def _sanitize_telegram_name(raw: str) -> str:
- """Telegram allows only ``[a-z0-9_]``: lowercase → hyphens to underscores → strip the rest → collapse/strip ``_``."""
+ """Telegram allows only ``[a-z0-9_]``: lowercase, hyphens -> ``_``, strip the rest,
+ collapse/strip ``_``."""
name = _TG_INVALID_CHARS.sub("", raw.lower().replace("-", "_"))
return _TG_MULTI_UNDERSCORE.sub("_", name).strip("_")
@@ -44,7 +50,9 @@ def _truncate_desc(desc: str, limit: int) -> str:
return desc if len(desc) <= limit else desc[:limit - 3] + "..."
-def _clamp_command_names(entries: Sequence[tuple[str, ...]], reserved: set[str]) -> list[tuple[str, ...]]:
+def _clamp_command_names(
+ entries: Sequence[tuple[str, ...]], reserved: set[str],
+) -> list[tuple[str, ...]]:
"""Enforce the 32-char Telegram/Discord name limit with collision avoidance.
Over-long names are truncated; if that collides with *reserved* or an
@@ -73,30 +81,27 @@ def _clamp_command_names(entries: Sequence[tuple[str, ...]], reserved: set[str])
return result
-# ---------------------------------------------------------------------------
-# Telegram
-# ---------------------------------------------------------------------------
+# --- Telegram ---------------------------------------------------------------
def telegram_bot_commands(*, include_plugins: bool = True) -> list[tuple[str, str]]:
"""Return (command_name, description) pairs for Telegram setMyCommands.
- Names are Telegram-sanitized; aliases are skipped (one menu entry per
- canonical command). Built-ins that require arguments are **included** —
- their handlers show usage text when selected bare. Plugin commands
- requiring arguments are **excluded** because plugins may lack a no-arg
- fallback; callers needing source metadata pass ``include_plugins=False``
- and use :func:`_collect_gateway_skill_entries`.
+ Names are Telegram-sanitized; aliases are skipped (one entry per canonical
+ command). Built-ins requiring arguments are **included** (their handlers show
+ usage when selected bare); plugin commands requiring arguments are **excluded**
+ because plugins may lack a no-arg fallback. Callers needing source metadata
+ pass ``include_plugins=False`` and use :func:`_collect_gateway_skill_entries`.
"""
- overrides = _resolve_config_gates()
- pairs = [(cmd.name, cmd.description) for cmd in COMMAND_REGISTRY if _is_gateway_available(cmd, overrides)]
+ pairs = [(cmd.name, cmd.description) for cmd in _gateway_available_commands()]
if include_plugins:
- pairs += [(n, d) for n, d, hint in _iter_plugin_command_entries() if not _requires_argument(hint)]
+ pairs += [(n, d) for n, d, hint in _iter_plugin_command_entries()
+ if not _requires_argument(hint)]
return [(tg, desc) for name, desc in pairs if (tg := _sanitize_telegram_name(name))]
-# Telegram allows 100 BotCommands; the 60-slot default keeps every built-in
-# plus common skill commands visible while staying under the ~4KB payload
-# limit. Tunable via platforms.telegram.extra.command_menu.max_commands.
+# Telegram allows 100 BotCommands; the 60-slot default keeps every built-in plus
+# common skill commands visible under the ~4KB payload limit. Tunable via
+# platforms.telegram.extra.command_menu.max_commands.
_DEFAULT_TELEGRAM_MENU_MAX_COMMANDS = 60
_TELEGRAM_BOT_API_MAX_COMMANDS = 100
# priority_mode -> rank tables consulted in order ("configured" = user list,
@@ -167,12 +172,9 @@ def _sanitized_rank(raw_names: Sequence[str]) -> dict[str, int]:
def _prioritize_telegram_menu_candidates(
candidates: list[tuple[str, str, str, str]],
) -> list[tuple[str, str, str, str]]:
- """Order ``(final_name, description, source, raw_name)`` candidates; default priority applies to core only.
-
- ``raw_name`` is the pre-clamp name so an explicitly configured long command
- stays addressable after Telegram name clamping. "replace" mode ignores the
- built-in defaults entirely.
- """
+ """Order ``(final_name, description, source, raw_name)`` candidates; the default
+ priority applies to core only, "replace" mode ignores it entirely. ``raw_name``
+ is the pre-clamp name so a configured long command stays addressable."""
# Lazy origin import: tests patch ``hermes_cli.commands._telegram_command_menu_config``.
from hermes_cli.commands import _telegram_command_menu_config as menu_config
@@ -195,27 +197,26 @@ def _prioritize_telegram_menu_candidates(
return [c for _i, c in sorted(enumerate(candidates), key=lambda item: _rank(*item))]
-# ---------------------------------------------------------------------------
-# Shared skill/plugin collection for gateway platforms
-# ---------------------------------------------------------------------------
+# --- Shared skill/plugin collection for gateway platforms -------------------
def _iter_gateway_skills(platform: str):
"""Yield ``(cmd_key, info, rel_parts)`` for skills eligible as gateway slash commands.
- Scan roots are the local ``SKILLS_DIR`` plus every configured
- ``skills.external_dirs`` / trusted project skills dir — a skill anywhere
- else, or under the hub dir (``SKILLS_DIR/.hub``), is skipped, as are skills
- disabled for *platform*. Paths are resolved on both sides so symlinked roots
- (macOS ``/var`` → ``/private/var``) still match, and matching is per path
- component so ``/my-skills`` never admits ``/my-skills-extra``. ``rel_parts``
- is the skill dir relative to its root (``("creative", "ascii-art")``) for
- category derivation. Iterates ``sorted(skill_cmds)`` so first-wins
- collision handling is alphabetical.
+ Scan roots: local ``SKILLS_DIR`` plus configured ``skills.external_dirs`` /
+ trusted project skills dirs; anything elsewhere or under ``SKILLS_DIR/.hub``
+ is skipped, as are skills disabled for *platform*. Paths are resolved on both
+ sides (symlinked roots such as macOS ``/var`` -> ``/private/var`` still match)
+ and matched per path component (``/my-skills`` never admits
+ ``/my-skills-extra``). ``rel_parts`` is the skill dir relative to its root
+ (``("creative", "ascii-art")``) for category derivation. Iterates
+ ``sorted(skill_cmds)`` so first-wins collision handling is alphabetical.
"""
from pathlib import Path
from agent.skill_commands import get_skill_commands
- from agent.skill_utils import get_disabled_skill_names, get_external_skills_dirs, get_project_skills_dirs
+ from agent.skill_utils import (
+ get_disabled_skill_names, get_external_skills_dirs, get_project_skills_dirs,
+ )
from tools.skills_tool import SKILLS_DIR
try:
@@ -260,13 +261,13 @@ def _collect_gateway_skill_entries(
Plugin slash commands come first and are never trimmed; skill commands
(alphabetical, see :func:`_iter_gateway_skills`) fill the remaining
- *max_slots* — ``None`` returns every candidate for a caller applying its
- own global cap. *reserved_names* (built-in names) is mutated in place as
- names are claimed. *sanitize_name* runs before clamping and may return ""
- to skip an entry. Returns ``(entries, hidden_count)`` with entries of
- ``(name, description, cmd_key, raw_name)`` — ``cmd_key`` is the original
- skill key ("" for plugins); ``raw_name`` the sanitized pre-clamp name used
- for configured-priority matching.
+ *max_slots* — ``None`` returns every candidate for a caller applying its own
+ cap. *reserved_names* (built-in names) is mutated in place as names are
+ claimed. *sanitize_name* runs before clamping and may return "" to skip an
+ entry. Returns ``(entries, hidden_count)`` with entries of
+ ``(name, description, cmd_key, raw_name)`` — ``cmd_key`` is the original skill
+ key ("" for plugins); ``raw_name`` the sanitized pre-clamp name used for
+ configured-priority matching.
"""
sanitize = sanitize_name or (lambda n: n)
# Tier 1: plugin slash commands (never trimmed). No cmd_key — "" placeholder.
@@ -275,10 +276,11 @@ def _collect_gateway_skill_entries(
from hermes_cli.plugins import get_plugin_commands
plugin_cmds = get_plugin_commands()
for cmd_name in sorted(plugin_cmds):
- if platform == "telegram" and _requires_argument(str(plugin_cmds[cmd_name].get("args_hint") or "")):
+ meta = plugin_cmds[cmd_name]
+ if platform == "telegram" and _requires_argument(str(meta.get("args_hint") or "")):
continue
if name := sanitize(cmd_name):
- desc = _truncate_desc(plugin_cmds[cmd_name].get("description", "Plugin command"), desc_limit)
+ desc = _truncate_desc(meta.get("description", "Plugin command"), desc_limit)
plugin_entries.append((name, desc, "", name))
except Exception:
pass
@@ -291,7 +293,8 @@ def _collect_gateway_skill_entries(
try:
for cmd_key, info, _rel in _iter_gateway_skills(platform):
if name := sanitize(cmd_key.lstrip("/")):
- skill_entries.append((name, _truncate_desc(info.get("description", ""), desc_limit), cmd_key, name))
+ desc = _truncate_desc(info.get("description", ""), desc_limit)
+ skill_entries.append((name, desc, cmd_key, name))
except Exception:
pass
skill_entries = _clamp_command_names(skill_entries, reserved_names)
@@ -306,11 +309,10 @@ def _collect_gateway_skill_entries(
def telegram_menu_commands(max_commands: int = 100) -> tuple[list[tuple[str, str]], int]:
"""Return ``(menu_commands, hidden_count)`` for Telegram, capped to the Bot API limit.
- Tier order: core CommandDefs, then plugin slash commands, then skill
- commands (alphabetical; hub skills and telegram-disabled skills excluded).
- Tiers keep their relative order unless named in
- ``platforms.telegram.extra.command_menu.priority`` — explicit priority is
- applied to the combined list *before* the cap, so a prioritized dynamic
+ Tier order: core CommandDefs, plugin slash commands, skill commands
+ (alphabetical; hub and telegram-disabled skills excluded). Tiers keep their
+ relative order unless named in ``platforms.telegram.extra.command_menu.priority``
+ — applied to the combined list *before* the cap, so a prioritized dynamic
command can displace an unprioritized core command.
"""
# Lazy origin import: tests patch ``hermes_cli.commands.telegram_bot_commands``.
@@ -325,16 +327,15 @@ def telegram_menu_commands(max_commands: int = 100) -> tuple[list[tuple[str, str
sanitize_name=_sanitize_telegram_name,
)
candidates = [(name, desc, "core", name) for name, desc in core_commands]
- candidates += [(name, desc, "skill" if cmd_key else "plugin", raw) for name, desc, cmd_key, raw in entries]
+ candidates += [(name, desc, "skill" if cmd_key else "plugin", raw)
+ for name, desc, cmd_key, raw in entries]
candidates = _prioritize_telegram_menu_candidates(candidates)
overflow_count = max(0, len(candidates) - max_commands)
menu = [(name, desc) for name, desc, _source, _raw_name in candidates[:max_commands]]
return menu, hidden_count + overflow_count
-# ---------------------------------------------------------------------------
-# Discord
-# ---------------------------------------------------------------------------
+# --- Discord ----------------------------------------------------------------
def discord_skill_commands_by_category(
reserved_names: set[str],
@@ -344,24 +345,22 @@ def discord_skill_commands_by_category(
Skills nested >= 2 levels under a scan root (``creative/ascii-art/SKILL.md``)
are grouped under ``categories[top_level]``; root-level skills are
*uncategorized*. Entries are ``(name, description, cmd_key)`` with names
- clamped to 32 chars and descriptions to 100. Eligibility follows
- :func:`_iter_gateway_skills`. No per-group cap is applied — the caller
- flattens everything into one autocomplete callback, which scales to
- thousands of entries; ``hidden_count`` only reports 32-char clamp
+ clamped to 32 chars and descriptions to 100; eligibility follows
+ :func:`_iter_gateway_skills`. No per-group cap — the caller flattens everything
+ into one autocomplete callback; ``hidden_count`` only reports 32-char clamp
collisions against reserved names or earlier skills.
"""
categories: dict[str, list[tuple[str, str, str]]] = {}
uncategorized: list[tuple[str, str, str]] = []
- # clamped name → origin. Reserved (gateway-builtin) names carry a sentinel
- # so the warning can distinguish "collided with a reserved command" from
- # "two skills collided on the 32-char clamp" — the rename-worthy case.
+ # clamped name -> origin. Reserved (gateway-builtin) names carry a sentinel so
+ # the warning distinguishes "collided with a reserved command" from "two
+ # skills collided on the 32-char clamp" — the rename-worthy case.
names_used: dict[str, str] = dict.fromkeys(reserved_names, "<reserved>")
hidden = 0
try:
for cmd_key, info, rel_parts in _iter_gateway_skills("discord"):
# On collision the first (alphabetical) skill wins and the loser is
- # dropped from the picker; warn loudly, since a silent ``hidden``
- # count gave skill authors no way to discover the drop.
+ # dropped from the picker; warn loudly so skill authors can discover it.
discord_name = cmd_key.lstrip("/")[:32]
prior = names_used.get(discord_name)
if prior == "<reserved>":
@@ -387,16 +386,17 @@ def discord_skill_commands_by_category(
continue
names_used[discord_name] = cmd_key
entry = (discord_name, _truncate_desc(info.get("description", ""), 100), cmd_key)
- # creative/ascii-art/SKILL.md → category "creative"; root-level skills are uncategorized.
- (categories.setdefault(rel_parts[0], []) if len(rel_parts) >= 2 else uncategorized).append(entry)
+ # creative/ascii-art/SKILL.md -> category "creative"; root-level = uncategorized.
+ if len(rel_parts) >= 2:
+ categories.setdefault(rel_parts[0], []).append(entry)
+ else:
+ uncategorized.append(entry)
except Exception:
pass
return categories, uncategorized, hidden
-# ---------------------------------------------------------------------------
-# Slack native slash commands
-# ---------------------------------------------------------------------------
+# --- Slack native slash commands --------------------------------------------
# Slack slash names: lowercase a-z, 0-9, hyphens, underscores, max 32 chars;
# an app manifest accepts up to 50 slash commands.
@@ -411,18 +411,19 @@ _SLACK_RESERVED_COMMANDS = frozenset({
"topic", "mute", "pro", "shortcuts",
})
-# Canonical commands intentionally NOT given a native Slack slash slot. Slack
-# caps apps at 50 slash commands and the registry is at that ceiling; rather
-# than let the clamp silently drop whichever command sorts last (breaking the
-# Telegram-parity test), low-frequency commands are routed through
-# ``/hermes <command>`` on Slack only. They stay native on every other surface.
-# Rule: when a new canonical command tips the registry past the cap, demote a
-# rarer one-off lookup here (version, whoami, platform, diff, update, ...)
-# rather than a recurring interactive surface (context, loop, save, approvals).
-# Keep TIGHT and intentional — the parity test reads this set. (Aliases are
-# never pinned ahead of canonicals: /bg and /btw became canonical commands
-# instead, so they win first-pass slots on their own.)
-_SLACK_VIA_HERMES_ONLY = frozenset({"topup", "moa", "debug", "egress", "init", "version", "diff", "update", "heartbeat", "refine", "review", "pause", "whoami", "platform", "insights"})
+# Canonical commands intentionally NOT given a native Slack slash slot: Slack caps
+# apps at 50 and the registry is at that ceiling, so rather than let the clamp
+# silently drop whichever command sorts last (breaking the Telegram-parity test),
+# low-frequency commands go through ``/hermes <command>`` on Slack only (native
+# everywhere else). Rule: when a new canonical command tips past the cap, demote a
+# rarer one-off lookup here (version, whoami, platform, diff, update, ...) rather
+# than a recurring interactive surface (context, loop, save, approvals). Keep
+# TIGHT — the parity test reads this set. Aliases are never pinned ahead of
+# canonicals (/bg and /btw became canonical so they win first-pass slots).
+_SLACK_VIA_HERMES_ONLY = frozenset({
+ "topup", "moa", "debug", "egress", "init", "version", "diff", "update", "heartbeat",
+ "refine", "review", "pause", "whoami", "platform", "insights",
+})
def _sanitize_slack_name(raw: str) -> str:
@@ -433,22 +434,22 @@ def _sanitize_slack_name(raw: str) -> str:
def slack_native_slashes() -> list[tuple[str, str, str]]:
"""Return (slash_name, description, usage_hint) triples for Slack.
- Every gateway-available command (canonical names first, then aliases,
- then plugin commands) becomes a standalone Slack slash, clamped to the
- 50-command cap with duplicate avoidance. Names colliding with a Slack
- built-in (``/status``, ``/me``, ...) or listed in _SLACK_VIA_HERMES_ONLY
- are skipped. ``/hermes`` is always the first entry so the
- ``/hermes <command>`` form keeps working for anything dropped.
+ Every gateway-available command (canonical names first, then aliases, then
+ plugin commands) becomes a standalone Slack slash, clamped to the 50-command
+ cap with duplicate avoidance. Names colliding with a Slack built-in
+ (``/status``, ``/me``, ...) or in _SLACK_VIA_HERMES_ONLY are skipped.
+ ``/hermes`` is always first so ``/hermes <command>`` works for anything dropped.
"""
- overrides = _resolve_config_gates()
- available = [cmd for cmd in COMMAND_REGISTRY if _is_gateway_available(cmd, overrides)]
+ available = _gateway_available_commands()
# Canonical names first so they win slots at the cap; aliases second; plugins third.
wanted = [(cmd.name, cmd.description, cmd.args_hint or "") for cmd in available]
wanted += [(alias, f"Alias for /{cmd.name} — {cmd.description}", cmd.args_hint or "")
for cmd in available for alias in cmd.aliases]
wanted += [(name, desc, hint or "") for name, desc, hint in _iter_plugin_command_entries()]
- entries: list[tuple[str, str, str]] = [("hermes", "Talk to Hermes or run a subcommand", "[subcommand] [args]")]
+ entries: list[tuple[str, str, str]] = [
+ ("hermes", "Talk to Hermes or run a subcommand", "[subcommand] [args]"),
+ ]
seen = {"hermes"}
for name, desc, hint in wanted:
slack_name = _sanitize_slack_name(name)
@@ -466,16 +467,19 @@ def slack_native_slashes() -> list[tuple[str, str, str]]:
return entries
-def slack_app_manifest(request_url: str = "https://hermes-agent.local/slack/commands") -> dict[str, Any]:
+def slack_app_manifest(
+ request_url: str = "https://hermes-agent.local/slack/commands",
+) -> dict[str, Any]:
"""Return the ``features.slash_commands`` manifest portion for all gateway slashes.
- ``request_url`` is schema-required but ignored in Socket Mode (a
- placeholder is fine). Only this portion is returned so we stay decoupled
- from the rest of the manifest users configure once in the Slack UI.
+ ``request_url`` is schema-required but ignored in Socket Mode (a placeholder is
+ fine). Only this portion is returned so we stay decoupled from the rest of the
+ manifest users configure once in the Slack UI.
"""
slashes = []
for name, desc, usage in slack_native_slashes():
- entry = {"command": f"/{name}", "description": desc or f"Run /{name}", "should_escape": False, "url": request_url}
+ entry = {"command": f"/{name}", "description": desc or f"Run /{name}",
+ "should_escape": False, "url": request_url}
if usage:
entry["usage_hint"] = usage
slashes.append(entry)
@@ -483,13 +487,11 @@ def slack_app_manifest(request_url: str = "https://hermes-agent.local/slack/comm
def slack_subcommand_map() -> dict[str, str]:
- """Return name/alias -> "/command" mapping for the Slack ``/hermes`` handler, plugin commands included."""
- overrides = _resolve_config_gates()
- mapping: dict[str, str] = {}
- for cmd in COMMAND_REGISTRY:
- if _is_gateway_available(cmd, overrides):
- for name in (cmd.name, *cmd.aliases):
- mapping[name] = f"/{name}"
+ """name/alias -> "/command" for the Slack ``/hermes`` handler, plugin commands included."""
+ mapping: dict[str, str] = {
+ name: f"/{name}"
+ for cmd in _gateway_available_commands() for name in (cmd.name, *cmd.aliases)
+ }
for name, _description, _args_hint in _iter_plugin_command_entries():
mapping.setdefault(name, f"/{name}")
return mapping