commands.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. """Slash command registry for the Hermes CLI and gateway.
  2. Every consumer -- CLI help, gateway dispatch, Telegram BotCommands, Slack
  3. subcommand mapping, autocomplete -- derives from ``COMMAND_REGISTRY``. To add a
  4. command, append a ``CommandDef``; to add an alias, set ``aliases=("short",)``.
  5. """
  6. from __future__ import annotations
  7. import logging
  8. import re
  9. from collections.abc import Iterable
  10. from dataclasses import dataclass
  11. from typing import Optional
  12. from utils import is_truthy_value
  13. from agent.i18n import t
  14. from hermes_constants import INDICATOR_STYLES
  15. logger = logging.getLogger(__name__)
  16. def _localized(key: str, default: str) -> str:
  17. """``t(key)`` with *default* when no catalog (not even ``en``) carries the key."""
  18. value = t(key)
  19. return default if value == key else value
  20. # Category identifiers -> ``slash.category.<slug>`` (identifiers stay English; labels are localized
  21. # only at render time via ``category_label``).
  22. _CATEGORY_SLUGS: dict[str, str] = {
  23. "Session": "session", "Configuration": "configuration", "Info": "info",
  24. "Tools & Skills": "tools_skills", "Plugins": "plugins", "Exit": "exit",
  25. "Context": "context", "Background & Automation": "background_automation",
  26. }
  27. def category_label(category: str) -> str:
  28. """Localized label for a registry category / help sub-group identifier."""
  29. slug = _CATEGORY_SLUGS.get(category)
  30. return _localized(f"slash.category.{slug}", category) if slug else category
  31. @dataclass(frozen=True)
  32. class CommandDef:
  33. """Definition of a single slash command."""
  34. name: str # canonical name without slash: "background"
  35. description: str # human-readable description
  36. category: str # "Session", "Configuration", etc.
  37. aliases: tuple[str, ...] = () # alternative names: ("bg",)
  38. args_hint: str = "" # argument placeholder: "<prompt>", "[name]"
  39. subcommands: tuple[str, ...] = () # tab-completable subcommands
  40. cli_only: bool = False # only available in CLI
  41. gateway_only: bool = False # only available in gateway/messaging
  42. gateway_config_gate: str | None = None # config dotpath; truthy overrides cli_only for gateway
  43. # Mid-run (agent busy) gateway behavior (gateway/run.py Guard-2 dispatcher): "dispatch" = run
  44. # while busy (normal handler or the ``busy_handler`` variant); "reject" = refuse mid-run
  45. # (generic "Agent is running" unless ``busy_handler`` names a reject message);
  46. # "interrupt_then_dispatch" = interrupt first (/stop, /new, /reset; Guard 1, platforms/base.py).
  47. busy_policy: str = "reject"
  48. busy_handler: str | None = None # key of a special mid-run handler in Guard-2 table
  49. # Key in ``hermes_cli.slash_exec.EXECUTORS`` (a string, not a callable: keeps this module
  50. # import-light for the gateway).
  51. execute: str | None = None
  52. argument_mode: str | None = None # desktop composer: options|text|mixed; None inferred
  53. # Desktop availability: None = offered; "hidden" = runs but out of the popover; else a reason.
  54. desktop: str | None = None
  55. # Desktop subcommand scope. When set, the desktop surface only offers
  56. # (completion) and forwards (exec) these subcommands — the first argument
  57. # token must be one of them. Use when a command family mixes desktop-
  58. # relevant review actions with CLI-hub mutations (e.g. /skills install),
  59. # so offering the command doesn't widen the whole family.
  60. desktop_subcommands: tuple[str, ...] | None = None
  61. def describe(self) -> str:
  62. """Localized description (``slash.<name>.description``); ``description`` is the English source."""
  63. return _localized(f"slash.{self.name}.description", self.description)
  64. VALID_BUSY_POLICIES: frozenset[str] = frozenset({"dispatch", "reject", "interrupt_then_dispatch"})
  65. COMMAND_REGISTRY: list[CommandDef] = [
  66. # Session
  67. CommandDef("start", "Acknowledge platform start pings without a reply", "Session",
  68. gateway_only=True, busy_policy="dispatch", busy_handler="start"),
  69. CommandDef("new", "Start a new session (fresh session ID + history)", "Session",
  70. aliases=("reset",), args_hint="[name]",
  71. busy_policy="interrupt_then_dispatch", busy_handler="new"),
  72. CommandDef("topic", "Enable or inspect Telegram DM topic sessions", "Session",
  73. gateway_only=True, args_hint="[off|help|session-id]"),
  74. CommandDef("clear", "Clear screen and start a new session", "Session",
  75. cli_only=True, desktop="terminal"),
  76. CommandDef("redraw", "Force a full UI repaint (recovers from terminal drift)", "Session",
  77. cli_only=True, desktop="terminal"),
  78. CommandDef("history", "Show conversation history", "Session",
  79. cli_only=True),
  80. CommandDef("save", "Export the current conversation (bare /save shows usage)", "Session",
  81. args_hint="<json|md|html> [filename] [redact]"),
  82. CommandDef("retry", "Retry the last message (resend to agent)", "Session"),
  83. CommandDef("prompt", "Compose your next prompt in $EDITOR (markdown), then send it", "Session",
  84. cli_only=True, args_hint="[initial text]", aliases=("compose",)),
  85. CommandDef("undo", "Back up N user turns and re-prompt (default 1)", "Session",
  86. args_hint="[N]"),
  87. CommandDef("rewind", "Rewind to an earlier prompt to edit & resend it, or fork from there (Esc Esc)",
  88. "Session", cli_only=True, args_hint="[N | fork N]", desktop="terminal"),
  89. CommandDef("title", "Set a title for the current session", "Session", args_hint="[name]"),
  90. CommandDef("handoff", "Hand off this session to a messaging platform (Telegram, Discord, etc.)", "Session",
  91. args_hint="<platform>", cli_only=True, argument_mode="options"),
  92. CommandDef("branch", "Branch the current session (new thread on Discord/Telegram/Slack/Matrix; --here stays here)",
  93. "Session", aliases=("fork",), args_hint="[--here] [name]"),
  94. CommandDef("worktree", "Show, list, create, or prune isolated git worktrees", "Session",
  95. cli_only=True, args_hint="[new [name]|list|prune [--dry-run]]",
  96. subcommands=("new", "list", "prune"), desktop="terminal"),
  97. CommandDef("compress", "Compress conversation context (add 'here [N]' to keep recent N turns; --preview shows what would happen)", "Session",
  98. aliases=("compact",), args_hint="[here [N] | focus topic | --preview|--dry-run]"),
  99. CommandDef("rollback", "List or restore filesystem checkpoints (restores keep your hand-edits; --all overrides)", "Session",
  100. args_hint="[number] [--all]"),
  101. CommandDef("snapshot", "Create or restore state snapshots of Hermes config/state", "Session",
  102. cli_only=True, aliases=("snap",), args_hint="[create|restore <id>|prune]",
  103. desktop="terminal"),
  104. CommandDef("export", "Export a profile (config, skills, theme) to a shareable archive", "Configuration",
  105. cli_only=True, args_hint="[profile] [-o output.tar.gz]"),
  106. CommandDef("import", "Import a shared profile archive as a new profile", "Configuration",
  107. cli_only=True, args_hint="<archive.tar.gz> [--name <name>]"),
  108. CommandDef("stop", "Kill all running background processes", "Session",
  109. busy_policy="interrupt_then_dispatch", busy_handler="stop"),
  110. CommandDef("discard", "Drop a turn lost when Hermes restarted so this chat's queue runs again", "Session",
  111. gateway_only=True, busy_policy="dispatch"),
  112. CommandDef("pause", "Pause new work globally (emergency stop); '/pause off' resumes", "Session",
  113. gateway_only=True, args_hint="[reason | off]", busy_policy="dispatch"),
  114. CommandDef("approve", "Approve a pending dangerous command", "Session",
  115. gateway_only=True, args_hint="[session|always]", busy_policy="dispatch"),
  116. CommandDef("deny", "Deny a pending dangerous command (optionally with a reason)", "Session",
  117. gateway_only=True, args_hint="[all] [reason]", busy_policy="dispatch"),
  118. CommandDef("bg", "Run a prompt in a separate background session", "Session",
  119. args_hint="<prompt>", busy_policy="dispatch"),
  120. CommandDef("btw", "Ask a side question about the current conversation without interrupting it", "Session",
  121. args_hint="<question>", busy_policy="dispatch"),
  122. CommandDef("agents", "Show active agents and running tasks", "Session",
  123. aliases=("tasks",), busy_policy="dispatch"),
  124. CommandDef("journey", "Open the learning journey timeline",
  125. "Session", aliases=("learning", "memory-graph"), cli_only=True,
  126. args_hint="[list|delete <id>|edit <id>]", subcommands=("list", "delete", "edit")),
  127. CommandDef("queue", "Queue a prompt for the next turn, or list/edit/rm/move/clear queued prompts", "Session",
  128. aliases=("q",), args_hint="[<prompt>|list|edit N <prompt>|rm N|move A B|clear]",
  129. subcommands=("list", "edit", "rm", "move", "clear", "add"),
  130. busy_policy="dispatch", busy_handler="queue"),
  131. CommandDef("steer", "Inject a message after the next tool call without interrupting", "Session",
  132. aliases=("s",), args_hint="<prompt>", busy_policy="dispatch", busy_handler="steer"),
  133. CommandDef("goal", "Set a standing goal Hermes works on across turns until achieved", "Session",
  134. args_hint="[text | -- <text> | draft <text> | show | gate add <cmd> | pause | resume | clear | status | wait <pid> | unwait]",
  135. argument_mode="mixed", busy_policy="dispatch", busy_handler="goal"),
  136. CommandDef("heartbeat", "Set a recurring prompt that re-enters this session when idle", "Session",
  137. aliases=("hb",), args_hint="[every <interval> <prompt> | status | pause | resume | clear]",
  138. subcommands=("status", "pause", "resume", "clear"),
  139. busy_policy="dispatch"),
  140. CommandDef("refine", "Review this conversation now and save lessons to memory/skills", "Session",
  141. args_hint="[focus instructions]"),
  142. CommandDef("review", "Spawn an independent subagent to review the work just discussed (PR, code, docs)", "Session",
  143. args_hint="[review instructions]"),
  144. CommandDef("loop", "Re-run a prompt on a recurring interval in this session", "Session",
  145. aliases=("proactive",),
  146. args_hint="[interval] <prompt> [--times N] [--until <condition>] | status | pause | resume | stop",
  147. argument_mode="mixed", busy_policy="dispatch", busy_handler="loop"),
  148. CommandDef("plan", "Write a markdown implementation plan to .hermes/plans/ without executing anything", "Session",
  149. args_hint="[task]"),
  150. CommandDef("moa", "Run one prompt through the default Mixture of Agents preset, then restore your model", "Session",
  151. args_hint="<prompt>", busy_policy="reject", busy_handler="moa"),
  152. CommandDef("subgoal", "Add or manage extra criteria on the active goal", "Session",
  153. args_hint="[text | remove N | clear]", busy_policy="dispatch"),
  154. CommandDef("status", "Show session, model, token, and context info", "Session",
  155. busy_policy="dispatch"),
  156. CommandDef("egress", "Show Docker egress proxy status", "Session",
  157. args_hint="[status]", subcommands=("status",), busy_policy="dispatch",
  158. busy_handler="egress", execute="egress"),
  159. CommandDef("context", "Show detailed context window view with usage gauge, category breakdown, compression stats, and throughput", "Session",
  160. aliases=("ctx",), args_hint="[all]", subcommands=("all",), busy_policy="dispatch"),
  161. CommandDef("whoami", "Show your slash command access (admin / user)", "Info"),
  162. CommandDef("profile", "Show active profile name and home directory", "Info",
  163. busy_policy="dispatch", execute="profile"),
  164. CommandDef("sethome", "Set this chat as the home channel", "Session",
  165. gateway_only=True, aliases=("set-home",), desktop="terminal"),
  166. CommandDef("resume", "Resume a previously-named session", "Session",
  167. args_hint="[name]", argument_mode="mixed"),
  168. CommandDef("sessions", "Browse and resume previous sessions", "Session"),
  169. # Configuration
  170. CommandDef("config", "Show current configuration", "Configuration",
  171. cli_only=True),
  172. CommandDef("model", "Switch model (session-scoped; --global to persist)", "Configuration",
  173. args_hint="[model|reset] [--provider name] [--reasoning level] [--global|--session] [--refresh]",
  174. busy_policy="reject", busy_handler="model", desktop="hidden"),
  175. CommandDef("codex-runtime", "Toggle codex app-server runtime for OpenAI/Codex models",
  176. "Configuration", aliases=("codex_runtime",), args_hint="[auto|codex_app_server]",
  177. busy_policy="reject", busy_handler="codex-runtime"),
  178. CommandDef("personality", "Set a predefined personality", "Configuration",
  179. args_hint="[name]", argument_mode="options"),
  180. CommandDef("statusbar", "Toggle the context/model status bar", "Configuration",
  181. cli_only=True, aliases=("sb",), desktop="terminal"),
  182. CommandDef("battery", "Toggle a color-coded battery indicator in the status bar",
  183. "Configuration", cli_only=True, args_hint="[on|off|status]",
  184. subcommands=("on", "off", "status")),
  185. CommandDef("timestamps", "Toggle [HH:MM] timestamps on messages and /history", "Configuration",
  186. cli_only=True, args_hint="[on|off|status]",
  187. subcommands=("on", "off", "status"), aliases=("ts",)),
  188. CommandDef("diff", "Show git changes in the working directory", "Info",
  189. args_hint="[staged|all|session] [--stat] [path...]",
  190. subcommands=("staged", "all", "session")),
  191. CommandDef("verbose", "Cycle tool progress display: off -> new -> all -> verbose",
  192. "Configuration", cli_only=True, gateway_config_gate="display.tool_progress_command",
  193. busy_policy="dispatch", desktop="terminal"),
  194. CommandDef("focus", "Toggle focus view — show only your prompt and the final response",
  195. "Configuration", cli_only=True, args_hint="[on|off|status]",
  196. subcommands=("on", "off", "status")),
  197. CommandDef("footer", "Toggle gateway runtime-metadata footer on final replies",
  198. "Configuration", args_hint="[on|off|status]", subcommands=("on", "off", "status"),
  199. busy_policy="dispatch", desktop="terminal"),
  200. CommandDef("yolo", "Toggle YOLO mode (skip all dangerous command approvals)",
  201. "Configuration", busy_policy="dispatch"),
  202. CommandDef("approvals", "Show or set the persistent dangerous-command approval mode",
  203. "Configuration", args_hint="[manual|smart|off]",
  204. subcommands=("manual", "smart", "off")),
  205. CommandDef("reasoning", "Manage reasoning effort and display", "Configuration",
  206. args_hint="[level|show|hide|full|clamp] [--global]",
  207. subcommands=("none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra", "show", "hide", "on", "off", "full", "clamp", "--global")),
  208. CommandDef("fast", "Fast mode — OpenAI Priority Processing / Anthropic Fast Mode (normal/fast/auto/cold/ultrafast)", "Configuration",
  209. args_hint="[normal|fast|auto|cold|ultrafast|status] [--global]",
  210. subcommands=("normal", "fast", "auto", "cold", "ultrafast", "ultra", "status", "on", "off", "--global"),
  211. desktop="advanced"),
  212. CommandDef("skin", "Show or change the display skin/theme", "Configuration",
  213. cli_only=True, args_hint="[name]", argument_mode="options"),
  214. CommandDef("indicator", "Pick the TUI busy-indicator style", "Configuration",
  215. cli_only=True, args_hint=f"[{'|'.join(INDICATOR_STYLES)}]",
  216. subcommands=INDICATOR_STYLES, desktop="terminal"),
  217. CommandDef("voice", "Toggle voice mode", "Configuration",
  218. args_hint="[on|off|tts|status]", subcommands=("on", "off", "tts", "status"),
  219. desktop="composer-voice"),
  220. CommandDef("wake", "Toggle the 'Hey Hermes' wake word listener", "Configuration",
  221. cli_only=True, args_hint="[on|off|status]", subcommands=("on", "off", "status")),
  222. CommandDef("busy", "Control how messages behave while Hermes is working", "Configuration",
  223. args_hint="[queue|steer|interrupt|status]",
  224. subcommands=("queue", "steer", "interrupt", "status"),
  225. busy_policy="dispatch", desktop="terminal"),
  226. CommandDef("autoprune", "Turn automatic pruning of old sessions on or off", "Configuration",
  227. args_hint="[on|off|later|status]", subcommands=("on", "off", "later", "status"),
  228. busy_policy="dispatch", execute="autoprune", argument_mode="options"),
  229. # Tools & Skills
  230. CommandDef("tools", "Manage tools: /tools [list|disable|enable] [name...]", "Tools & Skills",
  231. args_hint="[list|disable|enable] [name...]", cli_only=True, argument_mode="options"),
  232. CommandDef("toolsets", "List available toolsets", "Tools & Skills",
  233. cli_only=True, desktop="terminal"),
  234. CommandDef("skills", "Search, install, inspect, or manage skills",
  235. "Tools & Skills", cli_only=True,
  236. gateway_config_gate="skills.write_approval",
  237. subcommands=("search", "browse", "inspect", "install", "audit",
  238. "pending", "approve", "reject", "diff", "approval"),
  239. # Desktop exposes only the write-approval review slice — the
  240. # same surface the gateway handler offers. The hub mutations
  241. # (search/browse/inspect/install/audit) run a full interactive
  242. # CLI hub that must not be reachable from a desktop exec
  243. # (#98330 review).
  244. desktop_subcommands=("pending", "approve", "reject", "diff",
  245. "approval")),
  246. CommandDef("memory", "Review pending memory writes / toggle the approval gate",
  247. "Tools & Skills", args_hint="[pending|approve|reject|approval] [id|on|off]",
  248. subcommands=("pending", "approve", "reject", "approval")),
  249. CommandDef("bundles", "List skill bundles (aliases /<name> for multiple skills)",
  250. "Tools & Skills", execute="bundles"),
  251. CommandDef("pet", "Toggle or adopt a petdex mascot (/pet, /pet list, /pet <slug>)", "Tools & Skills",
  252. cli_only=True, args_hint="[toggle|list|scale <n>|<slug>]", subcommands=("toggle", "list", "scale", "off")),
  253. CommandDef("hatch", "Generate a new petdex pet from a description",
  254. "Tools & Skills", cli_only=True, aliases=("generate-pet",), args_hint="[description]"),
  255. CommandDef("learn", "Learn a reusable skill from anything you describe (dirs, URLs, this chat, notes)",
  256. "Tools & Skills", args_hint="<what to learn from>"),
  257. CommandDef("init", "Generate or update AGENTS.md project instructions from a repo scan",
  258. "Tools & Skills", args_hint="[notes]"),
  259. CommandDef("cron", "Manage scheduled tasks", "Tools & Skills",
  260. cli_only=True, args_hint="[subcommand]",
  261. subcommands=("list", "add", "create", "edit", "pause", "resume", "run", "remove"),
  262. desktop="terminal"),
  263. CommandDef("suggestions", "Review suggested automations (accept/dismiss)",
  264. "Tools & Skills", aliases=("suggest",), args_hint="[accept|dismiss N | catalog]",
  265. subcommands=("accept", "dismiss", "catalog", "clear")),
  266. CommandDef("blueprint", "Set up an automation from a blueprint template",
  267. "Tools & Skills", aliases=("bp",), args_hint="[name] [slot=value ...]"),
  268. CommandDef("curator", "Background skill maintenance (status, run, pin, archive, list-archived)",
  269. "Tools & Skills", args_hint="[subcommand]",
  270. subcommands=("status", "run", "pause", "resume", "pin", "unpin", "restore", "list-archived"),
  271. desktop="advanced"),
  272. CommandDef("kanban", "Multi-profile collaboration board (tasks, links, comments)",
  273. "Tools & Skills", args_hint="[subcommand]",
  274. subcommands=("init", "boards", "create", "list", "ls", "show", "assign",
  275. "reclaim", "reassign", "diagnostics", "diag", "link", "unlink",
  276. "claim", "comment", "complete", "edit", "block", "unblock",
  277. "archive", "tail", "dispatch", "stats", "notify-subscribe",
  278. "notify-list", "notify-unsubscribe", "log", "runs",
  279. "heartbeat", "assignees", "context", "specify", "gc"),
  280. busy_policy="dispatch", desktop="advanced"),
  281. CommandDef("reload", "Reload .env variables into the running session", "Tools & Skills",
  282. cli_only=True, desktop="terminal"),
  283. CommandDef("reload-mcp", "Reload MCP servers from config", "Tools & Skills",
  284. aliases=("reload_mcp",), desktop="advanced"),
  285. CommandDef("reload-skills", "Re-scan ~/.hermes/skills/ for newly installed or removed skills",
  286. "Tools & Skills", aliases=("reload_skills",), desktop="advanced"),
  287. CommandDef("browser", "Connect browser tools to your live Chromium-family browser via CDP", "Tools & Skills",
  288. cli_only=True, args_hint="[connect|disconnect|status]",
  289. subcommands=("connect", "disconnect", "status")),
  290. CommandDef("plugins", "List installed plugins and their status",
  291. "Tools & Skills", cli_only=True, desktop="terminal", args_hint="[update|auto-update [on|off]]",
  292. subcommands=("update", "auto-update")),
  293. # Info
  294. CommandDef("commands", "Browse all commands and skills (paginated)", "Info",
  295. gateway_only=True, args_hint="[page]", busy_policy="dispatch",
  296. execute="gateway_commands"),
  297. CommandDef("help", "Show available commands (/help skills lists skill commands, /help <text> filters)", "Info", busy_policy="dispatch",
  298. execute="gateway_help", args_hint="[skills|<filter>]"),
  299. CommandDef("palette", "Open the fuzzy command palette (also Ctrl+P)", "Info",
  300. cli_only=True, busy_policy="dispatch"),
  301. CommandDef("restart", "Gracefully restart the gateway after draining active runs", "Session",
  302. gateway_only=True, busy_policy="dispatch", desktop="terminal"),
  303. CommandDef("usage", "Show token usage and rate limits; `reset` redeems a banked Codex limit reset", "Info",
  304. args_hint="[reset [--force]]"),
  305. CommandDef("subscription", "View your Nous plan and change it in the browser", "Info",
  306. cli_only=True, aliases=("upgrade",)),
  307. CommandDef("login", "Sign in with a Nous account (keeps your connectors)", "Info",
  308. busy_policy="dispatch", desktop="settings"),
  309. CommandDef("topup", "Show your Nous balance and manage billing on the portal", "Info"),
  310. CommandDef("insights", "Show usage insights and analytics", "Info",
  311. args_hint="[days]", desktop="advanced"),
  312. CommandDef("platforms", "Show gateway/messaging platform status", "Info",
  313. cli_only=True, aliases=("gateway",), desktop="terminal"),
  314. CommandDef("platform", "Pause, resume, or list a failing gateway platform", "Info",
  315. gateway_only=True, args_hint="<pause|resume|list> [name]"),
  316. CommandDef("copy", "Copy the last assistant response to clipboard", "Info",
  317. cli_only=True, args_hint="[number]", desktop="terminal"),
  318. CommandDef("paste", "Attach clipboard image from your clipboard", "Info",
  319. cli_only=True, desktop="terminal"),
  320. CommandDef("image", "Attach a local image file for your next prompt", "Info",
  321. cli_only=True, args_hint="<path>", desktop="terminal"),
  322. CommandDef("update", "Update Hermes Agent to the latest version", "Info",
  323. busy_policy="dispatch", desktop="terminal"),
  324. CommandDef("version", "Show Hermes Agent version", "Info", aliases=("v",),
  325. busy_policy="dispatch", execute="version"),
  326. CommandDef("debug", "Upload debug report (system info + logs) and get shareable links", "Info",
  327. args_hint="[nous|local]"),
  328. # Exit
  329. CommandDef("quit", "Exit the CLI (use --delete to also remove session history)", "Exit",
  330. cli_only=True, aliases=("exit",), args_hint="[--delete]", desktop="terminal")]
  331. # Distinguishes ``mixed`` (subcommands plus free-text) from ``options``; no subcommands => ``text``.
  332. _PROSE_HINTS = ("<prompt>", "[text", "instructions", "[interval]", "<what")
  333. def infer_argument_mode(cmd: CommandDef) -> str | None:
  334. """Composer mode: explicit on the CommandDef, else inferred from its args."""
  335. if cmd.argument_mode in {"options", "text", "mixed"}:
  336. return cmd.argument_mode
  337. hint = (cmd.args_hint or "").strip()
  338. if cmd.subcommands:
  339. prose = hint and any(token in hint.lower() for token in _PROSE_HINTS)
  340. return "mixed" if prose else "options"
  341. return "text" if hint else None
  342. def command_desktop_meta(cmd: CommandDef) -> dict[str, object]:
  343. """Wire shape for ``commands.catalog`` — reads the CommandDef, nothing else."""
  344. meta: dict[str, object] = {"argument_mode": infer_argument_mode(cmd), "desktop": cmd.desktop}
  345. if cmd.desktop_subcommands is not None:
  346. meta["desktop_subcommands"] = list(cmd.desktop_subcommands)
  347. return meta
  348. def desktop_surface_registry() -> dict[str, str | None]:
  349. """``/name`` (and every alias) -> ``desktop`` disposition for EVERY registry command.
  350. Offered built-ins (no ``desktop=`` value) map to ``None``: the desktop needs their names
  351. too, or offline it cannot tell ``/context`` from a skill command and files it under
  352. Skills / routes it down the extension path until the live catalog warms up.
  353. The desktop app reads this live from ``commands.catalog``; the copy committed at
  354. ``apps/desktop/src/lib/desktop-slash-registry.json`` (``scripts/dump_desktop_slash_registry.py``)
  355. is its offline fallback before the catalog answers, so the registry stays the ONLY place a
  356. command's desktop disposition is authored. A test on each side fails when the two drift.
  357. """
  358. return {
  359. f"/{key}": cmd.desktop or None
  360. for cmd in COMMAND_REGISTRY
  361. for key in (cmd.name, *cmd.aliases)
  362. }
  363. # Every name and alias -> its CommandDef.
  364. _COMMAND_LOOKUP: dict[str, CommandDef] = {
  365. key: cmd for cmd in COMMAND_REGISTRY for key in (cmd.name, *cmd.aliases)}
  366. def resolve_command(name: str) -> CommandDef | None:
  367. """Resolve a command name or alias (leading slash optional) to its CommandDef."""
  368. return _COMMAND_LOOKUP.get(name.lower().lstrip("/"))
  369. def _build_description(cmd: CommandDef) -> str:
  370. """CLI-facing localized description including the usage hint."""
  371. if not cmd.args_hint:
  372. return cmd.describe()
  373. return t("slash.shared.usage_suffix", description=cmd.describe(), name=cmd.name, args_hint=cmd.args_hint)
  374. def build_commands_by_category() -> dict[str, dict[str, str]]:
  375. """Localized ``{category: {"/command": description}}`` (excludes gateway_only).
  376. Built per call so a ``display.language`` change applies without a restart; category keys are
  377. the registry identifiers -- render them with ``category_label``.
  378. """
  379. grouped: dict[str, dict[str, str]] = {}
  380. for cmd in COMMAND_REGISTRY:
  381. if cmd.gateway_only:
  382. continue
  383. entries = {f"/{cmd.name}": _build_description(cmd)}
  384. for alias in cmd.aliases:
  385. entries[f"/{alias}"] = t("slash.shared.alias_for", description=cmd.describe(), name=cmd.name)
  386. grouped.setdefault(cmd.category, {}).update(entries)
  387. return grouped
  388. def build_commands() -> dict[str, str]:
  389. """Localized flat ``{"/command": description}`` (excludes gateway_only)."""
  390. flat: dict[str, str] = {}
  391. for entries in build_commands_by_category().values():
  392. flat.update(entries)
  393. return flat
  394. # ``COMMANDS`` / ``COMMANDS_BY_CATEGORY`` resolve lazily through the module ``__getattr__`` below so
  395. # every ``from hermes_cli.commands import COMMANDS`` sees the active language.
  396. _LAZY_LOCALIZED_TABLES = {"COMMANDS": build_commands, "COMMANDS_BY_CATEGORY": build_commands_by_category}
  397. # Subcommands lookup: "/cmd" -> ["sub1", ...]; explicit ``subcommands`` first (in
  398. # registry order), then pipe patterns in args_hint ("[on|off|status]") as fallback.
  399. SUBCOMMANDS: dict[str, list[str]] = {
  400. f"/{_cmd.name}": list(_cmd.subcommands) for _cmd in COMMAND_REGISTRY if _cmd.subcommands}
  401. _PIPE_SUBS_RE = re.compile(r"[a-z]+(?:\|[a-z]+)+")
  402. for _cmd in COMMAND_REGISTRY:
  403. _m = _PIPE_SUBS_RE.search(_cmd.args_hint) if _cmd.args_hint else None
  404. if _m and f"/{_cmd.name}" not in SUBCOMMANDS:
  405. SUBCOMMANDS[f"/{_cmd.name}"] = _m.group(0).split("|")
  406. # /help sub-groups for the large "Session" category (category itself is load-bearing for gateway
  407. # help, so commands are not re-tagged); unlisted Session commands fall under the base header.
  408. HELP_SESSION_SUBGROUPS: dict[str, tuple[str, ...]] = {
  409. "Context": ("compress", "compact", "context", "ctx", "status"),
  410. "Background & Automation": (
  411. "bg", "btw", "agents", "tasks", "queue", "q", "steer", "s", "goal", "subgoal", "heartbeat", "hb",
  412. "refine", "loop", "proactive", "moa", "journey", "learning", "memory-graph")}
  413. # All names + aliases the gateway dispatches. Config-gated commands are
  414. # included; their handler checks the gate at runtime.
  415. GATEWAY_KNOWN_COMMANDS: frozenset[str] = frozenset(
  416. name for cmd in COMMAND_REGISTRY if not cmd.cli_only or cmd.gateway_config_gate
  417. for name in (cmd.name, *cmd.aliases))
  418. def is_gateway_known_command(name: str | None) -> bool:
  419. """True if ``name`` is a built-in or plugin gateway slash command (plugins looked
  420. up lazily); decides whether the gateway emits ``command:<name>`` hooks."""
  421. if not name:
  422. return False
  423. return name in GATEWAY_KNOWN_COMMANDS or any(
  424. plugin_name == name for plugin_name, _d, _h in _iter_plugin_command_entries())
  425. # Commands with explicit mid-run handling (busy_policy != "reject"). Kept
  426. # under its historical name for introspection/tests; the real bypass set is
  427. # every resolvable command (see should_bypass_active_session).
  428. ACTIVE_SESSION_BYPASS_COMMANDS: frozenset[str] = frozenset(
  429. cmd.name for cmd in COMMAND_REGISTRY if cmd.busy_policy != "reject")
  430. def is_interrupt_then_dispatch(command_name: str | None) -> bool:
  431. """Guard 1 (gateway/platforms/base.py) routes these through the cancel-handoff path."""
  432. cmd = resolve_command(command_name) if command_name else None
  433. return cmd is not None and cmd.busy_policy == "interrupt_then_dispatch"
  434. def should_bypass_active_session(command_name: str | None) -> bool:
  435. """True for any resolvable slash command: every recognized command is dispatched mid-run
  436. (Guard-2 handler or the "busy" catch-all), never queued — gateway.run's safety net discards
  437. command text reaching the pending queue, so a queued mid-run /model (or /reasoning, /voice,
  438. /insights, /title, /resume, /retry, /undo, /compress, /usage, /reload-mcp, /sethome, /reset)
  439. would silently interrupt the agent AND get discarded — a zero-char response. See issue
  440. #5057 / PRs #6252, #10370, #4665. ACTIVE_SESSION_BYPASS_COMMANDS remains the subset with
  441. explicit Level-2 handlers; the rest fall through to the catch-all.
  442. See #10370, #4665, #5057, #6252.
  443. """
  444. return resolve_command(command_name) is not None if command_name else False
  445. def _resolve_config_gates() -> set[str]:
  446. """Canonical names of commands whose ``gateway_config_gate`` dotpath is truthy in
  447. config.yaml (empty set on any error)."""
  448. gated = [c for c in COMMAND_REGISTRY if c.gateway_config_gate]
  449. if not gated:
  450. return set()
  451. try:
  452. from hermes_cli.config import cfg_get, read_raw_config
  453. cfg = read_raw_config()
  454. except Exception:
  455. return set()
  456. return {cmd.name for cmd in gated
  457. if is_truthy_value(cfg_get(cfg, *cmd.gateway_config_gate.split(".")), default=False)}
  458. def _is_gateway_available(cmd: CommandDef, config_overrides: set[str] | None = None) -> bool:
  459. """Not ``cli_only``, or its config gate is truthy (*config_overrides* from
  460. ``_resolve_config_gates()`` avoids re-reading config per command)."""
  461. if not cmd.cli_only:
  462. return True
  463. if not cmd.gateway_config_gate:
  464. return False
  465. overrides = config_overrides if config_overrides is not None else _resolve_config_gates()
  466. return cmd.name in overrides
  467. def gateway_help_lines(allowed: Optional[Iterable[str]] = None) -> list[str]:
  468. """Generate gateway help text lines from the registry.
  469. ``allowed`` (canonical names) restricts the catalog to what the caller may run -- the
  470. gateway passes a non-admin's slash-access floor + ``user_allowed_commands`` so /help never
  471. advertises admin-only commands the dispatcher would then refuse.
  472. """
  473. overrides = _resolve_config_gates()
  474. allowed_set = None if allowed is None else set(allowed)
  475. lines: list[str] = []
  476. for cmd in COMMAND_REGISTRY:
  477. if not _is_gateway_available(cmd, overrides):
  478. continue
  479. if allowed_set is not None and cmd.name not in allowed_set:
  480. continue
  481. args = f" {cmd.args_hint}" if cmd.args_hint else ""
  482. # Skip internal aliases like reload_mcp (underscore variant of the name).
  483. alias_parts = [f"`/{a}`" for a in cmd.aliases
  484. if not (a.replace("-", "_") == cmd.name.replace("-", "_") and a != cmd.name)]
  485. alias_note = t("slash.shared.alias_note", aliases=", ".join(alias_parts)) if alias_parts else ""
  486. lines.append(f"`/{cmd.name}{args}` -- {cmd.describe()}{alias_note}")
  487. return lines
  488. def _iter_plugin_command_entries() -> list[tuple[str, str, str]]:
  489. """(name, description, args_hint) for ``PluginContext.register_command`` slash commands.
  490. Lazy so importing this module never forces plugin discovery."""
  491. try:
  492. from hermes_cli.plugins import get_plugin_commands
  493. commands = get_plugin_commands() or {}
  494. except Exception:
  495. return []
  496. return [(name, str(meta.get("description") or t("slash.shared.plugin_default_desc", name=name)),
  497. str(meta.get("args_hint") or "").strip())
  498. for name, meta in commands.items() if isinstance(name, str) and isinstance(meta, dict)]
  499. def __getattr__(name): # PEP 562 — COMMANDS / COMMANDS_BY_CATEGORY are built per call so labels follow the active language
  500. localized = _LAZY_LOCALIZED_TABLES.get(name)
  501. if localized is None:
  502. raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
  503. return localized()