cli_tui_runtime_mixin.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. """Classic-TUI run loop phases: input processing, after-turn bookkeeping, startup banner/prewarm/maintenance, prompt_toolkit application build, signal handlers and shutdown.
  2. Mixin split out of ``cli.py``; bound onto ``HermesCLI`` via the MRO.
  3. """
  4. from __future__ import annotations
  5. import errno
  6. import logging
  7. import os
  8. import queue
  9. import shutil
  10. import sys
  11. import threading
  12. import time
  13. from agent.i18n import t
  14. from agent.interrupt_compat import request_hard_interrupt
  15. from agent import terminal_image
  16. from contextlib import suppress
  17. from hermes_constants import get_hermes_home
  18. from prompt_toolkit.application import Application
  19. from rich.markup import escape as _escape
  20. # Log-record parity with the origin module.
  21. logger = logging.getLogger("cli")
  22. class CLITuiRuntimeMixin:
  23. """Classic-TUI run loop phases: input processing, after-turn bookkeeping, startup banner/prewarm/maintenance, prompt_toolkit application build, signal handlers and shutdown."""
  24. def _tui_process_loop(self):
  25. """REPL worker thread: drain ``_pending_input``, run idle housekeeping, dispatch each input."""
  26. held = None
  27. while not self._should_exit:
  28. try:
  29. if held is not None:
  30. held, user_input = self._tui_hold_step(held)
  31. if user_input is not None:
  32. self._tui_process_one_input(user_input)
  33. continue
  34. try:
  35. user_input = self._pending_input.get(timeout=0.1)
  36. except queue.Empty:
  37. if not self._agent_running:
  38. self._tui_idle_tick()
  39. continue
  40. from hermes_cli.gateway_queue import OwnQueueHold
  41. held = OwnQueueHold.begin(self, user_input)
  42. if held is None:
  43. self._tui_process_one_input(user_input)
  44. except Exception as e:
  45. if isinstance(e, OSError) and e.errno == errno.EIO:
  46. self._mark_terminal_io_broken("process_loop")
  47. logger.warning("process_loop EIO — freezing UI paints (#81521): %s", e)
  48. continue
  49. logger.warning("process_loop unhandled error (msg may be lost): %s", e)
  50. def _tui_hold_step(self, hold):
  51. """One step of holding a local input behind this viewer's own ``/queue`` admission (#134889 N5):
  52. ``(hold or None, input to run now or None)``. A turn the owner runs now goes first; the held
  53. input runs once that admission was taken, left the queue, or the bounded wait ran out."""
  54. with suppress(Exception):
  55. self._drain_process_notifications("cli-idle") # adopts the admission on its message.start
  56. item = hold.take_gateway_turn(self._pending_input)
  57. if item is not None:
  58. return hold, item
  59. if hold.done():
  60. return None, hold.item
  61. time.sleep(0.05)
  62. return hold, None
  63. def _tui_idle_tick(self):
  64. """Idle housekeeping between inputs (agent not running)."""
  65. self._check_config_mcp_changes() # auto-reload MCP on mcp_servers change
  66. # Termios drift heal first: a drifted tty makes the CLI look dead while the loop is healthy.
  67. for step in (
  68. self._check_termios_drift,
  69. lambda: self._drain_process_notifications("cli-idle"),
  70. self._maybe_fire_loop_tick,
  71. self._maybe_resume_parked_goal,
  72. ):
  73. with suppress(Exception):
  74. step()
  75. def _tui_dock_drop_dequeued(self):
  76. """Re-read the live-work dock once an input has left ``_pending_input``.
  77. The spinner thread polls the dock once a second, so without this the prompt a turn just took
  78. (a seeded ``-q`` prompt above all) stays listed as queued while the turn starts. If the reply
  79. prints in that window the dock shrinks only after it, leaving blank rows under the prompt.
  80. The turn's own invalidate repaints the refreshed rows.
  81. """
  82. monitor = getattr(self, "_subagent_monitor", None)
  83. if monitor is not None:
  84. with suppress(Exception):
  85. monitor.refresh()
  86. def _tui_process_one_input(self, user_input):
  87. """Route one submitted input: file drop, /resume pick, ! shell, slash command, or a chat turn."""
  88. from cli import _DIM, _PASTE_REF_RE, _RST, _cprint, _detect_file_drop, _looks_like_slash_command, _strip_leaked_bracketed_paste_wrappers, _strip_leaked_terminal_responses_with_meta
  89. from tools.process_registry_notifications import TimelineNotification
  90. self._tui_dock_drop_dequeued()
  91. user_input, is_voice_input, is_seeded_query = self._tui_unwrap_input(user_input)
  92. if not user_input:
  93. return
  94. notification_preview = user_input if isinstance(user_input, TimelineNotification) else None
  95. self._status_bar_suppressed_after_resize = False # input ends post-resize suppression
  96. submit_images = []
  97. if isinstance(user_input, tuple):
  98. user_input, submit_images = user_input
  99. if isinstance(user_input, str):
  100. user_input = _strip_leaked_bracketed_paste_wrappers(user_input)
  101. user_input, _had_mouse_reports = _strip_leaked_terminal_responses_with_meta(user_input)
  102. if _had_mouse_reports:
  103. self._recover_terminal_input_modes(reason="mouse reports leaked into submitted input")
  104. # A typed bare stop phrase ends an active voice chat (transcripts are checked earlier).
  105. if not is_voice_input and self._typed_voice_stop(user_input):
  106. return
  107. # File drops are detected before any dispatch; seeded -q prompts are literal text.
  108. _file_drop = _detect_file_drop(user_input) if isinstance(user_input, str) and not is_seeded_query else None
  109. if _file_drop:
  110. _drop_path = _file_drop["path"]
  111. _remainder = _file_drop["remainder"]
  112. if _file_drop["is_image"]:
  113. submit_images.append(_drop_path)
  114. user_input = _remainder or f"[User attached image: {_drop_path.name}]"
  115. _cprint(" " + t("cli.tui.auto_attached_image", name=_drop_path.name))
  116. else:
  117. _cprint(" " + t("cli.tui.detected_file", name=_drop_path.name))
  118. user_input = f"[User attached file: {_drop_path}]" + (f"\n{_remainder}" if _remainder else "")
  119. elif isinstance(user_input, str):
  120. # A bare number right after a bare `/resume` selects that session (never sent to the agent).
  121. if self._pending_resume_sessions and self._consume_pending_resume_selection(user_input):
  122. return
  123. if not is_seeded_query:
  124. if self.handle_bang_shell(user_input):
  125. return
  126. if _looks_like_slash_command(user_input):
  127. user_input = self._tui_run_slash_input(user_input)
  128. if user_input is None:
  129. return
  130. if isinstance(user_input, str) and _PASTE_REF_RE.search(user_input):
  131. user_input = self._expand_paste_references(user_input)
  132. _cprint("")
  133. self._print_user_message_preview(notification_preview or user_input)
  134. if submit_images:
  135. n = len(submit_images)
  136. _attached = t("cli.tui.images_attached_one" if n == 1 else "cli.tui.images_attached_other", count=n)
  137. _cprint(f" {_DIM}{_attached}{_RST}")
  138. from hermes_cli.cli_inline_images import print_inline_images
  139. print_inline_images(self, submit_images)
  140. self._agent_running = self._interactive_turn = True
  141. self._pet_turn_error = self._pet_reasoning = False
  142. self._turn_summary_begin()
  143. self._app.invalidate()
  144. try:
  145. self.chat(notification_preview or user_input, images=submit_images or None, voice_input=is_voice_input)
  146. finally:
  147. self._tui_after_turn()
  148. def _tui_run_slash_input(self, user_input: str):
  149. """Dispatch a slash command. Returns the pending agent seed to run as a chat turn, else None."""
  150. from cli import _cprint
  151. _cprint(f"\n⚙️ {user_input}")
  152. try:
  153. if not self.process_command(user_input):
  154. self._should_exit = True
  155. if self._app.is_running:
  156. self._app.exit()
  157. except KeyboardInterrupt:
  158. # Ctrl+C during a slow slash command returns to the prompt instead of exiting.
  159. _cprint(f"\n[dim]{t('cli.tui.command_interrupted')}[/dim]")
  160. return None
  161. _seed, self._pending_agent_seed = self._pending_agent_seed, None
  162. return _seed or None
  163. def _tui_after_turn(self):
  164. """Post-turn bookkeeping after chat() returns (normal, error, or interrupt)."""
  165. from cli import _DIM, _RST, _cprint
  166. self._agent_running = self._pet_reasoning = False
  167. self._spinner_text = self._last_scrollback_tool = ""
  168. self._tool_start_time = 0.0
  169. self._pending_tool_info.clear()
  170. self.__dict__.pop("_running_tool_labels", None)
  171. self._pet_react_turn_end()
  172. self._turn_summary_emit()
  173. self._interactive_turn = False
  174. self._app.invalidate()
  175. # After an interrupt the renderer may have drifted (leaked CPR text, VT100 parser
  176. # stalled mid-escape): drain stray bytes and force a clean redraw.
  177. if self._last_turn_interrupted:
  178. self._recover_terminal_after_interrupt()
  179. # Re-queue any messages that arrived in _interrupt_queue while the agent was running and were never
  180. # claimed by the explicit interrupt path. See _drain_interrupt_queue_to_pending_input for the full
  181. # rationale. Regression of #17666 / #18760 — the drain block from the original PR #17939 was
  182. # deferred as "worth its own review" and never re-landed (#20271).
  183. self._drain_interrupt_queue_to_pending_input()
  184. # /goal continuation (queued user input still preempts), then /loop tick completion.
  185. for hook, what in (
  186. (self._maybe_continue_goal_after_turn, "goal continuation"),
  187. (self._maybe_complete_loop_tick_after_turn, "loop completion"),
  188. ):
  189. try:
  190. hook()
  191. except Exception as _exc:
  192. logging.debug("%s hook failed: %s", what, _exc)
  193. # Continuous voice: restart recording off-thread (beep + recorder start would block process_loop).
  194. if self._voice_mode and self._voice_continuous and not self._voice_recording:
  195. def _restart_recording():
  196. try:
  197. if self._voice_tts:
  198. self._voice_tts_done.wait(timeout=60)
  199. time.sleep(0.3)
  200. # A barge-in capture already owns the mic and submits the interruption itself.
  201. if self._voice_barge_capture.is_set():
  202. return
  203. self._voice_start_recording()
  204. self._app.invalidate()
  205. except Exception as e:
  206. _cprint(f"{_DIM}{t('cli.voice.autorestart_failed', error=e)}{_RST}")
  207. threading.Thread(target=_restart_recording, daemon=True).start()
  208. with suppress(Exception):
  209. self._drain_process_notifications("cli-post-turn")
  210. def _tui_signal_handler(self, signum, frame):
  211. """SIGHUP/SIGTERM -> graceful shutdown.
  212. The agent is hard-interrupted first so its daemon thread can kill the tool's
  213. setsid subprocess group before the main thread unwinds (else an orphan child).
  214. ``logger.debug`` is guarded: logging is not reentrant-safe and a shutdown race
  215. can raise ``KeyError`` inside the handler, bypassing prompt_toolkit's unwind.
  216. """
  217. from cli import _arm_exit_watchdog_on_shutdown_signal, _interrupt_agent_for_signal
  218. with suppress(Exception):
  219. logger.debug("Received signal %s, triggering graceful shutdown", signum)
  220. # Arm the backstop IMMEDIATELY: if the unwind wedges, _run_cleanup never arms its own.
  221. # Shutdown intent is now unambiguous — arm the exit backstop IMMEDIATELY, before the graceful unwind
  222. # below. If any step of that unwind wedges (main thread parked in a syscall, prompt_toolkit teardown
  223. # never returning), _run_cleanup never runs and would never arm its own watchdog — leaving a "dead"
  224. # CLI alive for minutes (#65998 class).
  225. # Arm the exit backstop now that shutdown intent is unambiguous — covers wedges in the unwind below
  226. # that would otherwise leave the process alive with no watchdog (#65998 class).
  227. _arm_exit_watchdog_on_shutdown_signal()
  228. if self._agent_running:
  229. _interrupt_agent_for_signal(self.agent, signum)
  230. # Prefer app.exit() over raising KeyboardInterrupt: a KBI from a signal handler
  231. # lands in a pt Task ("Unhandled exception in event loop" + "Press ENTER to
  232. # continue..."); call_soon_threadsafe lets the loop unwind normally.
  233. try:
  234. from prompt_toolkit.application.current import get_app_or_none
  235. _app = get_app_or_none()
  236. _loop = getattr(_app, "loop", None)
  237. if _loop is not None:
  238. _loop.call_soon_threadsafe(_app.exit)
  239. return # clean unwind — no traceback, no ENTER pause
  240. except Exception:
  241. pass
  242. raise KeyboardInterrupt() # fallback for non-prompt_toolkit contexts
  243. def _tui_print_startup(self):
  244. """Startup output: light-mode probe, banner, advisories, resume/welcome lines, tips."""
  245. from cli import _accent_hex, _detect_light_mode
  246. with suppress(Exception): # light-mode probe before pt grabs the tty (cached)
  247. _detect_light_mode()
  248. from hermes_cli.cli_inline_images import vscode_images_hint
  249. _show_vscode_images_hint = False
  250. with suppress(Exception): # VS Code image probe: same pre-pt window, cached, ~10 ms
  251. _show_vscode_images_hint = vscode_images_hint(self._inline_images_mode)
  252. # Scroll the cursor to the last row so banner, responses and prompt pin to the bottom.
  253. with suppress(Exception):
  254. _term_lines = shutil.get_terminal_size().lines
  255. if _term_lines > 2:
  256. print("\n" * (_term_lines - 1), end="", flush=True)
  257. from hermes_cli.gateway_client import GatewayClientError
  258. try:
  259. self._ensure_gateway_session() # the banner shows the gateway session's id and inventory
  260. except GatewayClientError as exc:
  261. # A refused open (a changed launch flag on --resume) is a startup error, not a traceback.
  262. print(f"Error: {exc}", file=sys.stderr)
  263. raise SystemExit(2) from None
  264. self.show_banner()
  265. self._show_security_advisories()
  266. # First-run: an unconfigured install routes into provider onboarding instead of
  267. # a chat that spins ~30s and fails with a provider-specific error. TTY only. A
  268. # configured profile whose credential is benched or signed out gets the reason instead.
  269. try:
  270. self._maybe_offer_first_run_setup()
  271. except Exception:
  272. logger.debug("first-run setup offer failed", exc_info=True)
  273. # A persisted Docker sandbox on the previous default image is kept until the user says
  274. # so; this TTY is where they can. Either answer pins an image, so it is asked once.
  275. if sys.stdin.isatty():
  276. try:
  277. from hermes_cli.sandbox_image_switch import offer_interactive
  278. from cli import _cprint
  279. offer_interactive(cprint=_cprint)
  280. except Exception:
  281. logger.debug("sandbox image switch offer failed", exc_info=True)
  282. # Low disk + auto-prune never decided: ask once (either answer ends it for good).
  283. try:
  284. from hermes_cli.prune_advisor import offer_interactive as _offer_auto_prune
  285. from cli import _cprint
  286. _offer_auto_prune(cprint=_cprint)
  287. except Exception:
  288. logger.debug("auto-prune offer failed", exc_info=True)
  289. if self._resumed and self._preload_resumed_session():
  290. self._display_resumed_history()
  291. _welcome_skin = None # stays None when the skin engine failed
  292. _welcome_text = t("cli.tui.welcome")
  293. _welcome_color = "#FFF8DC"
  294. try:
  295. from hermes_cli.skin_engine import get_active_skin
  296. _welcome_skin = get_active_skin()
  297. _welcome_text = _welcome_skin.get_branding("welcome", _welcome_text)
  298. _welcome_color = _welcome_skin.get_color("banner_text", _welcome_color)
  299. except Exception:
  300. pass
  301. self._console_print(f"[{_welcome_color}]{_welcome_text}[/]")
  302. self._tui_startup_prewarm_and_warnings(_welcome_skin)
  303. if _show_vscode_images_hint:
  304. from hermes_cli.skin_engine import get_active_skin
  305. _tip_color = get_active_skin().get_color("banner_dim", "#B8860B")
  306. self._console_print(f"[dim {_tip_color}]{t('cli.tip_line', tip=t('cli.tui.vscode_images_hint'))}[/]")
  307. else:
  308. self._print_random_tip()
  309. self._tui_startup_background_maintenance()
  310. # Before the background preload is folded in (at agent init), show the REQUESTED names.
  311. _skills_for_line = self.preloaded_skills or list(self._preload_skills_requested or [])
  312. if _skills_for_line and not self._startup_skills_line_shown:
  313. self._console_print(
  314. f"[bold {_accent_hex()}]{t('cli.tui.activated_skills_label')}[/] {', '.join(_skills_for_line)}")
  315. self._startup_skills_line_shown = True
  316. self._console_print()
  317. def _tui_startup_prewarm_and_warnings(self, _welcome_skin):
  318. """Idle-window prewarms (picker cache, agent runtime imports) plus the redaction-off and OpenClaw-residue banners."""
  319. # Warm the /model picker cache off-thread (else its first open blocks ~1-2s).
  320. with suppress(Exception):
  321. from hermes_cli.model_switch_providers import prewarm_picker_cache_async
  322. prewarm_picker_cache_async()
  323. # Pre-import the agent runtime (~1.5s: run_agent + OpenAI SDK) off-thread; the import
  324. # lock makes an early submit block on the remaining work rather than redo it.
  325. # Skipped when Termux defers agent startup on purpose.
  326. if os.environ.get("HERMES_DEFER_AGENT_STARTUP") != "1":
  327. def _prewarm_agent_runtime() -> None:
  328. try:
  329. import run_agent
  330. import openai
  331. except Exception:
  332. logger.debug("agent runtime pre-import failed", exc_info=True)
  333. threading.Thread(target=_prewarm_agent_runtime, name="agent-runtime-prewarm", daemon=True).start()
  334. # Redaction is ON by default; be loud when the operator turned it off.
  335. with suppress(Exception):
  336. # The redactor snapshots its state at import time so any toggle now won't affect the running
  337. # process — we just want the operator to see that they're running without the safety net. See
  338. # #17691.
  339. _redact_raw = os.getenv("HERMES_REDACT_SECRETS", "true")
  340. if _redact_raw.lower() not in {"1", "true", "yes", "on"}:
  341. self._console_print(
  342. f"[bold red]{t('cli.tui.redaction_disabled_title')}[/] "
  343. + t("cli.tui.redaction_disabled_body", value=_escape(_redact_raw),
  344. setting="[cyan]security.redact_secrets: true[/]")
  345. )
  346. # One-time banner when ~/.openclaw/ is left over from a migration.
  347. try:
  348. from agent.onboarding import (
  349. OPENCLAW_RESIDUE_FLAG, detect_openclaw_residue, is_seen, mark_seen, openclaw_residue_hint_cli,
  350. )
  351. if not is_seen(self.config, OPENCLAW_RESIDUE_FLAG) and detect_openclaw_residue():
  352. try:
  353. _resid_color = _welcome_skin.get_color("banner_dim", "#B8860B")
  354. except Exception:
  355. _resid_color = "#B8860B"
  356. self._console_print(f"[{_resid_color}]{openclaw_residue_hint_cli()}[/]")
  357. try:
  358. from hermes_cli.config import get_config_path as _get_cfg_path_resid
  359. mark_seen(_get_cfg_path_resid(), OPENCLAW_RESIDUE_FLAG)
  360. except Exception:
  361. pass # banner fires again next session
  362. except Exception:
  363. pass
  364. def _tui_startup_background_maintenance(self):
  365. """Best-effort startup passes: curator skill maintenance, personal + org skill sync.
  366. Off the main thread: the curator's deterministic pass snapshots and prunes the whole
  367. skills tree (a due weekly pass held the prompt for 6 minutes on a large library), and
  368. the sync pulls can hit the network. The REPL must never wait on housekeeping."""
  369. threading.Thread(target=self._run_startup_maintenance, name="startup-maintenance", daemon=True).start()
  370. def _run_startup_maintenance(self):
  371. with suppress(Exception):
  372. from agent.curator import maybe_run_curator
  373. maybe_run_curator(
  374. idle_for_seconds=float("inf"), # CLI startup = fully idle
  375. on_summary=lambda msg: self._console_print(f"[dim #6b7684]💾 {msg}[/]"),
  376. )
  377. def _tui_build_application(self, layout, kb, style):
  378. """Construct the prompt_toolkit Application for the REPL."""
  379. from cli import CLI_CONFIG, EditingMode, _STEADY_CURSOR, _select_classic_cli_pt_output
  380. _cpr_disabled_output = _select_classic_cli_pt_output(sys.stdout)
  381. # Kitty placeholders encode the image id in exact foreground RGB, so the whole app
  382. # runs 24-bit there. ColorDepth is imported lazily for tests that stub prompt_toolkit.
  383. extra_kw = {}
  384. if terminal_image.supports_kitty_placeholders():
  385. from prompt_toolkit.output import ColorDepth
  386. extra_kw["color_depth"] = ColorDepth.DEPTH_24_BIT
  387. if _cpr_disabled_output is not None:
  388. extra_kw["output"] = _cpr_disabled_output
  389. if _STEADY_CURSOR is not None:
  390. extra_kw["cursor"] = _STEADY_CURSOR
  391. if EditingMode is not None:
  392. # Vi editing mode when display.vim_mode is on.
  393. # EMACS is prompt_toolkit's own default, so non-opted-in behaviour is unchanged.
  394. extra_kw["editing_mode"] = EditingMode.VI if self._vim_mode else EditingMode.EMACS
  395. return Application(
  396. layout=layout,
  397. key_bindings=kb,
  398. style=style,
  399. full_screen=False,
  400. mouse_support=False,
  401. # 0 (default) avoids fighting terminal auto-scroll in non-fullscreen mode.
  402. refresh_interval=float(CLI_CONFIG.get("display", {}).get("cli_refresh_interval", 0)),
  403. # Erase the bottom chrome on exit instead of freezing a copy into scrollback.
  404. # Without this, prompt_toolkit's render_as_done teardown repaints the chrome one last time and
  405. # leaves it stranded above the exit summary — so a dead status bar + empty prompt sit between
  406. # the conversation transcript and the "Resume this session" block, and stack with the next
  407. # session's UI on resume (#38252). The actual conversation transcript is printed through
  408. # patch_stdout into normal scrollback and is unaffected; only the managed chrome is erased.
  409. # Applies to every exit path (/exit, /quit, EOF, Ctrl+C).
  410. erase_when_done=True,
  411. **extra_kw,
  412. )
  413. def _tui_install_signal_handlers(self):
  414. """SIGTERM/SIGHUP -> graceful shutdown; Windows absorbs SIGINT (see body)."""
  415. try:
  416. import signal as _signal
  417. _signal.signal(_signal.SIGTERM, self._tui_signal_handler)
  418. if hasattr(_signal, 'SIGHUP'):
  419. _signal.signal(_signal.SIGHUP, self._tui_signal_handler)
  420. # Windows: absorb SIGINT. Win32 delivers spurious CTRL_C_EVENT when children spawn
  421. # from background threads, which would unwind app.run() mid-turn. Real Ctrl+C is
  422. # bound by prompt_toolkit. Never call agent.interrupt() here (fake user message).
  423. if sys.platform == "win32":
  424. _signal.signal(_signal.SIGINT, lambda signum, frame: None)
  425. except Exception:
  426. pass # restricted environments
  427. def _tui_stdin_usable(self) -> bool:
  428. """Validate fd 0 before prompt_toolkit starts; on macOS fall back to a select() loop when kqueue can't watch it (uv-managed Python)."""
  429. try:
  430. os.fstat(0)
  431. except OSError:
  432. print(t("cli.tui.stdin_unavailable"))
  433. return False
  434. if sys.platform == "darwin":
  435. import selectors as _selectors
  436. try:
  437. if hasattr(_selectors, "KqueueSelector"):
  438. _kq = _selectors.KqueueSelector()
  439. try:
  440. _kq.register(0, _selectors.EVENT_READ)
  441. _kq.unregister(0)
  442. finally:
  443. _kq.close()
  444. except (OSError, ValueError, KeyError):
  445. import asyncio as _aio_probe
  446. class _SelectEventLoopPolicy(_aio_probe.DefaultEventLoopPolicy):
  447. def new_event_loop(self):
  448. return _aio_probe.SelectorEventLoop(_selectors.SelectSelector())
  449. _aio_probe.set_event_loop_policy(_SelectEventLoopPolicy())
  450. return True
  451. def _closing_session_id(self):
  452. """The session quit closes: the agent's, or (gateway) the session opened at the banner before
  453. any agent was built. Main created its row lazily at the first turn, so with no agent it had none."""
  454. if self.agent:
  455. return self.agent.session_id
  456. return self.session_id if getattr(self, "_gateway_session_open", False) else None
  457. def _tui_shutdown(self):
  458. """Teardown after the app exits: interrupt agent, stop voice/pet, persist + close session, cleanup, exit summary."""
  459. from cli import _DIM, _RST, _cprint, _invoke_interrupted_session_end, _run_cleanup, set_approval_callback, set_secret_capture_callback, set_sudo_password_callback
  460. self._should_exit = True
  461. self._pet_stop_anim()
  462. # Without this line the terminal sits silent through the whole cleanup window.
  463. with suppress(Exception):
  464. print(f"{_DIM}{t('cli.tui.shutting_down')}{_RST}", flush=True)
  465. from hermes_cli.cli_shutdown import _gateway_owns_session_end
  466. if self.agent and self._agent_running and not (
  467. self._detach_on_exit and _gateway_owns_session_end(self.agent)):
  468. # A gateway turn left by Ctrl+D is not interrupted: ``end_session`` below detaches this
  469. # viewer and the owner closes the row once the turn settles (gateway/session_viewer_close).
  470. with suppress(Exception):
  471. request_hard_interrupt(self.agent)
  472. if self._voice_recorder:
  473. with suppress(Exception):
  474. self._voice_recorder.shutdown()
  475. self._voice_recorder = None
  476. with suppress(Exception):
  477. from tools.voice_mode import cleanup_temp_recordings
  478. cleanup_temp_recordings()
  479. from agent.vault_backends.unlock import (lock as _vault_lock, set_code_prompt_callback,
  480. set_save_login_prompt_callback, set_unlock_prompt_callback)
  481. for _unset in (set_sudo_password_callback, set_approval_callback, set_secret_capture_callback,
  482. set_unlock_prompt_callback, set_save_login_prompt_callback, set_code_prompt_callback):
  483. _unset(None)
  484. _vault_lock() # session tokens for external password managers die with the session
  485. # On SIGHUP/SIGTERM the agent thread may be reaped before its own persistence runs.
  486. self._persist_active_session_before_close()
  487. _closing_sid = self._closing_session_id()
  488. if self._session_db and _closing_sid:
  489. try:
  490. self._session_db.end_session(_closing_sid, "cli_close")
  491. except (Exception, KeyboardInterrupt) as e:
  492. logger.debug("Could not close session in DB: %s", e)
  493. if not self._delete_session_on_exit:
  494. # Drop the empty row of a start-and-quit session so /resume stays clean.
  495. try:
  496. self._discard_session_if_empty(_closing_sid)
  497. except (Exception, KeyboardInterrupt) as e:
  498. logger.debug("Could not prune empty session: %s", e)
  499. else:
  500. # /exit --delete: remove transcripts + SQLite history.
  501. try:
  502. _sid = _closing_sid
  503. if self._session_db.delete_session(_sid, sessions_dir=get_hermes_home() / "sessions"):
  504. _cprint(f" {_DIM}{t('cli.tui.session_deleted', session_id=_escape(_sid))}{_RST}")
  505. else:
  506. _cprint(f" {_DIM}{t('cli.tui.session_delete_missing', session_id=_escape(_sid))}{_RST}")
  507. except (Exception, KeyboardInterrupt) as e:
  508. logger.debug("Could not delete session on exit: %s", e)
  509. # run_conversation() fires on_session_end on normal completion; only fire here mid-turn. A gateway
  510. # turn fires it in the gateway when the interrupted turn finalizes.
  511. if self.agent and self._agent_running and not _gateway_owns_session_end(self.agent):
  512. _invoke_interrupted_session_end(self.agent, self.agent.session_id, "shutdown")
  513. # Ask AND apply before _run_cleanup arms the exit watchdog, so a large archive is never cut
  514. # short; a signal-driven exit never asks.
  515. import cli as _cli_mod
  516. if not _cli_mod._signal_watchdog_armed and _cli_mod._active_worktree:
  517. from hermes_cli.worktree_exit import apply_exit_choice, ask_exit_choice
  518. with suppress(Exception, KeyboardInterrupt):
  519. ask_exit_choice(_cli_mod._active_worktree)
  520. apply_exit_choice(_cli_mod._active_worktree, _cprint)
  521. _run_cleanup()
  522. self._print_exit_summary()
  523. self._release_active_session()