cli_commands_mixin.py 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165
  1. """Slash-command handlers for the interactive CLI (``HermesCLI`` inherits ``CLICommandsMixin``).
  2. cli.py-internal symbols (``_cprint``/``_ACCENT``/``save_config_value``…) are imported LAZILY inside
  3. the helpers/handlers via ``from cli import ...`` — cli.py imports this module (cycle otherwise).
  4. """
  5. from __future__ import annotations
  6. import argparse
  7. import atexit
  8. import io
  9. import json
  10. import os
  11. import shlex
  12. import subprocess
  13. import tempfile
  14. import threading
  15. import time
  16. import uuid
  17. from contextlib import redirect_stdout, suppress
  18. from io import StringIO
  19. from datetime import datetime
  20. from urllib.parse import urlparse
  21. from rich import box as rich_box
  22. from rich.markup import escape as _escape
  23. from rich.panel import Panel
  24. from hermes_constants import display_hermes_home
  25. from hermes_state_ids import new_session_id as mint_session_id
  26. from agent.i18n import t
  27. from agent.message_metadata import message_identity
  28. from agent.turn_context import extract_api_content_sidecar
  29. from hermes_cli.cli_agent_setup_mixin import _gateway_open, _retire_agent
  30. from hermes_cli.cli_commands_session_tools import (
  31. CLICommandsSessionToolsMixin, _TTYBuf, _accent, _accent_line, _command_arg, _cp, _dim,
  32. _dim_line, _gt, _lines, _pr, _probe, _rollback_kept, _save, _say_block, _shlex_args, _t, _tn)
  33. from hermes_cli.cli_session_switch import (
  34. _end_current_session, _sync_agent_to_session)
  35. from hermes_cli.browser_connect import (
  36. DEFAULT_BROWSER_CDP_URL, discover_local_cdp_url, find_free_debug_port, is_browser_debug_ready,
  37. launch_chrome_debug, local_port_in_use, manual_chrome_debug_command)
  38. from hermes_cli.cli_browser_gateway import _normalize_cdp_url
  39. # Output helpers. Slash-command text is user-visible: every literal below is load-bearing.
  40. _FAILED = object()
  41. def _attempt(label: str, errors, fn, *args, **kwargs):
  42. """``fn(*args, **kwargs)``, or ``_FAILED`` after printing `` <label>: <exc>`` for ``errors``."""
  43. try:
  44. return fn(*args, **kwargs)
  45. except errors as exc:
  46. _cp(f" {label}: {exc}")
  47. return _FAILED
  48. def _take_flag(parts: list, flag: str):
  49. """Pop ``flag VALUE`` out of ``parts``: ``(rest, value, ok)``; ok=False when the value is
  50. missing (caller prints usage)."""
  51. if flag not in parts:
  52. return parts, None, True
  53. idx = parts.index(flag)
  54. if idx + 1 >= len(parts):
  55. return parts, None, False
  56. return parts[:idx] + parts[idx + 2:], parts[idx + 1], True
  57. def _summarize_paths(paths, limit: int = 5) -> str:
  58. """``a, b, c (+N more)`` for a list of paths."""
  59. more = _t("shared.more_suffix", count=len(paths) - limit) if len(paths) > limit else ""
  60. return ", ".join(paths[:limit]) + more
  61. def _ellipsize(text: str, limit: int) -> str:
  62. """``text[:limit]`` plus ``...`` when truncated."""
  63. return f"{text[:limit]}{'...' if len(text) > limit else ''}"
  64. # Small data tables.
  65. _ON_WORDS = {"on", "enable", "true", "1"}
  66. _OFF_WORDS = {"off", "disable", "false", "0"}
  67. # /busy modes; what Enter does while Hermes is working lives in the catalog as
  68. # ``cli.commands.busy.short_<mode>`` (status line) / ``long_<mode>`` (post-set explanation).
  69. _BUSY_MODES = ("queue", "steer", "interrupt")
  70. # /fast argument -> (service_tier value, persisted config value)
  71. _FAST_TIERS = {
  72. "fast": ("priority", "fast"), "on": ("priority", "fast"), "normal": (None, "normal"),
  73. "off": (None, "normal"), "auto": ("auto", "auto"), "cold": ("cold", "cold"),
  74. "ultrafast": ("ultrafast", "ultrafast"), "ultra": ("ultrafast", "ultrafast")}
  75. # /reasoning display toggles: arg -> (attr, value, headline key, follow-up note key or None);
  76. # the keys resolve under ``cli.commands.reasoning.*`` at call time.
  77. _REASONING_TOGGLES = {
  78. **dict.fromkeys(("show", "on"), ("show_reasoning", True, "headline_on", "note_show")),
  79. **dict.fromkeys(("hide", "off"), ("show_reasoning", False, "headline_off", None)),
  80. **dict.fromkeys(("full", "all"), ("reasoning_full", True, "headline_full", "note_full")),
  81. **dict.fromkeys(("clamp", "collapse", "short"), ("reasoning_full", False, "headline_clamped", None)),
  82. }
  83. # /bg AIAgent provider-routing kwargs -> HermesCLI attribute carrying the value.
  84. _BG_PROVIDER_KWARGS = {
  85. "providers_allowed": "_providers_only", "providers_ignored": "_providers_ignore",
  86. "providers_order": "_providers_order", "provider_sort": "_provider_sort",
  87. "provider_require_parameters": "_provider_require_params",
  88. "provider_data_collection": "_provider_data_collection",
  89. "openrouter_min_coding_score": "_openrouter_min_coding_score", "fallback_model": "_fallback_model"}
  90. # /worktree subcommand -> CLICommandsMixin method name (all need a repo root).
  91. _WORKTREE_SUBCOMMANDS = {
  92. **dict.fromkeys(("prune", "gc", "clean"), "_worktree_prune"),
  93. **dict.fromkeys(("list", "ls"), "_worktree_list"),
  94. **dict.fromkeys(("new", "add", "create"), "_worktree_new")}
  95. # Message fields copied verbatim onto a /branch row (plus role / tool_name / api_content).
  96. _BRANCH_COPY_KEYS = ("content", "tool_calls", "tool_call_id", "reasoning", "reasoning_content", "reasoning_details",
  97. "codex_reasoning_items", "codex_message_items", "timestamp", "data_use")
  98. # /hatch progress event -> catalog key (``cli.commands.hatch.*``).
  99. _HATCH_PROGRESS = {"compose": "hatch.progress_compose", "save": "hatch.progress_save"}
  100. # /diff argument -> mode (anything else is a path; --stat/stat is the stat flag).
  101. _DIFF_MODES = {
  102. "staged": "staged", "--staged": "staged", "cached": "staged", "--cached": "staged",
  103. "all": "all", "--all": "all", "head": "all", "session": "session"}
  104. # /diff mode -> stat headline catalog key (``cli.commands.diff.*``).
  105. _DIFF_LABELS = {"working": "diff.label_working", "staged": "diff.label_staged", "all": "diff.label_all"}
  106. def _persist_display_choice(key: str, value: str, label: str, note: str) -> None:
  107. """Save a /busy-style choice to config and report saved vs session-only."""
  108. if _save(key, value):
  109. _cp(_accent_line(_t("shared.set_saved", label=label, value=value)), _dim_line(note))
  110. else:
  111. _cp(_accent_line(_t("shared.set_session_only", label=label, value=value)))
  112. def _split_scope_flags(raw: str):
  113. """``(arg, explicit_global)`` for /reasoning + /fast: session scope by default, ``--global``
  114. persists to config.yaml, ``--session`` is an explicit no-op (parity with /model)."""
  115. tokens = raw.strip().lower().split()
  116. return " ".join(tok for tok in tokens if tok not in ("--global", "--session")), "--global" in tokens
  117. def _scope_outcome(explicit_global: bool, saved: bool) -> str:
  118. """Parenthetical tail for a scoped setting change."""
  119. if saved:
  120. return _t("shared.scope_saved")
  121. if explicit_global:
  122. return _t("shared.scope_save_failed")
  123. return _t("shared.scope_session")
  124. def _toggle_target(arg: str, current: bool):
  125. """Resolve a ``/x [on|off|status]`` argument: "status" for a status query, a bool for the
  126. new state (bare arg toggles), or None when the argument is unrecognized."""
  127. if arg in {"status", "?"}:
  128. return "status"
  129. if arg in _ON_WORDS:
  130. return True
  131. if arg in _OFF_WORDS:
  132. return False
  133. if arg == "":
  134. return not current
  135. return None
  136. def _cron_api(**kwargs) -> dict:
  137. """Call the cronjob model tool and decode its JSON reply."""
  138. from tools.cronjob_tools import cronjob as cronjob_tool
  139. return json.loads(cronjob_tool(**kwargs))
  140. # Session-switch plumbing (end, repoint) lives in ``hermes_cli/cli_session_switch.py``.
  141. def _without_session_meta(messages) -> list:
  142. return [m for m in (messages or []) if m.get("role") != "session_meta"]
  143. def _db_unavailable_line() -> str:
  144. from hermes_state import format_session_db_unavailable
  145. return f" {format_session_db_unavailable(details=True)}"
  146. def _print_side_result_panel(cli, *, header_lines, body, title_suffix, empty_note, console=None) -> None:
  147. """Print a worker-thread result (/bg, /btw, /login) into the scrollback: accent rules around
  148. ``header_lines``, then ``body`` in a skinned Rich panel (or ``empty_note``).
  149. Forces a TUI refresh first so the spinner/status bar don't overlap the output."""
  150. from cli import ChatConsole, _accent_hex, _maybe_remap_for_light_mode, _render_final_assistant_content
  151. _refresh_tui_before_print(cli)
  152. rich_console = console or ChatConsole()
  153. rich_console.print(f"[{_accent_hex()}]{'─' * 40}[/]")
  154. if console is None:
  155. _cp(*header_lines)
  156. else:
  157. for line in header_lines:
  158. console.print(line)
  159. rich_console.print(f"[{_accent_hex()}]{'─' * 40}[/]")
  160. if not body:
  161. return _cp(empty_note) if console is None else console.print(empty_note)
  162. try:
  163. from hermes_cli.skin_engine import get_active_skin
  164. _skin = get_active_skin()
  165. label = _skin.get_branding("response_label", "☤ Hermes")
  166. _resp_color = _maybe_remap_for_light_mode(_skin.get_color("response_border", "#CD7F32"))
  167. _resp_text = _maybe_remap_for_light_mode(_skin.get_color("banner_text", "#FFF8DC"))
  168. except Exception:
  169. label, _resp_color, _resp_text = "☤ Hermes", "#CD7F32", "#FFF8DC"
  170. rich_console.print(Panel(
  171. _render_final_assistant_content(body, mode=cli.final_response_markdown),
  172. title=f"[{_resp_color} bold]{label} {title_suffix}[/]", title_align="left",
  173. border_style=_resp_color, style=_resp_text, box=rich_box.HORIZONTALS, padding=(1, 4),
  174. width=cli._scrollback_box_width()))
  175. def _refresh_tui_before_print(cli) -> None:
  176. """Invalidate the running TUI (brief pause for the redraw) then print a blank separator, so
  177. worker-thread output doesn't overlap the spinner/status bar."""
  178. if cli._app:
  179. cli._app.invalidate()
  180. time.sleep(0.05)
  181. print()
  182. # /browser sub-handlers.
  183. def _print_lightpanda_engine_status() -> None:
  184. """``/browser status`` line(s) about ``browser.engine: lightpanda`` — silent unless set;
  185. says whether it is in use or which higher-precedence setting shadows it."""
  186. if not _probe("tools.browser_lightpanda", "using_lightpanda_engine", False):
  187. return
  188. used, reason = _probe("tools.browser_lightpanda", "lightpanda_engine_status", (None, None))
  189. if reason is None:
  190. return
  191. if not used:
  192. return print(f" {_t('browser.engine_not_in_use', reason=reason)}")
  193. print(f" {_t('browser.engine_lightpanda', reason=reason)}")
  194. try:
  195. from tools.browser_lightpanda import LIGHTPANDA_INSTALL_HINT, find_lightpanda_binary
  196. lightpanda_bin = find_lightpanda_binary()
  197. except Exception:
  198. return
  199. print(f" {_t('browser.binary', path=lightpanda_bin)}" if lightpanda_bin
  200. else f" {_t('browser.binary_not_found', hint=LIGHTPANDA_INSTALL_HINT)}")
  201. def _launch_default_cdp_browser(port: int):
  202. """Launch a local debug browser for the default CDP URL; returns the discovered CDP url or
  203. None (after printing what went wrong / how to launch manually)."""
  204. import platform as _plat
  205. launch_port = port
  206. if local_port_in_use(port):
  207. launch_port = find_free_debug_port(port)
  208. _pr(f" {_t('browser.port_occupied', port=port)}",
  209. f" {_t('browser.port_occupied_detail', launch_port=launch_port)}")
  210. else:
  211. print(f" {_t('browser.launching')}")
  212. launch = launch_chrome_debug(launch_port, _plat.system())
  213. if not launch.launched:
  214. print(f" {_t('browser.launch_failed')}")
  215. if launch.hint:
  216. print(f" {launch.hint}")
  217. chrome_cmd = manual_chrome_debug_command(launch_port, _plat.system())
  218. if chrome_cmd:
  219. _pr(f" {_t('browser.launch_manually')}", f" {chrome_cmd}")
  220. else:
  221. print(f" {_t('browser.no_executable')}")
  222. return None
  223. for _wait in range(10): # wait for the DevTools discovery endpoint to come up
  224. found = discover_local_cdp_url(launch_port, timeout=1.0)
  225. if found:
  226. print(f" {_t('browser.launched', port=launch_port)}")
  227. return found
  228. time.sleep(0.5)
  229. _pr(f" {_t('browser.not_responding', port=launch_port)}", f" {_t('browser.try_again')}")
  230. return None
  231. def _browser_connect(cli, cdp_url: str) -> None:
  232. """/browser connect [url] — validate the CDP URL, find or launch a debug browser, then
  233. point the browser tools at it (BROWSER_CDP_URL) and tell the model."""
  234. normalized = _normalize_cdp_url(cdp_url)
  235. if normalized is None:
  236. return
  237. cdp_url, port = normalized
  238. # Clear any existing browser sessions so the next tool call uses the new backend
  239. _probe("tools.browser_session_lifecycle", "cleanup_all_browsers", None)
  240. print()
  241. # Already serving CDP? For the default-local URL probe both loopbacks: a squatter
  242. # on 127.0.0.1:<port> (e.g. an IDE debugger) can push the browser to bind [::1] only.
  243. is_default = cdp_url == DEFAULT_BROWSER_CDP_URL
  244. if is_default:
  245. found = discover_local_cdp_url(port, timeout=1.0)
  246. else:
  247. found = cdp_url if is_browser_debug_ready(cdp_url, timeout=1.0) else None
  248. if found:
  249. print(f" {_t('browser.already_listening', url=found)}")
  250. elif is_default:
  251. found = _launch_default_cdp_browser(port)
  252. else:
  253. print(f" {_t('browser.port_unreachable', port=port, url=cdp_url)}")
  254. if not found:
  255. return _say_block(_t("browser.not_connected"))
  256. os.environ["BROWSER_CDP_URL"] = found
  257. # Eagerly start the CDP supervisor so pending_dialogs + frame_tree show up in the next snapshot.
  258. _probe("tools.browser_session_cdp", "ensure_cdp_supervisor", None, "default")
  259. _say_block(_t("browser.connected"), f" {_t('browser.endpoint', url=found)}")
  260. # Tell the model the CDP browser was made available on purpose.
  261. if hasattr(cli, '_pending_input'):
  262. cli._pending_input.put(
  263. "[System note: The user invoked /browser connect and connected your browser tools to "
  264. "a Chromium-family dev/debug browser via Chrome DevTools Protocol. "
  265. "Your browser tools (browser_exec, browser_cdp) now "
  266. "control that CDP browser. The command itself is a signal that using browser tools for "
  267. "their current browser-related request is expected; do not wait for separate permission "
  268. "just because CDP is connected. This is typically a Hermes-managed isolated debug "
  269. "profile, not the user's main everyday browser. It is still user-visible and may contain "
  270. "pages, logged-in sessions, or cookies in that debug profile, so avoid destructive actions, "
  271. "closing tabs, or navigating away unless the user's task calls for it.]")
  272. def _browser_disconnect(cli) -> None:
  273. if not os.environ.get("BROWSER_CDP_URL", "").strip():
  274. return _say_block(_t("browser.already_default"))
  275. os.environ.pop("BROWSER_CDP_URL", None)
  276. with suppress(Exception):
  277. from tools.browser_session_lifecycle import cleanup_all_browsers
  278. from tools.browser_session_cdp import stop_cdp_supervisor
  279. stop_cdp_supervisor("default")
  280. cleanup_all_browsers()
  281. _say_block(_t("browser.disconnected"), f" {_t('browser.reverted')}")
  282. if hasattr(cli, '_pending_input'):
  283. cli._pending_input.put(
  284. "[System note: The user has disconnected the browser tools from their live Chromium-family browser. "
  285. "Browser tools are back to default mode (headless local browser or cloud provider).]")
  286. # /browser status headline per local browser.engine value: (headline key, *detail keys) under
  287. # ``cli.commands.browser.*``; detail lines are indented at print time.
  288. _LOCAL_ENGINE_LINES = {
  289. "lightpanda": ("status_lightpanda", "status_lightpanda_note"),
  290. "auto": ("status_auto",)}
  291. def _local_engine_lines(engine: str) -> list:
  292. head, *details = _LOCAL_ENGINE_LINES.get(engine, _LOCAL_ENGINE_LINES["auto"])
  293. return [_t(f"browser.{head}"), *(f" {_t(f'browser.{key}')}" for key in details)]
  294. def _browser_status() -> None:
  295. current = os.environ.get("BROWSER_CDP_URL", "").strip()
  296. print()
  297. if current:
  298. _pr(_t("browser.status_connected"), f" {_t('browser.endpoint', url=current)}")
  299. _print_lightpanda_engine_status()
  300. _port = 9222
  301. with suppress(ValueError, IndexError):
  302. _port = int(current.rsplit(":", 1)[-1].split("/")[0])
  303. try:
  304. import socket
  305. socket.create_connection(("127.0.0.1", _port), timeout=1).close()
  306. print(f" {_t('browser.status_reachable')}")
  307. except Exception:
  308. print(f" {_t('browser.status_unreachable')}")
  309. else:
  310. provider = _probe("tools.browser_session_cloud", "get_cloud_provider", None)
  311. if provider is not None:
  312. print(_t("browser.status_cloud", provider=provider.display_name))
  313. _print_lightpanda_engine_status()
  314. else:
  315. engine = _probe("tools.browser_session_cloud", "get_browser_engine", "auto")
  316. _pr(*_local_engine_lines(engine))
  317. if engine == "lightpanda":
  318. _print_lightpanda_engine_status()
  319. _say_block(f" {_t('browser.status_connect_hint')}", f" {_t('browser.status_disconnect_hint')}")
  320. # /browser subcommand word → handler(cli, rest); ``rest`` is the raw (case-preserved)
  321. # remainder of the line. Adding a subcommand is one row here plus a usage line.
  322. _BROWSER_SUBCOMMANDS = {
  323. "connect": lambda cli, rest: _browser_connect(cli, rest or DEFAULT_BROWSER_CDP_URL),
  324. "disconnect": lambda cli, rest: _browser_disconnect(cli),
  325. "status": lambda cli, rest: _browser_status(),
  326. }
  327. class CLICommandsMixin(CLICommandsSessionToolsMixin):
  328. """Mixin holding the interactive-CLI slash-command handlers."""
  329. # ---- /rollback ------------------------------------------------------------------------
  330. def _checkpoint_manager(self, disabled_lines):
  331. """The agent's checkpoint manager, or None after printing why it is unavailable."""
  332. if not hasattr(self, 'agent') or not self.agent:
  333. return print(f" {_t('shared.no_active_agent_session')}")
  334. mgr = self.agent._checkpoint_mgr
  335. if not mgr.enabled:
  336. return _pr(*disabled_lines)
  337. return mgr
  338. def _handle_rollback_command(self, command: str):
  339. """Handle /rollback [diff] <N> [<file>|--all] — list, diff, or restore checkpoints.
  340. A restore also undoes the last chat turn; ``--all`` overwrites user hand-edits too."""
  341. from tools.checkpoint_manager import format_checkpoint_list
  342. from hermes_cli.gateway_side import connection_for
  343. if (connection := connection_for(self)) is not None:
  344. # Checkpoints are taken by the gateway's tools: list/diff/restore are the owner's.
  345. from hermes_cli.gateway_rollback import rollback
  346. return rollback(self, connection, command)
  347. mgr = self._checkpoint_manager(_lines(_t("rollback.not_enabled")))
  348. if mgr is None:
  349. return
  350. cwd = os.getenv("TERMINAL_CWD", os.getcwd())
  351. args = command.split()[1:]
  352. # --all / --force: classic full restore, overwriting user edits too.
  353. restore_all = any(a.lower() in ("--all", "--force") for a in args)
  354. args = [a for a in args if a.lower() not in ("--all", "--force")]
  355. if reason := mgr.unsupported_backend_reason(): # CLI: no session key, the "default" container
  356. # Container-backed session: any host checkpoint listed here belongs to another tree,
  357. # so diff/restore are refused; the list stays visible for local administration.
  358. print(f" {reason}")
  359. if args:
  360. return
  361. if not args:
  362. # No checkpoints for this dir → cross-project view (writes may sit under the session cwd).
  363. checkpoints = mgr.list_checkpoints(cwd)
  364. if not checkpoints:
  365. # List checkpoints — fall back to the cross-project view when the current directory has none
  366. # (#10505, reapply of PR #10633 by @nightq). The Aug 2026 QA sweep hit this live: writes
  367. # landed checkpoints under the session cwd (/tmp/qa-repo) while bare /rollback searched only
  368. # TERMINAL_CWD's project and reported "No checkpoints found" despite fresh checkpoints
  369. # existing.
  370. all_checkpoints = mgr.list_all_checkpoints()
  371. if all_checkpoints:
  372. print(f" {_t('rollback.none_here_showing_all', cwd=cwd)}")
  373. return print(format_checkpoint_list(all_checkpoints, _t("rollback.all_directories")))
  374. return print(format_checkpoint_list(checkpoints, cwd))
  375. is_diff = args[0].lower() == "diff"
  376. if is_diff and len(args) < 2:
  377. return print(f" {_t('rollback.usage_diff')}")
  378. checkpoints = mgr.list_checkpoints(cwd)
  379. if not checkpoints:
  380. return print(f" {_gt('rollback.none_found', cwd=cwd)}")
  381. target_hash = self._resolve_checkpoint_ref(args[1 if is_diff else 0], checkpoints)
  382. if not target_hash:
  383. return
  384. if is_diff:
  385. self._rollback_diff(mgr, cwd, target_hash)
  386. else:
  387. file_path = args[1] if len(args) > 1 else None
  388. self._rollback_restore(mgr, cwd, target_hash, file_path, restore_all)
  389. def _rollback_diff(self, mgr, cwd: str, target_hash: str) -> None:
  390. result = mgr.diff(cwd, target_hash)
  391. if not result["success"]:
  392. return print(f" ❌ {result['error']}")
  393. stat, diff = result.get("stat", ""), result.get("diff", "")
  394. if not stat and not diff:
  395. return print(f" {_t('rollback.no_changes_since')}")
  396. if stat:
  397. print(f"\n{stat}")
  398. if diff:
  399. # Limit diff output to avoid terminal flood
  400. diff_lines = diff.splitlines()
  401. if len(diff_lines) > 80:
  402. _pr("\n".join(diff_lines[:80]),
  403. f"\n {_t('rollback.more_lines', count=len(diff_lines) - 80)}")
  404. else:
  405. print(f"\n{diff}")
  406. def _rollback_restore(self, mgr, cwd, target_hash: str, file_path, restore_all: bool) -> None:
  407. result = mgr.restore(cwd, target_hash, file_path=file_path,
  408. safe=not restore_all and not file_path)
  409. if not result["success"]:
  410. return print(f" ❌ {result['error']}")
  411. restored = dict(hash=result["restored_to"], reason=result["reason"])
  412. print(f" {_t('rollback.restored_file', file=file_path, **restored)}" if file_path
  413. else f" {_t('rollback.restored_all', **restored)}")
  414. _rollback_kept(result)
  415. print(f" {_t('rollback.snapshot_saved')}")
  416. # Also undo the last conversation turn so the agent's context matches the restored files.
  417. if self.conversation_history:
  418. self.undo_last(prefill=False)
  419. print(f" {_t('rollback.chat_turn_undone')}")
  420. # ---- /diff ----------------------------------------------------------------------------
  421. def _handle_diff_command(self, command: str):
  422. """Handle /diff [working|staged|all|session] [--stat] [<path>...] — git changes in the
  423. cwd; ``session`` is everything Hermes changed since the checkpoint baseline."""
  424. stat_only = False
  425. mode = "working"
  426. paths: list[str] = []
  427. for arg in _shlex_args(command): # shlex preserves quoted paths
  428. low = arg.lower()
  429. if low in ("--stat", "stat"):
  430. stat_only = True
  431. elif low in _DIFF_MODES:
  432. mode = _DIFF_MODES[low]
  433. else:
  434. paths.append(arg)
  435. cwd = os.getenv("TERMINAL_CWD", os.getcwd())
  436. if mode == "session":
  437. return self._print_session_diff(cwd, stat_only)
  438. from tools.working_diff import collect_working_diff
  439. result = collect_working_diff(cwd, mode=mode, paths=paths or None)
  440. if not result.get("success"):
  441. return print(f" {result.get('error') or _t('shared.could_not_generate_diff')}")
  442. stat, diff = result.get("stat", ""), result.get("diff", "")
  443. untracked = result.get("untracked", [])
  444. if result.get("empty") or (not stat and not diff and not untracked):
  445. return print(f" {_gt('diff.no_changes')}")
  446. if stat:
  447. print(f"\n {_t(_DIFF_LABELS[mode])}:")
  448. self._print_diff_text(stat)
  449. if untracked and mode in ("working", "all"):
  450. _pr(f"\n {_t('diff.untracked')}", *(f" + {rel}" for rel in untracked[:20]))
  451. if len(untracked) > 20:
  452. print(f" {_t('diff.and_more', count=len(untracked) - 20)}")
  453. if diff and not stat_only:
  454. self._print_diff_body(diff, _t("diff.stat_hint"))
  455. def _print_diff_body(self, diff: str, stat_hint: str, limit: int = 400, total: int = 0) -> None:
  456. """Print a diff, capped at ``limit`` lines (of ``total`` when its sender cut it) with a pointer to the --stat form."""
  457. print()
  458. diff_lines = diff.splitlines()
  459. if (total := max(total, len(diff_lines))) > len(shown := diff_lines[:limit]):
  460. self._print_diff_text("\n".join(shown))
  461. print(f"\n {_t('diff.more_lines', count=total - len(shown), hint=stat_hint)}")
  462. else:
  463. self._print_diff_text(diff)
  464. def _print_session_diff(self, cwd: str, stat_only: bool):
  465. """Print the cumulative checkpoint-baseline diff (/diff session)."""
  466. mgr = self._checkpoint_manager(_lines(_t("diff.not_enabled")))
  467. if mgr is None:
  468. return
  469. if reason := mgr.unsupported_backend_reason(): # host baseline is not this session's tree
  470. return print(f" {reason}")
  471. from hermes_cli.cli_commands_session_tools import print_session_diff
  472. print_session_diff(self, mgr.session_diff(cwd), stat_only)
  473. def _print_diff_text(self, text: str) -> None:
  474. """Render diff/stat text with color when a rich console is present; plain print otherwise
  475. (e.g. unit tests instantiating the mixin standalone)."""
  476. console = getattr(self, "console", None)
  477. if console is not None:
  478. try:
  479. from cli import _rich_text_from_ansi
  480. console.print(_rich_text_from_ansi(text))
  481. return
  482. except Exception:
  483. pass
  484. print(text)
  485. # ---- /snapshot ------------------------------------------------------------------------
  486. def _handle_snapshot_command(self, command: str):
  487. """Handle /snapshot [list|create [label]|restore <id>|prune [N]] — state snapshots."""
  488. parts = command.split()
  489. subcmd = parts[1].lower() if len(parts) > 1 else "list"
  490. handler = {
  491. "list": self._snapshot_list, "ls": self._snapshot_list, "create": self._snapshot_create,
  492. "restore": self._snapshot_restore, "rewind": self._snapshot_restore,
  493. "prune": self._snapshot_prune}.get(subcmd)
  494. if handler is None:
  495. return _pr(f" {_t('snapshot.unknown_subcommand', subcommand=subcmd)}",
  496. f" {_t('snapshot.usage')}")
  497. handler(parts)
  498. def _snapshot_list(self, parts) -> None:
  499. from hermes_cli.backup import list_quick_snapshots
  500. snaps = list_quick_snapshots()
  501. if not snaps:
  502. return _pr(f" {_t('snapshot.none_yet')}", f" {_t('snapshot.create_hint')}")
  503. print(f" {_t('snapshot.list_header', dir=display_hermes_home())}\n")
  504. # Column labels are translated values re-padded here (never padded in the catalog).
  505. _pr(f" {_t('snapshot.col_num'):>3} {_t('snapshot.col_id'):<35} {_t('snapshot.col_files'):>5} "
  506. f"{_t('snapshot.col_size'):>10} {_t('snapshot.col_label')}",
  507. f" {'─'*3} {'─'*35} {'─'*5} {'─'*10} {'─'*20}")
  508. for i, s in enumerate(snaps, 1):
  509. size = s.get("total_size", 0)
  510. size_str = (f"{size} B" if size < 1024 else f"{size / 1024:.0f} KB"
  511. if size < 1024 * 1024 else f"{size / 1024 / 1024:.1f} MB")
  512. label = s.get("label") or ""
  513. print(f" {i:3} {s['id']:<35} {s.get('file_count', 0):>5} {size_str:>10} {label}")
  514. def _snapshot_create(self, parts) -> None:
  515. from hermes_cli.backup import create_quick_snapshot
  516. snap_id = create_quick_snapshot(label=" ".join(parts[2:]) if len(parts) > 2 else None)
  517. print(f" {_t('snapshot.created', snapshot_id=snap_id)}" if snap_id
  518. else f" {_t('snapshot.nothing_to_snapshot')}")
  519. def _snapshot_restore(self, parts) -> None:
  520. from hermes_cli.cli_snapshot import restore_snapshot_command
  521. restore_snapshot_command(self, parts)
  522. def _snapshot_prune(self, parts) -> None:
  523. from hermes_cli.backup import prune_quick_snapshots
  524. keep = 20
  525. if len(parts) > 2:
  526. # isdecimal() also rejects "-1": a negative keep would slice away the
  527. # newest snapshots instead of the oldest.
  528. if not parts[2].isdecimal():
  529. return print(f" {_t('snapshot.usage_prune')}")
  530. keep = int(parts[2])
  531. deleted = prune_quick_snapshots(keep=keep)
  532. print(f" {_t('snapshot.pruned', deleted=deleted, keep=keep)}")
  533. # ---- /export, /import -----------------------------------------------------------------
  534. def _handle_export_command(self, command: str):
  535. """Handle /export [profile] [-o path] — export a profile to a shareable .tar.gz archive."""
  536. from hermes_cli.profiles import export_profile, get_active_profile_name, get_profile_export_path
  537. parts, output, ok = _take_flag(command.split()[1:], "-o")
  538. if not ok:
  539. return print(f" {_t('export.usage')}")
  540. name = parts[0] if parts else (get_active_profile_name() or "default")
  541. try:
  542. result = export_profile(name, output or str(get_profile_export_path(name)))
  543. _pr(f" {_t('export.exported', name=name, path=result)}", f" {_t('export.share_hint')}")
  544. except (ValueError, FileNotFoundError, OSError) as e:
  545. print(f" {_t('shared.error', error=e)}")
  546. def _handle_import_command(self, command: str):
  547. """Handle /import <archive.tar.gz> [--name <name>] — import a shared profile archive as a
  548. new profile."""
  549. from hermes_cli.profiles import check_alias_collision, create_wrapper_script, import_profile
  550. parts, name, ok = _take_flag(command.split()[1:], "--name")
  551. if not ok or not parts:
  552. return print(f" {_t('import.usage')}")
  553. try:
  554. profile_dir = import_profile(" ".join(parts), name=name) # paths may contain spaces
  555. except (ValueError, FileExistsError, FileNotFoundError) as e:
  556. return print(f" {_t('shared.error', error=e)}")
  557. imported = profile_dir.name
  558. print(f" {_t('import.imported', name=imported, path=profile_dir)}")
  559. with suppress(Exception):
  560. if not check_alias_collision(imported):
  561. wrapper_path = create_wrapper_script(imported)
  562. if wrapper_path:
  563. print(f" {_t('import.wrapper_created', path=wrapper_path)}")
  564. print(f" {_t('import.use_it', name=imported)}")
  565. # ---- /handoff -------------------------------------------------------------------------
  566. _HANDOFF_PENDING_TIMEOUT = 60.0
  567. _HANDOFF_RUNNING_TIMEOUT = 900.0 # full synthetic agent turn + delivery
  568. _HANDOFF_HEARTBEAT_EVERY = 30.0
  569. @staticmethod
  570. def _handoff_keep(*lines: str) -> bool:
  571. """Print ``lines`` and keep the CLI session (the True verdict of /handoff)."""
  572. _cp(*lines)
  573. return True
  574. def _handle_handoff_command(self, cmd_original: str) -> bool:
  575. """Handle ``/handoff <platform>`` — transfer this CLI session to a gateway platform.
  576. Validate target → prepare session row → mark pending → block-poll (see ``_handoff_wait``).
  577. Returns False only on ``completed`` (caller exits like /quit); True keeps the session."""
  578. platform_name = _command_arg(cmd_original).lower()
  579. if not platform_name:
  580. return self._handoff_keep(
  581. f" {_t('handoff.usage')}", f" {_t('handoff.usage_detail_1')}",
  582. f" {_t('handoff.usage_detail_2')}")
  583. home = self._handoff_validate_target(platform_name)
  584. if home is None:
  585. return True
  586. session_title = self._handoff_prepare_session()
  587. if session_title is None:
  588. return True
  589. if not self._session_db.request_handoff(self.session_id, platform_name):
  590. return self._handoff_keep(f" {_t('handoff.already_in_flight')}")
  591. _cp(f" {_t('handoff.queued', title=session_title, platform=platform_name, home=home.name)}",
  592. f" {_t('handoff.waiting')}")
  593. return self._handoff_wait(platform_name, session_title)
  594. def _handoff_validate_target(self, platform_name: str):
  595. """Resolve the destination home channel via the live gateway config; None (after printing
  596. the reason) when the platform is unknown, disabled, or has no home channel."""
  597. try:
  598. from gateway.config import load_gateway_config, Platform
  599. except Exception as exc: # pragma: no cover — gateway pkg always shipped
  600. return _cp(f" {_t('handoff.config_load_failed', error=exc)}")
  601. try:
  602. platform = Platform(platform_name)
  603. except (ValueError, KeyError):
  604. return _cp(f" {_t('handoff.unknown_platform', platform=platform_name)}")
  605. try:
  606. gw_config = load_gateway_config()
  607. except Exception as exc:
  608. return _cp(f" {_t('handoff.config_load_failed', error=exc)}")
  609. pcfg = gw_config.platforms.get(platform)
  610. if not pcfg or not pcfg.enabled:
  611. # Relay aliasing: a relay-fronted gateway has only a RELAY block yet /handoff discord
  612. # is deliverable. UX pre-check only — the gateway watcher re-checks before dispatch.
  613. relay_fronts = False
  614. with suppress(Exception):
  615. from gateway.relay import relay_platform_identities
  616. relay_cfg = gw_config.platforms.get(Platform.RELAY)
  617. if relay_cfg and relay_cfg.enabled:
  618. relay_fronts = platform_name in {p for p, _ in relay_platform_identities()}
  619. if not relay_fronts:
  620. return _cp(f" {_t('handoff.platform_not_enabled', platform=platform_name)}")
  621. home = gw_config.get_home_channel(platform)
  622. if not home or not home.chat_id:
  623. return _cp(f" {_t('handoff.no_home_channel', platform=platform_name)}",
  624. f" {_t('handoff.set_home_hint')}")
  625. return home
  626. def _handoff_prepare_session(self):
  627. """Refuse mid-turn, make sure a SessionDB handle + session row exist, and return the
  628. display title (None after printing why the handoff cannot start)."""
  629. # An in-flight agent run would race the gateway's switch_session and the synthetic turn.
  630. if getattr(self, "_agent_running", False):
  631. return _cp(f" {_t('shared.agent_busy', command='/handoff')}")
  632. if not self._session_db:
  633. with suppress(Exception):
  634. from hermes_state_registry import acquire
  635. self._session_db = acquire()
  636. if not self._session_db:
  637. return _cp(_db_unavailable_line())
  638. # Ensure the session row exists (an empty session has flushed nothing yet): the gateway
  639. # needs a row to switch_session onto; set_session_title's INSERT OR IGNORE creates it.
  640. try:
  641. if not self._session_db.get_session(self.session_id):
  642. self._session_db.set_session_title(self.session_id, f"handoff-{self.session_id[:8]}")
  643. except Exception as exc:
  644. return _cp(f" {_t('handoff.session_row_failed', error=exc)}")
  645. session_title = ""
  646. with suppress(Exception):
  647. session_title = (self._session_db.get_session(self.session_id) or {}).get("title") or ""
  648. return session_title or self.session_id[:8]
  649. def _handoff_wait(self, platform_name: str, session_title: str) -> bool:
  650. """Two-phase 0.5s poll. PENDING (unclaimed): 60s, then CAS-fail the row so the user can
  651. retry (a claim racing this instant wins). RUNNING (claimed): the gateway replays the
  652. transcript via a synthetic turn (routinely >60s) — wait 15 min with heartbeats and on
  653. timeout do NOT touch the row; failing it here was the split-brain bug."""
  654. pending_deadline = time.time() + self._HANDOFF_PENDING_TIMEOUT
  655. running_deadline = None
  656. next_heartbeat = None
  657. last_state = "pending"
  658. while True:
  659. try:
  660. state_row = self._session_db.get_handoff_state(self.session_id)
  661. except Exception:
  662. state_row = None
  663. current = (state_row or {}).get("state") or "pending"
  664. if current != last_state:
  665. if current == "running":
  666. _cp(f" {_t('handoff.picked_up')}")
  667. running_deadline = time.time() + self._HANDOFF_RUNNING_TIMEOUT
  668. next_heartbeat = time.time() + self._HANDOFF_HEARTBEAT_EVERY
  669. last_state = current
  670. if current == "completed":
  671. _cp("", f" {_t('handoff.complete', platform=platform_name)}",
  672. f" {_t('handoff.resume_hint', title=session_title)}", "")
  673. # _run_cleanup must NOT finalize the row on exit: the gateway owns it now, and an
  674. # end_reason set under it would drop the handoff leg from session history/search.
  675. # See #88234.
  676. from cli import _handed_off_session_ids
  677. _handed_off_session_ids.add(self.session_id)
  678. self._should_exit = True # same exit semantics as /quit
  679. return False
  680. if current == "failed":
  681. err = (state_row or {}).get("error") or _t("handoff.unknown_error")
  682. return self._handoff_keep(
  683. f" {_t('handoff.failed', error=err)}", f" {_t('handoff.session_intact_retry')}")
  684. now = time.time()
  685. if current == "pending":
  686. if now >= pending_deadline:
  687. break
  688. else: # running
  689. if next_heartbeat is not None and now >= next_heartbeat:
  690. _cp(f" {_t('handoff.still_transferring')}")
  691. next_heartbeat = now + self._HANDOFF_HEARTBEAT_EVERY
  692. if running_deadline is not None and now >= running_deadline:
  693. # Do NOT fail the row: the gateway owns it (split-brain bug otherwise).
  694. return self._handoff_keep(
  695. f" {_t('handoff.taking_long')}",
  696. f" {_t('handoff.check_platform', platform=platform_name)}",
  697. f" {_t('handoff.no_longer_waiting')}", f" {_t('handoff.retry_when_settled')}")
  698. time.sleep(0.5)
  699. try: # pending timed out: CAS-clear so the user can retry
  700. self._session_db.fail_handoff(
  701. self.session_id, "timed out waiting for gateway", only_states=("pending",))
  702. except TypeError:
  703. # Older SessionDB without only_states (mixed installs): legacy unconditional fail.
  704. with suppress(Exception):
  705. self._session_db.fail_handoff(self.session_id, "timed out waiting for gateway")
  706. except Exception:
  707. pass
  708. return self._handoff_keep(f" {_t('handoff.timed_out')}", f" {_t('handoff.session_intact')}")
  709. # ---- /resume, /sessions, /branch ------------------------------------------------------
  710. def _handle_resume_command(self, cmd_original: str) -> None:
  711. """Handle /resume <session_id_or_title> — switch to a previous session mid-conversation."""
  712. if getattr(self, "_agent_running", False):
  713. return _cp(f" {_t('shared.agent_busy', command='/resume')}")
  714. from cli import _sync_process_session_id
  715. target = _command_arg(cmd_original)
  716. # Users copy the help text's placeholder brackets/quotes verbatim (``/resume <abc123>``).
  717. if len(target) >= 2 and target[0] + target[-1] in {"<>", "[]", '""', "''"}:
  718. target = target[1:-1].strip()
  719. if not target:
  720. _cp(f" {_t('resume.usage')}")
  721. if self._show_recent_sessions(reason="resume"):
  722. # Arm a one-shot bare-number selection; must be the same list the table showed
  723. # and the numbered branch resolves (all use _list_recent_sessions(limit=10)).
  724. # Arm a one-shot pending-resume selection so the user can type just the number (`3`) on the
  725. # next line instead of having to retype `/resume 3`. The list here must match the one shown
  726. # by _show_recent_sessions and used for index resolution below — all three go through
  727. # _list_recent_sessions(limit=10). See #34584.
  728. self._pending_resume_sessions = self._list_recent_sessions(limit=10)
  729. return
  730. return _cp(f" {_t('resume.tip_find_sessions')}")
  731. # Any explicit /resume <target> supersedes a previously-armed bare numbered prompt.
  732. self._pending_resume_sessions = None
  733. if not self._session_db:
  734. return _cp(_db_unavailable_line())
  735. resolved = self._resolve_resume_target(target)
  736. if resolved is None:
  737. return
  738. target_id, session_meta = resolved
  739. # A Kanban worker transcript must not become this chat's write-capable continuation
  740. # (#68779): the resumed conversation would be a writer the Kanban board cannot
  741. # observe, and unblocking the card could dispatch a competing worker. Keep the
  742. # CURRENT session instead of switching.
  743. from hermes_cli.kanban_resume_guard import kanban_resume_refusal
  744. if (kanban_refusal := kanban_resume_refusal(self._session_db, target_id)):
  745. return _cp(f" {kanban_refusal}")
  746. # One session.resume, before anything changes: it subscribes the target and names its receipt
  747. # owner; a target the gateway refuses this viewer stops the switch, so the current session is
  748. # neither ended nor swapped for one whose next prompt would be refused.
  749. read_id, (target_id, refusal) = target_id, _gateway_open(self._session_db, target_id)
  750. if refusal:
  751. return _cp(f" {_gt('resume.switch_failed')} {target_id} ({refusal})")
  752. if target_id == self.session_id:
  753. return _cp(f" {_t('resume.already_on')}")
  754. old_session_id = self.session_id
  755. _end_current_session(self, "resumed_other")
  756. self.session_id, self._resumed, self._pending_title = target_id, True, None
  757. _sync_process_session_id(target_id)
  758. # One lineage SELECT, two projections: model_history is alternation-repaired for live
  759. # replay (heals a durable user;user once); display_history is verbatim (as startup --resume).
  760. model_history, display_history = self._session_db.get_resume_conversations(read_id)
  761. self.conversation_history = _without_session_meta(model_history)
  762. self._resume_display_history = _without_session_meta(display_history)
  763. with suppress(Exception): # re-open the target session so it's not marked as ended
  764. self._session_db.reopen_session(target_id)
  765. _sync_agent_to_session(self, target_id, parent_session_id=old_session_id, reason="resume")
  766. title_part = f" \"{session_meta['title']}\"" if session_meta.get("title") else ""
  767. from agent.context_compressor import is_user_originated_turn
  768. # Count only user-originated turns: legacy compaction handoffs are durable role=user rows
  769. # without display_kind.
  770. msg_count = len([m for m in self._resume_display_history if is_user_originated_turn(m)])
  771. if self.conversation_history:
  772. _cp(" " + _tn("resume.resumed", msg_count, session_id=target_id, title=title_part,
  773. total=len(self.conversation_history)))
  774. self._display_resumed_history()
  775. else:
  776. _cp(f" {_t('resume.resumed_empty', session_id=target_id, title=title_part)}")
  777. # Same contract as startup --resume: retarget the tool cwd, restore the persisted YOLO
  778. # bypass (approval session key changed) and the model/provider (else config default).
  779. # Retarget the process + tool cwd to where the session was started, so a mid-chat /resume (and
  780. # /sessions <id>, which delegates here) lands in the same directory as a startup `hermes
  781. # -c`/`--resume`. The startup resume paths already call this; without it, the terminal/code-exec
  782. # tools and relative-path resolution keep operating in the wrong repo. Idempotent and a no-op when
  783. # the session recorded no cwd. See #38562.
  784. self._restore_session_cwd(session_meta)
  785. self._restore_session_yolo(session_meta)
  786. self._restore_session_model(session_meta)
  787. def _resolve_resume_target(self, target: str):
  788. """``(session_id, meta)`` for a numbered selection, title, or id (an empty compression-chain head
  789. redirects to the descendant holding the transcript); None after printing why it was not resolved."""
  790. if target.isdigit():
  791. sessions = self._list_recent_sessions(limit=10)
  792. index = int(target)
  793. if index < 1 or index > len(sessions):
  794. return _cp(*_lines(_gt("resume.out_of_range", index=index)))
  795. target_id = sessions[index - 1]["id"]
  796. else:
  797. from hermes_cli.main import _resolve_session_by_name_or_id
  798. target_id = _resolve_session_by_name_or_id(target) or target
  799. session_meta = self._session_db.get_session(target_id)
  800. if not session_meta:
  801. return _cp(f" {_t('resume.not_found', target=target)}", f" {_t('resume.not_found_hint')}")
  802. try:
  803. # If the target is the empty head of a compression chain, redirect to the descendant that
  804. # actually holds the transcript. See #15000.
  805. resolved_id = self._session_db.resolve_resume_session_id(target_id)
  806. except Exception:
  807. resolved_id = target_id
  808. if resolved_id and resolved_id != target_id:
  809. _cp(f" {_t('resume.compressed_redirect', session_id=target_id, resolved_id=resolved_id)}")
  810. target_id = resolved_id
  811. session_meta = self._session_db.get_session(target_id) or session_meta
  812. return target_id, session_meta
  813. def _handle_sessions_command(self, cmd_original: str) -> None:
  814. """Handle /sessions [list|<id_or_title>] — bare/``list`` prints the recent-sessions table;
  815. an explicit target delegates to /resume so both spellings behave identically."""
  816. arg = _command_arg(cmd_original)
  817. if arg and arg.lower() not in {"list", "ls", "browse"}:
  818. self._handle_resume_command(f"/resume {arg}")
  819. elif not self._session_db:
  820. _cp(_db_unavailable_line())
  821. elif not self._show_recent_sessions(reason="sessions"):
  822. _cp(f" {_t('sessions.none_yet')}")
  823. def _handle_branch_command(self, cmd_original: str) -> None:
  824. """Handle /branch [name] — fork the current session into a new independent copy of the
  825. full history so a different approach can be explored without losing the original."""
  826. # An in-flight agent run would flush through the rotating session identity: the branch
  827. # ends the parent row and repoints agent.session_id (_sync_agent_to_session), so the
  828. # turn's remaining messages land on the branch. Refuse mid-turn like /handoff does.
  829. if getattr(self, "_agent_running", False):
  830. return _cp(f" {_t('shared.agent_busy', command='/branch')}")
  831. from cli import _sync_process_session_id
  832. if not self.conversation_history:
  833. return _cp(f" {_gt('branch.no_conversation')}")
  834. if not self._session_db:
  835. return _cp(_db_unavailable_line())
  836. # CLI has no threads: always in place; strip the gateway's ``--here`` so it is never a title.
  837. from gateway.slash_commands_branch_thread import parse_branch_args
  838. _, branch_name = parse_branch_args(_command_arg(cmd_original))
  839. now = datetime.now()
  840. from tools.approval_yolo import transfer_session_yolo, with_session_yolo
  841. # Create the child BEFORE ending the parent: a failed create_session or gateway branch (or its /yolo
  842. # carry) must leave the session the user is still on open, not ended "branched" with no branch (#11030).
  843. # The stable ``_branched_from`` marker keeps the branch visible in /resume + /sessions even after the
  844. # parent is re-ended with a different end_reason; with_session_yolo keeps a live /yolo on the branch.
  845. # The child sends the parent's exact system prompt: a row without one makes the branch's first turn
  846. # rebuild (re-probing the workspace), losing the copied transcript's warm cache if the repo moved since.
  847. try:
  848. new_session_id = self._new_session_id(now, branch_of=self.session_id) # the gateway's branch child
  849. branch_title = branch_name or self._session_db.get_next_title_in_lineage(
  850. self._session_db.get_session_title(self.session_id) or "branch")
  851. parent_session_id = self.session_id
  852. parent_prompt = getattr(self.agent, "_cached_system_prompt", None)
  853. if not isinstance(parent_prompt, str) or not parent_prompt:
  854. with suppress(Exception):
  855. parent_prompt = (self._session_db.get_session(parent_session_id) or {}).get("system_prompt")
  856. self._session_db.create_session(
  857. session_id=new_session_id, source=os.environ.get("HERMES_SESSION_SOURCE", "cli"),
  858. model=self.model, parent_session_id=parent_session_id, system_prompt=parent_prompt or None,
  859. model_config=with_session_yolo({"max_iterations": self.max_turns, "reasoning_config":
  860. self.reasoning_config, "_branched_from": parent_session_id}, parent_session_id))
  861. except Exception as e:
  862. return _cp(f" {_gt('branch.create_failed', error=e)}")
  863. _end_current_session(self, "branched")
  864. # Best-effort chunked copy (a failed copy still yields a usable branch); the api_content
  865. # sidecar lets the branch's first turn replay the parent's exact wire bytes (warm cache).
  866. with suppress(Exception):
  867. self._session_db.append_messages_batch(new_session_id, [
  868. {"role": msg.get("role", "user"), "tool_name": msg.get("tool_name") or msg.get("name"),
  869. "api_content": extract_api_content_sidecar(msg),
  870. **{k: msg.get(k) for k in _BRANCH_COPY_KEYS}, **message_identity(msg, with_tool_uids=True)}
  871. for msg in self.conversation_history], chunk_rows=500)
  872. with suppress(Exception):
  873. self._session_db.set_session_title(new_session_id, branch_title)
  874. # Switch to the new session
  875. transfer_session_yolo(self.session_id, new_session_id)
  876. self.session_id, self.session_start, self._pending_title = new_session_id, now, None
  877. self._resumed = True # Prevents auto-title generation
  878. _sync_process_session_id(new_session_id)
  879. if self.agent:
  880. self.agent.session_start = now
  881. _sync_agent_to_session(self, new_session_id, parent_session_id=parent_session_id, reason="branch")
  882. msg_count = len([m for m in self.conversation_history if m.get("role") == "user"])
  883. _cp(" " + _tn("branch.branched", msg_count, title=branch_title),
  884. f" {_t('branch.original_session', session_id=parent_session_id)}",
  885. f" {_t('branch.branch_session', session_id=new_session_id)}")
  886. # ---- /worktree ------------------------------------------------------------------------
  887. def _handle_worktree_command(self, cmd_original: str) -> None:
  888. """Handle /worktree [new [name]|list|prune [--dry-run]] — isolated git worktrees.
  889. ``new`` moves this session into the tree (as ``hermes -w``: kept on exit only with
  890. unpushed commits); ``prune`` never deletes tracked changes, unique commits, or in-use trees."""
  891. import cli as _cli
  892. parts = cmd_original.split(None, 2)
  893. sub = parts[1].lower() if len(parts) > 1 else ""
  894. rest = parts[2].strip() if len(parts) > 2 else ""
  895. repo_root = _cli._git_repo_root()
  896. if not sub or sub in {"status", "show"}:
  897. active = _cli._active_worktree
  898. if active:
  899. _pr(f" {_t('worktree.active', path=active['path'])}",
  900. f" {_t('worktree.branch', branch=active['branch'])}")
  901. else:
  902. print(f" {_t('worktree.none_active')}")
  903. if repo_root:
  904. _pr(f" {_t('worktree.hint_new')}", f" {_t('worktree.hint_prune')}")
  905. else:
  906. print(f" {_t('worktree.not_in_repo_note')}")
  907. return
  908. handler = _WORKTREE_SUBCOMMANDS.get(sub)
  909. if handler is None:
  910. return _pr(f" {_t('worktree.unknown_subcommand', subcommand=sub)}", f" {_t('worktree.usage')}")
  911. if not repo_root:
  912. print(f" {_t('worktree.new_requires_repo')}" if handler == "_worktree_new"
  913. else f" {_t('worktree.not_in_repo')}")
  914. return
  915. getattr(self, handler)(repo_root, rest)
  916. def _worktree_prune(self, repo_root: str, rest: str) -> None:
  917. import cli as _cli
  918. from hermes_cli import worktree_gc
  919. rest = rest.lower()
  920. dry_run = "--dry-run" in rest or "-n" in rest.split()
  921. active = _cli._active_worktree
  922. tree_records = worktree_gc.audit_worktrees(repo_root, with_sizes=False)
  923. if active:
  924. # Never reap the tree this session is sitting in, even if judged clean+merged.
  925. active_path = str(active.get("path") or "")
  926. tree_records = [record for record in tree_records if record.path != active_path]
  927. actions = worktree_gc.reclaim_worktrees(repo_root, dry_run=dry_run, records=tree_records)
  928. actions += worktree_gc.reclaim_branches(repo_root, dry_run=dry_run)
  929. if actions:
  930. _pr(*(f" {line}" for line in actions),
  931. " " + _t("worktree.actions_planned" if dry_run else "worktree.actions_done", count=len(actions)))
  932. else:
  933. print(f" {_t('worktree.nothing_to_reclaim')}")
  934. kept = [r for r in tree_records
  935. if r.verdict == "keep" and "kanban" not in r.reason and "in use" not in r.reason]
  936. if kept:
  937. _pr(f" {_t('worktree.preserved', count=len(kept))}",
  938. *(f" {record.name}: {record.reason}" for record in kept))
  939. def _worktree_list(self, repo_root: str, rest: str) -> None:
  940. try:
  941. result = subprocess.run(
  942. ["git", "worktree", "list"], capture_output=True, text=True, encoding="utf-8",
  943. errors="replace", timeout=10, cwd=repo_root, check=False)
  944. out = result.stdout.strip() if result.returncode == 0 else ""
  945. except Exception:
  946. out = ""
  947. _pr(*(f" {line}" for line in out.splitlines()) if out else (f" {_t('worktree.list_failed')}",))
  948. def _worktree_new(self, repo_root: str, rest: str) -> None:
  949. import cli as _cli
  950. from hermes_cli.config import load_config
  951. try:
  952. sync_base = bool(load_config().get("worktree_sync", True))
  953. except Exception:
  954. sync_base = True
  955. wt_info = _cli._setup_worktree(repo_root=repo_root, sync_base=sync_base, name=rest or None)
  956. if not wt_info:
  957. return # _setup_worktree already printed the failure
  958. # Same keep-if-unpushed cleanup as `hermes -w`. Only one tree is "active" per process;
  959. # an earlier one keeps its own atexit registration (explicit info arg).
  960. atexit.register(_cli._cleanup_worktree, wt_info)
  961. from hermes_cli.cli_commands_worktree import enter_new_worktree
  962. if not enter_new_worktree(self, wt_info):
  963. return
  964. _cli._active_worktree = wt_info
  965. _pr(f" {_t('worktree.ready', path=wt_info['path'])}",
  966. f" {_t('worktree.branch', branch=wt_info['branch'])}", f" {_t('worktree.tools_in_worktree')}")
  967. # ---- /personality, /pet, /hatch -------------------------------------------------------
  968. def _handle_personality_command(self, cmd: str):
  969. """Handle /personality [name] — list or set a predefined personality. All resolution and
  970. persistence goes through hermes_cli.personality, the single owner of personality state."""
  971. from hermes_cli.personality import (
  972. describe_personality, normalize_personality_name, persist_personality, prompt_text,
  973. resolve_personality)
  974. personality_name = _command_arg(cmd)
  975. if not personality_name:
  976. try:
  977. from hermes_cli.config import read_raw_config
  978. current = normalize_personality_name(
  979. (read_raw_config().get("display") or {}).get("personality", ""))
  980. except Exception:
  981. current = ""
  982. _pr("", "+" + "-" * 50 + "+", "|" + _t("personality.title").center(50) + "|",
  983. "+" + "-" * 50 + "+", "",
  984. f" {' *' if not current else ' '}{'none':<12} - {_t('personality.none_option')}")
  985. for name, prompt in self.personalities.items():
  986. marker = " *" if name == current else " "
  987. print(f" {marker}{name:<12} - {describe_personality(prompt)}")
  988. return _pr("", f" {_t('personality.usage')}", "")
  989. try:
  990. name, personality_prompt = resolve_personality(personality_name, getattr(self, "config", None))
  991. except ValueError:
  992. print(_t("personality.unknown", name=personality_name.lower()))
  993. return print(f" {_t('personality.available', available=', '.join(self.personalities.keys()))}")
  994. saved = persist_personality(name)
  995. scope = _t("personality.scope_saved") if saved else _t("personality.scope_session")
  996. face = "(^_^)b" if saved else "(^_^)"
  997. if not name:
  998. # Neutral reset — fall back to the user-owned manual prompt.
  999. try:
  1000. from hermes_cli.config import cfg_get, read_raw_config
  1001. self.system_prompt = prompt_text(
  1002. cfg_get(read_raw_config(), "agent", "system_prompt", default=""))
  1003. except Exception:
  1004. self.system_prompt = ""
  1005. _retire_agent(self) # Force re-init
  1006. _pr(_t("personality.cleared", face=face, scope=scope), f" {_t('personality.cleared_note')}")
  1007. else:
  1008. self.system_prompt = personality_prompt
  1009. _retire_agent(self) # Force re-init
  1010. _pr(_t("personality.set_to", face=face, name=name, scope=scope),
  1011. f" \"{_ellipsize(personality_prompt, 60)}\"")
  1012. def _handle_pet_command(self, cmd: str):
  1013. """Handle /pet [toggle|list|scale <n>|off|<slug>] — the petdex mascot. Writes
  1014. ``display.pet.*`` to config; pet surfaces pick it up on their next poll."""
  1015. from agent.pet import store
  1016. from agent.pet.manifest import ManifestError
  1017. from hermes_cli.pets import (
  1018. _set_active, _set_enabled, print_pet_gallery, set_pet_scale, toggle_pet_display)
  1019. arg = _command_arg(cmd)
  1020. low = arg.lower()
  1021. if not arg or low == "toggle":
  1022. enabled, name, err = toggle_pet_display()
  1023. print(_t("pet.error", error=err) if err else _t("pet.is_out", name=name) if enabled
  1024. else _t("pet.put_away_named", name=name) if name else _t("pet.put_away"))
  1025. elif low in ("list", "gallery", "browse", "all"):
  1026. print_pet_gallery()
  1027. elif low == "scale" or low.startswith("scale "):
  1028. value = arg[len("scale"):].strip()
  1029. if not value:
  1030. return print(_t("pet.usage_scale"))
  1031. scale, err = set_pet_scale(value)
  1032. print(_t("pet.error", error=err) if err else _t("pet.scale_set", scale=f"{scale:g}"))
  1033. elif low == "off":
  1034. _set_enabled(False)
  1035. print(_t("pet.put_away"))
  1036. else:
  1037. print(_t("pet.fetching", name=arg))
  1038. try:
  1039. pet = store.install_pet(arg)
  1040. except (store.PetStoreError, ManifestError) as exc:
  1041. return print(_t("pet.adopt_failed", name=arg, error=exc))
  1042. _set_active(arg)
  1043. print(_t("pet.is_out", name=pet.display_name))
  1044. def _handle_hatch_command(self, cmd: str):
  1045. """Generate ("hatch") a new petdex pet from a description: base look, one animation row
  1046. per state, spritesheet, then adopt. Progress streams inline (~a minute of image calls).
  1047. The desktop app opens a richer overlay for this command instead."""
  1048. from agent.pet import store
  1049. from agent.pet.generate import orchestrate
  1050. from agent.pet.generate.imagegen import GenerationError
  1051. from hermes_cli.pets import _set_active
  1052. concept = _command_arg(cmd)
  1053. if not concept:
  1054. # prompt_toolkit owns stdin on this daemon thread — raw input() never renders and eats
  1055. # keystrokes; prefer the thread-aware helper (None when prompting isn't safe).
  1056. # Bare /hatch is dispatched from the process_loop daemon thread while prompt_toolkit owns stdin
  1057. # — a raw input() here types into a prompt that never renders and swallows the next keystrokes
  1058. # (same class as #23185; found in the Aug 2026 full-surface CLI QA sweep: bare /hatch left the
  1059. # session eating input until Ctrl+C). Route through the thread-aware prompt helper, which uses
  1060. # run_in_terminal on the main thread and cancels cleanly (None) when prompting isn't safe.
  1061. prompt_helper = getattr(self, "_prompt_text_input", None)
  1062. try:
  1063. concept = ((prompt_helper or input)(_t("hatch.describe_prompt")) or "").strip()
  1064. except (EOFError, KeyboardInterrupt):
  1065. return print()
  1066. if not concept:
  1067. return print(_t("hatch.usage"))
  1068. # A short, friendly display name from the first few words of the concept.
  1069. display_name = (" ".join(w.capitalize() for w in concept.split()[:3])[:28].strip()
  1070. or _t("hatch.default_name"))
  1071. slug = store.slugify(display_name) or store.slugify(concept) or "pet"
  1072. print(_t("hatch.designing", concept=concept))
  1073. try:
  1074. drafts = orchestrate.generate_base_drafts(concept, n=1)
  1075. except GenerationError as exc:
  1076. return print(_t("hatch.base_failed", error=exc))
  1077. if not drafts:
  1078. return print(_t("hatch.no_base_draft"))
  1079. def _progress(event: str, detail: str) -> None:
  1080. if event == "row": # detail is "<state>:<done>:<total>"; show the state name.
  1081. print(f" {_t('hatch.progress_drawing', state=detail.split(':', 1)[0])}")
  1082. elif event in _HATCH_PROGRESS:
  1083. print(f" {_t(_HATCH_PROGRESS[event])}")
  1084. try:
  1085. result = orchestrate.hatch_pet(
  1086. base_image=drafts[0], slug=slug, display_name=display_name, concept=concept,
  1087. on_progress=_progress)
  1088. except GenerationError as exc:
  1089. return print(_t("hatch.failed", error=exc))
  1090. _set_active(result.slug)
  1091. print(_t("hatch.hatched", name=result.display_name))
  1092. # ---- /cron ----------------------------------------------------------------------------
  1093. def _handle_cron_command(self, cmd: str):
  1094. """Handle the /cron command to manage scheduled tasks. Only without a gateway session: on the shared
  1095. gateway every /cron form runs there (hermes_cli/gateway_setting_commands.py)."""
  1096. from hermes_cli.cli_cron_lines import cron_command_lines
  1097. _pr(*cron_command_lines(_command_arg(cmd)))
  1098. # ---- delegating handlers: /suggestions, /blueprint, /curator, /kanban, /skills, /memory --
  1099. def _handle_suggestions_command(self, cmd: str):
  1100. """Handle /suggestions — review/accept/dismiss suggested automations via the shared handler.
  1101. CLI origin is the local platform so an accepted job's "origin" delivery resolves to a home channel."""
  1102. args = " ".join(_shlex_args(cmd))
  1103. try:
  1104. from hermes_cli.suggestions_cmd import handle_suggestions_command
  1105. output = handle_suggestions_command(args)
  1106. except Exception as e:
  1107. output = _t("suggestions.failed", error=e)
  1108. self._console_print(output)
  1109. def _handle_blueprint_command(self, cmd: str):
  1110. """Handle /blueprint — set up an automation from a blueprint template (shared handler).
  1111. Bare lists the catalog; ``<name>`` seeds the agent to ask for each value conversationally
  1112. (``agent_seed``, run as the next turn); ``<name> slot=val …`` creates the job directly."""
  1113. args = " ".join(shlex.quote(part) for part in _shlex_args(cmd))
  1114. try:
  1115. from hermes_cli.blueprint_cmd import handle_blueprint_command
  1116. result = handle_blueprint_command(args)
  1117. except Exception as e:
  1118. self._console_print(_t("blueprint.failed", error=e))
  1119. return
  1120. self._console_print(result.text)
  1121. seed = getattr(result, "agent_seed", None)
  1122. if seed:
  1123. # One-shot: the interactive loop picks this up right after the slash command
  1124. # returns and runs it as a normal agent turn.
  1125. self._pending_agent_seed = seed
  1126. def _handle_curator_command(self, cmd: str):
  1127. """Handle /curator — delegates to hermes_cli.curator so the CLI and the `hermes curator`
  1128. subcommand share the same handler set."""
  1129. tokens = shlex.split(cmd)[1:] if cmd else []
  1130. try:
  1131. from hermes_cli.curator import cli_main
  1132. cli_main(tokens or ["status"])
  1133. except SystemExit:
  1134. pass # argparse exits on --help/errors; don't kill the interactive session
  1135. except Exception as exc:
  1136. print(_t("curator.failed", error=exc))
  1137. def _handle_kanban_command(self, cmd: str):
  1138. """Handle /kanban — strip the leading ``/kanban`` and hand the rest to ``kanban.run_slash``."""
  1139. from hermes_cli.kanban import run_slash
  1140. rest = cmd.strip().lstrip("/")
  1141. if rest.startswith("kanban"):
  1142. rest = rest[len("kanban"):].lstrip()
  1143. try:
  1144. output = run_slash(rest)
  1145. except Exception as exc: # pragma: no cover - defensive
  1146. output = _t("kanban.failed", error=exc)
  1147. if output:
  1148. print(output)
  1149. def _handle_skills_command(self, cmd: str):
  1150. """Handle /skills slash command — delegates to hermes_cli.skills_hub, after intercepting the
  1151. write-approval review subcommands (pending/approve/reject/diff/mode)."""
  1152. from cli import ChatConsole
  1153. args = cmd.strip().split()[1:]
  1154. review_words = {"pending", "approve", "apply", "reject", "deny", "drop", "diff", "approval", "mode"}
  1155. if args and args[0].lower() in review_words:
  1156. from hermes_cli.write_approval_commands import handle_pending_subcommand
  1157. from tools import write_approval as wa
  1158. out = handle_pending_subcommand(
  1159. wa.SKILLS, args, set_mode_fn=lambda enabled: self._save_write_approval("skills", enabled),
  1160. )
  1161. if out is not None:
  1162. return print(out)
  1163. from hermes_cli.gateway_tools import handle_skills_slash # + the gateway's rescan
  1164. handle_skills_slash(cmd, ChatConsole(), cli=self)
  1165. def _handle_memory_command(self, cmd: str):
  1166. """Handle /memory slash command — pending review + approval-gate toggle."""
  1167. from hermes_cli.write_approval_commands import handle_pending_subcommand
  1168. from tools import write_approval as wa
  1169. args = cmd.strip().split()[1:]
  1170. store = getattr(self.agent, "_memory_store", None) if getattr(self, "agent", None) else None
  1171. if store is None:
  1172. # No live agent store (e.g. Desktop GUI): use a fresh on-disk store, as the gateway
  1173. # does — same MEMORY/USER.md, same configured char limits.
  1174. # Apply against a freshly loaded on-disk store, mirroring the gateway path
  1175. # (gateway/slash_commands.py): it persists to the same MEMORY/USER.md and creates MEMORY.md on
  1176. # the first approved write. Without this the shared handler returns "memory store unavailable".
  1177. # See #46783.
  1178. from tools.memory_tool import load_on_disk_store
  1179. store = load_on_disk_store()
  1180. out = handle_pending_subcommand(
  1181. wa.MEMORY, args, memory_store=store,
  1182. set_mode_fn=lambda enabled: self._save_write_approval("memory", enabled))
  1183. print(out if out is not None else _t("memory.unknown_subcommand"))
  1184. def _save_write_approval(self, subsystem: str, enabled: bool):
  1185. """Persist <subsystem>.write_approval to config (for /memory|/skills approval)."""
  1186. _save(f"{subsystem}.write_approval", bool(enabled))
  1187. # ---- prompt-queueing handlers: /learn, /plan, /init -----------------------------------
  1188. def _queue_prompt_turn(self, msg: str, command: str, ack: str = "") -> None:
  1189. """Inject ``msg`` onto the agent's input queue as the next normal user turn (the
  1190. /learn, /plan, /init pattern: no engine, no model-tool footprint, prompt-cache safe). ``ack``
  1191. paints first on the turn's own channel (_cprint), so the turn's `────` never overtakes it."""
  1192. if ack:
  1193. __import__("cli")._cli_visible_print("\n" + ack)
  1194. if hasattr(self, "_pending_input"):
  1195. self._pending_input.put(msg)
  1196. else: # pragma: no cover - defensive (no live input loop)
  1197. print(f" {_t('shared.needs_active_session', command=command)}")
  1198. def _handle_learn_command(self, cmd: str):
  1199. """Handle /learn — distill a reusable skill from anything the user describes (a directory,
  1200. a URL, "what we just did", pasted notes). The live agent gathers the material with the
  1201. tools it already has and authors the skill via ``skill_manage``."""
  1202. from agent.learn_prompt import build_learn_prompt
  1203. user_request = _command_arg(cmd)
  1204. self._queue_prompt_turn(build_learn_prompt(user_request), "/learn", _t("learn.from_description" if user_request else "learn.from_conversation"))
  1205. def _handle_plan_command(self, cmd: str):
  1206. """Handle /plan — write a markdown implementation plan, no execution. The live agent
  1207. inspects the workspace read-only and saves the plan under ``.hermes/plans/``."""
  1208. from agent.plan_prompt import build_plan_prompt
  1209. task = _command_arg(cmd) # optional — empty infers the task from conversation context
  1210. self._queue_prompt_turn(build_plan_prompt(task), "/plan", _t("plan.planning", task=_ellipsize(task, 80)) if task else _t("plan.from_conversation"))
  1211. def _handle_init_command(self, cmd: str):
  1212. """Handle /init — generate or update AGENTS.md from a project scan performed by the
  1213. live agent with its own read-only tools."""
  1214. from hermes_cli.init_command import build_init_prompt_for_cwd
  1215. # session_key="" targets the single-session CLI's "default" cwd record, which tracks
  1216. # `cd` and workspace switches, so /init follows the directory the user works in.
  1217. msg = build_init_prompt_for_cwd(extra=_command_arg(cmd), session_key="") # optional user emphasis
  1218. self._queue_prompt_turn(msg, "/init", _t("init.updating" if "UPDATE the existing AGENTS.md" in msg else "init.generating"))
  1219. # ---- side-session handlers: /bg, /btw -------------------------------------------------
  1220. def _handle_background_command(self, cmd: str):
  1221. """Handle /bg <prompt> — run a prompt in a separate background session (its own AIAgent
  1222. on a thread); the result prints here without touching the active history."""
  1223. prompt = _command_arg(cmd)
  1224. if not prompt:
  1225. return _cp(*_lines(_t("background.usage")))
  1226. self._background_task_counter += 1
  1227. task_num = self._background_task_counter
  1228. preview = _ellipsize(prompt, 60)
  1229. from hermes_cli import gateway_side
  1230. connection = gateway_side.connection_for(self)
  1231. if connection is not None:
  1232. # The gateway runs the side agent on this session's route (prompt.background); this
  1233. # process never builds one.
  1234. task_id, wait = gateway_side.start(connection, self.session_id, "background", prompt)
  1235. _cp(f" {_t('background.started', number=task_num, preview=preview)}",
  1236. f" {_t('background.task_id', task_id=task_id)}", f" {_t('background.keep_chatting')}\n")
  1237. return self._start_background_worker(task_id, task_num, preview, wait)
  1238. from cli import set_approval_callback, set_secret_capture_callback, set_sudo_password_callback
  1239. from run_agent import AIAgent
  1240. task_id = f"bg_{datetime.now().strftime('%H%M%S')}_{uuid.uuid4().hex[:6]}"
  1241. if not self._ensure_runtime_credentials():
  1242. return _cp(f" {_t('background.no_credentials')}")
  1243. _cp(f" {_t('background.started', number=task_num, preview=preview)}",
  1244. f" {_t('background.task_id', task_id=task_id)}", f" {_t('background.keep_chatting')}\n")
  1245. turn_route = self._resolve_turn_agent_config(prompt)
  1246. runtime = turn_route["runtime"]
  1247. def produce():
  1248. from agent.vault_backends.unlock import set_code_prompt_callback, set_save_login_prompt_callback, set_unlock_prompt_callback
  1249. from gateway.session_context import declare_stateless_channel
  1250. declare_stateless_channel() # nothing drains a bg_* session's completions later: delegations join (#140569)
  1251. set_sudo_password_callback(self._sudo_password_callback)
  1252. set_approval_callback(self._approval_callback)
  1253. set_unlock_prompt_callback(self._vault_unlock_callback)
  1254. set_save_login_prompt_callback(self._vault_save_login_callback)
  1255. set_code_prompt_callback(self._vault_code_callback)
  1256. with suppress(Exception):
  1257. set_secret_capture_callback(self._secret_capture_callback)
  1258. try:
  1259. bg_agent = AIAgent(
  1260. model=turn_route["model"], acp_command=runtime.get("command"),
  1261. acp_args=runtime.get("args"), max_iterations=self.max_turns,
  1262. **{k: runtime.get(k) for k in ("api_key", "base_url", "provider", "api_mode",
  1263. "max_tokens")}, enabled_toolsets=self.enabled_toolsets,
  1264. quiet_mode=True, verbose_logging=False, session_id=task_id, platform="cli",
  1265. side_agent=True,
  1266. session_db=self._session_db, reasoning_config=self.reasoning_config,
  1267. service_tier=self.service_tier,
  1268. request_overrides=turn_route.get("request_overrides"),
  1269. **{kw: getattr(self, attr) for kw, attr in _BG_PROVIDER_KWARGS.items()})
  1270. # Silence raw spinner; route thinking through TUI widget when no foreground agent is active.
  1271. bg_agent._print_fn = lambda *_a, **_kw: None
  1272. def _bg_thinking(text: str) -> None:
  1273. # Concurrent bg tasks may race on _spinner_text; acceptable for best-effort UI.
  1274. if not self._agent_running:
  1275. self._spinner_text = text
  1276. if self._app:
  1277. # Display result in the CLI (thread-safe via patch_stdout). Force a TUI refresh
  1278. # first so spinner/status bar don't overlap with the output (fixes #2718).
  1279. # Same TUI refresh pattern as success path (#2718)
  1280. self._app.invalidate()
  1281. bg_agent.thinking_callback = _bg_thinking
  1282. try:
  1283. result = bg_agent.run_conversation(user_message=prompt, task_id=task_id)
  1284. response = result.get("final_response", "") if result else ""
  1285. if not response and result and result.get("error"):
  1286. response = _gt("model.error_prefix", error=result["error"])
  1287. return response
  1288. finally:
  1289. # One agent per /bg task in a long-lived CLI: close() is the owner boundary (memory,
  1290. # tool subprocesses, httpx clients); unclosed, they leak until the CLI exits (#50197).
  1291. with suppress(Exception):
  1292. bg_agent.close()
  1293. finally:
  1294. with suppress(Exception):
  1295. set_sudo_password_callback(None)
  1296. set_approval_callback(None)
  1297. set_secret_capture_callback(None)
  1298. set_unlock_prompt_callback(None)
  1299. set_save_login_prompt_callback(None)
  1300. set_code_prompt_callback(None)
  1301. self._start_background_worker(task_id, task_num, preview, produce)
  1302. def _start_background_worker(self, task_id, task_num, preview, produce):
  1303. """The /bg result panel's daemon thread (``produce()`` returns the answer text)."""
  1304. def done():
  1305. self._background_tasks.pop(task_id, None)
  1306. if not self._agent_running: # clear spinner only if no foreground agent owns it
  1307. self._spinner_text = ""
  1308. thread = self._side_worker(
  1309. produce, name=f"bg-task-{task_id}", fail_label=_t("background.label", number=task_num),
  1310. header_lines=[f" {_t('background.complete', number=task_num)}",
  1311. f" {_t('background.prompt', preview=preview)}"],
  1312. title_suffix=_t("background.title_suffix", number=task_num),
  1313. empty_note=f" {_t('background.no_response')}", bell=True, on_done=done)
  1314. self._background_tasks[task_id] = thread
  1315. thread.start()
  1316. def _side_worker(self, produce, *, name, fail_label, header_lines, title_suffix, empty_note,
  1317. bell=False, on_done=None, console=None) -> threading.Thread:
  1318. """Daemon thread for /bg, /btw and /login: ``produce()`` returns the body to print in a side-result
  1319. panel; failures print ``fail_label`` failed; the TUI is always re-invalidated afterwards."""
  1320. def run():
  1321. try:
  1322. body = produce()
  1323. _print_side_result_panel(self, header_lines=header_lines, body=body,
  1324. title_suffix=title_suffix, empty_note=empty_note,
  1325. console=console)
  1326. if bell:
  1327. self._ring_bell(context=_t("side_result.complete", label=fail_label))
  1328. except Exception as e:
  1329. _refresh_tui_before_print(self)
  1330. line = f" {_t('side_result.failed', label=fail_label, error=e)}"
  1331. # Same console the caller captured, so a late failure can't splice into a later command.
  1332. if console is not None:
  1333. console.print(line, markup=False)
  1334. else:
  1335. _cp(line)
  1336. finally:
  1337. if on_done is not None:
  1338. on_done()
  1339. if self._app:
  1340. self._invalidate(min_interval=0)
  1341. return threading.Thread(target=run, daemon=True, name=name)
  1342. def _handle_login_command(self, cmd_original: str) -> None:
  1343. """Start an in-chat sign-in without blocking the input loop while approval is pending."""
  1344. from hermes_cli import anon_auth
  1345. # Pin the output target now. Under the live TUI ``self.console`` writes straight to
  1346. # patch_stdout's StdoutProxy, which mangles Rich's escapes — there ``None`` keeps the
  1347. # panel on the ``_cprint`` path. Only the slash worker (``_app`` is None) swaps the console.
  1348. console = None if getattr(self, "_app", None) else getattr(self, "console", None)
  1349. _cp(f" {anon_auth.LOGIN_STARTING}")
  1350. gen = anon_auth.run_sign_in(timeout_seconds=8.0)
  1351. try:
  1352. first = next(gen, None)
  1353. except KeyboardInterrupt:
  1354. with suppress(Exception):
  1355. gen.close()
  1356. return _cp(anon_auth.UPGRADE_CANCELLED)
  1357. if first is None:
  1358. return
  1359. if first.terminal:
  1360. return _cp(f" {first.copy}")
  1361. anon_auth.render_sign_in_cli_code(first, chat=True, printer=_cp)
  1362. def _settle_session_model(state) -> None:
  1363. """A completed sign-in moved this profile onto the account: the welcome host is gone and
  1364. the portal serves ``nous/welcome`` as a paid model, so a session still carrying it must
  1365. move too — the CLI counterpart of the gateway's on-``Completed`` sweep. Only the free
  1366. tier's own model is replaced; a model the user picked while the sign-in was pending
  1367. stands. Writing ``self.model`` is enough: ``chat()`` compares the turn-route signature
  1368. and rebuilds the agent on the next turn, so a turn already in flight keeps the agent it
  1369. started with. ``getattr``: tests drive this handler with minimal shells.
  1370. """
  1371. if state.kind != "completed" or not getattr(state, "model_changed", False):
  1372. return
  1373. if str(getattr(self, "model", "") or "") == anon_auth.GUEST_MODEL:
  1374. # "" when the settle cleared the default: _ensure_runtime_credentials then applies
  1375. # the provider's silent default, which is what settle_after_upgrade documents.
  1376. self.model = state.model or ""
  1377. thread = self._side_worker(
  1378. lambda: anon_auth.drain_sign_in_copy(gen, chat=True, on_terminal=_settle_session_model),
  1379. name="login", fail_label=_t("login.label"), header_lines=[f" {_t('login.label')}"],
  1380. title_suffix=_t("login.title_suffix"), empty_note=f" {_t('login.no_result')}", console=console)
  1381. thread.start()
  1382. def _handle_btw_command(self, cmd: str):
  1383. """Handle /btw <question> — answer a side question about this conversation from a
  1384. history snapshot via a one-shot auxiliary call. The live session is never touched
  1385. (no history mutation, no role-alternation risk, no cache invalidation)."""
  1386. question = _command_arg(cmd)
  1387. if not question:
  1388. return _cp(*_lines(_t("btw.usage")))
  1389. from hermes_cli import gateway_side
  1390. connection = gateway_side.connection_for(self)
  1391. if connection is not None:
  1392. # The gateway answers from its own copy of the conversation (prompt.btw): the live
  1393. # agent's fork when it has one, else the stored transcript.
  1394. _task_id, wait = gateway_side.start(connection, self.session_id, "btw", question)
  1395. preview = _ellipsize(question, 60)
  1396. _cp(*_lines(_gt("btw.started", preview=preview)), "")
  1397. self._side_worker(wait, name="btw-side-question", fail_label="/btw",
  1398. header_lines=[f" {_t('btw.header', preview=preview)}"],
  1399. title_suffix=_t("btw.title_suffix"),
  1400. empty_note=f" {_t('btw.no_answer')}").start()
  1401. return
  1402. if not self._ensure_runtime_credentials():
  1403. return _cp(f" {_t('btw.no_credentials')}")
  1404. # Snapshot NOW, on the UI thread — the foreground turn keeps appending to
  1405. # conversation_history while the worker runs.
  1406. history_snapshot = list(self.conversation_history or [])
  1407. # Live agent → cache-parity fork (full context, warm cache reads).
  1408. parent_agent = self.agent
  1409. turn_route = self._resolve_turn_agent_config(question)
  1410. runtime = turn_route["runtime"]
  1411. main_runtime = {
  1412. "model": turn_route["model"],
  1413. **{k: runtime.get(k) for k in ("provider", "base_url", "api_key", "api_mode")},
  1414. "session_id": getattr(parent_agent, "session_id", None),
  1415. }
  1416. preview = _ellipsize(question, 60)
  1417. _cp(*_lines(_gt("btw.started", preview=preview)), "")
  1418. def produce():
  1419. from agent.side_question import answer_side_question
  1420. return answer_side_question(
  1421. question, history_snapshot, parent_agent=parent_agent, main_runtime=main_runtime)
  1422. self._side_worker(produce, name="btw-side-question", fail_label="/btw",
  1423. header_lines=[f" {_t('btw.header', preview=preview)}"],
  1424. title_suffix=_t("btw.title_suffix"),
  1425. empty_note=f" {_t('btw.no_answer')}").start()
  1426. # ---- /bundles, /browser ---------------------------------------------------------------
  1427. def _handle_bundles_command(self, cmd: str) -> None:
  1428. """In-session ``/bundles`` — show installed skill bundles (``hermes bundles list`` rendered
  1429. inside the running CLI). Bundles are loaded via ``/<bundle-name>``."""
  1430. from cli import ChatConsole, _BOLD, _RST, _accent_hex
  1431. from hermes_cli.slash_exec import CommandContext, execute_command
  1432. reply = execute_command("bundles", CommandContext(surface="cli"))
  1433. if "error" in reply.data:
  1434. return _cp(f"\033[1;31m{_t('bundles.unavailable', error=reply.data['error'])}{_RST}")
  1435. bundles = reply.data["bundles"]
  1436. if not bundles:
  1437. return _cp(f" {_t('bundles.none_installed')}", _dim_line(_t("bundles.create_hint")),
  1438. _dim_line(_t("bundles.directory", dir=reply.data["dir"])))
  1439. _cp(f"\n ▣ {_BOLD}{_t('bundles.title')}{_RST} {_t('bundles.installed_count', count=len(bundles))}")
  1440. for info in bundles:
  1441. skill_count = len(info.get("skills", []))
  1442. desc = info.get("description") or _t("bundles.default_desc", count=skill_count)
  1443. ChatConsole().print(
  1444. f" [bold {_accent_hex()}]/{info['slug']:<20}[/] "
  1445. f"[dim]-[/] {_escape(desc)} [dim]{_escape(_t('bundles.skills_count', count=skill_count))}[/]")
  1446. for s in info.get("skills", []):
  1447. ChatConsole().print(f" [dim]· {_escape(s)}[/]")
  1448. _cp("\n" + _dim_line(_t("bundles.invoke_hint")))
  1449. def _handle_browser_command(self, cmd: str):
  1450. """Handle /browser connect|disconnect|status — manage the live Chromium-family CDP connection."""
  1451. # The subcommand word is matched case-insensitively; the raw argument keeps
  1452. # its case because a CDP URL's path segment is case-sensitive.
  1453. parts = _command_arg(cmd).split(None, 1)
  1454. word = parts[0].lower() if parts else "status"
  1455. rest = parts[1].strip() if len(parts) > 1 else ""
  1456. handler = _BROWSER_SUBCOMMANDS.get(word)
  1457. if handler is None:
  1458. _say_block(
  1459. _t("browser.usage"), "",
  1460. *(f" {_t(f'browser.usage_{sub}')}" for sub in ("connect", "disconnect", "status")))
  1461. return
  1462. from hermes_cli.gateway_side import connection_for
  1463. if (connection := connection_for(self)) is not None:
  1464. from hermes_cli.cli_browser_gateway import gateway_browser
  1465. return gateway_browser(self, connection, word, rest.strip())
  1466. handler(self, rest.strip())
  1467. # ---- /heartbeat, /refine, /review -----------------------------------------------------
  1468. def _session_manager(self, getter, label: str):
  1469. """The session-scoped manager from ``getter()``, or None after the standard dim
  1470. "<label> unavailable (no active session)." line."""
  1471. mgr = getter()
  1472. if mgr is None:
  1473. _cp(_dim_line(_t("shared.unavailable_no_session", label=label)))
  1474. return mgr
  1475. def _handle_heartbeat_command(self, cmd: str) -> None:
  1476. """Dispatch /heartbeat: set / status / pause / resume / clear. ``/heartbeat every 10m <prompt>``
  1477. sets the session's one recurring instruction, injected as a normal user turn when due.
  1478. Session-scoped and in-process — use `hermes cron` for durable schedules."""
  1479. from hermes_cli.heartbeat import format_interval
  1480. arg = _command_arg(cmd)
  1481. lower = arg.lower()
  1482. mgr = self._session_manager(self._get_heartbeat_manager, _t("heartbeat.label"))
  1483. if mgr is None:
  1484. return
  1485. if not arg or lower == "status":
  1486. _cp(f" {mgr.status_line()}")
  1487. elif lower == "pause":
  1488. state = mgr.pause()
  1489. _cp(f" {_t('heartbeat.paused', prompt=state.prompt)}" if state
  1490. else _dim_line(_t("heartbeat.none_set")))
  1491. elif lower == "resume":
  1492. state = mgr.resume()
  1493. if state is None:
  1494. _cp(_dim_line(_t("heartbeat.none_to_resume")))
  1495. else:
  1496. self._start_heartbeat_watchdog()
  1497. _cp(f" {_t('heartbeat.resumed', interval=format_interval(state.interval_seconds), prompt=state.prompt)}")
  1498. elif lower in {"clear", "stop", "off"}:
  1499. _cp(f" {_t('heartbeat.cleared')}" if mgr.clear() else _dim_line(_t("heartbeat.none_set")))
  1500. else:
  1501. self._heartbeat_set(mgr, arg)
  1502. def _heartbeat_set(self, mgr, arg: str) -> None:
  1503. """Set: ``/heartbeat every 10m <prompt>`` (also accepts ``10m <prompt>``)."""
  1504. from hermes_cli.heartbeat import parse_interval, format_interval
  1505. tokens = arg.split(None, 2)
  1506. interval = None
  1507. prompt = ""
  1508. if tokens and tokens[0].lower() == "every" and len(tokens) >= 2:
  1509. interval = parse_interval(f"every {tokens[1]}")
  1510. prompt = tokens[2] if len(tokens) > 2 else ""
  1511. elif tokens:
  1512. interval = parse_interval(tokens[0])
  1513. prompt = arg[len(tokens[0]):].strip() if interval and interval > 0 else ""
  1514. if interval is None:
  1515. return _cp(f" {_t('heartbeat.usage')}", _dim_line(_t("heartbeat.usage_also")))
  1516. if interval < 0:
  1517. from hermes_cli.heartbeat import MIN_INTERVAL_SECONDS
  1518. return _cp(f" {_t('heartbeat.interval_too_small', min_seconds=MIN_INTERVAL_SECONDS)}")
  1519. if not prompt.strip():
  1520. return _cp(f" {_t('heartbeat.prompt_required')}")
  1521. state = _attempt(_t("heartbeat.invalid_label"), ValueError, mgr.set, prompt, interval)
  1522. if state is _FAILED:
  1523. return
  1524. self._start_heartbeat_watchdog()
  1525. _cp(f" {_t('heartbeat.set', interval=format_interval(state.interval_seconds), prompt=state.prompt)}",
  1526. _dim_line(_t("heartbeat.set_note")))
  1527. def _handle_refine_command(self, cmd: str) -> None:
  1528. """Dispatch /refine — run the memory/skill review fork on demand (same machinery as the
  1529. automatic post-turn ``_spawn_background_review``), with optional focus text. Background
  1530. fork; the live conversation and prompt cache are never touched."""
  1531. focus = _command_arg(cmd)
  1532. agent = getattr(self, "agent", None)
  1533. if agent is None:
  1534. return _cp(_dim_line(_t("refine.nothing_yet")))
  1535. snapshot = list(getattr(self, "conversation_history", None) or [])
  1536. if not snapshot:
  1537. return _cp(_dim_line(_t("refine.empty")))
  1538. try:
  1539. agent._spawn_background_review(
  1540. messages_snapshot=snapshot, review_memory=True,
  1541. review_skills="skill_manage" in getattr(agent, "valid_tool_names", set()),
  1542. focus=focus or None, explicit=True)
  1543. except Exception as exc:
  1544. return _cp(f" {_t('refine.failed', error=exc)}")
  1545. tail = _t("refine.focus_suffix", focus=focus) if focus else ""
  1546. _cp(f" {_t('refine.started', focus=tail)}")
  1547. def _handle_review_command(self, cmd: str) -> None:
  1548. """Dispatch /review — snapshot the last N messages (+ argument text as instructions) and
  1549. spawn an independent reviewer subagent via async delegation; the review re-enters this
  1550. session as a normal delegation completion."""
  1551. prompt = _command_arg(cmd)
  1552. agent = getattr(self, "agent", None)
  1553. if agent is None:
  1554. return _cp(_dim_line(_t("review.nothing_yet")))
  1555. snapshot = list(getattr(self, "conversation_history", None) or [])
  1556. try:
  1557. from agent.review_engine import format_dispatch_note, start_review
  1558. result = start_review(agent, snapshot, prompt)
  1559. except ValueError as exc:
  1560. return _cp(_dim_line(str(exc)))
  1561. except Exception as exc:
  1562. return _cp(f" {_t('review.failed', error=exc)}")
  1563. _cp(f" {format_dispatch_note(result, prompt)}")
  1564. # ---- /goal, /loop, /subgoal -----------------------------------------------------------
  1565. def _handle_goal_command(self, cmd: str) -> None:
  1566. from hermes_cli.gateway_automation import dispatch_goal_command # /goal draft drafts on the gateway
  1567. from hermes_cli.goals import last_user_message_content
  1568. mgr = self._session_manager(self._get_goal_manager, _t("goal.label"))
  1569. if mgr is None:
  1570. return
  1571. result = dispatch_goal_command(
  1572. mgr, _command_arg(cmd), authorize_gate=lambda: None,
  1573. progress=lambda text: _cp(_dim_line(text)),
  1574. last_user_message=last_user_message_content(getattr(self, "conversation_history", None)),
  1575. )
  1576. for line in result.output.splitlines():
  1577. _cp(f" {line}")
  1578. if result.prompt:
  1579. queued = self._kick_goal(result.prompt)
  1580. if not result.kickoff:
  1581. _cp(_dim_line(_t("goal.continuing") if queued else _t("goal.send_to_kick")))
  1582. def _kick_goal(self, prompt: str) -> bool:
  1583. """Queue the next turn without mutating cached conversation history."""
  1584. try:
  1585. self._pending_input.put(prompt)
  1586. return True
  1587. except Exception:
  1588. return False
  1589. def _handle_loop_command(self, cmd: str) -> None:
  1590. """Dispatch /loop — recurring in-session wakeups: ``/loop [interval] <prompt> [--times N]
  1591. [--until <cond>]`` starts one; ``status | pause | resume | stop`` control it."""
  1592. arg = _command_arg(cmd)
  1593. mgr = self._session_manager(self._get_loop_manager, _t("loop.label"))
  1594. if mgr is None:
  1595. return
  1596. from hermes_cli.loops import dispatch_loop_command
  1597. result = dispatch_loop_command(mgr, arg)
  1598. for line in (result.get("output") or "").splitlines():
  1599. _cp(f" {line}")
  1600. if result.get("created"):
  1601. with suppress(Exception):
  1602. from hermes_cli.cli_loops_mixin import _goal_blocks_loop_tick
  1603. if _goal_blocks_loop_tick(mgr):
  1604. _cp(_dim_line(_t("loop.goal_defers_note")))
  1605. def _handle_subgoal_command(self, cmd: str) -> None:
  1606. """Dispatch /subgoal: bare → show, ``<text>`` → append, ``remove <n>`` (1-based), ``clear``.
  1607. Subgoals join the judge + continuation prompts at the next turn boundary (no kick)."""
  1608. parts = (cmd or "").strip().split(None, 2)
  1609. arg = " ".join(parts[1:]).strip() if len(parts) > 1 else ""
  1610. mgr = self._session_manager(self._get_goal_manager, _t("goal.label"))
  1611. if mgr is None:
  1612. return
  1613. if not mgr.has_goal():
  1614. return _cp(_dim_line(_t("subgoal.no_goal")))
  1615. if not arg: # list current subgoals
  1616. _cp(f" {mgr.status_line()}")
  1617. return _cp(f" {mgr.render_subgoals()}")
  1618. tokens = arg.split(None, 1)
  1619. verb = tokens[0].lower()
  1620. rest = tokens[1].strip() if len(tokens) > 1 else ""
  1621. if verb == "remove":
  1622. if not rest:
  1623. return _cp(f" {_t('subgoal.usage_remove')}")
  1624. try:
  1625. idx = int(rest.split()[0])
  1626. except ValueError:
  1627. return _cp(f" {_t('subgoal.remove_needs_int')}")
  1628. removed = _attempt("/subgoal remove", (IndexError, RuntimeError), mgr.remove_subgoal, idx)
  1629. if removed is not _FAILED:
  1630. _cp(f" {_t('subgoal.removed', index=idx, text=removed)}")
  1631. elif verb == "clear":
  1632. prev = _attempt("/subgoal clear", RuntimeError, mgr.clear_subgoals)
  1633. if prev is not _FAILED:
  1634. _cp(" " + _tn("subgoal.cleared", prev) if prev else _dim_line(_t("subgoal.none_to_clear")))
  1635. else: # append the whole arg as a new subgoal
  1636. text = _attempt("/subgoal", (ValueError, RuntimeError), mgr.add_subgoal, arg)
  1637. if text is not _FAILED:
  1638. idx = len(mgr.state.subgoals) if mgr.state else 0
  1639. _cp(f" {_t('subgoal.added', index=idx, text=text)}")
  1640. # ---- /skin, /prompt -------------------------------------------------------------------
  1641. def _handle_skin_command(self, cmd: str):
  1642. """Handle /skin [name] — show or change the display skin."""
  1643. from cli import _ACCENT
  1644. try:
  1645. from hermes_cli.skin_engine import list_skins, set_active_skin, get_active_skin_name
  1646. except ImportError:
  1647. return print(_t("skin.unavailable"))
  1648. new_skin = _command_arg(cmd).lower()
  1649. if not new_skin: # show current skin and list available
  1650. current = get_active_skin_name()
  1651. _pr(f"\n {_t('skin.current', name=current)}", f" {_t('skin.available_header')}")
  1652. for s in list_skins():
  1653. marker = " ●" if s["name"] == current else " "
  1654. source = f" ({s['source']})" if s["source"] == "user" else ""
  1655. print(f" {marker} {s['name']}{source} — {s['description']}")
  1656. return _pr(f"\n {_t('skin.usage')}",
  1657. f" {_t('skin.custom_hint', dir=display_hermes_home())}\n")
  1658. available = {s["name"] for s in list_skins()}
  1659. if new_skin not in available:
  1660. return _pr(f" {_t('skin.unknown', name=new_skin)}",
  1661. f" {_t('skin.available', names=', '.join(sorted(available)))}")
  1662. set_active_skin(new_skin)
  1663. _ACCENT.reset() # re-resolve ANSI color for the new skin (_DIM is a fixed escape)
  1664. saved = _t("skin.saved_suffix") if _save("display.skin", new_skin) else ""
  1665. _pr(f" {_t('skin.set_to', name=new_skin, saved=saved)}", f" {_t('skin.banner_note')}")
  1666. if self._apply_tui_skin_style():
  1667. print(f" {_t('skin.colors_updated')}")
  1668. def _compose_in_editor(self, initial_text: str = "") -> str:
  1669. """Open ``$VISUAL``/``$EDITOR`` on a temp markdown file and return the saved buffer with
  1670. ``#!`` comment lines stripped; "" if the editor failed or the buffer was left empty.
  1671. Factored out so the read-back/strip logic is unit-testable."""
  1672. editor = (os.environ.get("VISUAL") or os.environ.get("EDITOR")
  1673. or ("notepad" if os.name == "nt" else "nano"))
  1674. fd, path = tempfile.mkstemp(suffix=".md", prefix="hermes_prompt_")
  1675. try:
  1676. with os.fdopen(fd, "w", encoding="utf-8") as fh:
  1677. fh.write(_t("prompt_compose.editor_header") + "\n\n")
  1678. if initial_text:
  1679. fh.write(initial_text)
  1680. try:
  1681. editor_argv = [*shlex.split(editor), path]
  1682. except ValueError:
  1683. return "" # unbalanced quotes in $EDITOR: cancel, never retry through a shell
  1684. try:
  1685. status = subprocess.call(editor_argv)
  1686. except OSError:
  1687. return "" # editor not runnable: cancel the compose (#81364)
  1688. # A failed editor may leave seeded or abandoned text in the buffer.
  1689. if status != 0:
  1690. return ""
  1691. with open(path, "r", encoding="utf-8-sig") as fh:
  1692. raw = fh.read()
  1693. finally:
  1694. with suppress(OSError):
  1695. os.unlink(path)
  1696. return "\n".join(ln for ln in raw.splitlines() if not ln.startswith("#!")).strip()
  1697. def _handle_prompt_compose_command(self, cmd_original: str) -> None:
  1698. """Handle /prompt — compose the next prompt in $EDITOR (optionally seeded with the argument)
  1699. and queue it as the next agent turn via the one-shot ``_pending_agent_seed`` (as /blueprint)."""
  1700. parts = (cmd_original or "").strip().split(None, 1)
  1701. try:
  1702. composed = self._compose_in_editor(parts[1] if len(parts) > 1 else "")
  1703. except Exception as exc:
  1704. return _cp(_dim_line(_t("prompt_compose.editor_failed", error=exc)))
  1705. if not composed:
  1706. return _cp(_dim_line(_t("prompt_compose.empty")))
  1707. # One-shot seed: the interactive loop runs this as the next agent turn right after
  1708. # process_command() returns (see cli.py main loop).
  1709. self._pending_agent_seed = composed
  1710. # ---- /focus and its display hooks -----------------------------------------------------
  1711. def _handle_focus_command(self, cmd_original: str) -> None:
  1712. """``/focus [on|off|status]`` — DISPLAY-ONLY reduced output. Reuses the ``/verbose``
  1713. suppression path: on stashes tool_progress_mode and snaps it to "off" (what
  1714. ``agent/tool_executor.py`` gates on); off restores the stash verbatim. Never touches
  1715. history, system prompt, or request payloads."""
  1716. from hermes_cli.colors import Colors as _Colors
  1717. from hermes_cli.focus_view import (
  1718. FOCUS_CONFIG_KEY, FOCUS_TOOL_PROGRESS_MODE, format_focus_status,
  1719. format_focus_toggle_message, normalize_tool_progress_mode, resolve_focus_arg)
  1720. current = bool(getattr(self, "_focus_view_enabled", False))
  1721. action, target = resolve_focus_arg(_command_arg(cmd_original), current)
  1722. if action == "usage":
  1723. return _cp(f" {_t('focus.usage')}")
  1724. # The mode /focus off restores: while focus is ON the live mode is "off", so use the stash.
  1725. restore_mode = normalize_tool_progress_mode(
  1726. getattr(self, "_focus_saved_tool_progress", None) if current
  1727. else getattr(self, "tool_progress_mode", "all"))
  1728. if action == "status":
  1729. head, _, tail = format_focus_status(current, restore_mode).partition("\n")
  1730. label, _, rest = head.partition(":")
  1731. state_color = _Colors.GREEN if current else _Colors.DIM
  1732. return _cp(f" {_Colors.BOLD}{label}:{_Colors.RESET}{state_color}{rest}{_Colors.RESET}"
  1733. + (f"\n{_Colors.DIM} {tail.strip()}{_Colors.RESET}" if tail else ""))
  1734. if target == current: # idempotent explicit set — report without rewriting config
  1735. return _cp(f" {format_focus_toggle_message(current, restore_mode)}")
  1736. if target:
  1737. # Stash the user's configured mode, then reuse the EXISTING suppression path by
  1738. # snapping to "off".
  1739. self._focus_saved_tool_progress = restore_mode
  1740. self._set_tool_progress_mode(FOCUS_TOOL_PROGRESS_MODE)
  1741. else:
  1742. self._set_tool_progress_mode(restore_mode)
  1743. self._focus_saved_tool_progress = None
  1744. self._focus_view_enabled = bool(target)
  1745. self._focus_hidden_lines = 0
  1746. _save(FOCUS_CONFIG_KEY, bool(target))
  1747. message = format_focus_toggle_message(bool(target), restore_mode)
  1748. # Re-colour just the enabled/disabled word so the line matches siblings.
  1749. for word in ("enabled", "disabled"):
  1750. if word in message:
  1751. colour = _Colors.GREEN if target else _Colors.DIM
  1752. message = message.replace(word, f"{colour}{word}{_Colors.RESET}", 1)
  1753. break
  1754. _cp(f" {message}")
  1755. def _set_tool_progress_mode(self, mode: str) -> None:
  1756. """Set the live tool-progress mode on both the CLI and the agent (one write path for
  1757. /focus and /verbose — the agent copy is what ``agent/tool_executor.py`` gates on)."""
  1758. from hermes_cli.focus_view import normalize_tool_progress_mode
  1759. normalized = normalize_tool_progress_mode(mode)
  1760. self.tool_progress_mode = normalized
  1761. agent = getattr(self, "agent", None)
  1762. if agent is not None:
  1763. with suppress(Exception):
  1764. agent.tool_progress_mode = normalized
  1765. def _note_focus_hidden_line(self, function_name: str) -> None:
  1766. """Count one tool line focus view is suppressing this turn — against the mode the user had
  1767. BEFORE focus snapped to "off", so a prior ``/verbose off`` user is never told focus hid lines."""
  1768. if not getattr(self, "_focus_view_enabled", False):
  1769. return
  1770. from hermes_cli.focus_view import would_display_tool_line
  1771. saved = getattr(self, "_focus_saved_tool_progress", None)
  1772. last = getattr(self, "_focus_last_counted_tool", None)
  1773. if not would_display_tool_line(saved, function_name, last):
  1774. return
  1775. self._focus_last_counted_tool = function_name
  1776. self._focus_hidden_lines = int(getattr(self, "_focus_hidden_lines", 0)) + 1
  1777. def _emit_focus_recovery_line(self) -> None:
  1778. """Print the dim post-turn recovery line and reset the counter."""
  1779. count = int(getattr(self, "_focus_hidden_lines", 0) or 0)
  1780. self._focus_hidden_lines = 0
  1781. self._focus_last_counted_tool = None
  1782. if not getattr(self, "_focus_view_enabled", False):
  1783. return
  1784. from hermes_cli.focus_view import format_hidden_line
  1785. line = format_hidden_line(count)
  1786. if line:
  1787. with suppress(Exception):
  1788. _cp(_dim_line(line))
  1789. # ---- persisted display toggles: /approvals, /footer, /timestamps ----------------------
  1790. def _handle_approvals_command(self, cmd_original: str) -> None:
  1791. """Show or persist the profile-wide dangerous-command approval mode."""
  1792. from hermes_cli.approval_mode import run_approval_mode_command
  1793. parts = (cmd_original or "").strip().split(None, 1)
  1794. result = run_approval_mode_command(parts[1] if len(parts) > 1 else None)
  1795. _cp(f" {result.message}")
  1796. def _toggle_setting(self, arg: str, current: bool, *, usage: str, status_line: str,
  1797. config_key: str, label: str, failed: str):
  1798. """Shared /footer + /timestamps flow: status query, usage error, or save + report.
  1799. Returns the new bool state when it was saved (None otherwise)."""
  1800. from hermes_cli.colors import Colors as _Colors
  1801. new_state = _toggle_target(arg, current)
  1802. if new_state == "status":
  1803. state = _t("shared.state_on") if current else _t("shared.state_off")
  1804. return _cp(f" {_Colors.BOLD}{label}:{_Colors.RESET} {state}{status_line}")
  1805. if new_state is None:
  1806. return _cp(f" {_t('shared.usage', usage=usage)}")
  1807. if _save(config_key, new_state):
  1808. colour = _Colors.GREEN if new_state else _Colors.DIM
  1809. state = _t("shared.state_on") if new_state else _t("shared.state_off")
  1810. _cp(f" {label}: {colour}{state}{_Colors.RESET}")
  1811. else:
  1812. _cp(f" {_t('toggle.save_failed', setting=failed)}")
  1813. return new_state
  1814. def _handle_footer_command(self, cmd_original: str) -> None:
  1815. """Toggle or inspect ``display.runtime_footer.enabled`` (``/footer [on|off|status]``)."""
  1816. from hermes_cli.config import load_config
  1817. footer_cfg = (((load_config() or {}).get("display") or {}).get("runtime_footer") or {})
  1818. fields = footer_cfg.get("fields") or ["model", "context_pct", "cwd"]
  1819. self._toggle_setting(
  1820. _command_arg(cmd_original, lower=True), bool(footer_cfg.get("enabled", False)),
  1821. usage=_t("footer.usage"), status_line=f"\n {_t('footer.fields', fields=', '.join(fields))}",
  1822. config_key="display.runtime_footer.enabled", label=_t("footer.label"), failed="runtime_footer",
  1823. )
  1824. def _handle_timestamps_command(self, cmd_original: str) -> None:
  1825. """Toggle or inspect ``display.timestamps`` (``/timestamps [on|off|status]``). When on,
  1826. message labels carry an ``[HH:MM]`` suffix and ``/history`` prefixes stored-timestamp turns."""
  1827. arg = _command_arg(cmd_original, lower=True)
  1828. current = bool(getattr(self, "show_timestamps", False))
  1829. new_state = _toggle_target(arg, current)
  1830. if isinstance(new_state, bool):
  1831. self.show_timestamps = new_state
  1832. self._toggle_setting(
  1833. arg, current, usage=_t("timestamps.usage"), status_line="",
  1834. config_key="display.timestamps", label=_t("timestamps.label"), failed="timestamps")
  1835. # ---- model-behaviour settings: /reasoning, /busy, /indicator, /fast -------------------
  1836. def _handle_reasoning_command(self, cmd: str):
  1837. """Handle /reasoning [<level> [--global]|show|hide|full|clamp] — effort level (session
  1838. scope unless --global) and thinking display toggles (always saved)."""
  1839. from cli import CLI_CONFIG, _parse_reasoning_config
  1840. from agent.reasoning_effort import effort_display_label
  1841. raw = _command_arg(cmd)
  1842. from hermes_cli.codex_runtime_switch import get_current_runtime
  1843. # The live agent's api_mode, else the configured runtime: ``ultra`` is verbatim on the Codex app-server.
  1844. _route = (getattr(self, "provider", None), getattr(self, "model", None),
  1845. getattr(getattr(self, "agent", None), "api_mode", None) or get_current_runtime(CLI_CONFIG))
  1846. if not raw: # show current state
  1847. rc = self.reasoning_config
  1848. level = (_gt("reasoning.level_default") if rc is None else _gt("reasoning.level_disabled")
  1849. if rc.get("enabled") is False else effort_display_label(rc.get("effort", "medium"), *_route))
  1850. display_state = _t("reasoning.display_on") if self.show_reasoning else _t("reasoning.display_off")
  1851. full_state = (_t("reasoning.full_state_full") if getattr(self, "reasoning_full", False)
  1852. else _t("reasoning.full_state_clamped"))
  1853. return _cp(_accent_line(_t("reasoning.effort_line", level=level)),
  1854. _accent_line(_t("reasoning.display_line", display=display_state, full=full_state)),
  1855. _dim_line(_t("reasoning.usage")))
  1856. arg, explicit_global = _split_scope_flags(raw)
  1857. toggle = _REASONING_TOGGLES.get(arg)
  1858. if toggle is not None: # display show/hide or full/clamp recap toggle
  1859. attr, value, headline_key, note_key = toggle
  1860. setattr(self, attr, value)
  1861. if attr == "show_reasoning" and self.agent:
  1862. self.agent.reasoning_callback = self._current_reasoning_callback()
  1863. _save("display.platforms.cli.show_reasoning" if attr == "show_reasoning" else f"display.{attr}", value) # T7
  1864. _cp(_accent_line(_t("reasoning.display_saved", headline=_t(f"reasoning.{headline_key}"))))
  1865. if note_key:
  1866. _cp(_dim_line(f" {_t(f'reasoning.{note_key}')}"))
  1867. if attr == "reasoning_full" and value and not self.show_reasoning:
  1868. _cp(_dim_line(f" {_t('reasoning.display_off_note')}"))
  1869. return
  1870. # Effort level change
  1871. parsed = _parse_reasoning_config(arg)
  1872. if parsed is None:
  1873. return _cp(_dim_line(_t("shared.unknown_argument", arg=arg)),
  1874. _dim_line(_t("reasoning.valid_levels")), _dim_line(_t("reasoning.valid_display")),
  1875. _dim_line(_t("reasoning.valid_scope")))
  1876. self.reasoning_config = parsed
  1877. self._reasoning_user_set = True # the rebuilt gateway agent commits it to the session
  1878. _retire_agent(self) # Force agent re-init with new reasoning config
  1879. saved = explicit_global and _save("agent.reasoning_effort", arg)
  1880. if saved:
  1881. if not isinstance(CLI_CONFIG.get("agent"), dict):
  1882. CLI_CONFIG["agent"] = {}
  1883. CLI_CONFIG["agent"]["reasoning_effort"] = arg
  1884. _cp(_accent_line(_t("reasoning.effort_set", effort=effort_display_label(arg, *_route),
  1885. scope=_scope_outcome(explicit_global, saved))))
  1886. def _handle_busy_command(self, cmd: str):
  1887. """Handle /busy [status|queue|steer|interrupt] — what Enter does while Hermes is working."""
  1888. arg = _command_arg(cmd, lower=True)
  1889. usage = _dim_line(_t("busy.usage"))
  1890. if not arg or arg == "status":
  1891. mode = self.busy_input_mode if self.busy_input_mode in _BUSY_MODES else "interrupt"
  1892. return _cp(_accent_line(_t("busy.status", mode=self.busy_input_mode)),
  1893. _dim_line(_t("busy.enter_while_busy", behavior=_t(f"busy.short_{mode}"))), usage)
  1894. if arg not in _BUSY_MODES:
  1895. return _cp(_dim_line(_t("shared.unknown_argument", arg=arg)), usage)
  1896. self.busy_input_mode = arg
  1897. _persist_display_choice("display.busy_input_mode", arg, _t("busy.label"), _t(f"busy.long_{arg}"))
  1898. def _handle_indicator_command(self, cmd: str):
  1899. """Handle /indicator [status|kaomoji|emoji|unicode|ascii] — pick the TUI busy-indicator style.
  1900. Persists to ``display.tui_status_indicator`` (the key the TUI reads) for its next render."""
  1901. from hermes_constants import DEFAULT_INDICATOR_STYLE, INDICATOR_STYLES
  1902. current = (self.config.get("display") or {}).get("tui_status_indicator", DEFAULT_INDICATOR_STYLE)
  1903. arg = _command_arg(cmd, lower=True)
  1904. usage = _dim_line(_t("indicator.usage", styles="|".join(INDICATOR_STYLES)))
  1905. if not arg or arg == "status":
  1906. return _cp(_accent_line(_t("indicator.status", style=current)), usage)
  1907. if arg not in INDICATOR_STYLES:
  1908. return _cp(_dim_line(_t("indicator.unknown_style", arg=arg)), usage)
  1909. self.config.setdefault("display", {})["tui_status_indicator"] = arg
  1910. _persist_display_choice("display.tui_status_indicator", arg, _t("indicator.label"), _t("indicator.note"))
  1911. def _handle_fast_command(self, cmd: str):
  1912. """Handle /fast — toggle fast mode (OpenAI Priority Processing / Anthropic Fast Mode).
  1913. Session-scoped by default; ``--global`` persists agent.service_tier to config.yaml
  1914. (parity with /model and /reasoning)."""
  1915. if not self._fast_command_available():
  1916. return _cp(f" {_t('fast.not_supported')}")
  1917. # Determine the branding for the current model
  1918. model = getattr(getattr(self, "agent", None), "model", None) or getattr(self, "model", None)
  1919. anthropic = _probe("hermes_cli.models", "_is_anthropic_fast_model", None, model)
  1920. feature_name = _t("fast.feature_generic" if anthropic is None
  1921. else "fast.feature_anthropic" if anthropic else "fast.feature_openai")
  1922. raw = _command_arg(cmd)
  1923. usage = _dim_line(_t("fast.usage"))
  1924. if not raw or raw.lower() == "status":
  1925. from agent.fast_mode import service_tier_word
  1926. status = service_tier_word(self.service_tier)
  1927. return _cp(_accent_line(_t("fast.status", feature=feature_name, status=status)), usage)
  1928. arg, explicit_global = _split_scope_flags(raw)
  1929. if arg not in _FAST_TIERS:
  1930. return _cp(_dim_line(_t("shared.unknown_argument", arg=arg)), usage)
  1931. if _FAST_TIERS[arg][0] == "ultrafast":
  1932. if not _probe("agent.codex_service_tiers", "ultrafast_offered_for", False, self, model):
  1933. return _cp(_dim_line(_t("fast.ultrafast_not_supported", model=model or "?")), usage)
  1934. feature_name = _t("fast.feature_ultrafast")
  1935. self.service_tier, saved_value = _FAST_TIERS[arg]
  1936. _retire_agent(self) # Force agent re-init with new service-tier config
  1937. saved = explicit_global and _save("agent.service_tier", saved_value)
  1938. outcome = _scope_outcome(explicit_global, saved)
  1939. _cp(_accent_line(_t("fast.set_to", feature=feature_name, value=saved_value.upper(), scope=outcome)))
  1940. # ---- /debug, /update, /voice, /wake ---------------------------------------------------
  1941. def _handle_debug_command(self, cmd_original: str = ""):
  1942. """Handle /debug [nous|local] — upload debug report + logs and print share URLs.
  1943. Default: public paste service; ``nous``: Nous-internal (staff-only); ``local``: render to
  1944. stdout, no upload. ``local`` wins if both are given (never touches the network)."""
  1945. from hermes_cli.debug import run_debug_share
  1946. from types import SimpleNamespace
  1947. words = {w.lower() for w in cmd_original.split()[1:]}
  1948. local = "local" in words
  1949. # Typing /debug is the upload consent (yes=True); input() would hang in prompt_toolkit anyway.
  1950. run_debug_share(SimpleNamespace(
  1951. lines=200, expire=7, local=local, nous="nous" in words and not local, yes=True))
  1952. def _handle_update_command(self) -> bool:
  1953. """Handle /update — exit the session and relaunch as ``hermes update``. Returns True when
  1954. confirmed (the caller exits the app; the relaunch runs on the main thread after
  1955. prompt_toolkit restores terminal modes), False when cancelled."""
  1956. from hermes_cli.config import is_managed, format_managed_message
  1957. if is_managed():
  1958. print(f" ✗ {format_managed_message(_t('update.managed_action'))}")
  1959. return False
  1960. # prompt_toolkit-native modal: renders above the composer, no raw input() races.
  1961. choices = [("once", _t("update.choice_update"), _t("update.choice_update_desc")),
  1962. ("cancel", _t("update.choice_cancel"), _t("update.choice_cancel_desc"))]
  1963. raw = self._prompt_text_input_modal(
  1964. title=_t("update.title"), detail=_t("update.detail"), choices=choices)
  1965. if raw is None or self._normalize_slash_confirm_choice(raw, choices) != "once":
  1966. print(f" {_t('update.cancelled')}")
  1967. return False
  1968. _say_block(f" {_t('update.launching')}")
  1969. # run() execs this on the main thread after prompt_toolkit restores terminal modes;
  1970. # relaunching from this daemon thread would skip cleanup (POSIX) / only end the thread (Windows).
  1971. self._pending_relaunch = ["update"]
  1972. return True
  1973. def _handle_voice_command(self, command: str):
  1974. """Handle /voice [on|off|tts|status] command."""
  1975. subcommand = _command_arg(command, lower=True) or ("off" if self._voice_mode else "on")
  1976. actions = {"on": self._enable_voice_mode, "off": self._disable_voice_mode,
  1977. "tts": self._toggle_voice_tts, "status": self._show_voice_status}
  1978. if subcommand in actions:
  1979. actions[subcommand]()
  1980. else:
  1981. _cp(_t("voice.unknown_subcommand", subcommand=subcommand), _t("voice.usage"))
  1982. def _handle_wake_command(self, command: str):
  1983. """Handle /wake [on|off|status] — the 'Hey Hermes' hotword listener. The toggle IS the
  1984. config: on/off also writes ``wake_word.enabled`` so the choice persists; startup
  1985. auto-arm only reads it."""
  1986. subcommand = _command_arg(command, lower=True) or (
  1987. "off" if getattr(self, "_wake_word_active", False) else "on") # bare /wake toggles
  1988. if subcommand == "on":
  1989. if self._start_wake_word_listener(announce=True):
  1990. self._persist_wake_word_enabled(True)
  1991. elif subcommand == "off":
  1992. self._stop_wake_word_listener(announce=True)
  1993. self._persist_wake_word_enabled(False)
  1994. elif subcommand == "status":
  1995. self._show_wake_word_status()
  1996. else:
  1997. _cp(_t("wake.unknown_subcommand", subcommand=subcommand), _t("wake.usage"))
  1998. def _persist_wake_word_enabled(self, enabled: bool):
  1999. """Save ``wake_word.enabled`` so the /wake toggle sticks for future sessions."""
  2000. persisted = _probe("tools.wake_word", "load_wake_word_config", None)
  2001. if isinstance(persisted, dict) and bool(persisted.get("enabled")) == enabled:
  2002. return # already persisted — don't rewrite config or re-announce
  2003. if _save("wake_word.enabled", enabled):
  2004. _cp(_dim(_t("wake.enabled_in_config" if enabled else "wake.disabled_in_config")))