console_engine.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. """Safe Hermes Console command engine."""
  2. from __future__ import annotations
  3. import argparse
  4. import contextlib
  5. import difflib
  6. import functools
  7. import importlib
  8. import io
  9. import json
  10. import sys
  11. from contextlib import closing
  12. from dataclasses import dataclass
  13. from pathlib import Path
  14. from types import SimpleNamespace
  15. from typing import Callable, Iterable, Literal, NoReturn, Sequence
  16. from tools.ansi_strip import strip_ansi as _strip_ansi
  17. ConsoleStatus = Literal["ok", "error", "confirm_required", "exit", "clear"]
  18. class ConsoleCommandError(RuntimeError):
  19. """User-facing console command failure."""
  20. @dataclass(frozen=True)
  21. class ConsoleResult:
  22. status: ConsoleStatus
  23. output: str = ""
  24. command: str = ""
  25. confirmation_message: str = ""
  26. @dataclass(frozen=True)
  27. class ConsoleCommand:
  28. path: tuple[str, ...]
  29. usage: str
  30. summary: str
  31. handler: Callable[[HermesConsoleEngine, list[str]], str]
  32. mutating: bool = False
  33. confirmation: str = ""
  34. class _ArgumentParser(argparse.ArgumentParser):
  35. def error(self, message: str) -> NoReturn: # pragma: no cover - argparse hook
  36. raise ConsoleCommandError(f"{self.prog}: {message}")
  37. def _capture_output(fn: Callable[[], object]) -> str:
  38. stdout, stderr = io.StringIO(), io.StringIO()
  39. code, message = 0, ""
  40. with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
  41. try:
  42. result = fn()
  43. if isinstance(result, int) and result:
  44. raise SystemExit(result)
  45. except SystemExit as exc:
  46. # sys.exit("msg") carries the message as exc.code (not an int); int() on it would
  47. # raise ValueError past execute()'s handler and crash the REPL.
  48. if isinstance(exc.code, str):
  49. message, code = exc.code, 1
  50. else:
  51. code = int(exc.code or 0)
  52. except ConsoleCommandError:
  53. raise
  54. except RuntimeError as exc:
  55. # Fail-closed config write guards raise RuntimeError; surface it as a console error
  56. # instead of killing the REPL / websocket session.
  57. message, code = str(exc), 1
  58. text = stdout.getvalue() + stderr.getvalue()
  59. if code:
  60. raise ConsoleCommandError(
  61. message.strip() or text.strip() or f"Command exited with status {code}")
  62. return text.rstrip()
  63. def _is_status_footer_rule(line: str) -> bool:
  64. stripped = _strip_ansi(line).strip()
  65. return len(stripped) >= 8 and set(stripped.replace("\u2500", "-")) <= {"-"}
  66. def _drop_trailing_blank(lines: list[str]) -> None:
  67. while lines and not _strip_ansi(lines[-1]).strip():
  68. lines.pop()
  69. def _strip_console_status_footer(text: str) -> str:
  70. lines = text.splitlines()
  71. _drop_trailing_blank(lines)
  72. if len(lines) < 2:
  73. return text.rstrip()
  74. last, prev = (_strip_ansi(lines[i]).strip() for i in (-1, -2))
  75. if not (prev.startswith("Run 'hermes doctor'") and last.startswith("Run 'hermes setup'")):
  76. return text.rstrip()
  77. lines = lines[:-2]
  78. _drop_trailing_blank(lines)
  79. if lines and _is_status_footer_rule(lines[-1]):
  80. lines.pop()
  81. return "\n".join(lines).rstrip()
  82. def _table_summary(summary: str, *, limit: int = 76) -> str:
  83. summary = " ".join(summary.split())
  84. return summary if len(summary) <= limit else f"{summary[: limit - 3].rstrip()}..."
  85. def _split_line(line: str) -> list[str]:
  86. # Windows-safe splitter: plain shlex posix=True eats backslashes in paths.
  87. # See #78293.
  88. # See #83934.
  89. from hermes_cli._subprocess_compat import split_command_line
  90. try:
  91. return split_command_line(line)
  92. except ValueError as exc:
  93. raise ConsoleCommandError(f"Could not parse command: {exc}") from exc
  94. _SHELL_TOKENS = {"|", "||", "&", "&&", ";", ">", ">>", "<", "<<", "2>", "2>>"}
  95. def _contains_shell_syntax(line: str, tokens: Sequence[str]) -> bool:
  96. return (
  97. "$(" in line or "`" in line
  98. or any(token in _SHELL_TOKENS for token in tokens)
  99. or any(ch in line for ch in "|<>;"))
  100. def _format_sessions(sessions: Sequence[dict]) -> str:
  101. if not sessions:
  102. return "No sessions found."
  103. lines = [f"{'ID':<32} {'Source':<12} {'Msgs':>5} Title / Preview", "-" * 82]
  104. for session in sessions:
  105. sid = str(session.get("id") or "")[:32]
  106. source = str(session.get("source") or "-")[:12]
  107. messages = session.get("message_count") or 0
  108. title = str(session.get("title") or session.get("preview") or "").replace("\n", " ")[:60]
  109. lines.append(f"{sid:<32} {source:<12} {messages:>5} {title}")
  110. return "\n".join(lines)
  111. def _format_job(job: dict, action: str) -> str:
  112. from cron.jobs import effective_job_state
  113. job_id = job.get("id") or job.get("job_id") or "?"
  114. return f"{action} job: {job.get('name') or '(unnamed)'} ({job_id}) [{effective_job_state(job)}]"
  115. def _clean_summary(text: str | None) -> str:
  116. if not text or text is argparse.SUPPRESS:
  117. return ""
  118. summary = " ".join(str(text).split())
  119. return "" if summary.startswith("Run `hermes ") else summary
  120. def _choice_help(action: argparse._SubParsersAction, name: str) -> str:
  121. for choice in action._choices_actions:
  122. help_text = choice.help if name in (choice.dest, choice.metavar) else None
  123. if help_text and help_text is not argparse.SUPPRESS:
  124. return str(help_text)
  125. return ""
  126. def _summaries_from_parser(parser: argparse.ArgumentParser) -> dict[tuple[str, ...], str]:
  127. """``{subcommand path: help}`` over the whole tree; choice help beats child description."""
  128. summaries: dict[tuple[str, ...], str] = {}
  129. def walk(current: argparse.ArgumentParser, path: tuple[str, ...]) -> None:
  130. for action in current._actions:
  131. if not isinstance(action, argparse._SubParsersAction):
  132. continue
  133. for name, child in action.choices.items():
  134. child_path = (*path, name)
  135. summary = _clean_summary(_choice_help(action, name)) or _clean_summary(
  136. child.description)
  137. if summary:
  138. summaries.setdefault(child_path, summary)
  139. walk(child, child_path)
  140. walk(parser, ())
  141. return summaries
  142. def _noop_console_command(_args: argparse.Namespace) -> None:
  143. return None
  144. @dataclass(frozen=True)
  145. class _CliSurface:
  146. """How a CLI subcommand module hangs its argparse tree off a root subparsers action.
  147. ``extracted``: ``builder(subparsers, <handler>=fn)``, fn from hermes_cli.main.
  148. ``registered``: ``register(subparsers.add_parser(root))``, optional module ``handler``.
  149. ``builder``: ``top = builder(subparsers)``, func from hermes_cli.main.
  150. ``adder``: self-wiring."""
  151. kind: Literal["extracted", "registered", "builder", "adder"]
  152. module: str
  153. builder: str
  154. handler: str | None = None
  155. def build(self, root: str, *, live: bool) -> _ArgumentParser:
  156. """Build a throwaway parser; ``live=False`` wires no-op handlers (summary extraction)."""
  157. parser = _ArgumentParser(prog="hermes", add_help=False)
  158. subparsers = parser.add_subparsers(dest="_console_command")
  159. module = importlib.import_module(self.module)
  160. entry = getattr(module, self.builder)
  161. main_handler = (
  162. (lambda: getattr(importlib.import_module("hermes_cli.main"), self.handler))
  163. if live else (lambda: _noop_console_command))
  164. if self.kind == "extracted":
  165. entry(subparsers, **{self.handler: main_handler()})
  166. elif self.kind == "registered":
  167. top_parser = subparsers.add_parser(root)
  168. entry(top_parser)
  169. if live and self.handler:
  170. top_parser.set_defaults(func=getattr(module, self.handler))
  171. elif self.kind == "builder":
  172. top_parser = entry(subparsers)
  173. if live:
  174. top_parser.set_defaults(func=main_handler())
  175. else:
  176. entry(subparsers)
  177. return parser
  178. # Memoized: the surface is process-static, but the dashboard opens a fresh engine per
  179. # /api/console connection and would otherwise re-import + re-parse it on every reconnect.
  180. @functools.cache
  181. def _surface_summaries(surface: _CliSurface, root: str) -> dict[tuple[str, ...], str]:
  182. try:
  183. return _summaries_from_parser(surface.build(root, live=False))
  184. except Exception:
  185. return {}
  186. def _dispatch(
  187. surface: _CliSurface,
  188. root: str,
  189. fixed: Sequence[str],
  190. args: Sequence[str],
  191. namespace_update: Callable[[argparse.Namespace], None] | None = None) -> str:
  192. namespace = surface.build(root, live=True).parse_args([root, *fixed, *args])
  193. if namespace_update:
  194. namespace_update(namespace)
  195. func = getattr(namespace, "func", None)
  196. if not callable(func):
  197. raise ConsoleCommandError("No handler is available for that console command.")
  198. return _capture_output(lambda: func(namespace))
  199. def _paths(spec: str) -> list[tuple[tuple[str, ...], bool]]:
  200. """``"list, *snapshot export"`` -> ``[(("list",), False), (("snapshot", "export"), True)]``;
  201. ``*`` marks a mutating path, ``.`` is the bare root."""
  202. items = [item.strip() for item in spec.split(",") if item.strip()]
  203. return [
  204. (() if item.lstrip("*") == "." else tuple(item.lstrip("*").split()), item.startswith("*"))
  205. for item in items]
  206. def _sub(module: str, builder: str, handler: str) -> _CliSurface:
  207. return _CliSurface("extracted", f"hermes_cli.subcommands.{module}", builder, handler)
  208. def _reg(module: str, handler: str | None = None) -> _CliSurface:
  209. return _CliSurface("registered", f"hermes_cli.{module}", "register_cli", handler)
  210. # root -> (surface, subcommand paths as a ``_paths`` spec). Registered in this order.
  211. _CLI_FAMILIES: dict[str, tuple[_CliSurface, str]] = {
  212. "dump": (_sub("dump", "build_dump_parser", "cmd_dump"), "."),
  213. "debug": (_sub("debug", "build_debug_parser", "cmd_debug"), "*share, *delete"),
  214. "prompt-size": (_sub("prompt_size", "build_prompt_size_parser", "cmd_prompt_size"), "."),
  215. "insights": (_sub("insights", "build_insights_parser", "cmd_insights"), "."),
  216. "security": (_sub("security", "build_security_parser", "cmd_security"), "audit"),
  217. "backup": (_sub("backup", "build_backup_parser", "cmd_backup"), "*."),
  218. "import": (_sub("import_cmd", "build_import_cmd_parser", "cmd_import"), "*."),
  219. "config": (_sub("config", "build_config_parser", "cmd_config"), "env-path, check"),
  220. "tools": (
  221. _sub("tools", "build_tools_parser", "cmd_tools"),
  222. "list, *enable, *disable, *post-setup"),
  223. "plugins": (
  224. _sub("plugins", "build_plugins_parser", "cmd_plugins"),
  225. "list, *enable, *disable, *install, *update, *remove"),
  226. "skills": (
  227. _sub("skills", "build_skills_parser", "cmd_skills"),
  228. "browse, search, inspect, list, check, list-modified, diff, *install, *update, *audit, "
  229. "*uninstall, *reset, *opt-in, *opt-out, *repair-official, *snapshot export, "
  230. "*snapshot import, tap list, *tap add, *tap remove"),
  231. "mcp": (
  232. _sub("mcp", "build_mcp_parser", "cmd_mcp"),
  233. "list, catalog, test, *add, *remove, *install, *login, *reauth, *configure, *picker"),
  234. "memory": (_sub("memory", "build_memory_parser", "cmd_memory"), "status, *off, *reset"),
  235. "auth": (
  236. _sub("auth", "build_auth_parser", "cmd_auth"),
  237. "list, status, *reset, *priority, *refresh, *add, *remove, *logout"),
  238. "pairing": (
  239. _sub("pairing", "build_pairing_parser", "cmd_pairing"),
  240. "list, *approve, *revoke, *clear-pending"),
  241. "webhook": (
  242. _sub("webhook", "build_webhook_parser", "cmd_webhook"),
  243. "list, *subscribe, *remove, test"),
  244. "hooks": (_sub("hooks", "build_hooks_parser", "cmd_hooks"), "list, *test, *doctor, *revoke"),
  245. "slack": (_sub("slack", "build_slack_parser", "cmd_slack"), "manifest"),
  246. "profile": (
  247. _sub("profile", "build_profile_parser", "cmd_profile"),
  248. "list, show, info, *create, *use, *describe, *rename, *delete, *export, *import, "
  249. "*install, *update"),
  250. "cron": (_sub("cron", "build_cron_parser", "cmd_cron"), "*create, *edit, *remove, *tick"),
  251. "portal": (_CliSurface("adder", "hermes_cli.portal_cli", "add_parser"), "info, tools"),
  252. "project": (
  253. _CliSurface("builder", "hermes_cli.projects_cmd", "build_parser", "cmd_project"),
  254. "list, show, *create, *add-folder, *remove-folder, *rename, *set-primary, *use, "
  255. "*archive, *restore, *bind-board"),
  256. "kanban": (
  257. _CliSurface("builder", "hermes_cli.kanban", "build_parser", "cmd_kanban"),
  258. "*init, boards list, *boards create, *boards rm, *boards switch, boards current, "
  259. "*boards rename, *boards set-workdir, *create, list, show, *assign, *reclaim, *reassign, "
  260. "diagnose, *link, *unlink, *claim, *comment, *complete, *edit, *block, *schedule, "
  261. "*unblock, *promote, *archive, stats, runs, heartbeat, assignments, context"),
  262. "bundles": (_reg("bundles", "bundles_command"), "list, show, *create, *delete, *reload"),
  263. "checkpoints": (_reg("checkpoints"), "status, list, *prune, *clear, *clear-legacy"),
  264. "curator": (
  265. _reg("curator"),
  266. "status, *run, *pause, *resume, *pin, *unpin, *restore, list-archived, *archive, *prune, "
  267. "*backup, *rollback"),
  268. "pets": (_reg("pets"), "list, *install, *select, show, *off, *scale, *remove, doctor"),
  269. }
  270. # Only extracted/registered families skip nested prompts after console confirmation
  271. # (builder/adder families never did).
  272. _CONFIRMED_KINDS = {"extracted", "registered"}
  273. _SEND_SURFACE = _CliSurface("adder", "hermes_cli.send_cmd", "register_send_subparser")
  274. def _register_command_family(
  275. engine: HermesConsoleEngine, root: str, surface: _CliSurface, paths: str) -> None:
  276. summaries = _surface_summaries(surface, root)
  277. namespace_update = _apply_confirmed_defaults if surface.kind in _CONFIRMED_KINDS else None
  278. for child_path, mutating in _paths(paths):
  279. full_path = (root, *child_path)
  280. usage = " ".join(full_path)
  281. def handler(_engine: HermesConsoleEngine, args: list[str], fixed=child_path) -> str:
  282. return _dispatch(surface, root, fixed, args, namespace_update)
  283. engine.register(
  284. full_path, usage, summaries.get(full_path) or f"Run `hermes {usage}`.", handler,
  285. mutating=mutating, confirmation=f"Run `hermes {usage}`?")
  286. _BLOCKED_TOP = frozenset(
  287. "acp chat claw completion dashboard desktop fallback gateway gui login logout model moa "
  288. "oneshot proxy serve setup uninstall update whatsapp whatsapp-cloud".split())
  289. _BLOCKED_PAIRS = {
  290. ("config", "edit"): "`config edit` opens an editor and is not available in Hermes Console.",
  291. ("profile", "alias"): "`profile alias` creates shell wrappers and is not available in Hermes Console.",
  292. ("skills", "config"): "`skills config` is interactive and is not available in Hermes Console.",
  293. ("skills", "publish"): "`skills publish` is not available in Hermes Console.",
  294. ("portal", "login"): "`portal login` is interactive and is not available in Hermes Console.",
  295. ("portal", "open"): "`portal open` opens a browser and is not available in Hermes Console.",
  296. ("kanban", "tail"): "`kanban tail` streams output and is not available in Hermes Console.",
  297. ("kanban", "watch"): "`kanban watch` streams output and is not available in Hermes Console.",
  298. ("kanban", "daemon"): "`kanban daemon` starts a service and is not available in Hermes Console.",
  299. ("kanban", "dispatcher"): "`kanban dispatcher` starts a worker and is not available in Hermes Console.",
  300. ("kanban", "swarm"): "`kanban swarm` starts agent work and is not available in Hermes Console.",
  301. ("kanban", "decompose"): "`kanban decompose` starts agent work and is not available in Hermes Console.",
  302. ("kanban", "specify"): "`kanban specify` starts agent work and is not available in Hermes Console.",
  303. ("kanban", "gc"): "`kanban gc` is not available in Hermes Console.",
  304. ("sessions", "delete"): "`sessions delete` and `sessions prune` are not available in Hermes Console.",
  305. ("sessions", "prune"): "`sessions delete` and `sessions prune` are not available in Hermes Console.",
  306. }
  307. class HermesConsoleEngine:
  308. """Curated line-command executor for Hermes Console."""
  309. def __init__(self, *, output_limit: int = 20000):
  310. self.output_limit = output_limit
  311. self.history: list[str] = []
  312. self.commands: dict[tuple[str, ...], ConsoleCommand] = {}
  313. self._register_defaults()
  314. def execute(self, line: str, *, confirmed: bool = False) -> ConsoleResult:
  315. raw_line = line.strip()
  316. if not raw_line:
  317. return ConsoleResult("ok")
  318. try:
  319. tokens = _split_line(raw_line)
  320. if tokens and tokens[0] == "hermes":
  321. tokens = tokens[1:]
  322. if not tokens:
  323. return ConsoleResult("ok", output=self.help_text())
  324. if _contains_shell_syntax(raw_line, tokens):
  325. raise ConsoleCommandError(
  326. "Hermes Console does not run shell syntax. Use one supported "
  327. "Hermes command at a time.")
  328. builtin = self._execute_builtin(tokens)
  329. if builtin is not None:
  330. if raw_line not in {"history", "clear"}:
  331. self.history.append(raw_line)
  332. return builtin
  333. command, args = self._resolve_command(tokens)
  334. if command.mutating and not confirmed:
  335. return ConsoleResult(
  336. "confirm_required",
  337. command=raw_line,
  338. confirmation_message=command.confirmation or f"Run `{command.usage}`?")
  339. output = self._cap_output(command.handler(self, args).rstrip())
  340. self.history.append(raw_line)
  341. return ConsoleResult("ok", output=output, command=raw_line)
  342. except ConsoleCommandError as exc:
  343. return ConsoleResult("error", output=str(exc).strip(), command=raw_line)
  344. def help_text(self, subject: str | None = None) -> str:
  345. if subject:
  346. command, _args = self._resolve_command(subject.split())
  347. return f"{command.usage}\n{command.summary}"
  348. lines = ["Hermes Console", "", "Supported commands:"]
  349. for command in sorted(self.commands.values(), key=lambda c: c.usage):
  350. marker = " *" if command.mutating else " "
  351. lines.append(f"{marker} {command.usage:<32} {_table_summary(command.summary)}")
  352. lines += ["", "* requires confirmation",
  353. "Built-ins: help, help <command>, history, clear, exit, quit"]
  354. return "\n".join(lines)
  355. def _register_defaults(self) -> None:
  356. for path, usage, summary, handler, confirmation in _BUILTIN_COMMANDS:
  357. self.register(
  358. path, usage, summary, handler,
  359. mutating=bool(confirmation), confirmation=confirmation)
  360. for root, (surface, paths) in _CLI_FAMILIES.items():
  361. _register_command_family(self, root, surface, paths)
  362. self.register(
  363. ("send",), "send --to <target> <message>", "Send a message to a configured platform.",
  364. lambda _engine, args: _dispatch(_SEND_SURFACE, "send", (), args),
  365. mutating=True, confirmation="Send this message?")
  366. def register(
  367. self, path: Iterable[str], usage: str, summary: str,
  368. handler: Callable[[HermesConsoleEngine, list[str]], str], *,
  369. mutating: bool = False, confirmation: str = "") -> None:
  370. key = tuple(path)
  371. self.commands[key] = ConsoleCommand(key, usage, summary, handler, mutating, confirmation)
  372. def _execute_builtin(self, tokens: list[str]) -> ConsoleResult | None:
  373. head = tokens[0]
  374. if head == "help":
  375. subject = " ".join(tokens[1:]).strip() or None
  376. try:
  377. return ConsoleResult("ok", output=self.help_text(subject))
  378. except ConsoleCommandError as exc:
  379. return ConsoleResult("error", output=str(exc))
  380. if head == "history":
  381. output = "\n".join(f"{idx + 1}: {cmd}" for idx, cmd in enumerate(self.history))
  382. return ConsoleResult("ok", output=output or "No history yet.")
  383. if head == "clear":
  384. return ConsoleResult("clear", output="\033[2J\033[H")
  385. return ConsoleResult("exit") if head in {"exit", "quit"} else None
  386. def _resolve_command(self, tokens: Sequence[str]) -> tuple[ConsoleCommand, list[str]]:
  387. rejected = self._rejection_for(tokens)
  388. if rejected:
  389. raise ConsoleCommandError(rejected)
  390. for size in range(min(len(tokens), 3), 0, -1):
  391. command = self.commands.get(tuple(tokens[:size]))
  392. if command:
  393. return command, list(tokens[size:])
  394. available = [" ".join(path) for path in self.commands]
  395. probe = " ".join(tokens[:2]) if len(tokens) > 1 else tokens[0]
  396. suggestions = difflib.get_close_matches(probe, available, n=3, cutoff=0.45)
  397. suffix = f" Did you mean: {', '.join(suggestions)}?" if suggestions else ""
  398. raise ConsoleCommandError(f"Unsupported Hermes Console command: {probe}.{suffix}")
  399. def _rejection_for(self, tokens: Sequence[str]) -> str:
  400. first = tokens[0]
  401. if first.startswith("-"):
  402. return f"{first} is not available in Hermes Console."
  403. if first in _BLOCKED_TOP:
  404. return f"`hermes {first}` is not available in Hermes Console."
  405. return _BLOCKED_PAIRS.get(tuple(tokens[:2]), "")
  406. def _cap_output(self, output: str) -> str:
  407. if len(output) <= self.output_limit:
  408. return output
  409. omitted = len(output) - self.output_limit
  410. return f"{output[:self.output_limit]}\n... output truncated ({omitted} bytes omitted)"
  411. def _expect_no_args(args: Sequence[str], usage: str) -> None:
  412. if args:
  413. raise ConsoleCommandError(f"Usage: {usage}")
  414. def _parse(prog: str, args: Sequence[str], *specs) -> argparse.Namespace:
  415. """Parse ``args`` with a help-less parser; each spec is ``(flags, kwargs)`` or a bare flag."""
  416. parser = _ArgumentParser(prog=prog, add_help=False)
  417. for spec in specs:
  418. flags, kwargs = spec if isinstance(spec, tuple) else ((spec,), {})
  419. parser.add_argument(*flags, **kwargs)
  420. return parser.parse_args(args)
  421. def _captured(fn):
  422. """Handler decorator: run ``fn(engine, args)`` under ``_capture_output`` and return its text."""
  423. @functools.wraps(fn)
  424. def wrapper(engine: HermesConsoleEngine, args: list[str]) -> str:
  425. return _capture_output(lambda: fn(engine, args))
  426. return wrapper
  427. def _simple_command(usage: str, module: str, name: str, make_args=lambda: (), **kwargs):
  428. """Handler for no-arg commands that capture ``module.name(*make_args(), **kwargs)``."""
  429. def handler(_engine: HermesConsoleEngine, args: list[str]) -> str:
  430. _expect_no_args(args, usage)
  431. fn = getattr(importlib.import_module(module), name)
  432. return _capture_output(lambda: fn(*make_args(), **kwargs))
  433. return handler
  434. def _apply_confirmed_defaults(args: argparse.Namespace) -> None:
  435. """Skip nested prompts after the console-level confirmation has happened."""
  436. if hasattr(args, "yes"):
  437. args.yes = True
  438. if getattr(args, "_console_command", None) == "import":
  439. args.force = True
  440. # Every mutating checkpoints subcommand gates its own confirmation on --force; `prune`
  441. # reaches _confirm() for its orphan preview, and the console never redirects stdin.
  442. if getattr(args, "checkpoints_command", None) in {"prune", "clear", "clear-legacy"}:
  443. args.force = True
  444. if (
  445. getattr(args, "plugins_action", None) == "install"
  446. and not getattr(args, "enable", False)
  447. and not getattr(args, "no_enable", False)):
  448. args.no_enable = True
  449. if getattr(args, "auth_action", None) == "add":
  450. auth_type = getattr(args, "auth_type", None)
  451. if auth_type in {"api-key", "api_key"} and not getattr(args, "api_key", None):
  452. raise ConsoleCommandError(
  453. "auth add --type api-key requires --api-key in Hermes Console.")
  454. if getattr(args, "import_name", None) is not None:
  455. return # profile import has no prompt flag; leave it alone.
  456. if getattr(args, "skills_action", None) in {"install", "reset", "opt-out", "repair-official"}:
  457. args.yes = True
  458. if getattr(args, "memory_command", None) == "reset":
  459. args.yes = True
  460. _version = _simple_command(
  461. "version", "hermes_cli._startup_fast", "print_fast_version_info", check_updates=True)
  462. def _status(_engine: HermesConsoleEngine, args: list[str]) -> str:
  463. _expect_no_args(args, "status")
  464. from hermes_cli.status import show_status
  465. output = _capture_output(lambda: show_status(SimpleNamespace(full=True, deep=False)))
  466. return _strip_console_status_footer(output)
  467. _doctor = _simple_command(
  468. "doctor", "hermes_cli.doctor", "run_doctor", lambda: (SimpleNamespace(fix=False, ack=None),))
  469. _config_show = _simple_command("config show", "hermes_cli.config_show", "show_config")
  470. _cron_status = _simple_command("cron status", "hermes_cli.cron", "cron_status")
  471. def _logs(_engine: HermesConsoleEngine, args: list[str]) -> str:
  472. if "-f" in args or "--follow" in args:
  473. raise ConsoleCommandError("`logs -f` is not available in Hermes Console.")
  474. ns = _parse(
  475. "logs", args, (("log_name",), dict(nargs="?", default="agent")),
  476. (("-n", "--lines"), dict(type=int, default=50)),
  477. "--level", "--session", "--since", "--component")
  478. if ns.lines < 1 or ns.lines > 500:
  479. raise ConsoleCommandError("logs --lines must be between 1 and 500")
  480. from hermes_cli.logs import list_logs, tail_log
  481. if ns.log_name == "list":
  482. return _capture_output(list_logs)
  483. return _capture_output(
  484. lambda: tail_log(
  485. ns.log_name, num_lines=ns.lines, follow=False, level=ns.level,
  486. session=ns.session, since=ns.since, component=ns.component))
  487. def _session_db(*, read_only: bool = True):
  488. """``with _session_db() as db:`` — SessionDB closed on exit.
  489. The console runs inside the dashboard process, which already owns a handle on state.db;
  490. reads attach ``read_only`` so they never add a writer connection beside it (#100896).
  491. Mutating commands pass ``read_only=False``.
  492. """
  493. from hermes_state import SessionDB
  494. return closing(SessionDB(read_only=read_only))
  495. def _sessions_list(_engine: HermesConsoleEngine, args: list[str]) -> str:
  496. ns = _parse("sessions list", args, (("--limit",), dict(type=int, default=20)))
  497. if ns.limit < 1 or ns.limit > 200:
  498. raise ConsoleCommandError("sessions list --limit must be between 1 and 200")
  499. from hermes_state_sessions import INTERNAL_LISTING_SOURCES
  500. with _session_db() as db:
  501. sessions = db.list_sessions_rich(
  502. exclude_sources=list(INTERNAL_LISTING_SOURCES), limit=ns.limit, order_by_last_active=True)
  503. return _format_sessions(sessions)
  504. def _sessions_stats(_engine: HermesConsoleEngine, args: list[str]) -> str:
  505. _expect_no_args(args, "sessions stats")
  506. from hermes_state_sessions import INTERNAL_LISTING_SOURCES
  507. with _session_db() as db:
  508. total = db.session_count()
  509. listable = db.session_count(exclude_children=True, exclude_sources=list(INTERNAL_LISTING_SOURCES))
  510. lines = [
  511. f"Total sessions: {total}",
  512. f"Listable sessions: {listable}",
  513. f"Total messages: {db.message_count()}"]
  514. for source in ["cli", "tui", "telegram", "discord", "slack", "cron"]:
  515. count = db.session_count(source=source)
  516. if count:
  517. lines.append(f" {source}: {count}")
  518. return "\n".join(lines)
  519. def _config_path(_engine: HermesConsoleEngine, args: list[str]) -> str:
  520. _expect_no_args(args, "config path")
  521. from hermes_cli.config import get_config_path
  522. return str(get_config_path())
  523. def _config_set(_engine: HermesConsoleEngine, args: list[str]) -> str:
  524. if len(args) < 2:
  525. raise ConsoleCommandError("Usage: config set <key> <value>")
  526. from hermes_cli.config import set_config_value
  527. return _capture_output(lambda: set_config_value(args[0], " ".join(args[1:])))
  528. @_captured
  529. def _config_migrate(_engine: HermesConsoleEngine, args: list[str]) -> None:
  530. _expect_no_args(args, "config migrate")
  531. from hermes_cli.config import migrate_config
  532. results = migrate_config(interactive=False, quiet=False)
  533. if results.get("env_added") or results.get("config_added"):
  534. print("Configuration updated.")
  535. else:
  536. print("Configuration is up to date.")
  537. for warning in results.get("warnings") or []:
  538. print(f"Warning: {warning}")
  539. def _guard_exports(db, session_ids: list[str]) -> None:
  540. """Per-session export budget: only an individual runaway transcript trips it; 0 disables."""
  541. from hermes_state import SessionExportTooLargeError
  542. try:
  543. db.assert_exports_safe(session_ids)
  544. except SessionExportTooLargeError as exc:
  545. raise ConsoleCommandError(str(exc)) from exc
  546. @_captured
  547. def _sessions_export(_engine: HermesConsoleEngine, args: list[str]) -> None:
  548. from hermes_cli.session_export import export_projection
  549. ns = _parse("sessions export", args, "output", "--source", "--session-id")
  550. with _session_db() as db:
  551. if ns.session_id:
  552. resolved_session_id = db.resolve_session_id(ns.session_id)
  553. if not resolved_session_id:
  554. raise ConsoleCommandError(f"Session '{ns.session_id}' not found.")
  555. _guard_exports(db, [resolved_session_id])
  556. rows = [db.export_session(resolved_session_id, **export_projection(False))]
  557. if not rows[0]:
  558. raise ConsoleCommandError(f"Session '{ns.session_id}' not found.")
  559. else:
  560. found = db.search_sessions(source=ns.source, limit=100000)
  561. _guard_exports(db, [session["id"] for session in found])
  562. rows = db.export_all(source=ns.source, **export_projection(False))
  563. text = "\n".join(json.dumps(row, ensure_ascii=False) for row in rows)
  564. if text:
  565. text += "\n"
  566. if ns.output == "-":
  567. sys.stdout.write(text)
  568. else:
  569. Path(ns.output).expanduser().write_text(text, encoding="utf-8")
  570. print(f"Exported {len(rows)} session(s) to {ns.output}")
  571. @_captured
  572. def _sessions_rename(_engine: HermesConsoleEngine, args: list[str]) -> None:
  573. ns = _parse("sessions rename", args, "session_id", (("title",), dict(nargs="+")))
  574. with _session_db(read_only=False) as db:
  575. resolved_session_id = db.resolve_session_id(ns.session_id)
  576. title = " ".join(ns.title)
  577. if not resolved_session_id or not db.set_session_title(resolved_session_id, title):
  578. raise ConsoleCommandError(f"Session '{ns.session_id}' not found.")
  579. print(f"Session '{resolved_session_id}' renamed to: {title}")
  580. @_captured
  581. def _sessions_optimize(_engine: HermesConsoleEngine, args: list[str]) -> None:
  582. # --force is parsed HERE: the refusal below points at it, and a hint the surface cannot
  583. # accept would make this command refuse forever whenever a gateway is running.
  584. ns = _parse("sessions optimize", args, (("--force",), dict(action="store_true")))
  585. with _session_db(read_only=False) as db:
  586. from hermes_state_holders import held_store_refusal
  587. refusal = None if ns.force else held_store_refusal(
  588. db.db_path, command="optimize", force_hint="`sessions optimize --force`")
  589. if refusal:
  590. raise ConsoleCommandError(refusal)
  591. print(f"Optimized {db.vacuum()} FTS index(es).")
  592. @_captured
  593. def _sessions_repair(_engine: HermesConsoleEngine, args: list[str]) -> int | None:
  594. ns = _parse(
  595. "sessions repair", args, (("--check-only",), dict(action="store_true")),
  596. (("--no-backup",), dict(action="store_true")))
  597. from hermes_state import DEFAULT_DB_PATH
  598. from hermes_state_repair import _db_opens_cleanly, repair_state_db_schema
  599. db_path = DEFAULT_DB_PATH
  600. if not db_path.exists():
  601. print(f"No session database at {db_path} (nothing to repair).")
  602. return
  603. reason = _db_opens_cleanly(db_path)
  604. if reason is None:
  605. print(f"{db_path} opens cleanly; no repair needed.")
  606. return
  607. print(f"{db_path} does not open cleanly: {reason}")
  608. if ns.check_only:
  609. return 1 # _capture_output turns a non-zero status into a ConsoleCommandError carrying the printed reason
  610. report = repair_state_db_schema(db_path, backup=not ns.no_backup)
  611. if not report.get("repaired"):
  612. raise ConsoleCommandError(f"Repair failed: {report.get('error')}")
  613. if report.get("backup_path"):
  614. print(f"backup: {report['backup_path']}")
  615. print(f"strategy: {report.get('strategy')}")
  616. print("Repaired session database.")
  617. def _profile_status(_engine: HermesConsoleEngine, args: list[str]) -> str:
  618. _expect_no_args(args, "profile")
  619. return _dispatch(_CLI_FAMILIES["profile"][0], "profile", (), ())
  620. def _cron_list(_engine: HermesConsoleEngine, args: list[str]) -> str:
  621. ns = _parse("cron list", args, (("--all",), dict(action="store_true")))
  622. from hermes_cli.cron import cron_list
  623. return _capture_output(lambda: cron_list(show_all=ns.all))
  624. def _cron_job_action(args: list[str], usage: str, action: str, run) -> str:
  625. """Shared body for single-job cron commands: ``run(job_ref) -> job | None``."""
  626. if len(args) != 1:
  627. raise ConsoleCommandError(f"Usage: {usage}")
  628. from cron.jobs import AmbiguousJobReference
  629. try:
  630. job = run(args[0])
  631. except AmbiguousJobReference as exc:
  632. raise ConsoleCommandError(str(exc)) from exc
  633. if not job:
  634. raise ConsoleCommandError(f"Job not found: {args[0]}")
  635. return _format_job(job, action)
  636. def _cron_pause(_engine: HermesConsoleEngine, args: list[str]) -> str:
  637. from cron.jobs import pause_job
  638. return _cron_job_action(
  639. args, "cron pause <job>", "Paused",
  640. lambda ref: pause_job(ref, reason="paused from hermes console"))
  641. def _cron_resume(_engine: HermesConsoleEngine, args: list[str]) -> str:
  642. ns = _parse("cron resume", args, "job", "--at", (("--run-now",), dict(action="store_true")))
  643. if ns.at and ns.run_now:
  644. raise ConsoleCommandError("Use exactly one of --at or --run-now.")
  645. from cron.jobs import AmbiguousJobReference, _hermes_now, rearm_oneshot, resume_job
  646. try:
  647. job = (
  648. rearm_oneshot(ns.job, _hermes_now().isoformat() if ns.run_now else ns.at)
  649. if ns.at or ns.run_now else resume_job(ns.job))
  650. except (AmbiguousJobReference, ValueError) as exc:
  651. raise ConsoleCommandError(str(exc)) from exc
  652. if not job:
  653. raise ConsoleCommandError(f"Job not found: {ns.job}")
  654. return _format_job(job, "Resumed")
  655. def _cron_run(_engine: HermesConsoleEngine, args: list[str]) -> str:
  656. from cron.jobs import trigger_job
  657. return _cron_job_action(args, "cron run <job>", "Triggered", trigger_job)
  658. # (path, usage, summary, handler, confirmation prompt) — a non-empty prompt marks it mutating.
  659. _BUILTIN_COMMANDS = (
  660. (("status",), "status", "Show Hermes component status.", _status, ""),
  661. (("version",), "version", "Show Hermes version information.", _version, ""),
  662. (("doctor",), "doctor", "Run diagnostics without auto-fix.", _doctor, ""),
  663. (("logs",), "logs [name] [-n N]", "Show recent Hermes logs.", _logs, ""),
  664. (("sessions", "list"), "sessions list [--limit N]", "List recent sessions.", _sessions_list,
  665. ""),
  666. (("sessions", "stats"), "sessions stats", "Show session store statistics.", _sessions_stats,
  667. ""),
  668. (("config", "show"), "config show", "Show current configuration.", _config_show, ""),
  669. (("config", "path"), "config path", "Print config.yaml path.", _config_path, ""),
  670. (("cron", "list"), "cron list [--all]", "List scheduled jobs.", _cron_list, ""),
  671. (("cron", "status"), "cron status", "Show cron scheduler status.", _cron_status, ""),
  672. (("profile",), "profile", "Show active profile status.", _profile_status, ""),
  673. (("config", "set"), "config set <key> <value>", "Set a configuration value.", _config_set,
  674. "Update Hermes configuration?"),
  675. (("cron", "pause"), "cron pause <job>", "Pause a scheduled job.", _cron_pause,
  676. "Pause this cron job?"),
  677. (("cron", "resume"), "cron resume <job>", "Resume a paused cron job.", _cron_resume,
  678. "Resume this cron job?"),
  679. (("cron", "run"), "cron run <job>", "Run a job on the next scheduler tick.", _cron_run,
  680. "Trigger this cron job?"),
  681. (("config", "migrate"), "config migrate", "Update config with new options.", _config_migrate,
  682. "Update Hermes configuration with missing defaults?"),
  683. (("sessions", "export"), "sessions export <output> [--source SOURCE] [--session-id ID]",
  684. "Export sessions to JSONL.", _sessions_export, "Export session data?"),
  685. (("sessions", "rename"), "sessions rename <session> <title>", "Rename a session.",
  686. _sessions_rename, "Rename this session?"),
  687. (("sessions", "optimize"), "sessions optimize [--force]", "Optimize the session store.",
  688. _sessions_optimize, "Optimize the session database?"),
  689. (("sessions", "repair"), "sessions repair [--check-only] [--no-backup]",
  690. "Repair a malformed session database schema.", _sessions_repair,
  691. "Repair the session database?"))
  692. def run_console_repl(
  693. *, stdin=None, stdout=None, stderr=None, interactive: bool | None = None) -> int:
  694. """Run the local ``hermes console`` REPL."""
  695. stdin, stdout, stderr = stdin or sys.stdin, stdout or sys.stdout, stderr or sys.stderr
  696. if interactive is None:
  697. interactive = bool(getattr(stdin, "isatty", lambda: False)())
  698. engine = HermesConsoleEngine()
  699. def say(text: str, **kw) -> None:
  700. if interactive:
  701. print(text, file=stdout, **kw)
  702. say("Hermes Console. Type `help` for commands, `exit` to quit.")
  703. while True:
  704. say("hermes> ", end="", flush=True)
  705. line = stdin.readline()
  706. if line == "":
  707. say("")
  708. return 0
  709. result = engine.execute(line)
  710. if result.status == "confirm_required":
  711. if not interactive:
  712. print(f"Confirmation required: {result.confirmation_message}", file=stderr)
  713. return 1
  714. print(f"{result.confirmation_message} [y/N] ", end="", file=stdout, flush=True)
  715. if stdin.readline().strip().lower() not in {"y", "yes"}:
  716. print("Cancelled.", file=stdout)
  717. continue
  718. result = engine.execute(result.command, confirmed=True)
  719. if result.output:
  720. print(result.output, file=stderr if result.status == "error" else stdout)
  721. if result.status == "exit":
  722. return 0