cli_info_mixin.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. """Informational views and reload flows for the interactive CLI: banner, help, tools, usage,
  2. insights, MCP/skills reload, bang shell.
  3. Mixin split out of ``cli.py``; bound onto ``HermesCLI`` via the MRO. cli.py-internal symbols are
  4. imported LAZILY inside each method — the mixin never imports ``cli`` at module load time (cycle).
  5. """
  6. from __future__ import annotations
  7. import concurrent.futures
  8. import logging
  9. import os
  10. import shutil
  11. import threading
  12. import time
  13. from typing import Any, NamedTuple
  14. from agent.i18n import t
  15. from hermes_constants import is_termux as _is_termux_environment
  16. from rich.markup import escape as _escape
  17. from utils import base_url_hostname
  18. from hermes_cli.cli_modal_mixin import _gated_confirm
  19. from hermes_cli.colors import Colors as _Colors
  20. CONFIG_WATCH_INTERVAL = 5.0 # seconds between config.yaml stat() calls
  21. _TOOL_PROGRESS_CYCLE = ["off", "new", "all", "verbose"]
  22. # Raw ANSI (not Rich markup): _cprint routes through prompt_toolkit's renderer, while Rich markup
  23. # written to stdout gets mangled by patch_stdout's StdoutProxy ('?[33mTool progress: NEW?[0m', #2262).
  24. _TOOL_PROGRESS_STYLES = {
  25. "off": _Colors.DIM,
  26. "new": _Colors.YELLOW,
  27. "all": _Colors.GREEN,
  28. "verbose": f"{_Colors.BOLD}{_Colors.GREEN}",
  29. }
  30. def _tool_progress_label(mode: str) -> str:
  31. """Localized ``Tool progress: MODE — detail`` line for /verbose ("" for an unknown mode)."""
  32. style = _TOOL_PROGRESS_STYLES.get(mode)
  33. if style is None:
  34. return ""
  35. return f"{style}{t(f'cli.verbose.label_{mode}')}{_Colors.RESET} — {t(f'cli.verbose.detail_{mode}')}"
  36. def _reload_mcp_choices() -> list[tuple[str, str, str]]:
  37. """(id, label, hint) rows for the /reload-mcp confirm modal, in the active language."""
  38. return [
  39. ("once", t("cli.reload_mcp.choice_once"), t("cli.reload_mcp.choice_once_hint")),
  40. ("always", t("cli.reload_mcp.choice_always"), t("cli.reload_mcp.choice_always_hint")),
  41. ("cancel", t("cli.reload_mcp.choice_cancel"), t("cli.reload_mcp.choice_cancel_hint"))]
  42. # /help section headers: the category ids are load-bearing for gateway help and the registry, so
  43. # they stay identifiers and are only localized at render time.
  44. _HELP_SECTION_KEYS = {
  45. "Session": "session",
  46. "Configuration": "configuration",
  47. "Tools & Skills": "tools_skills",
  48. "Info": "info",
  49. "Exit": "exit",
  50. "Context": "context",
  51. "Background & Automation": "background_automation",
  52. }
  53. def _help_section_title(category: str) -> str:
  54. slug = _HELP_SECTION_KEYS.get(category)
  55. return t(f"cli.help.section_{slug}") if slug else category
  56. def _ascii_box(title: str, width: int) -> None:
  57. """Print the kawaii ``+---+ | title | +---+`` header used by /tools and /toolsets."""
  58. pad = width - len(title)
  59. print("+" + "-" * width + "+")
  60. print("|" + " " * (pad // 2) + title + " " * (pad - pad // 2) + "|")
  61. print("+" + "-" * width + "+")
  62. def _toolset_map(tools, availability, get_toolset_for_tool) -> dict:
  63. """tool name → toolset id, including tools of unavailable toolsets (banner snapshot)."""
  64. tmap = {tool["function"]["name"]: get_toolset_for_tool(tool["function"]["name"]) for tool in tools}
  65. for item in availability.get("unavailable_toolsets", []):
  66. for name in item.get("tools", []):
  67. tmap.setdefault(name, item.get("id", item.get("name", "")))
  68. return tmap
  69. def _skill_line(item: dict) -> str:
  70. nm = item.get("name", "")
  71. desc = item.get("description", "")
  72. return f" - {nm}: {desc}" if desc else f" - {nm}"
  73. class BannerPlan(NamedTuple):
  74. """What the welcome banner draws, shared by startup (``show_banner``) and ``/clear`` so the two
  75. cannot drift apart."""
  76. store: Any # the gateway session store, or None off the gateway
  77. inventory: dict | None # a gateway session's tools: its snapshot, never this process's registry
  78. ctx_len: int | None
  79. banner_kw: dict | None # build_welcome_banner's common kwargs; None → the compact banner
  80. def banner_plan(cli, console) -> BannerPlan:
  81. """The welcome banner's plan. The compact banner (``banner_kw`` None) is for a narrow terminal,
  82. ``display.compact``, or a gateway session with no snapshot yet."""
  83. from agent.context_pin import agent_context_marker
  84. from hermes_cli.gateway_tools_notify import gateway_store
  85. store = gateway_store(cli)
  86. inventory = store.banner_inventory() if store is not None else None
  87. agent = getattr(cli, "agent", None)
  88. compressor = getattr(agent, "context_compressor", None)
  89. ctx_len = compressor.context_length if compressor is not None else None
  90. if cli.compact or shutil.get_terminal_size().columns < 80 or (store is not None and inventory is None):
  91. return BannerPlan(store, inventory, ctx_len, None)
  92. return BannerPlan(store, inventory, ctx_len, dict(
  93. console=console, model=cli.model, cwd=os.getenv("TERMINAL_CWD", os.getcwd()),
  94. enabled_toolsets=cli.enabled_toolsets, session_id=cli.session_id, context_length=ctx_len,
  95. provider=cli.provider, context_marker=agent_context_marker(agent) if agent is not None else ""))
  96. class CLIInfoMixin:
  97. """Informational views and reload flows for the interactive CLI: banner, help, tools, usage,
  98. insights, MCP/skills reload, bang shell."""
  99. def _show_gateway_banner(self, build_welcome_banner, inventory, banner_kw):
  100. """Main's banner from the gateway session's snapshot (the TUI banner's data): the CLI
  101. enumerates nothing. The canonical id shows as main's 8-character label (display only)."""
  102. from hermes_cli.gateway_session_store import session_label
  103. build_welcome_banner(
  104. tools=inventory["tools"], get_toolset_for_tool=inventory["get_toolset_for_tool"],
  105. availability=inventory["availability"], skills_by_category=inventory["skills_by_category"],
  106. **{**banner_kw, "cwd": inventory["cwd"] or banner_kw["cwd"],
  107. "context_length": inventory["context_length"] or banner_kw["context_length"],
  108. "session_id": session_label(self.session_id)})
  109. def _print_gateway_tool_warnings(self, lines):
  110. """Main's ``_show_tool_availability_warnings`` lines, computed by the gateway that resolved
  111. this session's tools."""
  112. if lines:
  113. self._console_print()
  114. for line in lines:
  115. self._console_print(line)
  116. def show_banner(self):
  117. """Display the welcome banner in Claude Code style."""
  118. from cli import _build_compact_banner, get_tool_definitions, logger
  119. from hermes_cli.banner import build_welcome_banner
  120. self.console.clear()
  121. store, gateway_inventory, ctx_len, banner_kw = banner_plan(self, self.console)
  122. on_gateway = store is not None # its tools come from the gateway: never enumerated here
  123. # Auto-compact for narrow terminals — the full banner needs ~80 columns to avoid wrapping.
  124. if banner_kw is None:
  125. self._console_print(_build_compact_banner())
  126. self._show_status()
  127. else:
  128. # Warm-launch fast path: replay last launch's tool panel when the snapshot fingerprint
  129. # (config.yaml + .env + checkout rev + toolsets) is unchanged, skipping the ~0.5-0.9s
  130. # cold get_tool_definitions walk. The agent's REAL tool list is still computed fresh at
  131. # first message; a background refresh re-verifies the snapshot so drift self-heals.
  132. from hermes_cli.banner import (
  133. compute_toolset_availability, load_banner_snapshot, save_banner_snapshot)
  134. try:
  135. snapshot = load_banner_snapshot(self.enabled_toolsets)
  136. except Exception:
  137. snapshot = None
  138. if gateway_inventory is not None:
  139. self._show_gateway_banner(build_welcome_banner, gateway_inventory, banner_kw)
  140. elif snapshot is not None:
  141. self._defer_tool_warnings = True
  142. toolset_map = snapshot["toolset_map"]
  143. build_welcome_banner(
  144. tools=snapshot["tools"],
  145. get_toolset_for_tool=lambda name: toolset_map.get(name),
  146. availability=snapshot["availability"],
  147. skills_by_category=snapshot.get("skills_by_category"),
  148. **banner_kw)
  149. def _refresh_banner_snapshot() -> None:
  150. try:
  151. from model_tools import get_toolset_for_tool
  152. tools = get_tool_definitions(
  153. enabled_toolsets=self.enabled_toolsets,
  154. disabled_toolsets=self.disabled_toolsets, quiet_mode=True)
  155. availability = compute_toolset_availability(self.enabled_toolsets)
  156. tmap = _toolset_map(tools, availability, get_toolset_for_tool)
  157. save_banner_snapshot(tools, self.enabled_toolsets, availability, tmap)
  158. except Exception:
  159. logger.debug("banner snapshot refresh failed", exc_info=True)
  160. threading.Thread(
  161. target=_refresh_banner_snapshot, name="banner-snapshot-refresh", daemon=True,
  162. ).start()
  163. else:
  164. # Cold path: compute live, then persist the snapshot for the next launch.
  165. from model_tools import get_toolset_for_tool
  166. tools = get_tool_definitions(enabled_toolsets=self.enabled_toolsets,
  167. disabled_toolsets=self.disabled_toolsets, quiet_mode=True)
  168. availability = compute_toolset_availability(self.enabled_toolsets)
  169. build_welcome_banner(tools=tools, availability=availability, **banner_kw)
  170. try:
  171. tmap = _toolset_map(tools, availability, get_toolset_for_tool)
  172. save_banner_snapshot(tools, self.enabled_toolsets, availability, tmap)
  173. except Exception:
  174. logger.debug("banner snapshot save failed", exc_info=True)
  175. # Tool discovery is deferred on the Termux bare prompt path (warnings show once tools
  176. # init). On the snapshot fast path the check walks every check_fn (~180ms) — run it in
  177. # the background and let its output land above the prompt (patch_stdout-safe).
  178. if isinstance((gateway_inventory or {}).get("tool_availability_warnings"), list):
  179. self._print_gateway_tool_warnings(gateway_inventory["tool_availability_warnings"])
  180. elif not on_gateway and os.environ.get("HERMES_DEFER_AGENT_STARTUP") != "1":
  181. if getattr(self, "_defer_tool_warnings", False):
  182. threading.Thread(
  183. target=self._show_tool_availability_warnings,
  184. name="tool-availability-warnings",
  185. daemon=True).start()
  186. else:
  187. self._show_tool_availability_warnings()
  188. # Low context warning — tied to the runtime guard so guidance cannot drift.
  189. from agent.model_metadata import MINIMUM_CONTEXT_LENGTH, is_local_endpoint
  190. if ctx_len and ctx_len < MINIMUM_CONTEXT_LENGTH:
  191. self._console_print()
  192. self._console_print(f"[yellow]{t('cli.banner.context_too_low', tokens=f'{ctx_len:,}')}[/]")
  193. self._console_print(f"[dim] {t('cli.banner.context_minimum', tokens=f'{MINIMUM_CONTEXT_LENGTH:,}')}[/]")
  194. base_url = getattr(self, "base_url", "") or ""
  195. from urllib.parse import urlparse as _urlparse
  196. try:
  197. _port = _urlparse(base_url if "://" in base_url else f"//{base_url}").port
  198. except ValueError:
  199. _port = None
  200. if _port == 11434 or "ollama" in base_url_hostname(base_url):
  201. fix = t("cli.banner.fix_ollama", tokens=str(MINIMUM_CONTEXT_LENGTH))
  202. elif _port == 1234:
  203. fix = t("cli.banner.fix_lm_studio")
  204. elif is_local_endpoint(base_url): # llama.cpp / vLLM / any local server — not Ollama
  205. fix = t("cli.banner.fix_local_server",
  206. tokens_k=str(MINIMUM_CONTEXT_LENGTH // 1000), tokens=str(MINIMUM_CONTEXT_LENGTH))
  207. else:
  208. fix = t("cli.banner.fix_config")
  209. self._console_print(f"[dim] {fix}[/]")
  210. from hermes_cli.model_switch import is_nous_hermes_non_agentic
  211. if is_nous_hermes_non_agentic(getattr(self, "model", "") or ""):
  212. self._console_print()
  213. self._console_print(f"[bold yellow]{t('cli.banner.hermes_models_not_agentic')}[/]")
  214. self._console_print(f"[dim] {t('cli.banner.hermes_models_lack_tools')}[/]")
  215. self._console_print(f"[dim] {t('cli.banner.hermes_models_switch_hint')}[/]")
  216. # Project-local skills one-liner: trusted → count; untrusted-with-skills → point at
  217. # `hermes skills trust`. Never raises.
  218. try:
  219. from agent.skill_utils import (
  220. get_project_skills_dirs, get_untrusted_project_skills_root, iter_skill_index_files)
  221. _proj_dirs = get_project_skills_dirs()
  222. if _proj_dirs:
  223. _n = sum(sum(1 for _ in iter_skill_index_files(d, "SKILL.md")) for d in _proj_dirs)
  224. if _n:
  225. self._console_print(f"[dim]{t('cli.banner.project_skills_loaded', count=str(_n))}[/]")
  226. else:
  227. _untrusted = get_untrusted_project_skills_root()
  228. if _untrusted is not None:
  229. _root, _n = _untrusted
  230. self._console_print(
  231. f"[yellow]{t('cli.banner.project_skills_untrusted', count=str(_n), root=str(_root))}[/]")
  232. except Exception:
  233. logger.debug("project skills banner notice failed", exc_info=True)
  234. self._console_print()
  235. def _fast_command_available(self) -> bool:
  236. try:
  237. from hermes_cli.models import model_supports_fast_mode
  238. except Exception:
  239. return False
  240. agent = getattr(self, "agent", None)
  241. return model_supports_fast_mode(getattr(agent, "model", None) or getattr(self, "model", None))
  242. def _command_available(self, slash_command: str) -> bool:
  243. if slash_command == "/fast":
  244. return self._fast_command_available()
  245. return True
  246. def show_help(self, arg: str = ""):
  247. """Display help. Bare /help shows categorized core commands with the skill list collapsed
  248. to one line; /help skills lists all skill commands; /help <query> filters by substring."""
  249. from cli import (
  250. ChatConsole, _BOLD, _DIM, _RST, _accent_hex, _cprint, _session_skill_commands,
  251. _termux_example_image_path, get_skill_bundles)
  252. from hermes_cli.commands import COMMAND_REGISTRY, HELP_SESSION_SUBGROUPS
  253. arg = (arg or "").strip()
  254. skill_commands = _session_skill_commands(self)
  255. def _row(cmd: str, desc: str, width: int = 15) -> None:
  256. ChatConsole().print(
  257. f" [bold {_accent_hex()}]{cmd:<{width}}[/] [dim]-[/] {_escape(desc)}")
  258. # /help skills — the full list, kept out of the default view so core commands don't
  259. # scroll off screen.
  260. if arg.lower() in ("skills", "skill"):
  261. from hermes_cli import gateway_plugin_commands
  262. if skill_commands:
  263. _cprint(f"\n ⚡ {_BOLD}{t('cli.help.skill_commands')}{_RST} "
  264. f"({t('cli.help.n_installed', count=str(len(skill_commands)))}):")
  265. for cmd, info in sorted(skill_commands.items()):
  266. _row(cmd, info['description'], 22)
  267. else:
  268. _cprint(f"\n {t('cli.help.no_skill_commands')}")
  269. # Skills whose name is a built-in command never get a /<name> (agent.skill_commands guard).
  270. for note in gateway_plugin_commands.skill_notes(self):
  271. _cprint(f" {_DIM}⚠ {note}{_RST}")
  272. _cprint("")
  273. return
  274. query = arg.lower() if arg else ""
  275. default_header = t("cli.help.header")
  276. try:
  277. from hermes_cli.skin_engine import get_active_help_header
  278. header = get_active_help_header(default_header)
  279. except Exception:
  280. header = default_header
  281. header = ((header or "").strip() or default_header)[:55]
  282. _cprint(f"\n{_BOLD}+{'-' * 55}+{_RST}")
  283. _cprint(f"{_BOLD}|{header:^55}|{_RST}")
  284. _cprint(f"{_BOLD}+{'-' * 55}+{_RST}")
  285. def _section(title: str, rows) -> None:
  286. """Print available/matching rows under a `── title ──` header (omitted if empty)."""
  287. printed_header = False
  288. for cmd, desc in rows:
  289. if not self._command_available(cmd):
  290. continue
  291. if query and query not in cmd.lower() and query not in desc.lower():
  292. continue
  293. if not printed_header:
  294. _cprint(f"\n {_BOLD}── {_help_section_title(title)} ──{_RST}")
  295. printed_header = True
  296. _row(cmd, desc)
  297. # Rows come straight from the registry so descriptions resolve through the localized
  298. # ``CommandDef.describe()`` accessor (names/aliases stay identifiers).
  299. by_category: dict[str, list[tuple[str, str]]] = {}
  300. for cmd_def in COMMAND_REGISTRY:
  301. if cmd_def.gateway_only:
  302. continue
  303. desc = cmd_def.describe()
  304. rows = by_category.setdefault(cmd_def.category, [])
  305. rows.append((f"/{cmd_def.name}", t("cli.help.usage_suffix", description=desc, command=cmd_def.name,
  306. args=cmd_def.args_hint) if cmd_def.args_hint else desc))
  307. for alias in cmd_def.aliases:
  308. rows.append((f"/{alias}", t("cli.help.alias_suffix", description=desc, command=cmd_def.name)))
  309. for category, commands in by_category.items():
  310. if category != "Session":
  311. _section(category, commands)
  312. continue
  313. # The oversized Session category renders as sub-groups
  314. # (Session / Context / Background & Automation).
  315. sub_of = {f"/{n}": sub for sub, names in HELP_SESSION_SUBGROUPS.items() for n in names}
  316. buckets: dict[str, list[tuple[str, str]]] = {"Session": []}
  317. for _sub in HELP_SESSION_SUBGROUPS:
  318. buckets[_sub] = []
  319. for cmd, desc in commands:
  320. buckets[sub_of.get(cmd, "Session")].append((cmd, desc))
  321. for _sub in ("Session", *HELP_SESSION_SUBGROUPS.keys()):
  322. _section(_sub, buckets.get(_sub) or [])
  323. # Skill commands collapse to a one-line pointer by default so 60+ entries don't bury the
  324. # core reference; filter mode includes matching skill commands inline.
  325. if query:
  326. matched_skills = [
  327. (cmd, info) for cmd, info in sorted(skill_commands.items())
  328. if query in cmd.lower() or query in (info.get("description", "").lower())]
  329. if matched_skills:
  330. _cprint(f"\n ⚡ {_BOLD}{t('cli.help.skill_commands')}{_RST} "
  331. f"({t('cli.help.matching_query', query=arg)}):")
  332. for cmd, info in matched_skills:
  333. _row(cmd, info['description'], 22)
  334. elif skill_commands:
  335. _cprint(
  336. f"\n ⚡ {_BOLD}{t('cli.help.skill_commands')}{_RST}: "
  337. f"{t('cli.help.n_installed', count=str(len(skill_commands)))} "
  338. f"— {_DIM}/help skills{_RST} {t('cli.help.to_list_them')}")
  339. _bundles_now = get_skill_bundles()
  340. if _bundles_now and not query:
  341. _cprint(f"\n ▣ {_BOLD}{t('cli.help.skill_bundles')}{_RST} "
  342. f"({t('cli.help.n_installed', count=str(len(_bundles_now)))}):")
  343. for cmd, info in sorted(_bundles_now.items()):
  344. skill_count = len(info.get("skills", []))
  345. desc = info.get("description") or t("cli.help.load_n_skills", count=str(skill_count))
  346. ChatConsole().print(
  347. f" [bold {_accent_hex()}]{cmd:<22}[/] [dim]-[/] "
  348. f"{_escape(desc)} [dim]({t('cli.help.n_skills', count=str(skill_count))})[/]")
  349. quick_commands = self.config.get("quick_commands", {})
  350. if quick_commands and not query:
  351. _cprint(f"\n ⚡ {_BOLD}{t('cli.help.quick_commands')}{_RST} "
  352. f"({t('cli.help.n_configured', count=str(len(quick_commands)))}):")
  353. for name, qcmd in sorted(quick_commands.items()):
  354. _row('/' + name, qcmd.get("description", qcmd.get("type", "")), 22)
  355. if query:
  356. _cprint(f"\n {_DIM}{t('cli.help.filtered_by', query=arg)}{_RST}\n")
  357. return
  358. _cprint(f"\n {_DIM}{t('cli.help.tip_line')}{_RST}")
  359. _cprint(f" {_DIM}{t('cli.help.multiline_hint')}{_RST}")
  360. _cprint(f" {_DIM}{t('cli.help.draft_editor_hint')}{_RST}")
  361. if _is_termux_environment():
  362. _cprint(f" {_DIM}{t('cli.help.attach_image_hint', path=_termux_example_image_path())}{_RST}\n")
  363. else:
  364. _cprint(f" {_DIM}{t('cli.help.paste_image_hint')}{_RST}\n")
  365. def show_tools(self):
  366. """Display available tools with kawaii ASCII art."""
  367. from hermes_cli.gateway_tools import session_tools
  368. remote = session_tools() # the gateway session's catalog (its MCP + plugin tools included)
  369. if remote is not None:
  370. tools, get_toolset_for_tool = remote
  371. else:
  372. from cli import get_tool_definitions
  373. from model_tools import get_toolset_for_tool
  374. # Pre-assembly list: /tools is a discovery surface, so it must show the full catalog
  375. # including tools deferred behind the tool_search bridge (users verify MCP installs here).
  376. tools = get_tool_definitions(enabled_toolsets=self.enabled_toolsets,
  377. disabled_toolsets=self.disabled_toolsets, quiet_mode=True,
  378. skip_tool_search_assembly=True)
  379. if not tools:
  380. print(t("cli.tools.none_available"))
  381. return
  382. print()
  383. _ascii_box(t("cli.tools.header"), 78)
  384. print()
  385. toolsets: dict[str, list] = {}
  386. for tool in sorted(tools, key=lambda item: item["function"]["name"]):
  387. name = tool["function"]["name"]
  388. toolset = get_toolset_for_tool(name) or "unknown"
  389. desc = tool["function"].get("description", "").split("\n")[0]
  390. # First sentence: split on ". " (period+space) so "e.g." / "v2.0" stay intact.
  391. if ". " in desc:
  392. desc = desc[:desc.index(". ") + 1]
  393. toolsets.setdefault(toolset, []).append((name, desc))
  394. for toolset in sorted(toolsets.keys()):
  395. print(f" [{toolset}]")
  396. for name, desc in toolsets[toolset]:
  397. print(f" * {name:<20} - {desc}")
  398. print()
  399. print(f" {t('cli.tools.total', count=str(len(tools)))}")
  400. print()
  401. def show_toolsets(self):
  402. """Display available toolsets with kawaii ASCII art."""
  403. from hermes_cli.cli_info_lines import toolsets_lines
  404. print("\n".join(toolsets_lines(self.enabled_toolsets)))
  405. def _handle_whoami_command(self):
  406. """Display slash-command access for the local CLI surface."""
  407. import getpass
  408. try:
  409. user_name = getpass.getuser() or "?"
  410. except Exception:
  411. user_name = "?"
  412. print()
  413. print(f" {t('cli.whoami.you_label'):<15} {t('cli.whoami.you_value')}")
  414. print(f" {t('cli.whoami.user_label'):<15} {user_name}")
  415. print(f" {t('cli.whoami.tier_label'):<15} {t('cli.whoami.tier_value')}")
  416. print(f" {t('cli.whoami.slash_commands_label'):<15} {t('cli.whoami.slash_commands_value')}")
  417. print()
  418. def _busy_inline_command(self, text: str, has_images: bool, names: tuple) -> bool:
  419. """True when ``text`` is a slash command in ``names`` typed while the agent is running.
  420. Such commands MUST bypass the normal ``_pending_input`` → ``process_loop`` path: the loop
  421. is blocked inside ``self.chat()`` for the whole run, so by the time the queued command is
  422. pulled, ``_agent_running`` has flipped back to False and it would be delivered as a
  423. next-turn message. Dispatching inline on the UI thread acts mid-run (``agent.steer()`` is
  424. thread-safe; ``/bg`` / ``/btw`` start their side session without touching the foreground turn).
  425. """
  426. from cli import _looks_like_slash_command
  427. if not text or has_images or not _looks_like_slash_command(text):
  428. return False
  429. if not getattr(self, "_agent_running", False):
  430. return False
  431. try:
  432. from hermes_cli.commands import resolve_command
  433. cmd = resolve_command(text.split(None, 1)[0].lower().lstrip('/'))
  434. return bool(cmd and cmd.name in names)
  435. except Exception:
  436. return False
  437. def _should_handle_steer_command_inline(self, text: str, has_images: bool = False) -> bool:
  438. """Return True when /steer or /queue should be dispatched immediately while the agent is
  439. running. Queued raw, ``/queue <prompt>`` only re-enqueued itself after the turn and
  440. ``/queue list|rm|edit`` could not inspect the queue until it had already drained."""
  441. return self._busy_inline_command(text, has_images, ("steer", "queue"))
  442. def _should_handle_background_command_inline(
  443. self, text: str, has_images: bool = False) -> bool:
  444. """Return True when /bg or /btw should be dispatched while the agent runs (their
  445. ``CommandDef`` entries declare ``busy_policy="dispatch"``; the classic CLI honours it here)."""
  446. return self._busy_inline_command(text, has_images, ("bg", "btw"))
  447. def _should_handle_stop_command_inline(self, text: str, has_images: bool = False) -> bool:
  448. """Return True when /stop should be dispatched while the agent runs: its ``CommandDef`` declares
  449. ``busy_policy="interrupt_then_dispatch"``, and queued it would only run after the turn it stops."""
  450. return self._busy_inline_command(text, has_images, ("stop",))
  451. def handle_bang_shell(self, text: str) -> bool:
  452. """Run a ``!<command>`` submission. Returns True when it was handled.
  453. Dispatched from the input loop BEFORE slash routing and before anything is queued for the
  454. agent, so a bang command never becomes a turn: nothing touches ``conversation_history``,
  455. zero tokens, role alternation / prompt caching untouched by construction
  456. (tests/hermes_cli/test_bang_shell_mode.py). Returns False when the text is not a bang command or
  457. bang mode is disabled for this context (gateway/cron), so the caller routes normally.
  458. """
  459. from cli import _rich_text_from_ansi
  460. from hermes_cli.bang_shell import (
  461. USAGE_HINT, bang_shell_enabled, check_bang_approval, is_bang_command,
  462. parse_bang_command, resolve_bang_cwd, run_bang_command)
  463. if not is_bang_command(text):
  464. return False
  465. if not bang_shell_enabled():
  466. # Gateway / cron / API: no composer, no human at a keyboard, and those users already
  467. # have shells — route normally rather than becoming remote execution.
  468. return False
  469. command = parse_bang_command(text)
  470. if not command: # bare `!` — show what the feature does
  471. self._console_print(f"[dim]{USAGE_HINT}[/]")
  472. return True
  473. approval = check_bang_approval(command)
  474. if not approval.get("approved"):
  475. message = approval.get("message") or t(
  476. "cli.shell.command_denied",
  477. reason=approval.get("description") or t("cli.shell.flagged_as_dangerous"))
  478. self._console_print(f"[bold red]{_escape(str(message))}[/]")
  479. return True
  480. exit_code = run_bang_command(
  481. command,
  482. cwd=resolve_bang_cwd(getattr(self, "session_id", None)),
  483. writer=lambda line: self._console_print(_rich_text_from_ansi(line)))
  484. if exit_code:
  485. self._console_print(f"[dim]{t('cli.shell.exited', code=str(exit_code))}[/]")
  486. return True
  487. def _show_gateway_status(self):
  488. """Show status of the gateway and connected messaging platforms."""
  489. from hermes_cli.cli_info_lines import platforms_lines
  490. print("\n".join(platforms_lines()))
  491. def _print_random_tip(self) -> None:
  492. """Best-effort discovery tip (startup + /clear); never raises."""
  493. try:
  494. from hermes_cli.tips import get_random_tip
  495. _tip = get_random_tip()
  496. try:
  497. from hermes_cli.skin_engine import get_active_skin
  498. _tip_color = get_active_skin().get_color("banner_dim", "#B8860B")
  499. except Exception:
  500. _tip_color = "#B8860B"
  501. self._console_print(f"[dim {_tip_color}]{t('cli.tip_line', tip=_tip)}[/]")
  502. except Exception:
  503. pass
  504. def _toggle_verbose(self):
  505. """Cycle tool progress mode: off → new → all → verbose → off.
  506. Tool-progress display is INDEPENDENT of global DEBUG logging: this never changes
  507. ``self.verbose`` or the agent's ``verbose_logging`` / ``quiet_mode`` (those belong to
  508. ``-v`` and ``/verbose-logging``).
  509. """
  510. from cli import _cprint, save_config_value
  511. try:
  512. idx = _TOOL_PROGRESS_CYCLE.index(self.tool_progress_mode)
  513. except ValueError:
  514. idx = 2 # default to "all"
  515. self.tool_progress_mode = _TOOL_PROGRESS_CYCLE[(idx + 1) % len(_TOOL_PROGRESS_CYCLE)]
  516. # /verbose is the explicit tool-progress control, so cycling it takes ownership of the
  517. # mode back from focus view (else a "focus" badge + hidden-line counts would show while
  518. # tool lines visibly print). Display-only state change.
  519. if getattr(self, "_focus_view_enabled", False):
  520. self._focus_view_enabled = False
  521. self._focus_saved_tool_progress = None
  522. self._focus_hidden_lines = 0
  523. self._focus_last_counted_tool = None
  524. try:
  525. from hermes_cli.focus_view import FOCUS_CONFIG_KEY
  526. save_config_value(FOCUS_CONFIG_KEY, False)
  527. except Exception:
  528. pass
  529. if self.agent:
  530. self.agent.reasoning_callback = self._current_reasoning_callback()
  531. # Sync the live agent so tool_executor rendering reflects the new mode this turn.
  532. self.agent.tool_progress_mode = self.tool_progress_mode
  533. _cprint(_tool_progress_label(self.tool_progress_mode))
  534. def _handle_usage_command(self, cmd_original: str):
  535. """Dispatch `/usage [reset [--force]]`: bare `/usage` is the classic display; `reset`
  536. redeems one banked Codex rate-limit reset credit (refuses unless exhausted or --force)."""
  537. parts = cmd_original.split()
  538. args = [p.lower() for p in parts[1:]]
  539. if args and args[0] == "reset":
  540. self._usage_reset(force="--force" in args[1:])
  541. return
  542. if args:
  543. print(f" {t('cli.usage.unknown_subcommand', args=' '.join(parts[1:]))}")
  544. return
  545. self._show_usage()
  546. def _agent_or_self(self, name: str):
  547. """Provider-ish attribute from the live agent, falling back to the CLI's own value."""
  548. return (getattr(self.agent, name, None) if self.agent else None) or getattr(self, name, None)
  549. def _usage_reset(self, force: bool = False):
  550. """`/usage reset [--force]` — redeem one banked Codex reset credit."""
  551. if str(self._agent_or_self("provider") or "").strip().lower() != "openai-codex":
  552. print(f" {t('cli.usage.reset_wrong_provider')}")
  553. print(f" {t('cli.usage.reset_switch_hint')}")
  554. return
  555. from agent.account_usage import redeem_codex_reset_credit
  556. print(f" {t('cli.usage.checking_reset_credits')}")
  557. with concurrent.futures.ThreadPoolExecutor(max_workers=1) as _pool:
  558. try:
  559. result = _pool.submit(
  560. redeem_codex_reset_credit, base_url=self._agent_or_self("base_url"),
  561. api_key=self._agent_or_self("api_key"), force=force,
  562. ).result(timeout=45.0)
  563. except concurrent.futures.TimeoutError:
  564. print(f" {t('cli.usage.codex_timeout')}")
  565. return
  566. print(f" {result.message}")
  567. def _show_context_breakdown(self, cmd_original: str = ""):
  568. """`/context [all]` — 5×20 glyph grid (cell ≈ 1% of the window) plus an estimated
  569. per-category table; `all` appends per-skill / per-toolset costs. Read-only: same chars/4
  570. engine as the desktop popover (agent.context_breakdown) — no provider calls, no cache impact."""
  571. from hermes_cli.gateway_side import connection_for
  572. if (connection := connection_for(self)) is not None:
  573. return self._show_gateway_context_breakdown(connection)
  574. if not self.agent:
  575. print(f" {t('cli.shared.no_active_agent')}")
  576. return
  577. args = cmd_original.split(maxsplit=1)[1].strip().lower() if " " in cmd_original else ""
  578. expanded = args in {"all", "full", "details"}
  579. from agent.context_breakdown import (
  580. compute_context_details, compute_session_context_breakdown,
  581. render_context_breakdown_lines)
  582. try:
  583. payload = compute_session_context_breakdown(self.agent, self.conversation_history)
  584. except Exception as e:
  585. print(f" {t('cli.context.compute_failed', error=str(e))}")
  586. return
  587. details = None
  588. if expanded:
  589. try:
  590. details = compute_context_details(self.agent)
  591. except Exception:
  592. details = {"skills": [], "toolsets": []}
  593. from agent.context_file_sources import context_file_sources_for_agent, render_context_file_lines
  594. try:
  595. file_lines = render_context_file_lines(context_file_sources_for_agent(self.agent))
  596. except Exception:
  597. file_lines = []
  598. print()
  599. print(f" {t('cli.context.header', model=payload.get('model') or self.model)}")
  600. print()
  601. for line in render_context_breakdown_lines(payload, details=details, grid=True) + ([""] + file_lines if file_lines else []):
  602. print(f" {line}")
  603. print()
  604. def _show_gateway_context_breakdown(self, connection):
  605. """Main's ``/context`` grid and table over the gateway agent's own breakdown
  606. (``session.context_breakdown``): the session's prompt, tools and transcript live there."""
  607. from agent.context_breakdown import render_context_breakdown_lines
  608. from agent.context_file_sources import render_context_file_lines
  609. from hermes_cli.gateway_client import GatewayClientError
  610. try:
  611. payload = connection.call("session.context_breakdown", session_id=self.session_id)
  612. except GatewayClientError as e:
  613. print(f" {t('cli.context.compute_failed', error=str(e))}")
  614. return
  615. if not payload.get("categories"):
  616. print(f" {t('cli.shared.no_active_agent')}")
  617. return
  618. file_lines = render_context_file_lines(payload.get("context_files") or [])
  619. print()
  620. print(f" {t('cli.context.header', model=payload.get('model') or self.model)}")
  621. print()
  622. for line in render_context_breakdown_lines(payload, grid=True) + (["", *file_lines] if file_lines else []):
  623. print(f" {line}")
  624. print()
  625. def _show_usage(self):
  626. """Rate limits + session token usage (when a live agent exists) + Nous credits.
  627. The Nous credits block is agent-independent (portal fetch), so it runs even with no live
  628. agent — the TUI's /usage slash-worker resumes the session WITHOUT building an agent.
  629. """
  630. from cli import datetime, format_duration_compact
  631. def _credits_or(fallback: str) -> None:
  632. # Account limits (e.g. Codex subscription windows) need only the configured provider
  633. # plus on-disk credentials, so they render without a live agent too (#42904).
  634. shown = self._print_account_limits()
  635. if self._print_nous_credits_block():
  636. self._print_usage_cta()
  637. elif not shown:
  638. print(fallback)
  639. if not self.agent:
  640. _credits_or(t("cli.shared.no_active_agent"))
  641. return
  642. agent = self.agent
  643. calls = agent.session_api_calls
  644. if calls == 0:
  645. _credits_or(t("cli.usage.no_api_calls"))
  646. return
  647. rl_state = agent.get_rate_limit_state()
  648. if rl_state and rl_state.has_data:
  649. from agent.rate_limit_tracker import format_rate_limit_display
  650. print()
  651. print(format_rate_limit_display(rl_state))
  652. print()
  653. input_tokens = getattr(agent, "session_input_tokens", 0) or 0
  654. output_tokens = getattr(agent, "session_output_tokens", 0) or 0
  655. reasoning_tokens = getattr(agent, "session_reasoning_tokens", 0) or 0
  656. compressor = agent.context_compressor
  657. last_prompt = max(0, compressor.last_prompt_tokens)
  658. ctx_len = compressor.context_length
  659. pct = min(100, (last_prompt / ctx_len * 100)) if ctx_len else 0
  660. elapsed = format_duration_compact((datetime.now() - self.session_start).total_seconds())
  661. def _label_row(key: str, value: str) -> None:
  662. # Labels are re-padded here (not in the catalog) so translated widths still align.
  663. print(f" {t(key):<26} {value}")
  664. print(f" {t('cli.usage.header_session')}")
  665. print(f" {'─' * 40}")
  666. _label_row("cli.usage.label_model", str(agent.model))
  667. _label_row("cli.usage.label_input_tokens", f"{input_tokens:>10,}")
  668. _label_row("cli.usage.label_output_tokens", f"{output_tokens:>10,}")
  669. if reasoning_tokens:
  670. _label_row("cli.usage.label_reasoning_subset", f"{reasoning_tokens:>10,}")
  671. _label_row("cli.usage.label_prompt_tokens_total", f"{agent.session_prompt_tokens:>10,}")
  672. _label_row("cli.usage.label_completion_tokens", f"{agent.session_completion_tokens:>10,}")
  673. _label_row("cli.usage.label_total_tokens", f"{agent.session_total_tokens:>10,}")
  674. _label_row("cli.usage.label_api_calls", f"{calls:>10,}")
  675. _label_row("cli.usage.label_session_duration", f"{elapsed:>10}")
  676. print(f" {'─' * 40}")
  677. from agent.context_breakdown import context_display_source
  678. mark = "~" if context_display_source(compressor) != "provider_usage" else ""
  679. from agent.context_pin import agent_context_suffix
  680. pin_suffix = agent_context_suffix(agent) # " (pinned)" / " (fallback)"
  681. print(f" {t('cli.usage.label_current_context'):<17} {mark}{last_prompt:,} / {ctx_len:,} ({mark}{pct:.0f}%){pin_suffix}")
  682. print(f" {t('cli.usage.label_messages'):<17} {len(self.conversation_history)}")
  683. print(f" {t('cli.usage.label_compressions'):<17} {compressor.compression_count}")
  684. self._print_account_limits()
  685. if self._print_nous_credits_block():
  686. self._print_usage_cta()
  687. if self.verbose:
  688. logging.getLogger().setLevel(logging.DEBUG)
  689. for noisy in ('openai', 'openai._base_client', 'httpx', 'httpcore', 'asyncio', 'hpack', 'grpc', 'modal'):
  690. logging.getLogger(noisy).setLevel(logging.WARNING)
  691. else:
  692. logging.getLogger().setLevel(logging.INFO)
  693. def _print_account_limits(self) -> bool:
  694. """Provider account limits block for `/usage`; True if anything printed.
  695. Uses the live agent's route when present, else the CLI's own configured provider (the
  696. TUI/Desktop slash-worker runs without an agent). Fetched off-thread with a hard timeout so
  697. slow provider APIs don't hang the prompt; failures are non-fatal. Lazy import: pulls the
  698. OpenAI SDK chain.
  699. """
  700. provider = self._agent_or_self("provider")
  701. if not provider:
  702. return False
  703. from agent.account_usage import fetch_account_usage, render_account_usage_lines
  704. account_snapshot = None
  705. with concurrent.futures.ThreadPoolExecutor(max_workers=1) as _pool:
  706. try:
  707. account_snapshot = _pool.submit(
  708. fetch_account_usage, provider, base_url=self._agent_or_self("base_url"),
  709. api_key=self._agent_or_self("api_key"),
  710. ).result(timeout=10.0)
  711. except (concurrent.futures.TimeoutError, Exception):
  712. account_snapshot = None
  713. account_lines = [f" {line}" for line in render_account_usage_lines(account_snapshot)]
  714. if not account_lines:
  715. return False
  716. print()
  717. for line in account_lines:
  718. print(line)
  719. return True
  720. def _show_insights(self, command: str = "/insights"):
  721. """Show usage insights and analytics from session history (`--days N` / `N`, `--source`)."""
  722. parts = command.split()
  723. days = 30
  724. source = None
  725. i = 1
  726. while i < len(parts):
  727. if parts[i] == "--days" and i + 1 < len(parts):
  728. try:
  729. days = int(parts[i + 1])
  730. except ValueError:
  731. print(f" {t('gateway.insights.invalid_days', value=parts[i + 1])}")
  732. return
  733. i += 2
  734. elif parts[i] == "--source" and i + 1 < len(parts):
  735. source = parts[i + 1]
  736. i += 2
  737. else:
  738. if parts[i].isdigit():
  739. days = int(parts[i])
  740. i += 1
  741. from types import SimpleNamespace
  742. from hermes_cli.main_agent_cmds import cmd_insights
  743. cmd_insights(SimpleNamespace(days=days, source=source))
  744. def _check_config_mcp_changes(self) -> None:
  745. """Detect mcp_servers changes in config.yaml (polled from process_loop every
  746. CONFIG_WATCH_INTERVAL seconds) and react.
  747. Default (``mcp.auto_reload_on_config_change: true``) auto-triggers ``_reload_mcp()``.
  748. When opted out it only notifies and points at ``/reload-mcp`` — every reload rebuilds the
  749. tool surface and INVALIDATES the provider prompt cache (next message re-sends the full
  750. prefix), so silent reloads are wrong when external tooling rewrites config.yaml often.
  751. Instead it notifies the user that the config changed and that they can apply it with ``/reload-mcp``
  752. — while warning that ``/reload-mcp`` rebuilds the tool surface and **invalidates the provider prompt
  753. cache** (the next message re-sends the full input prefix, expensive on long-context / high-reasoning
  754. models). See #1474.
  755. """
  756. from hermes_cli.config_backend import config_version_or_none, read_config_doc
  757. now = time.monotonic()
  758. if now - self._last_config_check < CONFIG_WATCH_INTERVAL:
  759. return
  760. self._last_config_check = now
  761. from hermes_cli.config import get_config_path as _get_config_path
  762. cfg_path = _get_config_path()
  763. sig = config_version_or_none(cfg_path)
  764. if sig is None:
  765. return
  766. if sig == self._config_sig:
  767. return # unchanged — fast path
  768. self._config_sig = sig
  769. try:
  770. new_cfg = read_config_doc(cfg_path) or {}
  771. except Exception:
  772. return
  773. # Expand ${VAR} templates so the comparison matches the init snapshot (populated from the
  774. # deep-merged + expanded config); otherwise any save_config_value() rewrite of an
  775. # unrelated key would false-positive on "${POWERMEM_API_KEY}" vs its expanded value.
  776. from hermes_cli.config import _expand_env_vars
  777. new_mcp = _expand_env_vars(new_cfg.get("mcp_servers") or {})
  778. if new_mcp == self._config_mcp_servers:
  779. return # some other section was edited
  780. # Read the toggle from the config just parsed so the user can flip it in the same edit;
  781. # missing key means default-on.
  782. _mcp_cfg = new_cfg.get("mcp")
  783. _auto = _mcp_cfg.get("auto_reload_on_config_change", True) if isinstance(_mcp_cfg, dict) else True
  784. self._config_mcp_servers = new_mcp
  785. if not _auto:
  786. print()
  787. print(t("cli.mcp_watch.changed_reload_skipped"))
  788. print(f" {t('cli.mcp_watch.not_applied_run')}")
  789. print(" /reload-mcp")
  790. print(f" {t('cli.mcp_watch.cache_note')}")
  791. return
  792. # Separate thread so a hung MCP server can't block process_loop (freezing the TUI).
  793. print()
  794. print(t("cli.mcp_watch.changed_reloading"))
  795. threading.Thread(target=self._reload_mcp, daemon=True).start()
  796. def _confirm_and_reload_mcp(self, cmd_original: str = "") -> None:
  797. """Interactive /reload-mcp — confirm (Approve Once / Always Approve / Cancel, gated by
  798. ``approvals.mcp_reload_confirm``, default on), then reload. The config watcher's
  799. auto-reload calls ``_reload_mcp`` directly. Reloading invalidates the provider prompt cache
  800. (tool schemas are baked into the system prompt), hence the warning."""
  801. choice = _gated_confirm(
  802. self, "reload-mcp", "mcp_reload_confirm",
  803. title=t("cli.reload_mcp.title"),
  804. detail=t("cli.reload_mcp.detail"),
  805. choices=_reload_mcp_choices(),
  806. unchanged=t("cli.reload_mcp.unchanged"),
  807. always_msg=t("cli.reload_mcp.always_msg"),
  808. once_verb=t("cli.reload_mcp.once_verb"))
  809. if choice is None:
  810. return
  811. with self._busy_command(self._slow_command_status(cmd_original)):
  812. self._reload_mcp()
  813. def _reload_gateway_mcp(self, connection):
  814. """``/reload-mcp`` on the shared gateway: the gateway owns the MCP servers and the session's
  815. agent, so it reconciles them with config and refreshes its agents (``reload.mcp``); main's
  816. "Agent updated" line then counts the tools the gateway session now loads."""
  817. from hermes_cli.gateway_client import GatewayClientError
  818. if not self._command_running:
  819. print(t("cli.reload_mcp.reloading"))
  820. try:
  821. result = connection.call("reload.mcp", session_id=self.session_id, confirm=True)
  822. snapshot = connection.call("session.resume", session_id=self.session_id) or {}
  823. except GatewayClientError as e:
  824. print(f" {t('gateway.reload_mcp.failed', error=str(e))}")
  825. return
  826. print(f" {result.get('message') or ''}".rstrip())
  827. connection.state(self.session_id).adopt_snapshot(snapshot)
  828. info = snapshot.get("info") or {}
  829. count = info.get("tool_count")
  830. if not isinstance(count, int):
  831. count = sum(len(names or []) for names in (info.get("tools") or {}).values())
  832. print(f" {t('cli.reload_mcp.agent_updated', count=str(count))}")
  833. def _reload_mcp(self):
  834. """Reload MCP servers: disconnect all, re-read config.yaml, reconnect, then refresh the
  835. agent's tool list so the model sees the updated tools on the next turn."""
  836. from hermes_cli.gateway_side import connection_for
  837. if (connection := connection_for(self)) is not None:
  838. return self._reload_gateway_mcp(connection)
  839. try:
  840. from tools.mcp_tool_lifecycle import shutdown_mcp_servers
  841. from tools.mcp_tool_discovery import discover_mcp_tools
  842. from tools.mcp_tool_agent import reprobe_tool_availability
  843. from tools.mcp_tool import _servers, _lock
  844. with _lock:
  845. old_servers = set(_servers.keys())
  846. if not self._command_running:
  847. print(t("cli.reload_mcp.reloading"))
  848. shutdown_mcp_servers()
  849. reprobe_tool_availability() # explicit reload also re-probes check_fn availability
  850. new_tools = discover_mcp_tools() # reads config.yaml fresh
  851. with _lock:
  852. connected_servers = set(_servers.keys())
  853. # English labels are model-facing (the [IMPORTANT: …] note below); the printed lines
  854. # resolve their own localized key per bucket.
  855. diff = {
  856. "Added": connected_servers - old_servers,
  857. "Removed": old_servers - connected_servers,
  858. "Reconnected": connected_servers & old_servers}
  859. for label, key in (("Reconnected", "cli.reload_mcp.reconnected"), ("Added", "cli.reload_mcp.added"),
  860. ("Removed", "cli.reload_mcp.removed")):
  861. if diff[label]:
  862. print(f" {t(key, names=', '.join(sorted(diff[label])))}")
  863. if not connected_servers:
  864. print(f" {t('gateway.reload_mcp.none_connected')}")
  865. else:
  866. print(f" {t('cli.reload_mcp.tools_available', tools=str(len(new_tools)), servers=str(len(connected_servers)))}")
  867. # Route through the shared helper so this path stays in lockstep with the TUI RPC /
  868. # gateway reload / late-binding paths (name-diff, thread-safe, additive-preserving so
  869. # memory-provider and context-engine tools survive the rebuild).
  870. if self.agent is not None:
  871. from tools.mcp_tool_agent import refresh_agent_mcp_tools
  872. # Pick up servers ENABLED in config this session: enabled_toolsets was resolved at
  873. # startup, so merge now-connected names in (unless `all`/`*` is pinned) so a
  874. # freshly-added server isn't filtered out. Mirrors startup (see __init__).
  875. enabled_override = None
  876. et = self.enabled_toolsets
  877. if et and "all" not in et and "*" not in et:
  878. merged = list(et)
  879. for _name in sorted(connected_servers):
  880. if _name not in merged:
  881. merged.append(_name)
  882. enabled_override = merged
  883. refresh_agent_mcp_tools(self.agent, enabled_override=enabled_override, quiet_mode=True)
  884. if enabled_override is not None:
  885. self.enabled_toolsets = enabled_override
  886. # Tell the model tools changed — appended at the END so the prefix cache survives.
  887. change_parts = [
  888. f"{label} servers: {', '.join(sorted(names))}" for label, names in diff.items() if names
  889. ]
  890. tool_summary = f"{len(new_tools)} MCP tool(s) now available" if new_tools else "No MCP tools available"
  891. change_detail = ". ".join(change_parts) + ". " if change_parts else ""
  892. self.conversation_history.append({
  893. "role": "user",
  894. "content": f"[IMPORTANT: MCP servers have been reloaded. {change_detail}{tool_summary}. The tool list for this conversation has been updated accordingly.]",
  895. })
  896. # Persist now so the session log reflects the refreshed tools list (best-effort).
  897. if self.agent is not None:
  898. try:
  899. self.agent._persist_session(self.conversation_history, self.conversation_history)
  900. except Exception:
  901. pass
  902. print(f" {t('cli.reload_mcp.agent_updated', count=str(len(self.agent.tools if self.agent else [])))}")
  903. except Exception as e:
  904. print(f" {t('gateway.reload_mcp.failed', error=str(e))}")
  905. def _reload_skills(self) -> None:
  906. """Reload skills: rescan ~/.hermes/skills/ and queue a note for the next user turn.
  907. Skills are invoked at runtime (``/skill-name``, ``skills_list``, ``skill_view``), not from
  908. the system prompt, so this does NOT clear the prompt cache. If anything was added/removed
  909. a one-shot note is prepended to the NEXT user message (``_pending_skills_reload_note``,
  910. same pattern as ``_pending_model_switch_note``) — nothing is written to
  911. conversation_history, so message alternation stays intact.
  912. """
  913. try:
  914. from hermes_cli.gateway_tools import process_view
  915. if not self._command_running:
  916. print(t("cli.reload_skills.reloading"))
  917. view = process_view()
  918. if view is not None: # the gateway session's rescan (its plugin skills too): nothing is scanned here
  919. result = (view.connection.call("skills.reload", session_id=view.session_id) or {}).get("result") or {}
  920. from hermes_cli.gateway_plugin_commands import invalidate
  921. invalidate(self) # /help, completion and dispatch read the rescanned list
  922. else:
  923. from agent.skill_commands import reload_skills
  924. result = reload_skills()
  925. added = result.get("added", []) # [{"name", "description"}, ...]
  926. removed = result.get("removed", [])
  927. total = result.get("total", 0)
  928. if not added and not removed:
  929. print(f" {t('gateway.reload_skills.no_new')}")
  930. print(f" {t('cli.reload_skills.total', count=str(total))}")
  931. return
  932. if added:
  933. print(f" {t('cli.reload_skills.added_header')}")
  934. for item in added:
  935. print(f" {_skill_line(item)}")
  936. if removed:
  937. print(f" {t('cli.reload_skills.removed_header')}")
  938. for item in removed:
  939. print(f" {_skill_line(item)}")
  940. print(f" {t('cli.reload_skills.total', count=str(total))}")
  941. # Same shape as the system prompt's skill catalog (`` - name: description``).
  942. sections = ["[USER INITIATED SKILLS RELOAD:"]
  943. if added:
  944. sections += ["", "Added Skills:", *(_skill_line(item) for item in added)]
  945. if removed:
  946. sections += ["", "Removed Skills:", *(_skill_line(item) for item in removed)]
  947. sections += ["", "Use skills_list to see the updated catalog.]"]
  948. self._pending_skills_reload_note = "\n".join(sections)
  949. except Exception as e:
  950. print(f" {t('gateway.reload_skills.failed', error=str(e))}")