slash_exec.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. """Registry-owned slash command execution (thin slice).
  2. Invariant: an executor's output depends only on ``ctx.args`` / ``ctx.options`` — never on
  3. ``ctx.surface`` — so the core text is identical across surfaces for a fixed context (enforced by
  4. tests/hermes_cli/test_commands_execute.py).
  5. """
  6. from __future__ import annotations
  7. from collections.abc import Callable, Mapping
  8. from dataclasses import dataclass, field
  9. from typing import Any
  10. from agent.i18n import t
  11. __all__ = [
  12. "EXECUTORS",
  13. "CommandContext",
  14. "CommandReply",
  15. "execute_command",
  16. "resolve_executor",
  17. "run_execute",
  18. ]
  19. @dataclass(frozen=True)
  20. class CommandContext:
  21. """Surface-provided inputs for a shared command executor."""
  22. surface: str = "cli" # "cli" | "gateway" | "tui" — decoration only
  23. args: str = "" # raw argument string after the command word
  24. options: Mapping[str, Any] = field(default_factory=dict) # surface params (page_size, ...)
  25. config_get: Callable[[str, Any], Any] | None = None # optional config accessor
  26. @dataclass(frozen=True)
  27. class CommandReply:
  28. """Canonical result of a shared executor: surface-independent ``text`` plus the structured
  29. ``data`` it derived so a surface can re-render with its own decoration."""
  30. text: str
  31. data: Mapping[str, Any] = field(default_factory=dict)
  32. format: str = "plain" # "plain" | "markdown" (hint, not a contract)
  33. # Executors — pure formatters, no agent/session mutation.
  34. def _exec_version(ctx: CommandContext) -> CommandReply:
  35. """Core /version text — the banner version label."""
  36. from hermes_cli.banner import format_banner_version_label
  37. return CommandReply(format_banner_version_label())
  38. def _exec_egress(ctx: CommandContext) -> CommandReply:
  39. """Core /egress text — Docker egress proxy status."""
  40. from hermes_cli.proxy_cli import format_status_text
  41. return CommandReply(format_status_text())
  42. def _exec_profile(ctx: CommandContext) -> CommandReply:
  43. """Core /profile data — active profile name + home directory.
  44. A multiplexed gateway may pre-resolve the per-source profile/home via ``options``
  45. (``profile_name`` / ``home_display``); otherwise process-level values are used.
  46. """
  47. from hermes_cli.profiles import get_active_profile_name
  48. from hermes_constants import display_hermes_home
  49. profile_name = str(ctx.options.get("profile_name") or "").strip() or get_active_profile_name()
  50. home_display = str(ctx.options.get("home_display") or "").strip() or display_hermes_home()
  51. # Presentation-only display name (profile.yaml); `data.profile` stays the canonical id.
  52. label = profile_name
  53. try:
  54. from hermes_cli.profiles import format_profile_label, get_profile_dir, read_profile_meta
  55. display = read_profile_meta(get_profile_dir(profile_name)).get("display_name", "")
  56. label = format_profile_label(profile_name, display)
  57. except Exception:
  58. pass
  59. return CommandReply(t("gateway.profile.plain", profile=label, home=home_display),
  60. data={"profile": profile_name, "home": home_display})
  61. def _exec_autoprune(ctx: CommandContext) -> CommandReply:
  62. """Core /autoprune text — record the auto-prune decision or show its state."""
  63. from hermes_cli.prune_advisor import run_command
  64. return CommandReply(run_command(ctx.args))
  65. def _exec_bundles(ctx: CommandContext) -> CommandReply:
  66. """Core /bundles data — installed skill bundles listing."""
  67. try:
  68. from agent.skill_bundles import _bundles_dir, list_bundles
  69. except Exception as exc: # pragma: no cover - env-specific
  70. return CommandReply(t("gateway.bundles.unavailable", error=exc), data={"error": str(exc)})
  71. bundles = list_bundles()
  72. bundles_dir = str(_bundles_dir())
  73. if not bundles:
  74. return CommandReply(t("gateway.bundles.none_plain", dir=bundles_dir), data={"bundles": [], "dir": bundles_dir})
  75. lines = [t("gateway.bundles.header_plain", count=len(bundles))]
  76. for info in bundles:
  77. skills = info.get("skills", [])
  78. desc = info.get("description") or t("gateway.bundles.default_desc", count=len(skills))
  79. lines.append(t("gateway.bundles.item_plain", slug=info["slug"], desc=desc, count=len(skills)))
  80. lines.extend(f" · {s}" for s in skills)
  81. lines.append(t("gateway.bundles.invoke_hint_plain"))
  82. return CommandReply("\n".join(lines), data={"bundles": bundles, "dir": bundles_dir})
  83. def _skill_commands() -> dict:
  84. """Registered skill commands, or ``{}`` when the skill subsystem is unavailable."""
  85. try:
  86. from agent.skill_commands import get_skill_commands
  87. return get_skill_commands() or {}
  88. except Exception:
  89. return {}
  90. def _exec_help(ctx: CommandContext) -> CommandReply:
  91. """Core gateway /help body (pre platform mention decoration)."""
  92. from hermes_cli.commands import gateway_help_lines
  93. # ``allowed_commands`` (gateway, non-admin caller): only the commands the slash-access
  94. # policy lets this user run; skill commands are hidden too since the gate refuses them.
  95. allowed = ctx.options.get("allowed_commands")
  96. lines = [t("gateway.help.header"), *gateway_help_lines(allowed)]
  97. skill_cmds = _skill_commands() if allowed is None else {}
  98. try:
  99. if skill_cmds:
  100. lines.append(t("gateway.help.skill_header", count=len(skill_cmds)))
  101. sorted_cmds = sorted(skill_cmds) # first 10, then point to /commands for the rest
  102. lines.extend(f"`{cmd}` — {skill_cmds[cmd]['description']}"
  103. for cmd in sorted_cmds[:10])
  104. if len(sorted_cmds) > 10:
  105. lines.append(t("gateway.help.more_use_commands", count=len(sorted_cmds) - 10))
  106. except Exception:
  107. pass
  108. return CommandReply("\n".join(lines), format="markdown")
  109. def _exec_commands(ctx: CommandContext) -> CommandReply:
  110. """Core gateway /commands body — paginated command + skill listing.
  111. ``ctx.options["page_size"]`` is a surface parameter (Telegram uses 15, everything else 20).
  112. """
  113. from hermes_cli.commands import gateway_help_lines
  114. try:
  115. requested_page = int((ctx.args or "").strip() or 1)
  116. except ValueError:
  117. return CommandReply(t("gateway.commands.usage"), format="markdown")
  118. allowed = ctx.options.get("allowed_commands")
  119. entries = list(gateway_help_lines(allowed))
  120. skill_cmds = _skill_commands() if allowed is None else {}
  121. try:
  122. if skill_cmds:
  123. entries.extend(["", t("gateway.commands.skill_header")])
  124. for cmd in sorted(skill_cmds):
  125. desc = skill_cmds[cmd].get("description", "").strip() or t("gateway.commands.default_desc")
  126. entries.append(f"`{cmd}` — {desc}")
  127. # Skills kept off the menu because a built-in owns the name (agent.skill_commands guard).
  128. from agent.skill_commands import skill_command_collision_note
  129. from tools.skills_tool import find_all_skills
  130. entries.extend(f"⚠ {note}" for note in filter(None, map(
  131. skill_command_collision_note, sorted(s["name"] for s in find_all_skills()))))
  132. except Exception:
  133. pass
  134. if not entries:
  135. return CommandReply(t("gateway.commands.none"), format="markdown")
  136. try:
  137. page_size = max(1, int(ctx.options.get("page_size", 20)))
  138. except (TypeError, ValueError):
  139. page_size = 20
  140. total_pages = max(1, (len(entries) + page_size - 1) // page_size)
  141. page = max(1, min(requested_page, total_pages))
  142. start = (page - 1) * page_size
  143. lines = [t("gateway.commands.header", total=len(entries), page=page, total_pages=total_pages),
  144. "", *entries[start:start + page_size]]
  145. if total_pages > 1:
  146. nav_parts = ([t("gateway.commands.nav_prev", page=page - 1)] if page > 1 else []) + (
  147. [t("gateway.commands.nav_next", page=page + 1)] if page < total_pages else [])
  148. lines.extend(["", " | ".join(nav_parts)])
  149. if page != requested_page:
  150. lines.append(t("gateway.commands.out_of_range", requested=requested_page, page=page))
  151. return CommandReply("\n".join(lines), format="markdown")
  152. EXECUTORS: dict[str, Callable[[CommandContext], CommandReply]] = {
  153. "version": _exec_version,
  154. "egress": _exec_egress,
  155. "profile": _exec_profile,
  156. "bundles": _exec_bundles,
  157. "autoprune": _exec_autoprune,
  158. "gateway_help": _exec_help,
  159. "gateway_commands": _exec_commands}
  160. def resolve_executor(cmd_def: Any) -> Callable[[CommandContext], CommandReply] | None:
  161. """Return the shared executor for ``cmd_def`` (or None when not migrated)."""
  162. return EXECUTORS.get(getattr(cmd_def, "execute", None) or "")
  163. def run_execute(cmd_def: Any, ctx: CommandContext) -> CommandReply | None:
  164. """Run ``cmd_def``'s registry-owned executor, if any."""
  165. fn = resolve_executor(cmd_def)
  166. return None if fn is None else fn(ctx)
  167. def execute_command(name: str, ctx: CommandContext) -> CommandReply:
  168. """Run the shared executor for ``name``; ``LookupError`` when unknown or not migrated."""
  169. from hermes_cli.commands import resolve_command
  170. cmd_def = resolve_command(name)
  171. reply = run_execute(cmd_def, ctx) if cmd_def is not None else None
  172. if reply is None:
  173. raise LookupError(f"no registry-owned executor for /{name}")
  174. return reply