commands_platforms.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. """Gateway platform command derivations (Telegram / Discord / Slack) from ``COMMAND_REGISTRY``.
  2. """
  3. from __future__ import annotations
  4. import logging
  5. import re
  6. from collections.abc import Callable, Mapping, Sequence
  7. from typing import Any
  8. from agent.i18n import t
  9. from hermes_cli.commands import (
  10. COMMAND_REGISTRY, _is_gateway_available, _iter_plugin_command_entries, _resolve_config_gates)
  11. # Logger name parity with the origin module (tests capture "hermes_cli.commands").
  12. logger = logging.getLogger("hermes_cli.commands")
  13. _CMD_NAME_LIMIT = 32 # max command name length shared by Telegram and Discord
  14. _TG_INVALID_CHARS = re.compile(r"[^a-z0-9_]")
  15. _TG_MULTI_UNDERSCORE = re.compile(r"_{2,}")
  16. def _gateway_available_commands() -> list:
  17. """Registry entries visible on gateway surfaces (config gates read once)."""
  18. overrides = _resolve_config_gates()
  19. return [cmd for cmd in COMMAND_REGISTRY if _is_gateway_available(cmd, overrides)]
  20. def _requires_argument(args_hint: str) -> bool:
  21. """True when selecting a command without text would be incomplete."""
  22. return args_hint.strip().startswith("<")
  23. def _sanitize_telegram_name(raw: str) -> str:
  24. """Telegram allows only ``[a-z0-9_]``: lowercase, hyphens -> ``_``, collapse/strip ``_``.
  25. A name that would lose letters (``中文helper`` -> ``helper``) is omitted (``""``): the menu
  26. entry could not resolve back to the registered ``/中文helper`` and would answer
  27. "Unknown command"."""
  28. lowered = raw.lower().replace("-", "_")
  29. name = _TG_INVALID_CHARS.sub("", lowered)
  30. if any(ch.isalnum() for ch in _TG_INVALID_CHARS.findall(lowered)):
  31. return ""
  32. return _TG_MULTI_UNDERSCORE.sub("_", name).strip("_")
  33. _TG_DASHES = re.compile("[\u2012\u2013\u2014\u2015\u2212]")
  34. def _normalize_telegram_desc(desc: str) -> str:
  35. """Fold Unicode dashes (em/en/figure/horizontal-bar/minus) to ASCII ``-``.
  36. BotFather rejects setMyCommands descriptions containing them (#2925)."""
  37. return _TG_DASHES.sub("-", desc)
  38. def _truncate_desc(desc: str, limit: int) -> str:
  39. """Clamp a menu description to *limit* chars with a ``...`` tail."""
  40. return desc if len(desc) <= limit else desc[:limit - 3] + "..."
  41. def _clamp_command_names(
  42. entries: Sequence[tuple[str, ...]], reserved: set[str]) -> list[tuple[str, ...]]:
  43. """Enforce the 32-char Telegram/Discord name limit: over-long names are truncated; on a
  44. collision with *reserved* or an earlier entry a 31-char prefix + digit ``0``-``9`` is tried,
  45. then the entry is silently dropped. Duplicates are dropped; extra tuple elements pass through.
  46. """
  47. used: set[str] = set(reserved)
  48. result: list = []
  49. for name, desc, *extra in entries:
  50. if len(name) > _CMD_NAME_LIMIT:
  51. candidate = name[:_CMD_NAME_LIMIT]
  52. if candidate in used:
  53. prefix = name[:_CMD_NAME_LIMIT - 1]
  54. for digit in range(10):
  55. candidate = f"{prefix}{digit}"
  56. if candidate not in used:
  57. break
  58. else:
  59. continue
  60. name = candidate
  61. if name in used:
  62. continue
  63. used.add(name)
  64. result.append((name, desc, *extra))
  65. return result
  66. # --- Telegram ---------------------------------------------------------------
  67. def telegram_bot_commands(*, include_plugins: bool = True) -> list[tuple[str, str]]:
  68. """(command_name, description) pairs for Telegram setMyCommands: sanitized canonical names
  69. only (no aliases). Built-ins needing arguments are included (their handlers show usage when
  70. selected bare); plugin commands needing arguments are excluded (may lack a no-arg fallback)."""
  71. pairs = [(cmd.name, cmd.describe()) for cmd in _gateway_available_commands()]
  72. if include_plugins:
  73. pairs += [(n, d) for n, d, hint in _iter_plugin_command_entries()
  74. if not _requires_argument(hint)]
  75. return [(tg, _normalize_telegram_desc(desc)) for name, desc in pairs if (tg := _sanitize_telegram_name(name))]
  76. # Telegram allows 100 BotCommands; the 60-slot default keeps every built-in plus common skill
  77. # commands under the ~4KB payload limit (platforms.telegram.extra.command_menu.max_commands).
  78. _DEFAULT_TELEGRAM_MENU_MAX_COMMANDS = 60
  79. _TELEGRAM_BOT_API_MAX_COMMANDS = 100
  80. # priority_mode -> rank tables consulted in order ("configured" = user list,
  81. # "default" = _TELEGRAM_MENU_PRIORITY); unranked candidates keep stable order after.
  82. _TELEGRAM_PRIORITY_TIERS: dict[str, tuple[str, ...]] = {
  83. "prepend": ("configured", "default"), "append": ("default", "configured"),
  84. "replace": ("configured",)}
  85. # Built-ins that must survive Telegram's small visible menu cap (everything else stays
  86. # dispatchable when typed). Order = rank: everyday, maintenance, mid-turn control, operational.
  87. _TELEGRAM_MENU_PRIORITY = (
  88. "help", "new", "stop", "status", "egress", "resume", "sessions", "model",
  89. "debug", "restart", "update", "verbose", "commands",
  90. "approve", "deny", "queue", "steer", "bg", "btw",
  91. "reasoning", "usage", "platforms", "platform", "profile", "whoami")
  92. def _telegram_command_menu_config() -> dict[str, Any]:
  93. """Normalized ``platforms.telegram.extra.command_menu`` config with safe defaults."""
  94. try:
  95. from hermes_cli.config import read_raw_config
  96. node: Any = read_raw_config() or {}
  97. except Exception:
  98. node = {}
  99. for key in ("platforms", "telegram", "extra", "command_menu"):
  100. node = node.get(key) if isinstance(node, Mapping) else None
  101. menu_cfg: Mapping[str, Any] = node if isinstance(node, Mapping) else {}
  102. try:
  103. max_commands = int(menu_cfg.get("max_commands", _DEFAULT_TELEGRAM_MENU_MAX_COMMANDS))
  104. except (TypeError, ValueError):
  105. max_commands = _DEFAULT_TELEGRAM_MENU_MAX_COMMANDS
  106. priority_mode = str(menu_cfg.get("priority_mode") or "prepend").strip().lower()
  107. raw_priority = menu_cfg.get("priority")
  108. if isinstance(raw_priority, list):
  109. priority = [str(item) for item in raw_priority if str(item).strip()]
  110. else:
  111. priority = [raw_priority] if isinstance(raw_priority, str) and raw_priority.strip() else []
  112. return {
  113. "max_commands": max(1, min(_TELEGRAM_BOT_API_MAX_COMMANDS, max_commands)),
  114. "priority_mode": priority_mode if priority_mode in _TELEGRAM_PRIORITY_TIERS else "prepend",
  115. "priority": priority}
  116. def telegram_menu_max_commands() -> int:
  117. """Return configured Telegram BotCommand menu cap with safe bounds."""
  118. return int(_telegram_command_menu_config()["max_commands"])
  119. def _sanitized_rank(raw_names: Sequence[str]) -> dict[str, int]:
  120. """name -> rank for the deduped, Telegram-sanitized *raw_names* (first occurrence wins)."""
  121. rank: dict[str, int] = {}
  122. for raw in raw_names:
  123. name = _sanitize_telegram_name(str(raw))
  124. if name and name not in rank:
  125. rank[name] = len(rank)
  126. return rank
  127. def _prioritize_telegram_menu_candidates(
  128. candidates: list[tuple[str, str, str, str]]) -> list[tuple[str, str, str, str]]:
  129. """Order ``(final_name, description, source, raw_name)`` candidates; the default priority
  130. applies to core only, "replace" mode ignores it. ``raw_name`` is the pre-clamp name so a
  131. configured long command stays addressable."""
  132. menu_cfg = _telegram_command_menu_config()
  133. configured_rank = _sanitized_rank(menu_cfg["priority"])
  134. default_rank = _sanitized_rank(_TELEGRAM_MENU_PRIORITY)
  135. tiers = _TELEGRAM_PRIORITY_TIERS[menu_cfg["priority_mode"]]
  136. def _rank(stable_index: int, candidate: tuple[str, str, str, str]) -> tuple[int, int, int]:
  137. final_name, _desc, source, raw_name = candidate
  138. indexes = {
  139. "configured": configured_rank.get(raw_name, configured_rank.get(final_name)),
  140. "default": default_rank.get(final_name) if source == "core" else None}
  141. for tier, table in enumerate(tiers):
  142. if indexes[table] is not None:
  143. return (tier, indexes[table], stable_index)
  144. return (len(tiers), 0, stable_index)
  145. return [c for _i, c in sorted(enumerate(candidates), key=lambda item: _rank(*item))]
  146. # --- Shared skill/plugin collection for gateway platforms -------------------
  147. def _iter_gateway_skills(platform: str):
  148. """Yield ``(cmd_key, info, rel_parts)`` for skills eligible as gateway slash commands.
  149. Scan roots: ``SKILLS_DIR`` plus ``skills.external_dirs`` / trusted project skills dirs;
  150. anything elsewhere or under ``SKILLS_DIR/.hub`` is skipped, as are skills disabled for
  151. *platform*. Paths are resolved on both sides (symlinked roots still match) and matched per
  152. path component (``/my-skills`` never admits ``/my-skills-extra``). ``rel_parts`` is the skill
  153. dir relative to its root (``("creative", "ascii-art")``). Alphabetical so first-wins
  154. collision handling is deterministic.
  155. """
  156. from pathlib import Path
  157. from agent.skill_commands import get_skill_commands
  158. from agent.skill_utils import (
  159. get_disabled_skill_names, get_external_skills_dirs, get_project_skills_dirs)
  160. from tools.skills_tool import SKILLS_DIR
  161. try:
  162. disabled = get_disabled_skill_names(platform=platform)
  163. except Exception:
  164. disabled = set()
  165. hub_dir = (SKILLS_DIR / ".hub").resolve()
  166. roots = [SKILLS_DIR.resolve()]
  167. for getter in (get_external_skills_dirs, get_project_skills_dirs):
  168. try:
  169. for d in getter():
  170. try:
  171. roots.append(Path(d).resolve())
  172. except Exception:
  173. continue
  174. except Exception:
  175. pass
  176. skill_cmds = get_skill_commands()
  177. for cmd_key in sorted(skill_cmds):
  178. info = skill_cmds[cmd_key]
  179. skill_path = info.get("skill_md_path", "")
  180. if not skill_path:
  181. continue
  182. sp = Path(skill_path).resolve()
  183. if sp.is_relative_to(hub_dir):
  184. continue
  185. root = next((r for r in roots if sp.is_relative_to(r)), None)
  186. if root is None or info.get("name", "") in disabled:
  187. continue
  188. yield cmd_key, info, sp.parent.relative_to(root).parts
  189. def _collect_gateway_skill_entries(
  190. platform: str, max_slots: int | None, reserved_names: set[str], desc_limit: int = 100,
  191. sanitize_name: Callable[[str], str] | None = None,
  192. ) -> tuple[list[tuple[str, str, str, str]], int]:
  193. """Collect plugin + skill entries for a gateway platform.
  194. Plugin slash commands come first and are never trimmed; skill commands (alphabetical) fill
  195. the remaining *max_slots* (``None`` = every candidate, caller caps). *reserved_names* is
  196. mutated in place as names are claimed; *sanitize_name* runs before clamping and may return
  197. "" to skip. Returns ``(entries, hidden_count)``, entries ``(name, description, cmd_key,
  198. raw_name)`` — ``cmd_key`` "" for plugins; ``raw_name`` is the sanitized pre-clamp name used
  199. for configured-priority matching (both survive a clamp-induced rename).
  200. """
  201. sanitize = sanitize_name or (lambda n: n)
  202. def _entries(rows) -> list[tuple[str, str, str, str]]:
  203. """Sanitize + truncate ``(raw_name, description, cmd_key)`` rows, then clamp against
  204. ``reserved_names``; any failure in the lazy source yields the rows collected so far."""
  205. out: list[tuple[str, str, str, str]] = []
  206. try:
  207. for raw, desc, cmd_key in rows:
  208. if name := sanitize(raw):
  209. out.append((name, _truncate_desc(desc, desc_limit), cmd_key, name))
  210. except Exception:
  211. pass
  212. return _clamp_command_names(out, reserved_names)
  213. def _plugin_rows():
  214. from hermes_cli.plugins import get_plugin_commands
  215. plugin_cmds = get_plugin_commands()
  216. for cmd_name in sorted(plugin_cmds):
  217. meta = plugin_cmds[cmd_name]
  218. if platform == "telegram" and _requires_argument(str(meta.get("args_hint") or "")):
  219. continue
  220. yield cmd_name, meta.get("description") or t("slash.shared.plugin_command_desc"), ""
  221. plugin_entries = _entries(_plugin_rows())
  222. reserved_names.update(n for n, *_rest in plugin_entries)
  223. skill_entries = _entries(
  224. (cmd_key.lstrip("/"), info.get("description", ""), cmd_key)
  225. for cmd_key, info, _rel in _iter_gateway_skills(platform))
  226. if max_slots is None:
  227. return plugin_entries + skill_entries, 0
  228. remaining = max(0, max_slots - len(plugin_entries))
  229. hidden_count = max(0, len(skill_entries) - remaining)
  230. return (plugin_entries + skill_entries[:remaining])[:max_slots], hidden_count
  231. def telegram_menu_commands(max_commands: int = 100) -> tuple[list[tuple[str, str]], int]:
  232. """``(menu_commands, hidden_count)`` for Telegram, capped to the Bot API limit. Tier order:
  233. core CommandDefs, plugin slash commands, skill commands (alphabetical; hub and
  234. telegram-disabled skills excluded). Tiers keep relative order unless named in
  235. ``platforms.telegram.extra.command_menu.priority`` — applied *before* the cap, so a
  236. prioritized dynamic command can displace an unprioritized core command."""
  237. core_commands = list(telegram_bot_commands(include_plugins=False))
  238. entries, hidden_count = _collect_gateway_skill_entries(
  239. platform="telegram", max_slots=None, reserved_names={n for n, _ in core_commands},
  240. desc_limit=40, sanitize_name=_sanitize_telegram_name)
  241. candidates = [(name, desc, "core", name) for name, desc in core_commands]
  242. candidates += [(name, desc, "skill" if cmd_key else "plugin", raw)
  243. for name, desc, cmd_key, raw in entries]
  244. candidates = _prioritize_telegram_menu_candidates(candidates)
  245. overflow_count = max(0, len(candidates) - max_commands)
  246. menu = [(name, _normalize_telegram_desc(desc)) for name, desc, _source, _raw_name in candidates[:max_commands]]
  247. return menu, hidden_count + overflow_count
  248. # --- Discord ----------------------------------------------------------------
  249. def discord_skill_commands_by_category(
  250. reserved_names: set[str],
  251. ) -> tuple[dict[str, list[tuple[str, str, str]]], list[tuple[str, str, str]], int]:
  252. """``(categories, uncategorized, hidden_count)`` for Discord ``/skill`` autocomplete.
  253. Skills nested >= 2 levels under a scan root (``creative/ascii-art/SKILL.md``) group under
  254. ``categories[top_level]``; root-level skills are *uncategorized*. Entries are
  255. ``(name, description, cmd_key)``, names clamped to 32 chars, descriptions to 100. No
  256. per-group cap (the caller flattens into one autocomplete callback); ``hidden_count`` only
  257. reports 32-char clamp collisions against reserved names or earlier skills.
  258. Scan roots include the local ``SKILLS_DIR`` **and** any configured ``skills.external_dirs`` — matching
  259. the widened filter applied to the flat ``discord_skill_commands()`` collector in #18741. Without this
  260. parity, external-dir skills are visible via ``hermes skills list`` and the agent's ``/skill-name``
  261. dispatch but silently absent from Discord's ``/skill`` autocomplete.
  262. The legacy 25-group × 25-subcommand caps (from the old nested ``/skill <cat> <name>`` layout) are
  263. **not** applied — the live caller (``_register_skill_group`` in ``gateway/platforms/discord.py``,
  264. refactored in PR #11580) flattens these results and feeds them into a single autocomplete callback,
  265. which scales to thousands of entries without any per-command payload concerns. ``hidden_count`` is
  266. retained in the return tuple for backward compatibility and still reports skills dropped for other
  267. reasons (32-char clamp collision vs a reserved name).
  268. """
  269. categories: dict[str, list[tuple[str, str, str]]] = {}
  270. uncategorized: list[tuple[str, str, str]] = []
  271. # clamped name -> origin; reserved names carry a sentinel so the warning distinguishes a
  272. # reserved-command collision from two skills colliding on the clamp (the rename-worthy case).
  273. names_used: dict[str, str] = dict.fromkeys(reserved_names, "<reserved>")
  274. hidden = 0
  275. try:
  276. for cmd_key, info, rel_parts in _iter_gateway_skills("discord"):
  277. # First (alphabetical) skill wins; the loser is dropped from the picker — warn loudly.
  278. discord_name = cmd_key.lstrip("/")[:32]
  279. prior = names_used.get(discord_name)
  280. if prior == "<reserved>":
  281. logger.warning(
  282. "Discord /skill: %r (from %r) collides on its 32-char "
  283. "clamp with a reserved gateway command name %r — the "
  284. "skill will not appear in the /skill autocomplete. "
  285. "Rename the skill's frontmatter ``name:`` to differ "
  286. "in its first 32 chars.",
  287. discord_name, cmd_key, discord_name)
  288. elif prior is not None:
  289. logger.warning(
  290. "Discord /skill: %r and %r both clamp to %r on "
  291. "Discord's 32-char command-name limit — only %r "
  292. "will appear in the /skill autocomplete. Rename "
  293. "one skill's frontmatter ``name:`` to differ in "
  294. "its first 32 chars.",
  295. prior, cmd_key, discord_name, prior)
  296. if prior is not None:
  297. hidden += 1
  298. continue
  299. names_used[discord_name] = cmd_key
  300. entry = (discord_name, _truncate_desc(info.get("description", ""), 100), cmd_key)
  301. if len(rel_parts) >= 2:
  302. categories.setdefault(rel_parts[0], []).append(entry)
  303. else:
  304. uncategorized.append(entry)
  305. except Exception:
  306. pass
  307. return categories, uncategorized, hidden
  308. # --- Slack native slash commands --------------------------------------------
  309. # Slack slash names: lowercase a-z, 0-9, hyphens, underscores, max 32 chars; an app manifest
  310. # accepts up to 50 slash commands. Reserved = Slack built-ins apps cannot register
  311. # (https://slack.com/help/articles/201259356-Use-built-in-slash-commands).
  312. _SLACK_MAX_SLASH_COMMANDS = 50
  313. _SLACK_NAME_LIMIT = 32
  314. _SLACK_INVALID_CHARS = re.compile(r"[^a-z0-9_\-]")
  315. _SLACK_RESERVED_COMMANDS = frozenset({
  316. "me", "status", "away", "dnd", "shrug", "remind", "msg", "feed", "who", "collapse", "expand",
  317. "leave", "join", "open", "search", "topic", "mute", "pro", "shortcuts"})
  318. # Canonical commands deliberately routed through ``/hermes <command>`` on Slack only: the registry
  319. # sits at Slack's 50-slash cap, so rather than let the clamp silently drop whichever command sorts
  320. # last (breaking the Telegram-parity test), low-frequency ones are demoted here. Rule: when a new
  321. # canonical command tips past the cap, demote a rarer one-off lookup (version, whoami, diff, ...)
  322. # rather than a recurring interactive surface (context, loop, save, approvals). Keep TIGHT — the
  323. # parity test reads this set. Aliases are never pinned ahead of canonicals.
  324. _SLACK_VIA_HERMES_ONLY = frozenset({
  325. "topup", "moa", "debug", "egress", "init", "version", "diff", "update", "heartbeat",
  326. "refine", "review", "pause", "whoami", "platform", "insights", "login",
  327. # Recovery-only, after a restart lost a turn: `/hermes discard` reaches it.
  328. "discard",
  329. # One-time answer to the low-disk prompt; `/hermes autoprune on` reaches it.
  330. "autoprune"})
  331. def _sanitize_slack_name(raw: str) -> str:
  332. """Lowercase, strip chars outside ``[a-z0-9_-]`` and edge ``-_``, clamp to 32."""
  333. return _SLACK_INVALID_CHARS.sub("", raw.lower()).strip("-_")[:_SLACK_NAME_LIMIT]
  334. def slack_native_slashes() -> list[tuple[str, str, str]]:
  335. """(slash_name, description, usage_hint) triples for Slack: every gateway-available command
  336. (canonical names first so they win slots at the cap, then aliases, then plugins) becomes a
  337. standalone slash, deduped and clamped to the 50-command cap; Slack built-ins and
  338. _SLACK_VIA_HERMES_ONLY are skipped. ``/hermes`` is always first for anything dropped."""
  339. available = _gateway_available_commands()
  340. wanted = [(cmd.name, cmd.describe(), cmd.args_hint or "") for cmd in available]
  341. wanted += [(alias, t("slash.shared.slack_alias_for", name=cmd.name, description=cmd.describe()),
  342. cmd.args_hint or "") for cmd in available for alias in cmd.aliases]
  343. wanted += [(name, desc, hint or "") for name, desc, hint in _iter_plugin_command_entries()]
  344. entries: list[tuple[str, str, str]] = [
  345. ("hermes", t("slash.hermes.description"), "[subcommand] [args]")]
  346. seen = {"hermes"}
  347. for name, desc, hint in wanted:
  348. slack_name = _sanitize_slack_name(name)
  349. if (not slack_name or slack_name in seen or slack_name in _SLACK_RESERVED_COMMANDS
  350. or slack_name in _SLACK_VIA_HERMES_ONLY
  351. or len(entries) >= _SLACK_MAX_SLASH_COMMANDS):
  352. continue
  353. # Slack description cap is 2000 chars; keep it short.
  354. entries.append((slack_name, desc[:140], hint[:100]))
  355. seen.add(slack_name)
  356. return entries
  357. def slack_app_manifest(
  358. request_url: str = "https://hermes-agent.local/slack/commands") -> dict[str, Any]:
  359. """``features.slash_commands`` manifest portion only (decoupled from the rest of the manifest
  360. users configure in the Slack UI); ``request_url`` is schema-required, ignored in Socket Mode."""
  361. slashes = []
  362. for name, desc, usage in slack_native_slashes():
  363. entry = {"command": f"/{name}", "description": desc or t("slash.shared.plugin_default_desc", name=name),
  364. "should_escape": False, "url": request_url}
  365. if usage:
  366. entry["usage_hint"] = usage
  367. slashes.append(entry)
  368. return {"features": {"slash_commands": slashes}}
  369. def slack_subcommand_map() -> dict[str, str]:
  370. """name/alias -> "/command" for the Slack ``/hermes`` handler, plugin commands included."""
  371. mapping: dict[str, str] = {
  372. name: f"/{name}"
  373. for cmd in _gateway_available_commands() for name in (cmd.name, *cmd.aliases)}
  374. for name, _description, _args_hint in _iter_plugin_command_entries():
  375. mapping.setdefault(name, f"/{name}")
  376. return mapping