mirror of
https://github.com/NousResearch/hermes-agent.git
synced 2026-11-21 07:55:08 +00:00
refactor: registry-owned execute() on CommandDef — informational commands unified (thin slice)
This commit is contained in:
parent
ab08e8fc76
commit
bcb352eeab
7 changed files with 448 additions and 105 deletions
7
cli.py
7
cli.py
|
|
@ -9754,9 +9754,12 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):
|
|||
elif canonical == "context":
|
||||
self._show_context_breakdown(cmd_original)
|
||||
elif canonical == "egress":
|
||||
from hermes_cli.proxy_cli import format_status_text
|
||||
from hermes_cli.slash_exec import CommandContext, execute_command
|
||||
|
||||
self._console_print(format_status_text(), highlight=False, markup=False)
|
||||
self._console_print(
|
||||
execute_command("egress", CommandContext(surface="cli")).text,
|
||||
highlight=False, markup=False,
|
||||
)
|
||||
elif canonical == "statusbar":
|
||||
self._status_bar_visible = not self._status_bar_visible
|
||||
state = "visible" if self._status_bar_visible else "hidden"
|
||||
|
|
|
|||
|
|
@ -341,7 +341,7 @@ class GatewaySlashCommandsMixin:
|
|||
reports the active profile and default home, byte-identical to before.
|
||||
"""
|
||||
from hermes_constants import display_hermes_home
|
||||
from hermes_cli.profiles import get_active_profile_name
|
||||
from hermes_cli.slash_exec import CommandContext, execute_command
|
||||
|
||||
multiplexed = getattr(
|
||||
getattr(self, "config", None), "multiplex_profiles", False
|
||||
|
|
@ -349,11 +349,9 @@ class GatewaySlashCommandsMixin:
|
|||
source = getattr(event, "source", None)
|
||||
|
||||
profile_name = ""
|
||||
display = ""
|
||||
if multiplexed:
|
||||
profile_name = (getattr(source, "profile", "") or "").strip()
|
||||
profile_name = profile_name or get_active_profile_name()
|
||||
|
||||
if multiplexed:
|
||||
try:
|
||||
from gateway.run import _profile_runtime_scope
|
||||
|
||||
|
|
@ -362,12 +360,20 @@ class GatewaySlashCommandsMixin:
|
|||
display = display_hermes_home()
|
||||
except Exception:
|
||||
display = display_hermes_home()
|
||||
else:
|
||||
display = display_hermes_home()
|
||||
|
||||
# Shared executor resolves process-level fallbacks; the multiplexed
|
||||
# per-source overrides (when any) ride in via options.
|
||||
reply = execute_command(
|
||||
"profile",
|
||||
CommandContext(
|
||||
surface="gateway",
|
||||
options={"profile_name": profile_name, "home_display": display},
|
||||
),
|
||||
)
|
||||
|
||||
lines = [
|
||||
t("gateway.profile.header", profile=profile_name),
|
||||
t("gateway.profile.home", home=display),
|
||||
t("gateway.profile.header", profile=reply.data["profile"]),
|
||||
t("gateway.profile.home", home=reply.data["home"]),
|
||||
]
|
||||
|
||||
return "\n".join(lines)
|
||||
|
|
@ -1624,89 +1630,38 @@ class GatewaySlashCommandsMixin:
|
|||
|
||||
async def _handle_version_command(self, event: MessageEvent) -> str:
|
||||
"""Handle /version — show the running Hermes Agent version."""
|
||||
from hermes_cli.banner import format_banner_version_label
|
||||
from hermes_cli.slash_exec import CommandContext, execute_command
|
||||
|
||||
return format_banner_version_label()
|
||||
return execute_command("version", CommandContext(surface="gateway")).text
|
||||
|
||||
async def _handle_help_command(self, event: MessageEvent) -> str:
|
||||
"""Handle /help command - list available commands."""
|
||||
from gateway.run import _telegramize_command_mentions
|
||||
from hermes_cli.commands import gateway_help_lines
|
||||
lines = [
|
||||
t("gateway.help.header"),
|
||||
*gateway_help_lines(),
|
||||
]
|
||||
try:
|
||||
from agent.skill_commands import get_skill_commands
|
||||
skill_cmds = get_skill_commands()
|
||||
if skill_cmds:
|
||||
lines.append(t("gateway.help.skill_header", count=len(skill_cmds)))
|
||||
# Show first 10, then point to /commands for the rest
|
||||
sorted_cmds = sorted(skill_cmds)
|
||||
for cmd in sorted_cmds[:10]:
|
||||
lines.append(f"`{cmd}` — {skill_cmds[cmd]['description']}")
|
||||
if len(sorted_cmds) > 10:
|
||||
lines.append(t("gateway.help.more_use_commands", count=len(sorted_cmds) - 10))
|
||||
except Exception:
|
||||
pass
|
||||
from hermes_cli.slash_exec import CommandContext, execute_command
|
||||
|
||||
reply = execute_command("help", CommandContext(surface="gateway"))
|
||||
return _telegramize_command_mentions(
|
||||
"\n".join(lines),
|
||||
reply.text,
|
||||
getattr(getattr(event, "source", None), "platform", None),
|
||||
)
|
||||
|
||||
async def _handle_commands_command(self, event: MessageEvent) -> str:
|
||||
from gateway.run import _telegramize_command_mentions
|
||||
from hermes_cli.commands import gateway_help_lines
|
||||
|
||||
raw_args = event.get_command_args().strip()
|
||||
if raw_args:
|
||||
try:
|
||||
requested_page = int(raw_args)
|
||||
except ValueError:
|
||||
return t("gateway.commands.usage")
|
||||
else:
|
||||
requested_page = 1
|
||||
|
||||
# Build combined entry list: built-in commands + skill commands
|
||||
entries = list(gateway_help_lines())
|
||||
try:
|
||||
from agent.skill_commands import get_skill_commands
|
||||
skill_cmds = get_skill_commands()
|
||||
if skill_cmds:
|
||||
entries.append("")
|
||||
entries.append(t("gateway.commands.skill_header"))
|
||||
for cmd in sorted(skill_cmds):
|
||||
desc = skill_cmds[cmd].get("description", "").strip() or t("gateway.commands.default_desc")
|
||||
entries.append(f"`{cmd}` — {desc}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not entries:
|
||||
return t("gateway.commands.none")
|
||||
|
||||
from hermes_cli.slash_exec import CommandContext, execute_command
|
||||
from gateway.config import Platform
|
||||
page_size = 15 if event.source.platform == Platform.TELEGRAM else 20
|
||||
total_pages = max(1, (len(entries) + page_size - 1) // page_size)
|
||||
page = max(1, min(requested_page, total_pages))
|
||||
start = (page - 1) * page_size
|
||||
page_entries = entries[start:start + page_size]
|
||||
|
||||
lines = [
|
||||
t("gateway.commands.header", total=len(entries), page=page, total_pages=total_pages),
|
||||
"",
|
||||
*page_entries,
|
||||
]
|
||||
if total_pages > 1:
|
||||
nav_parts = []
|
||||
if page > 1:
|
||||
nav_parts.append(t("gateway.commands.nav_prev", page=page - 1))
|
||||
if page < total_pages:
|
||||
nav_parts.append(t("gateway.commands.nav_next", page=page + 1))
|
||||
lines.extend(["", " | ".join(nav_parts)])
|
||||
if page != requested_page:
|
||||
lines.append(t("gateway.commands.out_of_range", requested=requested_page, page=page))
|
||||
# Page size is a surface parameter (Telegram messages are shorter).
|
||||
page_size = 15 if event.source.platform == Platform.TELEGRAM else 20
|
||||
reply = execute_command(
|
||||
"commands",
|
||||
CommandContext(
|
||||
surface="gateway",
|
||||
args=event.get_command_args(),
|
||||
options={"page_size": page_size},
|
||||
),
|
||||
)
|
||||
return _telegramize_command_mentions(
|
||||
"\n".join(lines),
|
||||
reply.text,
|
||||
getattr(getattr(event, "source", None), "platform", None),
|
||||
)
|
||||
|
||||
|
|
@ -5177,19 +5132,20 @@ class GatewaySlashCommandsMixin:
|
|||
message suitable for any gateway adapter; bundles are loaded by
|
||||
invoking the bundle's own ``/<slug>`` command, not by this one.
|
||||
"""
|
||||
try:
|
||||
from agent.skill_bundles import list_bundles, _bundles_dir
|
||||
except Exception as exc:
|
||||
logger.warning("Bundles command unavailable: %s", exc)
|
||||
return f"Bundles subsystem unavailable: {exc}"
|
||||
from hermes_cli.slash_exec import CommandContext, execute_command
|
||||
|
||||
bundles = list_bundles()
|
||||
reply = execute_command("bundles", CommandContext(surface="gateway"))
|
||||
if "error" in reply.data:
|
||||
logger.warning("Bundles command unavailable: %s", reply.data["error"])
|
||||
return reply.text
|
||||
|
||||
bundles = reply.data["bundles"]
|
||||
if not bundles:
|
||||
return (
|
||||
"No skill bundles installed.\n"
|
||||
"Create one on the host with:\n"
|
||||
" `hermes bundles create <name> --skill <s1> --skill <s2>`\n"
|
||||
f"Directory: `{_bundles_dir()}`"
|
||||
f"Directory: `{reply.data['dir']}`"
|
||||
)
|
||||
|
||||
lines = [f"**Skill Bundles** ({len(bundles)} installed):", ""]
|
||||
|
|
|
|||
|
|
@ -693,11 +693,11 @@ class CLICommandsMixin:
|
|||
|
||||
def _handle_profile_command(self):
|
||||
"""Display active profile name and home directory."""
|
||||
from hermes_constants import display_hermes_home
|
||||
from hermes_cli.profiles import get_active_profile_name
|
||||
from hermes_cli.slash_exec import CommandContext, execute_command
|
||||
|
||||
display = display_hermes_home()
|
||||
profile_name = get_active_profile_name()
|
||||
reply = execute_command("profile", CommandContext(surface="cli"))
|
||||
profile_name = reply.data["profile"]
|
||||
display = reply.data["home"]
|
||||
|
||||
print()
|
||||
print(f" Profile: {profile_name}")
|
||||
|
|
@ -2020,20 +2020,21 @@ class CLICommandsMixin:
|
|||
of their session. Bundles are loaded via ``/<bundle-name>``.
|
||||
"""
|
||||
from cli import ChatConsole, _BOLD, _DIM, _RST, _accent_hex, _cprint
|
||||
try:
|
||||
from agent.skill_bundles import list_bundles, _bundles_dir
|
||||
except Exception as exc:
|
||||
_cprint(f"\033[1;31mBundle subsystem unavailable: {exc}{_RST}")
|
||||
from hermes_cli.slash_exec import CommandContext, execute_command
|
||||
|
||||
reply = execute_command("bundles", CommandContext(surface="cli"))
|
||||
if "error" in reply.data:
|
||||
_cprint(f"\033[1;31mBundle subsystem unavailable: {reply.data['error']}{_RST}")
|
||||
return
|
||||
|
||||
bundles = list_bundles()
|
||||
bundles = reply.data["bundles"]
|
||||
if not bundles:
|
||||
_cprint(" No skill bundles installed.")
|
||||
_cprint(
|
||||
f" {_DIM}Create one with: hermes bundles create "
|
||||
f"<name> --skill <s1> --skill <s2>{_RST}"
|
||||
)
|
||||
_cprint(f" {_DIM}Directory: {_bundles_dir()}{_RST}")
|
||||
_cprint(f" {_DIM}Directory: {reply.data['dir']}{_RST}")
|
||||
return
|
||||
|
||||
_cprint(f"\n ▣ {_BOLD}Skill Bundles{_RST} ({len(bundles)} installed):")
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import shutil
|
|||
import subprocess
|
||||
import time
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from utils import is_truthy_value
|
||||
|
|
@ -77,6 +77,15 @@ class CommandDef:
|
|||
# normal handler (e.g. /goal's control-verb whitelist, /queue's FIFO
|
||||
# enqueue, /model's custom busy-reject text).
|
||||
busy_handler: str | None = None
|
||||
# Registry-owned shared execution (thin slice, informational commands).
|
||||
# Names a key in ``hermes_cli.slash_exec.EXECUTORS`` — a pure formatter
|
||||
# producing the canonical, surface-independent core text. Surfaces
|
||||
# resolve it via ``hermes_cli.slash_exec.run_execute`` and apply only
|
||||
# their own decoration (Rich markup, emoji/markdown, telegramize). A
|
||||
# string key (not a callable) keeps this module import-light: the
|
||||
# gateway can import commands.py without prompt_toolkit and without
|
||||
# pulling in executor dependencies.
|
||||
execute: str | None = None
|
||||
|
||||
|
||||
# Valid values for CommandDef.busy_policy (see field docs above).
|
||||
|
|
@ -153,13 +162,14 @@ COMMAND_REGISTRY: list[CommandDef] = [
|
|||
busy_policy="dispatch"),
|
||||
CommandDef("egress", "Show Docker egress proxy status", "Session",
|
||||
args_hint="[status]", subcommands=("status",),
|
||||
busy_policy="dispatch", busy_handler="egress"),
|
||||
busy_policy="dispatch", busy_handler="egress",
|
||||
execute="egress"),
|
||||
CommandDef("context", "Show detailed context window view with usage gauge, category breakdown, compression stats, and throughput", "Session",
|
||||
aliases=("ctx",), args_hint="[all]", subcommands=("all",),
|
||||
busy_policy="dispatch"),
|
||||
CommandDef("whoami", "Show your slash command access (admin / user)", "Info"),
|
||||
CommandDef("profile", "Show active profile name and home directory", "Info",
|
||||
busy_policy="dispatch"),
|
||||
busy_policy="dispatch", execute="profile"),
|
||||
CommandDef("sethome", "Set this chat as the home channel", "Session",
|
||||
gateway_only=True, aliases=("set-home",)),
|
||||
CommandDef("resume", "Resume a previously-named session", "Session",
|
||||
|
|
@ -242,7 +252,7 @@ COMMAND_REGISTRY: list[CommandDef] = [
|
|||
args_hint="[pending|approve|reject|approval] [id|on|off]",
|
||||
subcommands=("pending", "approve", "reject", "approval")),
|
||||
CommandDef("bundles", "List skill bundles (aliases /<name> for multiple skills)",
|
||||
"Tools & Skills"),
|
||||
"Tools & Skills", execute="bundles"),
|
||||
CommandDef("pet", "Toggle or adopt a petdex mascot (/pet, /pet list, /pet <slug>)", "Tools & Skills",
|
||||
cli_only=True, args_hint="[toggle|list|scale <n>|<slug>]", subcommands=("toggle", "list", "scale", "off")),
|
||||
CommandDef("hatch", "Generate a new petdex pet from a description",
|
||||
|
|
@ -285,8 +295,10 @@ COMMAND_REGISTRY: list[CommandDef] = [
|
|||
|
||||
# Info
|
||||
CommandDef("commands", "Browse all commands and skills (paginated)", "Info",
|
||||
gateway_only=True, args_hint="[page]", busy_policy="dispatch"),
|
||||
CommandDef("help", "Show available commands", "Info", busy_policy="dispatch"),
|
||||
gateway_only=True, args_hint="[page]", busy_policy="dispatch",
|
||||
execute="gateway_commands"),
|
||||
CommandDef("help", "Show available commands", "Info", busy_policy="dispatch",
|
||||
execute="gateway_help"),
|
||||
CommandDef("restart", "Gracefully restart the gateway after draining active runs", "Session",
|
||||
gateway_only=True, busy_policy="dispatch"),
|
||||
CommandDef("usage", "Show token usage and rate limits; `reset` redeems a banked Codex limit reset", "Info",
|
||||
|
|
@ -309,7 +321,7 @@ COMMAND_REGISTRY: list[CommandDef] = [
|
|||
CommandDef("update", "Update Hermes Agent to the latest version", "Info",
|
||||
busy_policy="dispatch"),
|
||||
CommandDef("version", "Show Hermes Agent version", "Info", aliases=("v",),
|
||||
busy_policy="dispatch"),
|
||||
busy_policy="dispatch", execute="version"),
|
||||
CommandDef("debug", "Upload debug report (system info + logs) and get shareable links", "Info",
|
||||
args_hint="[nous|local]"),
|
||||
|
||||
|
|
|
|||
|
|
@ -4677,9 +4677,11 @@ def cmd_import(args):
|
|||
|
||||
def _print_version_info(*, check_updates: bool = True) -> None:
|
||||
from hermes_cli.config import detect_install_method
|
||||
from hermes_cli.banner import format_banner_version_label
|
||||
from hermes_cli.slash_exec import CommandContext, execute_command
|
||||
|
||||
print(format_banner_version_label())
|
||||
# Core version line is registry-owned (shared with the gateway /version);
|
||||
# the install/python/SDK detail below is CLI-only decoration.
|
||||
print(execute_command("version", CommandContext(surface="cli")).text)
|
||||
print(f"Install directory: {PROJECT_ROOT}")
|
||||
print(f"Install method: {detect_install_method(PROJECT_ROOT)}")
|
||||
|
||||
|
|
|
|||
272
hermes_cli/slash_exec.py
Normal file
272
hermes_cli/slash_exec.py
Normal file
|
|
@ -0,0 +1,272 @@
|
|||
"""Registry-owned slash command execution (thin slice).
|
||||
|
||||
Shared, surface-independent executors for informational slash commands.
|
||||
``CommandDef.execute`` (hermes_cli/commands.py) names a key in
|
||||
:data:`EXECUTORS`; each surface (CLI REPL, gateway, TUI slash worker via the
|
||||
CLI) resolves that key through :func:`run_execute` and applies only its own
|
||||
decoration (Rich markup, emoji/markdown, ``_telegramize_command_mentions``)
|
||||
to the canonical :class:`CommandReply`.
|
||||
|
||||
Invariant: an executor's output depends only on ``ctx.args`` / ``ctx.options``
|
||||
— never on ``ctx.surface`` — so the core text is identical across surfaces
|
||||
for a fixed context (enforced by tests/hermes_cli/test_commands_execute.py).
|
||||
|
||||
Import discipline: this module imports nothing heavy at module level and
|
||||
``hermes_cli.commands`` does NOT import this module (the ``execute`` field is
|
||||
a plain string), so the gateway can keep importing ``commands.py`` without
|
||||
prompt_toolkit and without cycles.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
__all__ = [
|
||||
"CommandContext",
|
||||
"CommandReply",
|
||||
"EXECUTORS",
|
||||
"execute_command",
|
||||
"resolve_executor",
|
||||
"run_execute",
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Context / reply dataclasses
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CommandContext:
|
||||
"""Surface-provided inputs for a shared command executor."""
|
||||
|
||||
surface: str = "cli" # "cli" | "gateway" | "tui" — decoration only
|
||||
args: str = "" # raw argument string after the command word
|
||||
options: Mapping[str, Any] = field(default_factory=dict) # surface params (page_size, ...)
|
||||
config_get: Callable[[str, Any], Any] | None = None # optional config accessor
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CommandReply:
|
||||
"""Canonical result of a shared executor.
|
||||
|
||||
``text`` is the surface-independent core text. ``data`` carries the
|
||||
structured values the executor derived so a surface may re-render them
|
||||
with its own decoration (Rich columns, markdown bullets) without
|
||||
duplicating the computation. ``format`` is a rendering hint only.
|
||||
"""
|
||||
|
||||
text: str
|
||||
data: Mapping[str, Any] = field(default_factory=dict)
|
||||
format: str = "plain" # "plain" | "markdown" (hint, not a contract)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Executors — pure formatters, no agent/session mutation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _exec_version(ctx: CommandContext) -> CommandReply:
|
||||
"""Core /version text — the banner version label."""
|
||||
from hermes_cli.banner import format_banner_version_label
|
||||
|
||||
return CommandReply(format_banner_version_label())
|
||||
|
||||
|
||||
def _exec_egress(ctx: CommandContext) -> CommandReply:
|
||||
"""Core /egress text — Docker egress proxy status."""
|
||||
from hermes_cli.proxy_cli import format_status_text
|
||||
|
||||
return CommandReply(format_status_text())
|
||||
|
||||
|
||||
def _exec_profile(ctx: CommandContext) -> CommandReply:
|
||||
"""Core /profile data — active profile name + home directory.
|
||||
|
||||
A multiplexed gateway may pre-resolve the per-source profile/home and pass
|
||||
them via ``options`` (``profile_name`` / ``home_display``); otherwise the
|
||||
process-level values are used (identical to the old CLI + non-multiplex
|
||||
gateway behavior).
|
||||
"""
|
||||
profile_name = str(ctx.options.get("profile_name") or "").strip()
|
||||
home_display = str(ctx.options.get("home_display") or "").strip()
|
||||
|
||||
if not profile_name:
|
||||
from hermes_cli.profiles import get_active_profile_name
|
||||
|
||||
profile_name = get_active_profile_name()
|
||||
if not home_display:
|
||||
from hermes_constants import display_hermes_home
|
||||
|
||||
home_display = display_hermes_home()
|
||||
|
||||
return CommandReply(
|
||||
f"Profile: {profile_name}\nHome: {home_display}",
|
||||
data={"profile": profile_name, "home": home_display},
|
||||
)
|
||||
|
||||
|
||||
def _exec_bundles(ctx: CommandContext) -> CommandReply:
|
||||
"""Core /bundles data — installed skill bundles listing."""
|
||||
try:
|
||||
from agent.skill_bundles import _bundles_dir, list_bundles
|
||||
except Exception as exc: # pragma: no cover - env-specific
|
||||
return CommandReply(
|
||||
f"Bundles subsystem unavailable: {exc}",
|
||||
data={"error": str(exc)},
|
||||
)
|
||||
|
||||
bundles = list_bundles()
|
||||
bundles_dir = str(_bundles_dir())
|
||||
if not bundles:
|
||||
return CommandReply(
|
||||
"No skill bundles installed.\n"
|
||||
"Create one with: hermes bundles create <name> --skill <s1> --skill <s2>\n"
|
||||
f"Directory: {bundles_dir}",
|
||||
data={"bundles": [], "dir": bundles_dir},
|
||||
)
|
||||
|
||||
lines = [f"Skill Bundles ({len(bundles)} installed):"]
|
||||
for info in bundles:
|
||||
skill_count = len(info.get("skills", []))
|
||||
desc = info.get("description") or f"Load {skill_count} skills"
|
||||
lines.append(f"/{info['slug']} — {desc} ({skill_count} skills)")
|
||||
for s in info.get("skills", []):
|
||||
lines.append(f" · {s}")
|
||||
lines.append("Invoke a bundle with /<slug> to load all its skills.")
|
||||
return CommandReply(
|
||||
"\n".join(lines),
|
||||
data={"bundles": bundles, "dir": bundles_dir},
|
||||
)
|
||||
|
||||
|
||||
def _exec_help(ctx: CommandContext) -> CommandReply:
|
||||
"""Core gateway /help body (pre platform mention decoration)."""
|
||||
from agent.i18n import t
|
||||
from hermes_cli.commands import gateway_help_lines
|
||||
|
||||
lines = [
|
||||
t("gateway.help.header"),
|
||||
*gateway_help_lines(),
|
||||
]
|
||||
try:
|
||||
from agent.skill_commands import get_skill_commands
|
||||
skill_cmds = get_skill_commands()
|
||||
if skill_cmds:
|
||||
lines.append(t("gateway.help.skill_header", count=len(skill_cmds)))
|
||||
# Show first 10, then point to /commands for the rest
|
||||
sorted_cmds = sorted(skill_cmds)
|
||||
for cmd in sorted_cmds[:10]:
|
||||
lines.append(f"`{cmd}` — {skill_cmds[cmd]['description']}")
|
||||
if len(sorted_cmds) > 10:
|
||||
lines.append(t("gateway.help.more_use_commands", count=len(sorted_cmds) - 10))
|
||||
except Exception:
|
||||
pass
|
||||
return CommandReply("\n".join(lines), format="markdown")
|
||||
|
||||
|
||||
def _exec_commands(ctx: CommandContext) -> CommandReply:
|
||||
"""Core gateway /commands body — paginated command + skill listing.
|
||||
|
||||
``ctx.options["page_size"]`` is a surface parameter (Telegram uses 15,
|
||||
everything else 20) — for a fixed context the text is surface-invariant.
|
||||
"""
|
||||
from agent.i18n import t
|
||||
from hermes_cli.commands import gateway_help_lines
|
||||
|
||||
raw_args = (ctx.args or "").strip()
|
||||
if raw_args:
|
||||
try:
|
||||
requested_page = int(raw_args)
|
||||
except ValueError:
|
||||
return CommandReply(t("gateway.commands.usage"), format="markdown")
|
||||
else:
|
||||
requested_page = 1
|
||||
|
||||
# Build combined entry list: built-in commands + skill commands
|
||||
entries = list(gateway_help_lines())
|
||||
try:
|
||||
from agent.skill_commands import get_skill_commands
|
||||
skill_cmds = get_skill_commands()
|
||||
if skill_cmds:
|
||||
entries.append("")
|
||||
entries.append(t("gateway.commands.skill_header"))
|
||||
for cmd in sorted(skill_cmds):
|
||||
desc = skill_cmds[cmd].get("description", "").strip() or t("gateway.commands.default_desc")
|
||||
entries.append(f"`{cmd}` — {desc}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not entries:
|
||||
return CommandReply(t("gateway.commands.none"), format="markdown")
|
||||
|
||||
try:
|
||||
page_size = int(ctx.options.get("page_size", 20))
|
||||
except (TypeError, ValueError):
|
||||
page_size = 20
|
||||
page_size = max(1, page_size)
|
||||
total_pages = max(1, (len(entries) + page_size - 1) // page_size)
|
||||
page = max(1, min(requested_page, total_pages))
|
||||
start = (page - 1) * page_size
|
||||
page_entries = entries[start:start + page_size]
|
||||
|
||||
lines = [
|
||||
t("gateway.commands.header", total=len(entries), page=page, total_pages=total_pages),
|
||||
"",
|
||||
*page_entries,
|
||||
]
|
||||
if total_pages > 1:
|
||||
nav_parts = []
|
||||
if page > 1:
|
||||
nav_parts.append(t("gateway.commands.nav_prev", page=page - 1))
|
||||
if page < total_pages:
|
||||
nav_parts.append(t("gateway.commands.nav_next", page=page + 1))
|
||||
lines.extend(["", " | ".join(nav_parts)])
|
||||
if page != requested_page:
|
||||
lines.append(t("gateway.commands.out_of_range", requested=requested_page, page=page))
|
||||
return CommandReply("\n".join(lines), format="markdown")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Registry + resolution
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
EXECUTORS: dict[str, Callable[[CommandContext], CommandReply]] = {
|
||||
"version": _exec_version,
|
||||
"egress": _exec_egress,
|
||||
"profile": _exec_profile,
|
||||
"bundles": _exec_bundles,
|
||||
"gateway_help": _exec_help,
|
||||
"gateway_commands": _exec_commands,
|
||||
}
|
||||
|
||||
|
||||
def resolve_executor(cmd_def: Any) -> Callable[[CommandContext], CommandReply] | None:
|
||||
"""Return the shared executor for ``cmd_def`` (or None when not migrated)."""
|
||||
key = getattr(cmd_def, "execute", None)
|
||||
if not key:
|
||||
return None
|
||||
return EXECUTORS.get(key)
|
||||
|
||||
|
||||
def run_execute(cmd_def: Any, ctx: CommandContext) -> CommandReply | None:
|
||||
"""Run ``cmd_def``'s registry-owned executor, if any."""
|
||||
fn = resolve_executor(cmd_def)
|
||||
if fn is None:
|
||||
return None
|
||||
return fn(ctx)
|
||||
|
||||
|
||||
def execute_command(name: str, ctx: CommandContext) -> CommandReply:
|
||||
"""Run the shared executor for the command named ``name``.
|
||||
|
||||
Raises ``LookupError`` when the command is unknown or not migrated —
|
||||
call sites use this only for commands they know carry ``execute``.
|
||||
"""
|
||||
from hermes_cli.commands import resolve_command
|
||||
|
||||
cmd_def = resolve_command(name)
|
||||
reply = run_execute(cmd_def, ctx) if cmd_def is not None else None
|
||||
if reply is None:
|
||||
raise LookupError(f"no registry-owned executor for /{name}")
|
||||
return reply
|
||||
97
tests/hermes_cli/test_commands_execute.py
Normal file
97
tests/hermes_cli/test_commands_execute.py
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
"""Invariant tests for registry-owned slash execution (CommandDef.execute).
|
||||
|
||||
Every ``CommandDef`` with ``execute`` set must:
|
||||
* name a key that exists in :data:`hermes_cli.slash_exec.EXECUTORS`, and
|
||||
* produce IDENTICAL core text across surfaces for a fixed context — the
|
||||
executor may only vary on ``args``/``options``, never on ``surface``.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from hermes_cli.commands import COMMAND_REGISTRY, resolve_command
|
||||
from hermes_cli.slash_exec import (
|
||||
EXECUTORS,
|
||||
CommandContext,
|
||||
CommandReply,
|
||||
execute_command,
|
||||
resolve_executor,
|
||||
run_execute,
|
||||
)
|
||||
|
||||
MIGRATED = [cmd for cmd in COMMAND_REGISTRY if cmd.execute]
|
||||
|
||||
SURFACES = ("cli", "gateway", "tui")
|
||||
|
||||
|
||||
def test_some_commands_are_migrated():
|
||||
names = {cmd.name for cmd in MIGRATED}
|
||||
# The thin-slice set — extend as more commands migrate.
|
||||
assert {"version", "egress", "profile", "bundles", "help", "commands"} <= names
|
||||
|
||||
|
||||
def test_every_execute_key_resolves():
|
||||
for cmd in MIGRATED:
|
||||
assert cmd.execute in EXECUTORS, (
|
||||
f"/{cmd.name} names execute={cmd.execute!r} but no such key in "
|
||||
f"hermes_cli.slash_exec.EXECUTORS"
|
||||
)
|
||||
assert resolve_executor(cmd) is EXECUTORS[cmd.execute]
|
||||
|
||||
|
||||
def test_unmigrated_commands_have_no_executor():
|
||||
for cmd in COMMAND_REGISTRY:
|
||||
if not cmd.execute:
|
||||
assert resolve_executor(cmd) is None
|
||||
assert run_execute(cmd, CommandContext()) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cmd", MIGRATED, ids=lambda c: c.name)
|
||||
def test_core_text_is_surface_invariant(cmd):
|
||||
"""Fixed context ⇒ identical CommandReply text on every surface."""
|
||||
replies = []
|
||||
for surface in SURFACES:
|
||||
ctx = CommandContext(surface=surface, args="", options={"page_size": 20})
|
||||
reply = run_execute(cmd, ctx)
|
||||
assert isinstance(reply, CommandReply)
|
||||
assert isinstance(reply.text, str) and reply.text
|
||||
replies.append(reply.text)
|
||||
assert replies[0] == replies[1] == replies[2], (
|
||||
f"/{cmd.name} core text varies by surface — executors must not "
|
||||
f"branch on ctx.surface"
|
||||
)
|
||||
|
||||
|
||||
def test_execute_command_helper_resolves_aliases():
|
||||
# /v is an alias of /version — the helper resolves through the registry.
|
||||
a = execute_command("version", CommandContext(surface="cli"))
|
||||
b = execute_command("v", CommandContext(surface="gateway"))
|
||||
assert a.text == b.text
|
||||
|
||||
|
||||
def test_execute_command_raises_for_unmigrated():
|
||||
with pytest.raises(LookupError):
|
||||
execute_command("model", CommandContext())
|
||||
with pytest.raises(LookupError):
|
||||
execute_command("definitely-not-a-command", CommandContext())
|
||||
|
||||
|
||||
def test_profile_options_override_process_values():
|
||||
reply = run_execute(
|
||||
resolve_command("profile"),
|
||||
CommandContext(options={"profile_name": "work", "home_display": "~/.hermes-work"}),
|
||||
)
|
||||
assert reply.data == {"profile": "work", "home": "~/.hermes-work"}
|
||||
assert reply.text == "Profile: work\nHome: ~/.hermes-work"
|
||||
|
||||
|
||||
def test_commands_page_size_is_an_option_not_a_surface_branch():
|
||||
"""Telegram's smaller page is parameterized — same option, same text."""
|
||||
cmd = resolve_command("commands")
|
||||
tg = run_execute(cmd, CommandContext(surface="gateway", options={"page_size": 15}))
|
||||
cli = run_execute(cmd, CommandContext(surface="cli", options={"page_size": 15}))
|
||||
assert tg.text == cli.text
|
||||
|
||||
|
||||
def test_commands_bad_page_arg_returns_usage():
|
||||
reply = run_execute(resolve_command("commands"), CommandContext(args="notanumber"))
|
||||
assert "commands" in reply.text.lower() or "usage" in reply.text.lower()
|
||||
Loading…
Add table
Add a link
Reference in a new issue