cli_loops_mixin.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. """Simple slash-command wrappers plus goal/heartbeat/loop manager hooks for the interactive CLI.
  2. Mixin on ``HermesCLI``; cli.py symbols are imported lazily inside methods (import cycle)."""
  3. from __future__ import annotations
  4. import logging
  5. import threading
  6. import time
  7. from agent.i18n import t
  8. from hermes_cli.gateway_client import GatewayClientError
  9. from rich.markup import escape as _escape
  10. def _fresh_start() -> str:
  11. """Banner line printed after /clear — resolved at call time so the active language applies."""
  12. return f" {t('cli.session.fresh_start')}\n"
  13. def _preview(payload: str) -> str:
  14. return f"{payload[:80]}{'...' if len(payload) > 80 else ''}"
  15. def _queue_usage() -> str:
  16. return t("cli.queue.usage")
  17. def _parse_queue_index(token: str) -> int | None:
  18. """1-based queue index from one whitespace-free token, or None when it isn't one.
  19. ``str.isdigit()`` alone is not enough: it accepts characters ``int()`` rejects
  20. (``²``, ``②``), and ``int()`` also refuses digit strings past Python's
  21. conversion limit. A ValueError here would escape the slash handler and take
  22. down the prompt_toolkit app, so every queue index goes through this.
  23. """
  24. if not token.isdigit():
  25. return None
  26. try:
  27. return int(token)
  28. except ValueError:
  29. return None
  30. # management verb -> (handler, takes a leading item index). Verbs without an index are
  31. # only management when they stand alone; index verbs when a number follows or when the
  32. # verb stands alone (the handler then prints its usage line).
  33. _QUEUE_VERBS: dict[str, tuple[str, bool]] = {
  34. "list": ("_queue_list", False), "ls": ("_queue_list", False), "show": ("_queue_list", False),
  35. "clear": ("_queue_clear", False),
  36. "edit": ("_queue_edit", True), "set": ("_queue_edit", True),
  37. "rm": ("_queue_remove", True), "remove": ("_queue_remove", True), "delete": ("_queue_remove", True),
  38. "del": ("_queue_remove", True), "pop": ("_queue_remove", True),
  39. "move": ("_queue_move", True),
  40. }
  41. def _print_decision_message(decision: dict) -> bool:
  42. """Print a manager decision's ``message`` (if any) via _cprint; True when one was printed."""
  43. from cli import _cprint
  44. msg = decision.get("message") or ""
  45. if msg:
  46. _cprint(f" {msg}")
  47. return bool(msg)
  48. def _goal_blocks_loop_tick(mgr) -> bool:
  49. """``loops.goal_blocks_loop_tick`` for this loop's session: asked of the gateway when the manager
  50. is the gateway's (it reads the goal row and its barrier where they live)."""
  51. if hasattr(mgr, "goal_blocks_tick"):
  52. return mgr.goal_blocks_tick()
  53. from hermes_cli.loops import goal_blocks_loop_tick
  54. return goal_blocks_loop_tick(mgr.session_id)
  55. class CLILoopsMixin:
  56. """Simple slash-command wrappers plus goal/heartbeat/loop manager hooks for the interactive CLI"""
  57. def _cmd_exit(self, cmd_original: str):
  58. # /exit --delete also removes the session's transcripts + SQLite history.
  59. from cli import _DIM, _RST, _cprint, _slash_args
  60. _args = _slash_args(cmd_original).lower()
  61. # Ported from google-gemini/gemini-cli#19332.
  62. if _args in {"--delete", "-d"}:
  63. self._delete_session_on_exit = True
  64. elif _args:
  65. _cprint(f" {_DIM}{t('cli.exit.unknown_argument', argument=_escape(_args))}{_RST}")
  66. return True
  67. return False
  68. def _cmd_help(self, cmd_original: str):
  69. from cli import _slash_args
  70. self.show_help(_slash_args(cmd_original))
  71. def _cmd_redraw(self, cmd_original: str):
  72. # Manual recovery for terminal buffer drift (mux tab switches, subshell ``clear``,
  73. # SSH restores; #8688). Ctrl+L is bound to the same helper.
  74. from cli import _DIM, _RST, _cprint
  75. self._force_full_redraw()
  76. _cprint(f" {_DIM}{t('cli.display.ui_redrawn')}{_RST}")
  77. def _cmd_clear(self, cmd_original: str):
  78. from cli import ChatConsole, _build_compact_banner, _clear_output_history, _cprint, get_tool_definitions
  79. from hermes_cli.banner import build_welcome_banner
  80. if self._confirm_destructive_slash(
  81. "clear",
  82. "This clears the screen and starts a new session.\n"
  83. "The current conversation history will be discarded.",
  84. cmd_original=cmd_original,
  85. ) is None:
  86. return True # confirmation cancelled — command handled, keep REPL alive
  87. self.new_session(silent=True)
  88. _clear_output_history()
  89. if not self._app:
  90. self.console.clear()
  91. self.show_banner()
  92. print(_fresh_start())
  93. self._print_random_tip()
  94. return
  95. # Inside the TUI, Rich's console.clear() and self.console both go through
  96. # patch_stdout's StdoutProxy, which swallows the clear escapes / mangles raw
  97. # output: clear via prompt_toolkit's output and print through ChatConsole.
  98. out = self._app.output
  99. out.erase_screen()
  100. out.cursor_goto(0, 0)
  101. out.flush()
  102. cc = ChatConsole()
  103. # The banner plan startup uses (show_banner): a gateway session's banner is the new
  104. # session's snapshot (its tools, MCP included, and main's short label), never this
  105. # process's registry.
  106. from hermes_cli.cli_info_mixin import banner_plan
  107. plan = banner_plan(self, cc)
  108. if plan.banner_kw is None:
  109. cc.print(_build_compact_banner())
  110. elif plan.inventory is not None:
  111. self._show_gateway_banner(build_welcome_banner, plan.inventory, plan.banner_kw)
  112. else:
  113. tools = get_tool_definitions(enabled_toolsets=self.enabled_toolsets,
  114. disabled_toolsets=self.disabled_toolsets, quiet_mode=True)
  115. build_welcome_banner(tools=tools, **plan.banner_kw)
  116. _cprint(_fresh_start())
  117. self._print_random_tip()
  118. def _cmd_title(self, cmd_original: str):
  119. from cli import _cprint
  120. from hermes_state import format_session_db_unavailable
  121. parts = cmd_original.split(maxsplit=1)
  122. if len(parts) == 1:
  123. # No argument: show current title and session ID.
  124. if not self._session_db:
  125. _cprint(f" {format_session_db_unavailable(details=True)}")
  126. return
  127. _cprint(f" {t('cli.title.session_id', session_id=self.session_id)}")
  128. session = self._session_db.get_session(self.session_id)
  129. if session and session.get("title"):
  130. _cprint(f" {t('cli.title.current', title=session['title'])}")
  131. elif self._pending_title:
  132. _cprint(f" {t('cli.title.pending', title=self._pending_title)}")
  133. else:
  134. _cprint(f" {t('cli.title.none_set_usage')}")
  135. return
  136. raw_title = parts[1].strip()
  137. if not raw_title:
  138. _cprint(f" {t('cli.title.usage')}")
  139. return
  140. if not self._session_db:
  141. _cprint(f" {format_session_db_unavailable(details=True)}")
  142. return
  143. # Sanitize early so feedback matches what gets stored. A rejection (e.g. too
  144. # long) prints that one reason and stops — never a second, contradictory
  145. # "empty after cleanup" error (SC-05).
  146. try:
  147. from hermes_state import SessionDB
  148. new_title = SessionDB.sanitize_title(raw_title)
  149. except ValueError as e:
  150. _cprint(f" {e}")
  151. return True
  152. if not new_title:
  153. _cprint(f" {t('cli.title.empty_after_cleanup')}")
  154. elif self._session_db.get_session(self.session_id):
  155. try:
  156. if self._session_db.set_session_title(self.session_id, new_title):
  157. self._status_bar_title_checked_at = 0.0
  158. _cprint(f" {t('cli.title.set', title=new_title)}")
  159. else:
  160. _cprint(f" {t('gateway.shared.session_not_found')}")
  161. except ValueError as e:
  162. _cprint(f" {e}")
  163. else:
  164. # Session not created yet — check uniqueness now, defer the title.
  165. existing = self._session_db.get_session_by_title(new_title)
  166. if existing:
  167. _cprint(f" {t('cli.title.already_in_use', title=new_title, session_id=existing['id'])}")
  168. else:
  169. self._pending_title = new_title
  170. _cprint(f" {t('cli.title.queued', title=new_title)}")
  171. def _cmd_new(self, cmd_original: str):
  172. # Strip inline-skip tokens (now/--yes/-y) before deriving the title so
  173. # "/new now My Session" yields title="My Session". See _split_destructive_skip.
  174. _new_args, _ = self._split_destructive_skip(cmd_original)
  175. title = _new_args.strip() or None
  176. if self._confirm_destructive_slash(
  177. "new",
  178. "This starts a fresh session.\n"
  179. "The current conversation history will be discarded.",
  180. cmd_original=cmd_original,
  181. ) is None:
  182. return True # confirmation cancelled — command handled, keep REPL alive
  183. self.new_session(title=title)
  184. def _record_model_friction(self, signal: str, turns: int = 1) -> None:
  185. # The TUI slash worker's shadow CLI has no metrics surface: tui_gateway counts what it executes.
  186. if self._slash_metrics_surface:
  187. from hermes_cli.observability.shared_metrics_model import record_model_friction
  188. record_model_friction(
  189. signal, session_id=getattr(self, "session_id", None), agent=getattr(self, "agent", None),
  190. provider=getattr(self, "provider", None), model=getattr(self, "model", None), turns=turns)
  191. def _cmd_retry(self, cmd_original: str):
  192. retry_msg = self.retry_last()
  193. if retry_msg:
  194. self._record_model_friction("retry")
  195. if retry_msg and hasattr(self, '_pending_input'):
  196. self._pending_input.put(retry_msg) # process_loop sends it to the agent
  197. def _cmd_undo(self, cmd_original: str):
  198. # "/undo" → 1, "/undo 3" → 3.
  199. _undo_n = 1
  200. _undo_parts = cmd_original.split()
  201. if len(_undo_parts) > 1:
  202. try:
  203. _undo_n = max(1, int(_undo_parts[1]))
  204. except ValueError:
  205. print(t("cli.undo.invalid_count", value=repr(_undo_parts[1])))
  206. return True # bad arg — command handled, keep the REPL alive
  207. # Nothing to undo → say so; no destructive confirmation for a no-op (SC-06).
  208. if not self.conversation_history:
  209. print(t("cli.session.undo_no_messages"))
  210. return True
  211. _undo_desc = (
  212. t("cli.undo.removes_last_exchange")
  213. if _undo_n == 1
  214. else t("cli.undo.removes_last_turns", count=_undo_n))
  215. if self._confirm_destructive_slash("undo", _undo_desc, cmd_original=cmd_original) is None:
  216. return True # confirmation cancelled — command handled, keep REPL alive
  217. turns_undone = self.undo_last(_undo_n)
  218. if turns_undone: # None when nothing was rewound
  219. self._record_model_friction("undo", turns_undone)
  220. def _cmd_skills(self, cmd_original: str):
  221. with self._busy_command(self._slow_command_status(cmd_original)):
  222. self._handle_skills_command(cmd_original)
  223. def _cmd_egress(self, cmd_original: str):
  224. from hermes_cli.slash_exec import CommandContext, execute_command
  225. text = execute_command("egress", CommandContext(surface="cli")).text
  226. self._console_print(text, highlight=False, markup=False)
  227. def _cmd_statusbar(self, cmd_original: str):
  228. self._status_bar_visible = not self._status_bar_visible
  229. self._console_print(
  230. f" {t('cli.display.status_bar_visible') if self._status_bar_visible else t('cli.display.status_bar_hidden')}")
  231. def _cmd_update(self, cmd_original: str) -> bool:
  232. # A truthy result means the process is relaunching — leave the REPL.
  233. return not self._handle_update_command()
  234. def _cmd_version(self, cmd_original: str):
  235. from hermes_cli.main import _print_version_info
  236. _print_version_info(check_updates=True)
  237. def _cmd_reload(self, cmd_original: str):
  238. from hermes_cli.config import reload_env
  239. count = reload_env()
  240. print(f" {t('cli.reload.env_reloaded', count=count)}")
  241. def _cmd_reload_skills(self, cmd_original: str):
  242. with self._busy_command(self._slow_command_status(cmd_original)):
  243. self._reload_skills()
  244. def _cmd_plugins(self, cmd_original: str):
  245. from hermes_constants import display_hermes_home
  246. parts = cmd_original.split()[1:]
  247. if parts and parts[0] in ("update", "auto-update"):
  248. from hermes_cli.plugins_auto_update import plugins_slash_action
  249. with self._busy_command(self._slow_command_status(cmd_original)):
  250. for line in plugins_slash_action(parts):
  251. print(line)
  252. return
  253. try:
  254. # Discover from disk (bundled + user) like `hermes plugins list`, so
  255. # installed-but-not-enabled plugins show up; the plugin manager only knows
  256. # *loaded* plugins and made fresh installs look like "nothing installed".
  257. from hermes_cli.plugins_cmd import (
  258. _discover_all_plugins, _get_disabled_set, _get_enabled_set, _plugin_status)
  259. entries = _discover_all_plugins()
  260. enabled = _get_enabled_set()
  261. disabled = _get_disabled_set()
  262. # `/plugins` is a quick glance: user plugins only, bundled ones summarized
  263. # on one line (full catalog behind `hermes plugins list`).
  264. user_entries = [e for e in entries if e[3] != "bundled"]
  265. bundled_count = len(entries) - len(user_entries)
  266. if not user_entries:
  267. print(t("cli.plugins.none_installed"))
  268. print(f" {t('cli.plugins.install_hint')}")
  269. print(f" {t('cli.plugins.drop_dir_hint', path=f'{display_hermes_home()}/plugins/')}")
  270. if bundled_count:
  271. print(f" {t('cli.plugins.bundled_available', count=bundled_count)}")
  272. return
  273. from hermes_cli import gateway_plugin_commands
  274. loaded = gateway_plugin_commands.loaded(self) # the gateway's; None off the gateway
  275. if loaded is None:
  276. try: # loaded-plugin details (tools/hooks/commands counts, errors) by name
  277. from hermes_cli.plugins import get_plugin_manager
  278. loaded = {p["name"]: p for p in get_plugin_manager().list_plugins()}
  279. except Exception:
  280. loaded = {}
  281. print(t("cli.plugins.user_plugins_header", count=len(user_entries)))
  282. for name, version, _desc, source, _dir, key in sorted(user_entries):
  283. state = _plugin_status(name, enabled, disabled, key=key)
  284. info = loaded.get(name) or {}
  285. bits = [f"{info[k]} {t(f'cli.plugins.count_noun_{k}')}" for k in ("tools", "hooks", "commands") if info.get(k)]
  286. glyph = {"enabled": "✓", "disabled": "✗"}.get(state, "○")
  287. ver = f" v{version}" if version else ""
  288. detail = f" ({', '.join(bits)})" if bits else ""
  289. label = "" if state == "enabled" else f" [{state}]"
  290. error = f" — {info['error']}" if info.get("error") else ""
  291. print(f" {glyph} {name}{ver}{label}{detail}{error}")
  292. if bundled_count:
  293. print(f" {t('cli.plugins.bundled_more', count=bundled_count)}")
  294. print(f" {t('cli.plugins.enable_disable_hint')}")
  295. except Exception as e:
  296. print(t("cli.plugins.system_error", error=e))
  297. # ── /queue: enqueue, list, edit, rm, move, clear ─────────────────
  298. # A queued next-turn prompt can be inspected and changed before it is sent.
  299. def _pending_input_items(self) -> list:
  300. """Snapshot of queued next-turn prompts (raw items; may include ``_VoiceInputMessage``)."""
  301. with self._pending_input.mutex:
  302. return list(self._pending_input.queue)
  303. def _mutate_pending_input(self, mutate) -> tuple[list, list]:
  304. """Apply ``mutate(items) -> items`` to the queued prompts under the queue's own mutex,
  305. so a voice/interrupt ``put`` from another thread can't slip between snapshot and
  306. write-back. Returns ``(before, after)``."""
  307. q = self._pending_input
  308. with q.mutex:
  309. before = list(q.queue)
  310. after = list(mutate(list(before)))
  311. q.queue.clear()
  312. q.queue.extend(after)
  313. q.unfinished_tasks = len(after)
  314. if after:
  315. q.not_empty.notify_all()
  316. return before, after
  317. def _gateway_queue_store(self):
  318. """The gateway session store when this CLI is a viewer of the gateway's session, else None."""
  319. from hermes_cli.gateway_tools_notify import gateway_store
  320. return gateway_store(self) if getattr(self, "session_id", None) else None
  321. def _queue_items(self) -> list:
  322. """``[(admission_id | None, item)]``: the owner's queued admissions (run first, in its FIFO
  323. order), then the turns still waiting in ``_pending_input``."""
  324. items: list = []
  325. store = self._gateway_queue_store()
  326. if store is not None:
  327. from hermes_cli import gateway_queue
  328. items = list(gateway_queue.queued_rows(self, store))
  329. return items + [(None, item) for item in self._pending_input_items()]
  330. def _queue_enqueue(self, text: str) -> None:
  331. from cli import _cprint
  332. payload = self._expand_paste_references(text)
  333. store = self._gateway_queue_store() if self._agent_running else None
  334. if store is not None:
  335. # #134889 N5: the gateway's durable FIFO holds it (committed at accept, kept across an owner
  336. # restart, run once after the current turn), never this process.
  337. from hermes_cli import gateway_queue
  338. try:
  339. gateway_queue.submit_queued(self, store, payload)
  340. except gateway_queue.QueueOutcomeUnknown as exc: # sent, no answer: it may be queued
  341. _cprint(f" {t('cli.queue.submit_unknown', error=exc)}")
  342. return
  343. except GatewayClientError as exc: # the owner refused, or it was never sent: nothing is held here
  344. _cprint(f" {t('cli.queue.gateway_refused', error=exc)}")
  345. return
  346. else:
  347. self._pending_input.put(payload)
  348. key = "cli.queue.queued_next_turn" if self._agent_running else "cli.queue.queued"
  349. _cprint(f" {t(key, preview=_preview(payload))}")
  350. def _queue_list(self, rest: str) -> None:
  351. from cli import _VoiceInputMessage, _cprint
  352. items = self._queue_items()
  353. if not items:
  354. _cprint(f" {t('cli.queue.empty')}" + ("" if rest else " " + _queue_usage()))
  355. return
  356. _cprint(f" {t('cli.queue.pending_header', count=len(items))}")
  357. for idx, (_, item) in enumerate(items, 1):
  358. tag = " [voice]" if isinstance(item, _VoiceInputMessage) else ""
  359. _cprint(f" {idx}. {_preview(str(item).replace(chr(10), ' '))}{tag}")
  360. def _queue_gateway_call(self, verb, index, *args):
  361. """One owner verb on queued item ``index``; its refusal is printed (in its own words), never raised."""
  362. from cli import _cprint
  363. from hermes_cli import gateway_queue
  364. from hermes_cli.gateway_client import GatewayRPCError
  365. try:
  366. return getattr(gateway_queue, verb)(self, self._gateway_queue_store(), *args)
  367. except GatewayRPCError as exc:
  368. if str(exc) in gateway_queue.STARTED_REFUSALS: # the drain claimed it first: it runs as sent
  369. _cprint(f" {t('cli.queue.already_started', index=index)}")
  370. else:
  371. key = "cli.queue.edit_refused" if verb == "replace" else "cli.queue.remove_refused"
  372. _cprint(f" {t(key, index=index, error=exc)}")
  373. except GatewayClientError as exc: # no answer: the owner may have applied it
  374. _cprint(f" {t('cli.queue.change_unknown', index=index, error=exc)}")
  375. return None
  376. def _queue_clear(self, rest: str) -> None:
  377. from cli import _cprint
  378. owned = [admission for admission, _ in self._queue_items() if admission]
  379. cleared = sum(1 for idx, admission in enumerate(owned, 1)
  380. if self._queue_gateway_call("cancel", idx, admission) == "cancelled")
  381. before, _ = self._mutate_pending_input(lambda items: [])
  382. cleared += len(before)
  383. key = "cli.queue.cleared_one" if cleared == 1 else "cli.queue.cleared_other"
  384. _cprint(f" {t(key, count=cleared)}")
  385. def _queue_remove(self, rest: str) -> None:
  386. from cli import _cprint
  387. bits = rest.split()
  388. idx = _parse_queue_index(bits[0]) if len(bits) == 1 else None
  389. if idx is None:
  390. _cprint(f" {t('cli.queue.usage_remove')}")
  391. return
  392. items = self._queue_items()
  393. owned = sum(1 for admission, _ in items if admission)
  394. if 1 <= idx <= owned:
  395. admission, text = items[idx - 1]
  396. verdict = self._queue_gateway_call("cancel", idx, admission)
  397. if verdict == "cancelled":
  398. _cprint(f" {t('cli.queue.removed', index=idx, preview=_preview(str(text)))}")
  399. elif verdict == "stopped": # claimed between the list and the cancel: the owner interrupted it
  400. _cprint(f" {t('cli.queue.started_stopped', index=idx)}")
  401. elif verdict == "started":
  402. _cprint(f" {t('cli.queue.already_started', index=idx)}")
  403. return
  404. local = idx - owned
  405. removed: list = []
  406. before, _ = self._mutate_pending_input(
  407. lambda items: (removed.append(items.pop(local - 1)) or items) if 1 <= local <= len(items) else items)
  408. if removed:
  409. _cprint(f" {t('cli.queue.removed', index=idx, preview=_preview(str(removed[0])))}")
  410. else:
  411. _cprint(f" {t('cli.queue.item_not_found', index=idx, size=owned + len(before))}")
  412. def _queue_edit(self, rest: str) -> None:
  413. from cli import _VoiceInputMessage, _cprint
  414. # Split on any whitespace, like ``_cmd_queue``'s routing check, so
  415. # ``edit 1<TAB>text`` doesn't leave "1\ttext" as the index token.
  416. bits = rest.split(None, 1)
  417. idx = _parse_queue_index(bits[0]) if len(bits) == 2 else None
  418. if idx is None:
  419. _cprint(f" {t('cli.queue.usage_edit')}")
  420. return
  421. new_prompt = bits[1]
  422. new_text = self._expand_paste_references(new_prompt.strip())
  423. items = self._queue_items()
  424. owned = sum(1 for admission, _ in items if admission)
  425. if 1 <= idx <= owned:
  426. # The owner admits the edit as a new admission at the back of its FIFO.
  427. if self._queue_gateway_call("replace", idx, items[idx - 1][0], new_text):
  428. _cprint(f" {t('cli.queue.updated', index=idx, preview=_preview(new_text))}")
  429. return
  430. local = idx - owned
  431. def _edit(items: list) -> list:
  432. if 1 <= local <= len(items):
  433. # A voice-queued item keeps its sentinel so the concise voice-response
  434. # prefix still applies (#65827).
  435. voice = isinstance(items[local - 1], _VoiceInputMessage)
  436. items[local - 1] = _VoiceInputMessage(new_text) if voice else new_text
  437. return items
  438. before, after = self._mutate_pending_input(_edit)
  439. if before == after:
  440. _cprint(f" {t('cli.queue.item_not_found', index=idx, size=owned + len(before))}")
  441. else:
  442. _cprint(f" {t('cli.queue.updated', index=idx, preview=_preview(new_text))}")
  443. def _queue_move(self, rest: str) -> None:
  444. from cli import _cprint
  445. bits = rest.split()
  446. src, dst = (_parse_queue_index(b) for b in bits) if len(bits) == 2 else (None, None)
  447. if src is None or dst is None:
  448. _cprint(f" {t('cli.queue.usage_move')}")
  449. return
  450. owned = sum(1 for admission, _ in self._queue_items() if admission)
  451. if owned and min(src, dst) <= owned and src != dst:
  452. # The owner's FIFO runs admissions in the order they were sent; it has no reorder verb.
  453. _cprint(f" {t('cli.queue.move_gateway_fifo')}")
  454. return
  455. src, dst = src - owned, dst - owned
  456. def _move(items: list) -> list:
  457. if 1 <= src <= len(items) and 1 <= dst <= len(items):
  458. items.insert(dst - 1, items.pop(src - 1))
  459. return items
  460. before, after = self._mutate_pending_input(_move)
  461. if before == after and src != dst:
  462. _cprint(f" {t('cli.queue.move_out_of_range', size=owned + len(before))}")
  463. else:
  464. _cprint(f" {t('cli.queue.moved', source=src + owned, destination=dst + owned)}")
  465. def _cmd_queue(self, cmd_original: str):
  466. """``/queue <prompt>`` enqueues; a leading management verb whose arguments fit
  467. (``list``/``clear`` alone, ``edit N …``/``rm N``/``move A B``) manages the queue
  468. instead. Anything else — ``clear the logs``, ``edit the config`` — is still a prompt;
  469. ``/queue add <prompt>`` forces enqueueing."""
  470. from cli import _cprint, _slash_args
  471. payload = _slash_args(cmd_original)
  472. if not payload:
  473. self._queue_list("")
  474. return
  475. verb, _, rest = payload.partition(" ")
  476. verb, rest = verb.lower(), rest.strip()
  477. if verb == "add":
  478. if rest:
  479. self._queue_enqueue(rest)
  480. else:
  481. _cprint(f" {t('cli.queue.usage_add')}")
  482. return
  483. handler, takes_index = _QUEUE_VERBS.get(verb, (None, False))
  484. is_management = handler is not None and (
  485. rest.split(None, 1)[0].isdigit() if takes_index and rest else not rest
  486. )
  487. if is_management:
  488. getattr(self, handler)(rest)
  489. else:
  490. self._queue_enqueue(payload)
  491. def _cmd_steer(self, cmd_original: str):
  492. # Inject a message after the next tool call without interrupting: while the
  493. # agent runs, push into its pending_steer slot (drained by _execute_tool_calls_*
  494. # into the next tool result); otherwise fall back to /queue semantics.
  495. from cli import _cprint, _slash_args
  496. payload = _slash_args(cmd_original)
  497. if not payload:
  498. _cprint(f" {t('cli.steer.usage')}")
  499. elif self._agent_running and self.agent is not None and hasattr(self.agent, "steer"):
  500. try:
  501. accepted = self.agent.steer(payload)
  502. except Exception as exc:
  503. _cprint(f" {t('cli.steer.failed', error=exc)}")
  504. else:
  505. if accepted == "voice_stopped": # TUI-26: the owner ended the voice chat; consumed
  506. pass
  507. elif accepted:
  508. _cprint(f" {t('cli.steer.queued', preview=_preview(payload))}")
  509. else:
  510. _cprint(f" {t('cli.steer.rejected_empty')}")
  511. else:
  512. self._pending_input.put(payload)
  513. _cprint(f" {t('cli.steer.no_agent_queued', preview=_preview(payload))}")
  514. # ────────────────────────────────────────────────────────────────
  515. # Session-bound managers: /goal (Ralph-style loop), /heartbeat, /loop
  516. # ────────────────────────────────────────────────────────────────
  517. def _session_bound_manager(self, attr: str, label: str, load):
  518. """Return the manager cached on ``self.<attr>``, rebuilt when ``session_id`` changed
  519. (after /new or a compression-driven session split).
  520. ``load()`` does the imports and returns a ``sid -> manager`` factory; an import
  521. failure is logged and yields None, as does an empty session_id.
  522. """
  523. try:
  524. make = load()
  525. except Exception as exc:
  526. logging.debug("%s unavailable: %s", label, exc)
  527. return None
  528. sid = getattr(self, "session_id", None) or ""
  529. if not sid:
  530. return None
  531. existing = getattr(self, attr, None)
  532. if existing is not None and getattr(existing, "session_id", None) == sid:
  533. return existing
  534. mgr = make(sid)
  535. setattr(self, attr, mgr)
  536. return mgr
  537. def _automation_connection(self):
  538. """``(gateway, connection)``: on a gateway session store the managers are the gateway's
  539. (``hermes_cli.gateway_automation``), and none exists until the gateway session is open, so this
  540. process never opens state.db read-write nor calls the goal judge. Off the gateway (tests, the
  541. TUI slash worker's shadow CLI) main's in-process managers apply."""
  542. from hermes_cli.gateway_session_store import GatewaySessionStore
  543. store = getattr(self, "_session_db", None)
  544. if not isinstance(store, GatewaySessionStore):
  545. return False, None
  546. return True, store.connection if getattr(self, "_gateway_session_open", False) else None
  547. def _automation_manager(self, attr, label, local, remote):
  548. gateway, connection = self._automation_connection()
  549. if gateway and connection is None:
  550. return None
  551. return self._session_bound_manager(
  552. attr, label, (lambda: lambda sid: remote(sid, connection)) if gateway else local)
  553. def _mark_automation_stale(self) -> None:
  554. """Agent thread: the gateway published this session's goal/loop state mid-turn (a tool moved it).
  555. The dock re-reads the mirrored managers on its next spinner-thread poll (``cli_session_dock``)."""
  556. self._automation_stale = True
  557. def _get_goal_manager(self):
  558. """GoalManager bound to the current session_id (see ``_session_bound_manager``)."""
  559. def max_turns():
  560. from hermes_cli.config import load_config
  561. try:
  562. goals_cfg = (load_config() or {}).get("goals") or {}
  563. return int(goals_cfg.get("max_turns", 20) or 20)
  564. except Exception: # health: allow BLE001 -- main's fallback: an unreadable goals config is the 20-turn default
  565. return 20
  566. def load():
  567. from hermes_cli.goals import GoalManager
  568. return lambda sid: GoalManager(session_id=sid, default_max_turns=max_turns())
  569. def remote(sid, connection):
  570. from hermes_cli.gateway_automation import GatewayGoalManager
  571. return GatewayGoalManager(sid, connection)
  572. return self._automation_manager("_goal_manager", "goal manager", load, remote)
  573. def _get_heartbeat_manager(self):
  574. """HeartbeatManager bound to the current session_id (see ``_session_bound_manager``)."""
  575. def load():
  576. from hermes_cli.heartbeat import HeartbeatManager
  577. return lambda sid: HeartbeatManager(session_id=sid)
  578. def remote(sid, connection):
  579. from hermes_cli.gateway_automation import GatewayHeartbeatManager
  580. return GatewayHeartbeatManager(sid, connection)
  581. return self._automation_manager("_heartbeat_manager", "heartbeat manager", load, remote)
  582. def _get_loop_manager(self):
  583. """LoopManager bound to the current session_id (see ``_session_bound_manager``)."""
  584. def load():
  585. from hermes_cli.loops import LoopManager
  586. return lambda sid: LoopManager(session_id=sid)
  587. def remote(sid, connection):
  588. from hermes_cli.gateway_automation import GatewayLoopManager
  589. return GatewayLoopManager(sid, connection)
  590. return self._automation_manager("_loop_manager", "loop manager", load, remote)
  591. def _start_heartbeat_watchdog(self):
  592. """Start the idle-poll daemon that injects a due heartbeat prompt into
  593. ``_pending_input`` as a normal user turn when the session is idle. Missed ticks
  594. coalesce (the anchor resets on fire, so a busy hour yields ONE heartbeat turn).
  595. Idempotent; safe to call on every /heartbeat set."""
  596. if getattr(self, "_heartbeat_watchdog_started", False):
  597. return
  598. self._heartbeat_watchdog_started = True
  599. from hermes_cli.gateway_automation import GatewayHeartbeatManager
  600. from hermes_cli.heartbeat import POLL_SECONDS
  601. def _loop():
  602. try:
  603. while not getattr(self, "_should_exit", False):
  604. time.sleep(POLL_SECONDS)
  605. try:
  606. mgr = self._get_heartbeat_manager()
  607. if isinstance(mgr, GatewayHeartbeatManager):
  608. # The gateway poller stands down while this watchdog runs, so a resume,
  609. # set or re-anchor from another viewer must reach this copy.
  610. mgr.refresh()
  611. if mgr is None or not mgr.is_active():
  612. continue
  613. busy = (
  614. self._agent_running
  615. or getattr(self, "_voice_recording", False)
  616. or getattr(self, "_voice_processing", False)
  617. or not self._pending_input.empty())
  618. if busy:
  619. continue
  620. prompt = mgr.due_prompt()
  621. if prompt:
  622. self._pending_input.put(prompt)
  623. except Exception as exc:
  624. logging.debug("heartbeat watchdog tick failed: %s", exc)
  625. finally:
  626. self._heartbeat_watchdog_started = False
  627. threading.Thread(target=_loop, daemon=True, name="heartbeat-watchdog").start()
  628. def _maybe_resume_parked_goal(self) -> None:
  629. """Idle hook run from process_loop: when a parked /goal's barrier has lifted (the process
  630. exited, the timer elapsed, or the wait aged past its cap), queue the continuation so the
  631. loop resumes WITHOUT waiting for an unrelated turn to re-evaluate it. The barrier used to be
  632. checked only lazily, on the next turn; a session with nothing else arriving stayed parked
  633. indefinitely (one run: 3 h 22 min on a grandchild's poller)."""
  634. now = time.time()
  635. if now - getattr(self, "_last_goal_barrier_check", 0.0) < 5.0:
  636. return
  637. self._last_goal_barrier_check = now
  638. try:
  639. if not self._pending_input.empty():
  640. return
  641. mgr = self._get_goal_manager()
  642. state = getattr(mgr, "state", None) if mgr is not None else None
  643. if state is None or state.status != "active":
  644. return
  645. if not (state.waiting_on_pid is not None or state.waiting_on_session is not None or state.waiting_until):
  646. return # not parked
  647. if mgr.is_waiting():
  648. return # barrier still holds (is_waiting() also applies the age cap)
  649. prompt = mgr.next_continuation_prompt()
  650. if prompt:
  651. from cli import _DIM, _RST, _cprint
  652. _cprint(f" {_DIM}{t('cli.goal.barrier_lifted')}{_RST}")
  653. self._pending_input.put(prompt)
  654. except Exception as exc:
  655. logging.debug("parked-goal resume check failed: %s", exc)
  656. def _maybe_fire_loop_tick(self) -> None:
  657. """Idle hook run from process_loop: fire a due /loop wakeup.
  658. Only while the agent is idle and nothing is queued — a real user message always
  659. wins the idle boundary, and so does an active (non-parked) /goal, whose
  660. judge-driven continuations own it; the loop defers to the next poll.
  661. """
  662. from cli import _DIM, _RST, _cprint
  663. mgr = self._get_loop_manager()
  664. if mgr is None or not mgr.is_due():
  665. return
  666. # The idle poll runs at ~10 Hz; a due-but-deferred tick would otherwise hit the
  667. # DB (goal_blocks_loop_tick) on every poll. Throttle the re-check.
  668. now = time.time()
  669. if now - getattr(self, "_last_loop_tick_check", 0.0) < 2.0:
  670. return
  671. self._last_loop_tick_check = now
  672. try:
  673. if not self._pending_input.empty():
  674. return
  675. except Exception:
  676. return
  677. try:
  678. if _goal_blocks_loop_tick(mgr):
  679. return
  680. except Exception:
  681. pass
  682. wakeup = mgr.fire_tick()
  683. if not wakeup:
  684. return
  685. try:
  686. state = mgr.state
  687. tick_no = state.ticks_fired if state else "?"
  688. _cprint(f" {_DIM}{t('cli.loop.wakeup_firing', tick=tick_no)}{_RST}")
  689. self._pending_input.put(wakeup)
  690. except Exception as exc:
  691. logging.debug("loop tick injection failed: %s", exc)
  692. try:
  693. mgr.abandon_tick()
  694. except Exception:
  695. pass
  696. return
  697. # A slash-command loop (`/loop 10m /recap`) is dispatched via process_command and
  698. # never reaches chat()'s post-turn finally, so its tick would never complete and
  699. # the loop would wedge on awaiting_response. Slash ticks have no model reply to
  700. # judge; complete them immediately (caps and scheduling still apply).
  701. if wakeup.lstrip().startswith("/"):
  702. try:
  703. _print_decision_message(mgr.complete_tick(""))
  704. except Exception:
  705. pass
  706. def _last_assistant_response_text(self) -> str:
  707. """Text of the most recent assistant message ("" when none); multimodal parts are flattened."""
  708. try:
  709. for msg in reversed(self.conversation_history or []):
  710. if msg.get("role") == "assistant":
  711. content = msg.get("content", "")
  712. if isinstance(content, list):
  713. parts = [
  714. p.get("text", "")
  715. for p in content
  716. if isinstance(p, dict) and p.get("type") in {"text", "output_text"}]
  717. return "\n".join(t for t in parts if t)
  718. return str(content or "")
  719. except Exception:
  720. pass
  721. return ""
  722. def _maybe_complete_loop_tick_after_turn(self) -> None:
  723. """Post-turn hook: evaluate a finished /loop wakeup turn.
  724. No-op unless the turn was a loop wakeup (``awaiting_response`` set by
  725. ``fire_tick``). Detects the LOOP_COMPLETE marker, judges --until, applies caps,
  726. and schedules the next tick. Mirrors _maybe_continue_goal_after_turn's shape.
  727. """
  728. from cli import _DIM, _RST, _cprint
  729. mgr = self._get_loop_manager()
  730. if mgr is None:
  731. return
  732. state = mgr.state
  733. if state is None or not state.awaiting_response:
  734. return
  735. # A user-interrupted wakeup turn pauses the loop (recoverable via /loop resume)
  736. # — same contract as the goal loop's Ctrl+C handling.
  737. if getattr(self, "_last_turn_interrupted", False):
  738. try:
  739. mgr.pause(reason="user-interrupted (Ctrl+C)")
  740. except Exception:
  741. pass
  742. _cprint(f" {_DIM}{t('cli.loop.paused_interrupted')}{_RST}")
  743. return
  744. decision = mgr.complete_tick("" if getattr(self, "_last_turn_failed", False)
  745. else self._last_assistant_response_text())
  746. # With the live-work dock up its loop row carries the countdown; the one-shot line would go stale.
  747. if (not _print_decision_message(decision) and decision.get("status") == "active"
  748. and mgr.state is not None and getattr(self, "_subagent_monitor", None) is None):
  749. _cprint(f" {_DIM}{t('cli.loop.remaining', label=mgr.state.remaining_label())}{_RST}")
  750. def _maybe_continue_goal_after_turn(self) -> None:
  751. """Post-turn hook: judge the goal and maybe re-queue a continuation. A real user
  752. message already queued preempts judging (re-judged after their turn). Ctrl+C
  753. AUTO-PAUSES instead of judging — the judge on partial output nearly always says
  754. "continue" and would re-queue exactly what was cancelled; pausing is recoverable
  755. via ``/goal resume``. Empty-response skip mirrors ``gateway/run.py``."""
  756. from cli import _DIM, _RST, _cprint, _looks_like_slash_command
  757. mgr = self._get_goal_manager()
  758. if mgr is None or not mgr.is_active():
  759. return
  760. # Slash commands don't count as "real user messages": they're dispatched via
  761. # process_command, not chat(), so a queued /subgoal would consume its slot without
  762. # ever re-firing this hook and the goal loop would silently stall. Peek at every
  763. # queued entry (Queue.queue is the deque; FIFO undisturbed) and defer only on a
  764. # non-slash payload. Bundled payloads are (text, images) tuples.
  765. try:
  766. pending = getattr(self, "_pending_input", None)
  767. if pending is not None and not pending.empty():
  768. try:
  769. entries = [e[0] if isinstance(e, tuple) and e else e for e in list(pending.queue)]
  770. has_real_message = any(
  771. not (isinstance(e, str) and _looks_like_slash_command(e)) for e in entries)
  772. except Exception:
  773. has_real_message = True # can't introspect — defer to be safe
  774. if has_real_message:
  775. return
  776. except Exception:
  777. pass
  778. if getattr(self, "_last_turn_interrupted", False):
  779. try:
  780. mgr.pause(reason="user-interrupted (Ctrl+C)")
  781. except Exception as exc:
  782. logging.debug("goal pause-on-interrupt failed: %s", exc)
  783. _cprint(f" {_DIM}{t('cli.goal.paused_interrupted')}{_RST}")
  784. return
  785. # Empty/whitespace responses are almost always transient failures (API error,
  786. # empty stream): judging would say "continue" and trip the parse-failure backstop.
  787. # A failed turn (a refused one: its folder is gone) never reached the model, so the judge
  788. # would grade the previous reply and burn the whole budget; same rule as the TUI's hook.
  789. if getattr(self, "_last_turn_failed", False):
  790. return
  791. last_response = self._last_assistant_response_text()
  792. if not last_response.strip():
  793. return
  794. _active_deleg = 0
  795. try:
  796. from hermes_cli.goals import count_active_delegations, gather_background_processes as _gather_bg
  797. # Only THIS session's processes: subagents' pollers must not park the parent's goal.
  798. _bg_procs = _gather_bg(owner_task_id=getattr(self, "session_id", None) or None)
  799. _active_deleg = count_active_delegations(getattr(self.agent, "session_id", None))
  800. except Exception:
  801. _bg_procs = None
  802. decision = mgr.evaluate_after_turn(
  803. last_response, user_initiated=True, background_processes=_bg_procs, active_delegations=_active_deleg)
  804. _print_decision_message(decision)
  805. if decision.get("should_continue"):
  806. prompt = decision.get("continuation_prompt")
  807. if prompt:
  808. try:
  809. self._pending_input.put(prompt)
  810. except Exception as exc:
  811. logging.debug("goal continuation enqueue failed: %s", exc)