cli.py 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794
  1. #!/usr/bin/env python3
  2. """Hermes Agent CLI — interactive terminal interface (``python cli.py --help`` for usage)."""
  3. # Must be the very first import (UTF-8 stdio on Windows). Missing only mid-``hermes update``.
  4. try:
  5. import hermes_bootstrap
  6. except ModuleNotFoundError as exc:
  7. if exc.name != "hermes_bootstrap":
  8. raise # the bootstrap exists but cannot load: skipping it would skip PM activation
  9. import logging
  10. import os
  11. import functools
  12. # Tests patch shutil/time/datetime through the cli facade; siblings also resolve datetime
  13. # lazily through it — these imports are load-bearing despite being unused in this file.
  14. import shutil
  15. import sys
  16. import re
  17. import atexit
  18. import errno
  19. import time
  20. from collections import deque
  21. from dataclasses import dataclass
  22. from contextlib import contextmanager, suppress
  23. from pathlib import Path
  24. from datetime import datetime
  25. from typing import List, Dict, Any, Optional
  26. logger = logging.getLogger(__name__)
  27. os.environ["HERMES_QUIET"] = "1" # suppress our modules' startup chatter
  28. from hermes_cli.cli_agent_setup_mixin import CLIAgentSetupMixin
  29. from hermes_cli.cli_commands_mixin import CLICommandsMixin
  30. from hermes_cli.cli_billing_mixin import CLIBillingMixin
  31. from hermes_cli.cli_loops_mixin import CLILoopsMixin
  32. from hermes_cli.cli_info_mixin import CLIInfoMixin
  33. from hermes_cli.cli_terminal_mixin import CLITerminalMixin
  34. from hermes_cli.cli_modal_mixin import CLIModalMixin
  35. from hermes_cli.cli_stream_mixin import CLIStreamMixin
  36. from hermes_cli.cli_session_mixin import CLISessionMixin
  37. from hermes_cli.cli_model_switch_mixin import CLIModelSwitchMixin
  38. from hermes_cli.cli_voice_mixin import CLIVoiceMixin
  39. from hermes_cli.cli_status_bar_mixin import CLIStatusBarMixin
  40. from hermes_cli.cli_tui_mixin import CLITuiMixin
  41. from hermes_cli.cli_process_notifications import CLIProcessNotificationsMixin
  42. from hermes_cli.cli_init_mixin import CLIInitMixin
  43. from hermes_cli.cli_tui_runtime_mixin import CLITuiRuntimeMixin
  44. from hermes_cli.cli_backtrack import CLIBacktrackMixin
  45. # Extracted clusters (mechanical split, #116911); re-exported here so `cli.<name>` stays the seam.
  46. from hermes_cli.cli_shutdown import (
  47. _CLEANUP_STEPS,
  48. _arm_exit_watchdog,
  49. _emit_interrupted_session_end,
  50. _exit_watchdog_timeout,
  51. _finalize_single_query,
  52. _float_env,
  53. _flush_logging_and_stdio,
  54. _flush_one_shot_session_store,
  55. _interrupt_async_delegations,
  56. _invoke_interrupted_session_end,
  57. _notify_session_finalize,
  58. _notify_single_query_session_finalize,
  59. _oneshot_agent_and_session,
  60. _should_emit_cleanup_session_finalize,
  61. _shutdown_agent_memory_provider,
  62. _shutdown_cached_aux_clients,
  63. _shutdown_mcp_servers,
  64. _stop_cli_wake_word,
  65. _sync_process_session_id,
  66. _wait_for_oneshot_background_completions,
  67. )
  68. from hermes_cli.cli_auto_maintenance import (
  69. _run_checkpoint_auto_maintenance,
  70. _run_state_db_auto_maintenance,
  71. )
  72. from hermes_cli.cli_render import (
  73. ChatConsole,
  74. _ACCENT,
  75. _ACCENT_ANSI_DEFAULT,
  76. _BOLD,
  77. _DA1_REPLY_RE,
  78. _DIM,
  79. _FALSE_RE,
  80. _LIGHT_DEFAULT_TERM_PROGRAMS,
  81. _LIGHT_MODE_REMAP,
  82. _LIGHT_MODE_REMAP_UPPER,
  83. _REASONING_TAGS,
  84. _RST,
  85. _STREAM_PAD,
  86. _STREAM_PARTIAL_PREVIEW_LEN,
  87. _SkinAwareAnsi,
  88. _TOOL_CALL_TAGS,
  89. _TRUE_RE,
  90. _WINDOWS_PATH_WITH_DOT_SEGMENT_RE,
  91. _accent_hex,
  92. _add_suspect_rows,
  93. _append_blank_panel_line,
  94. _append_panel_line,
  95. _assistant_content_as_text,
  96. _assistant_copy_text,
  97. _b,
  98. _build_compact_banner,
  99. _clear_output_history,
  100. _cli_visible_print,
  101. _coerce_output_history_limit,
  102. _cprint,
  103. _d,
  104. _detect_light_mode_uncached,
  105. _heal_cooked_mode_drift,
  106. _hex_to_ansi,
  107. _install_skin_light_mode_hook,
  108. _line_rows,
  109. _luminance_from_hex,
  110. _maybe_remap_for_light_mode,
  111. _output_history_lines,
  112. _output_history_recording,
  113. _output_history_rows,
  114. _output_tail_fitting,
  115. _painted_columns,
  116. _PaintedLine,
  117. _panel_box_width,
  118. _post_stream_transform_output,
  119. _prepend_note_to_message,
  120. _preserve_windows_dot_segments_for_markdown,
  121. _pt_app_is_running,
  122. _pt_print_ansi,
  123. _query_osc11_background,
  124. _record_output_history,
  125. _record_output_history_entry,
  126. _release_paints,
  127. _render_final_assistant_content,
  128. _rich_text_from_ansi,
  129. _set_chrome_floor,
  130. _strip_markdown_syntax,
  131. _strip_reasoning_tags,
  132. _terminal_columns,
  133. _terminal_reflows,
  134. _terminal_width_for_streaming,
  135. _tty_wrap,
  136. _wrap_panel_text,
  137. _wrap_panel_text_keep_ws,
  138. )
  139. from hermes_cli.cli_config_load import (
  140. _AUXILIARY_TASK_ENV,
  141. _CWD_PLACEHOLDERS,
  142. _TERMINAL_ENV_MAPPINGS,
  143. _cli_config_defaults,
  144. _init_logging_and_display_from_config,
  145. _load_prefill_messages,
  146. _merge_file_config,
  147. _mirror_config_to_env,
  148. _parse_reasoning_config,
  149. _parse_service_tier_config,
  150. _resolve_prefill_messages_file,
  151. load_cli_config,
  152. )
  153. from hermes_cli.cli_terminal_input import (
  154. _BACKSLASH_LINE_CONTINUATION_RE,
  155. _DSR_CPR_ESC_RE,
  156. _DSR_CPR_VISIBLE_RE,
  157. _EXTENDED_ENTER_KEYS_SEQ,
  158. _IMAGE_EXTENSIONS,
  159. _KITTY_KEYBOARD_PUSH_SEQ,
  160. _MODIFY_OTHER_KEYS_SEQ,
  161. _SGR_MOUSE_BARE_RE,
  162. _SGR_MOUSE_ESC_RE,
  163. _SGR_MOUSE_VISIBLE_RE,
  164. _TERMINAL_INPUT_MODE_RESET_SEQ,
  165. _apply_backslash_line_continuation,
  166. _apply_bracketed_paste_timeout_patch,
  167. _bind_prompt_submit_keys,
  168. _build_cpr_disabled_output,
  169. _cli_multiline_shortcuts_enabled,
  170. _collect_query_images,
  171. _detect_file_drop,
  172. _disable_prompt_toolkit_cpr_warning,
  173. _enable_extended_enter_keys,
  174. _estimate_tui_input_height,
  175. _file_drop_result,
  176. _format_image_attachment_badges,
  177. _hermes_call_output_screen_diff,
  178. _is_backslash_line_continuation,
  179. _is_ghostty_terminal,
  180. _preserve_ctrl_enter_newline,
  181. _resolve_attachment_path,
  182. _select_classic_cli_pt_output,
  183. _should_auto_attach_clipboard_image_on_paste,
  184. _split_path_input,
  185. _status_bar_visible_from_display_config,
  186. _strip_leaked_terminal_responses_with_meta,
  187. _terminal_may_leak_cpr,
  188. _terminal_supports_extended_enter_keys,
  189. _termux_example_image_path,
  190. )
  191. from hermes_cli.cli_single_query import (
  192. _TERMINAL_PROVIDER_REASONS,
  193. _TRANSIENT_PROVIDER_REASONS,
  194. _collect_kanban_task_images,
  195. _configure_quiet_agent,
  196. _install_single_query_signal_handlers,
  197. _int_or,
  198. _interrupt_agent_for_signal,
  199. _route_single_query_images,
  200. _run_kanban_goal_loop_chat,
  201. _run_kanban_goal_loop_q,
  202. _run_quiet_single_query,
  203. _run_single_query_mode,
  204. _single_query_exit_code,
  205. _sync_cli_session_id_from_agent,
  206. )
  207. try:
  208. from prompt_toolkit.patch_stdout import patch_stdout
  209. except ImportError: # partial/broken prompt_toolkit (#96075); sole use is a `with patch_stdout():`
  210. from contextlib import nullcontext as patch_stdout
  211. try:
  212. from prompt_toolkit.enums import EditingMode
  213. except ImportError: # partial prompt_toolkit stubs in tests
  214. EditingMode = None
  215. from prompt_toolkit import print_formatted_text as _pt_print
  216. from prompt_toolkit.formatted_text import ANSI as _PT_ANSI
  217. try:
  218. from prompt_toolkit.cursor_shapes import CursorShape
  219. _STEADY_CURSOR = CursorShape.BLOCK
  220. except (ImportError, AttributeError):
  221. _STEADY_CURSOR = None
  222. try:
  223. from hermes_cli import pt_input_extras as _pt_extras
  224. _pt_extras.install_shift_enter_alias()
  225. _pt_extras.install_ctrl_enter_alias()
  226. _pt_extras.install_cmd_backspace_alias()
  227. _pt_extras.install_modify_other_keys_aliases()
  228. _pt_extras.install_keypress_data_normalization()
  229. _pt_extras.install_ignored_terminal_sequences()
  230. del _pt_extras
  231. except Exception:
  232. pass
  233. import threading
  234. import queue
  235. def _lazy_shim(module: str, name: str, alias: str | None = None):
  236. """Import ``module.name`` on first call; keeps heavy imports off startup while ``cli.<name>`` stays patchable."""
  237. import importlib
  238. def shim(*args, **kwargs):
  239. return getattr(importlib.import_module(module), name)(*args, **kwargs)
  240. shim.__name__ = shim.__qualname__ = alias or name
  241. return shim
  242. def format_duration_compact(*args, **kwargs):
  243. seconds = float(args[0] if args else kwargs.get("seconds", 0.0))
  244. if seconds < 60:
  245. return f"{seconds:.0f}s"
  246. minutes = seconds / 60
  247. if minutes < 60:
  248. return f"{minutes:.0f}m"
  249. hours = minutes / 60
  250. if hours < 24:
  251. remaining_min = int(minutes % 60)
  252. return f"{int(hours)}h {remaining_min}m" if remaining_min else f"{int(hours)}h"
  253. days = hours / 24
  254. return f"{days:.1f}d"
  255. # model id -> shortest configured alias (process-lifetime cache; config is read once).
  256. _REVERSE_ALIAS_CACHE: dict[str, str] | None = None
  257. def _reverse_alias_for_display(model_name: str) -> str:
  258. """Shortest alias for ``model_name`` from ``model_aliases:`` or ``model.aliases:``, else ``model_name``."""
  259. global _REVERSE_ALIAS_CACHE
  260. if not model_name:
  261. return model_name
  262. if _REVERSE_ALIAS_CACHE is None:
  263. rmap: dict[str, str] = {}
  264. def _put(m: str, alias: str) -> None:
  265. if m and (m not in rmap or len(alias) < len(rmap[m])):
  266. rmap[m] = alias
  267. try:
  268. from hermes_cli.config import load_config
  269. cfg = load_config() or {}
  270. ma = cfg.get("model_aliases")
  271. if isinstance(ma, dict):
  272. for alias, entry in ma.items():
  273. if isinstance(entry, dict):
  274. _put(str(entry.get("model", "") or "").strip(), alias)
  275. mdl = cfg.get("model", {}) or {}
  276. if isinstance(mdl, dict):
  277. simple = mdl.get("aliases")
  278. if isinstance(simple, dict):
  279. for alias, val in simple.items():
  280. if isinstance(val, str) and val.strip():
  281. v = val.strip()
  282. _put(v.split("/", 1)[1] if "/" in v else v, alias)
  283. except Exception:
  284. pass
  285. _REVERSE_ALIAS_CACHE = rmap
  286. return _REVERSE_ALIAS_CACHE.get(model_name, model_name)
  287. def format_token_count_compact(*args, **kwargs):
  288. value = int(args[0] if args else kwargs.get("value", 0))
  289. abs_value = abs(value)
  290. if abs_value < 1_000:
  291. return str(value)
  292. sign = "-" if value < 0 else ""
  293. units = ((1_000_000_000, "B"), (1_000_000, "M"), (1_000, "K"))
  294. for threshold, suffix in units:
  295. if abs_value >= threshold:
  296. scaled = abs_value / threshold
  297. text = f"{scaled:.{2 if scaled < 10 else 1 if scaled < 100 else 0}f}"
  298. if "." in text:
  299. text = text.rstrip("0").rstrip(".")
  300. return f"{sign}{text}{suffix}"
  301. return f"{value:,}"
  302. realign_markdown_tables = _lazy_shim("agent.markdown_tables", "realign_markdown_tables")
  303. _COMMAND_SPINNER_FRAMES = ("⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏")
  304. # ~/.hermes/.env first, project .env as dev fallback; user env files override stale shell exports.
  305. from hermes_constants import get_hermes_home
  306. from hermes_cli.env_loader import load_hermes_dotenv
  307. from agent.i18n import t as _t
  308. _hermes_home = get_hermes_home()
  309. _project_env = Path(__file__).parent / '.env'
  310. load_hermes_dotenv(hermes_home=_hermes_home, project_env=_project_env)
  311. CLI_CONFIG = load_cli_config()
  312. _init_logging_and_display_from_config()
  313. # Neuter AsyncHttpxClientWrapper.__del__ before any AsyncOpenAI client exists: it
  314. # schedules aclose() on the running loop (prompt_toolkit's, during idle), closing
  315. # transports bound to dead worker loops ("Event loop is closed" / "Press ENTER to
  316. # continue..."). A meta_path finder patches ``openai._base_client`` at first import —
  317. # eager import costs ~166ms/30MB cold, and the patch is guaranteed to land before
  318. # instantiation. See ``agent.auxiliary_client.neuter_async_httpx_del``.
  319. try:
  320. import sys as _httpx_neuter_sys
  321. import importlib.util as _httpx_neuter_imp_util
  322. class _AsyncHttpxDelNeuter:
  323. """Patch ``AsyncHttpxClientWrapper.__del__`` to a no-op when ``openai._base_client`` loads."""
  324. _armed = True
  325. def find_spec(self, fullname, path=None, target=None):
  326. if not self._armed or fullname != "openai._base_client":
  327. return None
  328. # Disarm before delegating so the recursive find_spec doesn't loop through us.
  329. self._armed = False
  330. try:
  331. _httpx_neuter_sys.meta_path.remove(self)
  332. except ValueError:
  333. pass
  334. spec = _httpx_neuter_imp_util.find_spec(fullname)
  335. if spec is None or spec.loader is None:
  336. return None
  337. _orig_exec = spec.loader.exec_module
  338. def _patched_exec(module):
  339. _orig_exec(module)
  340. try:
  341. cls = getattr(module, "AsyncHttpxClientWrapper", None)
  342. if cls is not None:
  343. cls.__del__ = lambda self: None # type: ignore[assignment]
  344. except Exception:
  345. pass
  346. spec.loader.exec_module = _patched_exec # type: ignore[method-assign]
  347. return spec
  348. _httpx_neuter_sys.meta_path.insert(0, _AsyncHttpxDelNeuter())
  349. except Exception:
  350. pass
  351. # Agent/tool systems load lazily: bare startup only needs the prompt.
  352. def get_tool_definitions(*args, **kwargs):
  353. from hermes_cli.mcp_startup import wait_for_mcp_discovery
  354. from model_tools import get_tool_definitions as _get_tool_definitions
  355. wait_for_mcp_discovery()
  356. return _get_tool_definitions(*args, **kwargs)
  357. validate_toolset = _lazy_shim("toolsets", "validate_toolset")
  358. _cleanup_all_terminals = _lazy_shim("tools.terminal_tool", "cleanup_all_environments", "_cleanup_all_terminals")
  359. set_sudo_password_callback = _lazy_shim("tools.terminal_tool", "set_sudo_password_callback")
  360. set_approval_callback = _lazy_shim("tools.terminal_tool", "set_approval_callback")
  361. set_secret_capture_callback = _lazy_shim("tools.skills_tool", "set_secret_capture_callback")
  362. _cleanup_all_browsers = _lazy_shim("tools.browser_session_lifecycle", "emergency_cleanup_all_sessions", "_cleanup_all_browsers")
  363. _cleanup_done = False # _run_cleanup runs exactly once
  364. _cleanup_in_progress = False
  365. _session_end_messages: list[str] = [] # plugin on_session_finalize text awaiting the exit summary
  366. _cli_wake_owner = None
  367. # One-shot finalization runs before process cleanup (plugins see the boundary while the
  368. # agent is attached); atexit cleanup must not finalize those sessions again.
  369. _single_query_finalize_attempted_session_ids: set[str | None] = set()
  370. # /handoff sessions belong to the gateway: finalizing them here would stamp end_reason on
  371. # a row the gateway just reopened, making the handoff leg vanish from history.
  372. # Session IDs that were handed off to the gateway via /handoff. The CLI process exits after a successful
  373. # handoff, but the gateway now owns the session lifecycle — _run_cleanup must NOT call finalize_session on
  374. # these, because doing so sets end_reason on a row the gateway just reopened and is actively writing to
  375. # (#88234). The race made the handoff leg vanish from session history and broke session_search recall for
  376. # the handed-off session.
  377. _handed_off_session_ids: set[str | None] = set()
  378. _active_agent_ref = None # active AIAgent, for memory-provider shutdown at exit
  379. # Set once the TUI app starts (focus reporting + mouse tracking on); gates the on-exit
  380. # terminal reset so non-TUI one-shot runs never emit codes for modes they never enabled.
  381. _tui_input_modes_active = False
  382. # Set True once the TUI's prompt_toolkit app starts (which enables focus reporting + mouse tracking). Gates
  383. # the on-exit terminal reset so non-TUI one-shot CLI runs — which also register _run_cleanup via atexit —
  384. # don't emit escape codes for modes they never enabled (#36823).
  385. def _mark_tui_input_modes_active() -> None:
  386. """Record that the TUI app started, so _run_cleanup resets input modes."""
  387. global _tui_input_modes_active
  388. _tui_input_modes_active = True
  389. _signal_watchdog_armed = False
  390. def _arm_exit_watchdog_on_shutdown_signal() -> None:
  391. """Arm the exit backstop the moment a termination signal arrives (idempotent; never raises).
  392. The graceful unwind has wedge points BEFORE ``_run_cleanup`` arms its own watchdog
  393. (main thread in a syscall, prompt_toolkit teardown never returning). Leash is 2x
  394. the cleanup timeout so a progressing cleanup is never cut short. Never arm at
  395. startup: the timer exits unconditionally.
  396. SIGTERM/SIGHUP establish unambiguous shutdown intent, but the graceful path from signal →
  397. ``agent.interrupt()`` → ``app.exit()`` / ``KeyboardInterrupt`` → ``finally`` → ``_run_cleanup`` has
  398. several wedge points BEFORE ``_run_cleanup`` arms the normal watchdog: a main thread parked in a syscall
  399. that never observes the unwind, a prompt_toolkit teardown that never returns, or an agent worker
  400. blocking the ``finally``. When that happens the process has NO backstop and a "dead" CLI lingers
  401. (observed: ``hermes --tui`` alive ~47 min at 4% CPU after terminal close — the #65998 class).
  402. """
  403. global _signal_watchdog_armed
  404. if _signal_watchdog_armed:
  405. return
  406. _signal_watchdog_armed = True
  407. base = _exit_watchdog_timeout()
  408. if base <= 0:
  409. return # explicitly disabled
  410. with suppress(Exception): # never let the backstop break signal handling
  411. _arm_exit_watchdog(timeout_s=base * 2, from_signal=True)
  412. def _run_cleanup(*, notify_session_finalize: bool = True):
  413. """Run resource cleanup exactly once."""
  414. global _cleanup_done, _cleanup_in_progress
  415. if _cleanup_done:
  416. return
  417. _cleanup_done = True
  418. _cleanup_in_progress = True
  419. try:
  420. _arm_exit_watchdog()
  421. # Reset terminal input modes FIRST: teardown below can take seconds and a later
  422. # step raising must not skip the reset. No-op unless the TUI ran.
  423. # See #36823.
  424. _reset_terminal_input_modes_on_exit()
  425. for step, swallow in _CLEANUP_STEPS:
  426. with suppress(swallow):
  427. globals()[step]()
  428. if notify_session_finalize:
  429. cleanup_session_id = _active_agent_ref.session_id if _active_agent_ref else None
  430. if _should_emit_cleanup_session_finalize(cleanup_session_id):
  431. # Printed by _print_exit_summary, which clears the screen first.
  432. _session_end_messages.extend(
  433. _notify_session_finalize(session_id=cleanup_session_id, platform="cli", reason="shutdown"))
  434. try:
  435. _shutdown_agent_memory_provider(_active_agent_ref)
  436. except Exception as e:
  437. logger.warning("CLI cleanup memory shutdown failed: %s", e, exc_info=True)
  438. finally:
  439. _cleanup_in_progress = False
  440. def _reset_terminal_input_modes_on_exit() -> None:
  441. """Disable focus reporting + mouse tracking on TUI exit (best-effort).
  442. Ctrl+C / SIGTERM / crashes bypass prompt_toolkit's unwind, leaving focus events and
  443. mouse reports as visible text in the next shell. Writes to stdout when it is the
  444. terminal, else /dev/tty (the TUI may have run with stdout redirected).
  445. Called from ``_run_cleanup`` (atexit-registered + invoked on the normal / EOF / interrupt exit paths)
  446. this covers normal quit, Ctrl+C and SIGTERM/SIGHUP. ``kill -9`` is uncatchable, and the kanban worker's
  447. ``os._exit(0)`` path bypasses ``atexit``; neither runs this — but both are non-TTY / non-TUI, so there
  448. is nothing to reset there. See #36823.
  449. """
  450. global _tui_input_modes_active
  451. if not _tui_input_modes_active:
  452. return
  453. # Clear first so a re-armed _run_cleanup doesn't re-emit.
  454. _tui_input_modes_active = False
  455. try:
  456. stream = sys.stdout
  457. if stream is not None and stream.isatty():
  458. stream.write(_TERMINAL_INPUT_MODE_RESET_SEQ)
  459. stream.flush()
  460. return
  461. except Exception:
  462. pass
  463. with suppress(Exception), open("/dev/tty", "w", encoding="ascii") as tty:
  464. tty.write(_TERMINAL_INPUT_MODE_RESET_SEQ)
  465. tty.flush()
  466. from hermes_cli.worktree_ops import (
  467. _git_quiet,
  468. _git_repo_root,
  469. _maintain_pack_health,
  470. _prune_stale_worktrees,
  471. _repo_is_shallow,
  472. _setup_worktree,
  473. _worktree_has_unpushed_commits,
  474. _worktree_is_dirty,
  475. release_lsp_clients,
  476. )
  477. # ============================================================================= Git Worktree Isolation
  478. # (#652) =============================================================================
  479. _active_worktree: Optional[dict[str, str]] = None
  480. def _cleanup_worktree(info: dict[str, str] | None = None) -> None:
  481. """Remove a clean worktree and its branch on exit; preserve recoverable work."""
  482. global _active_worktree
  483. info = info or _active_worktree
  484. if not info:
  485. return
  486. wt_path, branch, repo_root = info["path"], info["branch"], info["repo_root"]
  487. if not Path(wt_path).exists():
  488. return
  489. _active_worktree = None
  490. from hermes_cli.worktree_exit import apply_exit_choice
  491. if apply_exit_choice(info, _cprint): # an exit-question answer not applied yet (normally none)
  492. return
  493. if _worktree_is_dirty(wt_path, repo_root, timeout=10):
  494. # Uncommitted work: say so, and don't hint at `remove --force`, which would destroy it.
  495. _cprint(f"\n\033[33m{_t('cli.worktree.uncommitted_keeping', path=wt_path)}\033[0m")
  496. return
  497. if _worktree_has_unpushed_commits(wt_path, timeout=10):
  498. if _repo_is_shallow(repo_root):
  499. # Shallow boundary makes the unpushed verdict unreliable; the startup pruner reaps later.
  500. _cprint(f"\n\033[33m{_t('cli.worktree.shallow_clone_keeping', path=wt_path)}\033[0m")
  501. print(f" {_t('cli.worktree.next_session_deepens')}")
  502. else:
  503. _cprint(f"\n\033[33m{_t('cli.worktree.unpushed_keeping', path=wt_path)}\033[0m")
  504. print(f" {_t('cli.worktree.clean_up_manually', path=wt_path)}")
  505. return
  506. from hermes_cli.worktree_ops import removal_blocked
  507. blocked = removal_blocked(wt_path) # an embedded repo or private ref dies with it
  508. if blocked:
  509. _cprint(f"\n\033[33m{_t('cli.worktree.kept_reason', path=wt_path, reason=blocked[1])}\033[0m")
  510. return
  511. # Release the tree's language servers while the path still exists, then unlock so `remove`
  512. # isn't blocked by the lock placed at creation. Fail-soft.
  513. release_lsp_clients(wt_path)
  514. _git_quiet(["worktree", "unlock", wt_path], repo_root, log="git worktree unlock failed (non-fatal)")
  515. _git_quiet(["worktree", "remove", wt_path, "--force"], repo_root, timeout=15, log="Failed to remove worktree")
  516. _git_quiet(["branch", "-D", branch], repo_root, log=f"Failed to delete branch {branch}")
  517. _cprint(f"\033[32m{_t('cli.worktree.cleaned_up', path=wt_path)}\033[0m")
  518. # Light/dark terminal detection (mirrors ui-tui/src/theme.ts detectLightMode()). Priority:
  519. # HERMES_LIGHT/HERMES_TUI_LIGHT env, HERMES_TUI_THEME, HERMES_TUI_BACKGROUND, COLORFGBG
  520. # (bg slot 7/15 = light), OSC 11 query, default dark. Cached so the terminal is queried once.
  521. _LIGHT_MODE_CACHE: bool | None = None
  522. def _detect_light_mode() -> bool:
  523. global _LIGHT_MODE_CACHE
  524. if _LIGHT_MODE_CACHE is not None:
  525. return _LIGHT_MODE_CACHE
  526. try:
  527. result = _detect_light_mode_uncached()
  528. except Exception:
  529. result = False
  530. _LIGHT_MODE_CACHE = result
  531. return result
  532. _install_skin_light_mode_hook()
  533. # Prime the light-mode cache when interactive so OSC 11 happens before prompt_toolkit owns the tty.
  534. with suppress(Exception):
  535. if sys.stdin.isatty() and sys.stdout.isatty():
  536. _detect_light_mode()
  537. _OUTPUT_HISTORY_ENABLED = True
  538. _OUTPUT_HISTORY_REPLAYING = False
  539. _OUTPUT_HISTORY_SUPPRESSED = False
  540. _OUTPUT_HISTORY_MAX_LINES = 200
  541. _OUTPUT_HISTORY = deque(maxlen=_OUTPUT_HISTORY_MAX_LINES)
  542. def _configure_output_history(enabled: bool, max_lines=200) -> None:
  543. """Configure recent CLI output replayed after terminal redraws."""
  544. global _OUTPUT_HISTORY_ENABLED, _OUTPUT_HISTORY_MAX_LINES, _OUTPUT_HISTORY
  545. _OUTPUT_HISTORY_ENABLED = bool(enabled)
  546. _OUTPUT_HISTORY_MAX_LINES = _coerce_output_history_limit(max_lines)
  547. _OUTPUT_HISTORY = deque(maxlen=_OUTPUT_HISTORY_MAX_LINES)
  548. @contextmanager
  549. def _suspend_output_history():
  550. global _OUTPUT_HISTORY_SUPPRESSED
  551. old_value = _OUTPUT_HISTORY_SUPPRESSED
  552. _OUTPUT_HISTORY_SUPPRESSED = True
  553. try:
  554. yield
  555. finally:
  556. _OUTPUT_HISTORY_SUPPRESSED = old_value
  557. def _replay_output_history(fit=None, output=None) -> None:
  558. """Repaint recent output above the prompt after a full screen clear.
  559. ``fit=(rows, columns, painted, top)`` replays only the newest lines whose wrapped height
  560. fits ``rows`` (see ``_output_tail_fitting``) — the older ones are still in scrollback
  561. (#95375) — from screen row ``top`` when known (``_set_chrome_floor``). ``output``: paint
  562. now, straight to this prompt_toolkit output, where the caller just erased the viewport and
  563. reset the renderer — ``run_in_terminal`` would first erase below the top row, which
  564. scroll-on-clear terminals (tmux) take as a clear and copy the blank screen into scrollback.
  565. """
  566. global _OUTPUT_HISTORY_REPLAYING
  567. if not _OUTPUT_HISTORY_ENABLED or not _OUTPUT_HISTORY:
  568. return
  569. _OUTPUT_HISTORY_REPLAYING = True
  570. try:
  571. rendered_lines = _output_history_lines()
  572. top = None
  573. if fit is not None:
  574. rows, columns, painted, top = fit
  575. rendered_lines = _output_tail_fitting(rendered_lines, rows, columns, painted)
  576. if rendered_lines:
  577. # One payload: per-line pt prints each force a sync redraw (a waterfall of old output).
  578. if output is None:
  579. _pt_print(_PT_ANSI("\n".join(rendered_lines)))
  580. else:
  581. from prompt_toolkit.renderer import print_formatted_text as _paint_formatted_text
  582. from prompt_toolkit.styles import Style
  583. _paint_formatted_text(output, _PT_ANSI("\n".join(rendered_lines) + "\n"), Style([]))
  584. size = output.get_size()
  585. if top is not None: # the chrome's top is now this many rows down
  586. top += sum(_line_rows(line, columns) for line in rendered_lines)
  587. _set_chrome_floor(max(0, size.rows - top))
  588. if size.columns != columns:
  589. _add_suspect_rows(top + 1 - size.rows)
  590. width = _painted_columns() if fit is None else columns
  591. for line in rendered_lines: # repainted: they wrap at today's width from now on
  592. if isinstance(line, _PaintedLine):
  593. line.width = width
  594. except Exception:
  595. pass
  596. finally:
  597. _OUTPUT_HISTORY_REPLAYING = False
  598. _strip_leaked_bracketed_paste_wrappers = _lazy_shim(
  599. "hermes_cli.input_sanitize", "strip_leaked_bracketed_paste_wrappers", "_strip_leaked_bracketed_paste_wrappers"
  600. )
  601. # OSC sequences (e.g. OSC-8 links): pt's ANSI parser strips the ESC but leaks the payload as text.
  602. _OSC_ESCAPE_RE = re.compile(r"\x1b\][\s\S]*?(?:\x07|\x1b\\)")
  603. def _looks_like_slash_command(text: str) -> bool:
  604. """``/help`` yes, ``/Users/x/file.md`` no: a command's first word has no further ``/``."""
  605. if not text or not text.startswith("/"):
  606. return False
  607. return "/" not in text.split()[0][1:]
  608. _skill_commands = None
  609. _skill_bundles = None
  610. def _slash_args(cmd: str) -> str:
  611. """Text after the slash-command word, stripped ("" when absent)."""
  612. parts = cmd.split(None, 1)
  613. return parts[1].strip() if len(parts) > 1 else ""
  614. def _ensure_skill_commands() -> dict:
  615. if _skill_commands is not None:
  616. return _skill_commands
  617. from agent.skill_commands import get_interactive_skill_commands
  618. return get_interactive_skill_commands()
  619. def get_skill_commands() -> dict:
  620. return _ensure_skill_commands()
  621. def _session_skill_commands(cli) -> dict:
  622. """Skill commands for ``cli``: on its gateway session the gateway's (its plugin skills included), so
  623. this process scans no plugin to list them; otherwise this process's own."""
  624. from hermes_cli import gateway_plugin_commands
  625. found = gateway_plugin_commands.skills(cli)
  626. return _ensure_skill_commands() if found is None else found
  627. build_skill_invocation_message = _lazy_shim("agent.skill_commands", "build_skill_invocation_message")
  628. build_preloaded_skills_prompt = _lazy_shim("agent.skill_commands", "build_preloaded_skills_prompt")
  629. def get_skill_bundles() -> dict:
  630. global _skill_bundles
  631. if _skill_bundles is None:
  632. from agent.skill_bundles import get_skill_bundles as _impl
  633. _skill_bundles = _impl()
  634. return _skill_bundles
  635. build_bundle_invocation_message = _lazy_shim("agent.skill_bundles", "build_bundle_invocation_message")
  636. def _get_plugin_cmd_handler_names() -> set:
  637. """Return plugin command names (without slash prefix) for dispatch matching."""
  638. try:
  639. from hermes_cli.plugins import get_plugin_commands
  640. return set(get_plugin_commands().keys())
  641. except Exception:
  642. return set()
  643. def _parse_skills_argument(skills: str | list[str] | tuple[str, ...] | None) -> list[str]:
  644. """Normalize a CLI skills flag into a deduplicated list of skill identifiers."""
  645. if not skills:
  646. return []
  647. raw_values = [str(item) for item in skills if item is not None] if isinstance(skills, (list, tuple)) else [str(skills)]
  648. parts = (p.strip() for raw in raw_values for p in raw.split(","))
  649. return list(dict.fromkeys(p for p in parts if p))
  650. def save_config_value(key_path: str, value: any) -> bool:
  651. """Persist dot-separated ``key_path`` = value into HERMES_HOME/config.yaml; True on success.
  652. Never the repo's cli-config.yaml: no config reader loads it, so the value would vanish.
  653. """
  654. config_path = get_hermes_home() / 'config.yaml'
  655. try:
  656. from hermes_constants import mkdir_under_hermes_home
  657. mkdir_under_hermes_home(config_path.parent)
  658. from hermes_cli.config_backend import write_config_key
  659. write_config_key(config_path, key_path, value)
  660. try: # owner-only: config files contain API keys
  661. os.chmod(config_path, 0o600)
  662. except (OSError, NotImplementedError):
  663. pass
  664. return True
  665. except Exception as e:
  666. logger.error("Failed to save config: %s", e)
  667. return False
  668. def _normalize_moa_model(model: Optional[str]) -> tuple[Optional[str], Optional[str]]:
  669. """``moa:<preset>`` -> ``("moa", preset)`` (same routing as ``/moa``); anything else -> ``(None, model)``.
  670. Returns ``("moa", "<preset>")`` when *model* selects the MoA virtual provider, otherwise ``(None,
  671. model)`` unchanged. This gives non-interactive ``hermes chat -Q -m moa:<preset>`` the same routing the
  672. interactive ``/moa`` command and the model picker already use: ``resolve_runtime_provider`` handles
  673. ``requested_provider == "moa"`` and ``agent_init`` builds the MoAClient off ``provider == "moa"``.
  674. Without this the raw ``moa:<preset>`` string is sent to the real provider and rejected with a 401/400
  675. "model not supported" (#56828).
  676. """
  677. if isinstance(model, str) and model.strip().lower().startswith("moa:"):
  678. preset = model.strip().split(":", 1)[1].strip()
  679. if preset:
  680. return "moa", preset
  681. return None, model
  682. _split_model_config_default = _lazy_shim("hermes_cli.config", "split_model_config_default", "_split_model_config_default")
  683. class _VoiceInputMessage:
  684. """Sentinel for voice-transcribed input so the concise voice prefix never applies to typed text.
  685. Distinguishes STT output from manually typed text while voice mode is active, so the
  686. concise-voice-response prefix is applied only to messages that actually came from the microphone
  687. (#65827).
  688. """
  689. __slots__ = ("text",)
  690. def __init__(self, text: str):
  691. self.text = text
  692. def __str__(self) -> str:
  693. return self.text
  694. class _SeededQueryMessage:
  695. """Sentinel for a ``-q`` prompt seeded into an interactive session; treated LITERALLY (no slash/!/file-drop)."""
  696. __slots__ = ("admission_id", "images", "text")
  697. def __init__(self, text: str, images=None, admission_id=None):
  698. self.text = text or ""
  699. self.images = list(images or [])
  700. # A ``/queue`` admission the gateway is running (#134889 N5): ``run_conversation`` pumps that
  701. # admission by this id, never by comparing the (sanitized) text.
  702. self.admission_id = admission_id
  703. def __str__(self) -> str:
  704. return self.text
  705. def _should_seed_interactive(query, image, quiet: bool, oneshot: bool) -> bool:
  706. """``-q`` seeds an interactive session only on a real TTY without ``--oneshot``/``-Q`` (automation answers and exits)."""
  707. if not (query or image) or oneshot or quiet:
  708. return False
  709. try:
  710. return bool(sys.stdin.isatty() and sys.stdout.isatty())
  711. except Exception:
  712. return False
  713. @dataclass
  714. class _ChatTurn:
  715. """Per-turn state shared by the ``chat()`` phases and the agent worker thread.
  716. ``result`` is written by the worker and read after the join; ``tts_normal_exit`` is
  717. set only when the TTS worker drained on its own so the last sentence is never cut.
  718. """
  719. result: Optional[dict] = None
  720. mute_notification_reply: bool = False
  721. use_streaming_tts: bool = False
  722. box_opened: bool = False
  723. thinking_started: bool = False
  724. text_queue: Optional[queue.Queue] = None
  725. tts_thread: Optional[threading.Thread] = None
  726. stream_callback: Optional[Any] = None
  727. stop_event: Optional[threading.Event] = None
  728. tts_normal_exit: bool = False
  729. voice_prefix: str = ""
  730. from hermes_cli.cli_chat_turn_mixin import CLIChatTurnMixin
  731. _PASTE_REF_RE = re.compile(r'\[Pasted text #\d+: \d+ lines \u2192 (.+?)\]')
  732. class HermesCLI(CLIBacktrackMixin, CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin, CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin, CLITuiMixin, CLIStatusBarMixin, CLIVoiceMixin, CLIModelSwitchMixin, CLISessionMixin, CLIStreamMixin, CLIModalMixin, CLITerminalMixin, CLIInfoMixin, CLILoopsMixin, CLIChatTurnMixin):
  733. """Interactive REPL for the Hermes Agent."""
  734. # Seeded -q first message (see _should_seed_interactive); run() re-creates
  735. # _pending_input, so it is enqueued only after the fresh queue exists.
  736. _seeded_first_message: Optional[_SeededQueryMessage] = None
  737. # Inspection surfaces (banner, /tools, status line) read this on partially built instances too.
  738. disabled_toolsets: Optional[list[str]] = None
  739. def __init__(
  740. self,
  741. model: str | None = None,
  742. toolsets: list[str] | None = None,
  743. provider: str | None = None,
  744. reasoning: str | None = None,
  745. api_key: str | None = None,
  746. base_url: str | None = None,
  747. max_turns: int | None = None,
  748. run_budget: float | None = None,
  749. verbose: Optional[bool] = None,
  750. compact: bool = False,
  751. resume: str | None = None,
  752. checkpoints: bool = False,
  753. pass_session_id: bool = False,
  754. ignore_rules: bool = False,
  755. ):
  756. """CLI args win over config; ``reasoning`` is per-run only; ``resume`` restores history from SQLite."""
  757. self._init_display_options(verbose, compact)
  758. self._init_model_routing(model, toolsets, provider, reasoning, api_key, base_url, max_turns, run_budget,
  759. checkpoints, pass_session_id, ignore_rules)
  760. self._init_runtime_state(resume)
  761. def _claim_active_session(self, surface: str = "cli", *, stderr: bool = False) -> bool:
  762. """Claim a global active-session slot for this CLI process."""
  763. if self._active_session_lease is not None:
  764. return True
  765. try:
  766. from hermes_cli.active_sessions import format_refusal_stderr, try_acquire_active_session
  767. lease, message = try_acquire_active_session(
  768. session_id=self.session_id,
  769. surface=surface,
  770. config=self.config,
  771. # Writer identity: a re-claim by this process replaces its own entry.
  772. # See #94595.
  773. metadata={"live_session_id": str(self.session_id)},
  774. )
  775. except Exception as exc:
  776. logger.warning("Failed to claim active session slot: %s", exc)
  777. return True
  778. if message:
  779. print(format_refusal_stderr(message), file=sys.stderr) if stderr else self._console_print(f"[bold red]{message}[/]")
  780. return False
  781. self._active_session_lease = lease
  782. with suppress(Exception):
  783. atexit.register(self._release_active_session)
  784. return True
  785. def _release_active_session(self) -> None:
  786. lease = getattr(self, "_active_session_lease", None)
  787. if lease is None:
  788. return
  789. try:
  790. lease.release()
  791. except Exception:
  792. logger.debug("Failed to release active session slot", exc_info=True)
  793. finally:
  794. self._active_session_lease = None
  795. _PET_FRAME_INTERVAL = 0.16
  796. _PET_CFG_INTERVAL = 2.5
  797. def _install_tool_callbacks(self) -> None:
  798. """Install tool callbacks that need the live prompt UI."""
  799. if self._tool_callbacks_installed:
  800. return
  801. set_sudo_password_callback(self._sudo_password_callback)
  802. set_approval_callback(self._approval_callback)
  803. set_secret_capture_callback(self._secret_capture_callback)
  804. from agent.vault_backends.unlock import set_code_prompt_callback, set_save_login_prompt_callback, set_unlock_prompt_callback
  805. set_unlock_prompt_callback(self._vault_unlock_callback)
  806. set_save_login_prompt_callback(self._vault_save_login_callback)
  807. set_code_prompt_callback(self._vault_code_callback)
  808. self._tool_callbacks_installed = True
  809. def _show_security_advisories(self):
  810. """Startup banner for unacked security advisories, on stderr (piped stdout stays clean); 24h rate-limited."""
  811. try:
  812. from hermes_cli.security_advisories import detect_compromised, startup_banner
  813. banner = startup_banner(detect_compromised())
  814. if banner:
  815. print(banner, file=sys.stderr, flush=True)
  816. except Exception:
  817. pass # never block startup
  818. def finalize_preloaded_skills(self) -> None:
  819. """Join the background --skills preload and fold it into the prompt (idempotent).
  820. Raises ``ValueError`` only when EVERY requested skill was unknown.
  821. """
  822. if getattr(self, "_preload_skills_finalized", False):
  823. return
  824. thread = getattr(self, "_preload_skills_thread", None)
  825. if thread is None:
  826. self._preload_skills_finalized = True
  827. return
  828. thread.join(timeout=120)
  829. self._preload_skills_finalized = True
  830. err = getattr(self, "_preload_skills_error", None)
  831. if err is not None:
  832. raise err
  833. auto_result = getattr(self, "_auto_load_skills_result", None)
  834. if auto_result and auto_result[2]:
  835. logger.warning("skills.auto_load: skill(s) not found or disabled, skipped: %s", ", ".join(auto_result[2]))
  836. # auto_load names first, then explicit -s names that were not already pinned.
  837. self.preloaded_skills = list(auto_result[1]) if auto_result else []
  838. result = getattr(self, "_preload_skills_result", None)
  839. if not result:
  840. return
  841. skills_prompt, loaded_skills, missing_skills = result
  842. if missing_skills:
  843. from agent.skill_commands import format_missing_skills
  844. # A typo'd name must not crash a kanban worker; only a fully-missing set fails loudly.
  845. if not loaded_skills:
  846. raise ValueError(format_missing_skills(missing_skills))
  847. logger.warning("Skipping %s. Continuing with: %s. List available skills with `hermes skills list`.",
  848. format_missing_skills(missing_skills), ", ".join(loaded_skills))
  849. if skills_prompt:
  850. self.system_prompt = "\n\n".join(p for p in (self.system_prompt, skills_prompt) if p).strip()
  851. self.preloaded_skills += [name for name in loaded_skills if name not in self.preloaded_skills]
  852. def _show_tool_availability_warnings(self):
  853. """Warn about toolsets switched off at startup (missing API keys, unusable terminal backend)."""
  854. try:
  855. # Runs on a daemon thread on the snapshot fast path: keep the imports to modules the
  856. # registry walk already loaded plus the pure notices module (a heavy import here races
  857. # importlib's module locks against the main thread).
  858. from model_tools import check_tool_availability
  859. from hermes_cli.tool_availability_notices import (
  860. current_terminal_backend, filter_to_enabled_toolsets, tool_availability_warning_lines,
  861. )
  862. from tools.terminal_tool import terminal_backend_unavailable_reason
  863. from toolsets import resolve_toolset
  864. _, unavailable = check_tool_availability()
  865. # Only toolsets this CLI session actually has. The selection is usually a composite bundle
  866. # (``hermes-cli``), so expand it to tool names before matching — a raw name comparison
  867. # matched nothing on a default install and silently dropped the terminal notice.
  868. unavailable = filter_to_enabled_toolsets(unavailable, self.enabled_toolsets or [], resolve_toolset)
  869. lines = tool_availability_warning_lines(
  870. unavailable, terminal_reason=terminal_backend_unavailable_reason(),
  871. terminal_backend=current_terminal_backend())
  872. if lines:
  873. self._console_print()
  874. for line in lines:
  875. self._console_print(line)
  876. except Exception:
  877. pass
  878. def show_config(self):
  879. """Display current configuration with kawaii ASCII art."""
  880. from hermes_cli.config_backend import config_exists
  881. terminal_env = os.getenv("TERMINAL_ENV", "local")
  882. terminal_cwd = os.getenv("TERMINAL_CWD", os.getcwd())
  883. terminal_timeout = os.getenv("TERMINAL_TIMEOUT", "60")
  884. config_path = _hermes_home / 'config.yaml'
  885. if not config_exists(config_path):
  886. config_path = Path(__file__).parent / 'cli-config.yaml'
  887. config_status = _t("cli.config.loaded") if config_exists(config_path) else _t("cli.config.not_found")
  888. from hermes_cli.config_backend import get_config_backend
  889. if not get_config_backend().supports_file_tooling(): # no local file: name where config comes from
  890. config_path, config_status = get_config_backend().describe(_hermes_home), ""
  891. # ``api_key`` may be a callable bearer provider (Entra ID, Vertex OAuth, key_cmd, ...):
  892. # label it by its tagged source and never invoke it (that would mint a token just to mask
  893. # it). Prefer the LIVE agent's key: the constructor seeds self.api_key from env before
  894. # provider resolution, so on non-OpenAI providers it can be another vendor's key.
  895. from agent.credential_source import credential_label
  896. display_key = self.api_key
  897. if self.agent is not None and getattr(self.agent, "api_key", None):
  898. display_key = self.agent.api_key
  899. if label := credential_label(display_key):
  900. api_key_display = label
  901. elif isinstance(display_key, str) and len(display_key) > 12:
  902. api_key_display = f"{display_key[:8]}...{display_key[-4:]}"
  903. else:
  904. api_key_display = _t("cli.config.api_key_not_set")
  905. title = _t("cli.config.title")
  906. width = 50
  907. pad = width - len(title)
  908. _unset = _t("cli.config.value_not_set")
  909. ssh_target = (
  910. f"{os.getenv('TERMINAL_SSH_USER', _unset)}@{os.getenv('TERMINAL_SSH_HOST', _unset)}"
  911. f":{os.getenv('TERMINAL_SSH_PORT', '22')}"
  912. ) if terminal_env == "ssh" else None
  913. # (section key, ((label key, value), ...)); labels are re-padded at print time so
  914. # translated widths still line up instead of carrying alignment spaces in the catalog.
  915. sections = (
  916. ("cli.config.section_model", (
  917. ("cli.config.label_model", self.model),
  918. ("cli.config.label_base_url", self.base_url),
  919. ("cli.config.label_api_key", api_key_display))),
  920. ("cli.config.section_terminal", (
  921. ("cli.config.label_environment", terminal_env),
  922. *((("cli.config.label_ssh_target", ssh_target),) if ssh_target else ()),
  923. ("cli.config.label_working_dir", terminal_cwd),
  924. ("cli.config.label_timeout", f"{terminal_timeout}s"),
  925. )),
  926. ("cli.config.section_agent", (
  927. ("cli.config.label_max_turns", self.max_turns),
  928. ("cli.config.label_toolsets", ", ".join(self.enabled_toolsets) if self.enabled_toolsets else "all"),
  929. ("cli.config.label_verbose", self.verbose),
  930. )),
  931. ("cli.config.section_session", (
  932. ("cli.config.label_started", self.session_start.strftime("%Y-%m-%d %H:%M:%S")),
  933. ("cli.config.label_config_file", f"{config_path} {config_status}"),
  934. )),
  935. )
  936. print()
  937. print("+" + "-" * width + "+")
  938. print("|" + " " * (pad // 2) + title + " " * (pad - pad // 2) + "|")
  939. print("+" + "-" * width + "+")
  940. for section_key, rows in sections:
  941. print()
  942. print(f" -- {_t(section_key)} --")
  943. label_width = max(len(_t(label_key)) for label_key, _ in rows)
  944. for label_key, value in rows:
  945. print(f" {_t(label_key):<{label_width}} {value}")
  946. print()
  947. # canonical command -> (method name, pass cmd_original?). Absent commands resolve to
  948. # ``_handle_<name>_command(cmd)``. Looked up via getattr at dispatch time so
  949. # monkeypatching works. A handler returning False exits the REPL.
  950. _SLASH_DISPATCH: dict[str, tuple[str, bool]] = {
  951. "exit": ("_cmd_exit", True), "quit": ("_cmd_exit", True), "help": ("_cmd_help", True),
  952. "palette": ("_open_command_palette", False), "whoami": ("_handle_whoami_command", False),
  953. "profile": ("_handle_profile_command", False), "toolsets": ("show_toolsets", False),
  954. "config": ("show_config", False), "redraw": ("_cmd_redraw", True), "clear": ("_cmd_clear", True),
  955. "history": ("show_history", False), "title": ("_cmd_title", True), "new": ("_cmd_new", True),
  956. "model": ("_handle_model_switch", True), "codex-runtime": ("_handle_codex_runtime", True),
  957. "retry": ("_cmd_retry", True), "prompt": ("_handle_prompt_compose_command", True),
  958. "undo": ("_cmd_undo", True), "save": ("save_conversation", True), "skills": ("_cmd_skills", True),
  959. "platforms": ("_show_gateway_status", False), "status": ("_show_session_status", False),
  960. "context": ("_show_context_breakdown", True), "egress": ("_cmd_egress", True),
  961. "statusbar": ("_cmd_statusbar", True), "verbose": ("_toggle_verbose", False), "yolo": ("_toggle_yolo", False),
  962. "compress": ("_manual_compress", True), "subscription": ("_show_subscription", False),
  963. "topup": ("_show_billing", True), "insights": ("_show_insights", True), "update": ("_cmd_update", True),
  964. "version": ("_cmd_version", True), "paste": ("_handle_paste_command", False), "reload": ("_cmd_reload", True),
  965. "reload-mcp": ("_confirm_and_reload_mcp", True), "reload-skills": ("_cmd_reload_skills", True),
  966. "plugins": ("_cmd_plugins", True), "stop": ("_handle_stop_command", False),
  967. "agents": ("_handle_agents_command", False), "bg": ("_handle_background_command", True),
  968. "queue": ("_cmd_queue", True), "steer": ("_cmd_steer", True), "moa": ("_cmd_moa", True),
  969. }
  970. @classmethod
  971. def _slash_handler(cls, canonical: str) -> tuple[str, bool] | None:
  972. """(method name, pass cmd_original?) for a registered command, else None."""
  973. entry = cls._SLASH_DISPATCH.get(canonical)
  974. if entry is None:
  975. name = f"_handle_{canonical.replace('-', '_')}_command"
  976. if callable(getattr(cls, name, None)):
  977. entry = (name, True)
  978. return entry
  979. # Shared-metrics surface for user-typed commands; None where another process owns the count
  980. # (the TUI slash worker: tui_gateway records the command it forwards).
  981. _slash_metrics_surface: str | None = "cli"
  982. def process_command(self, command: str, *, redispatch: bool = False) -> bool:
  983. """Dispatch a slash command; returns False to exit the REPL. ``redispatch`` marks an internal
  984. re-entry (quick-command alias, prefix expansion) so the user's command is counted once."""
  985. cmd_lower = command.lower().strip() # lowercase only for matching; args keep their case
  986. cmd_original = command.strip()
  987. # Aliases resolve via the central registry (hermes_cli/commands.py).
  988. from hermes_cli.commands import resolve_command as _resolve_cmd
  989. _base_word = cmd_lower.split()[0].lstrip("/")
  990. _cmd_def = _resolve_cmd(_base_word)
  991. canonical = _cmd_def.name if _cmd_def else _base_word
  992. if not redispatch and self._slash_metrics_surface:
  993. from hermes_cli.observability.shared_metrics_events import record_slash_command
  994. record_slash_command(command=canonical, surface=self._slash_metrics_surface)
  995. # A bare `/resume` prompt is one-shot: any other command disarms it so a later
  996. # number isn't swallowed as a stale selection.
  997. # See #34584.
  998. if canonical not in {"resume", "sessions"}:
  999. # Armed when a bare `/resume` prints the recent-sessions list so the very next bare numeric
  1000. # input (e.g. `3`) resolves to that session. Holds the exact list used for index resolution;
  1001. # one-shot (cleared on the next submitted input, whether it's the selection or anything else).
  1002. # See #34584.
  1003. self._pending_resume_sessions = None
  1004. entry = self._slash_handler(canonical)
  1005. from hermes_cli.gateway_setting_commands import run as run_gateway_setting
  1006. if entry is not None and run_gateway_setting(self, canonical, cmd_original):
  1007. return True # a per-session setting the gateway's handler applied (pre_command fired there)
  1008. # Observer-only pre_command plugin hook (return values ignored; never raises), fired by the gateway
  1009. # for a command this process runs (not a named refusal, not a command with no handler here).
  1010. from hermes_cli.gateway_cli_commands import REFUSED
  1011. from hermes_cli.gateway_plugin_commands import observe
  1012. runs = entry is not None and canonical not in REFUSED
  1013. if _cmd_def is not None and not observe(self, _base_word, _slash_args(cmd_original), runs=runs):
  1014. from hermes_cli.plugins import fire_pre_command_hook
  1015. fire_pre_command_hook(
  1016. surface="cli", command=canonical, alias_used=_base_word, args_raw=_slash_args(cmd_original),
  1017. session_key=getattr(self, "session_id", None), platform="cli",
  1018. )
  1019. if entry is None:
  1020. return self._process_unregistered_slash(cmd_original, cmd_lower)
  1021. from hermes_cli.gateway_cli_commands import run as run_gateway_command
  1022. if run_gateway_command(self, canonical, cmd_original):
  1023. return True # state the gateway session owns (checkpoints, .env, handoff)
  1024. method_name, pass_arg = entry
  1025. handler = getattr(self, method_name)
  1026. result = handler(cmd_original) if pass_arg else handler()
  1027. return result is not False
  1028. def _process_unregistered_slash(self, cmd_original: str, cmd_lower: str) -> bool:
  1029. """Slash input with no built-in handler; precedence: quick_commands -> plugins -> bundles -> skills -> prefix expansion."""
  1030. base_cmd = cmd_lower.split()[0]
  1031. bare = base_cmd.lstrip("/")
  1032. skill_bundles = get_skill_bundles()
  1033. quick_commands = self.config.get("quick_commands", {})
  1034. user_args = cmd_original[len(base_cmd):].strip()
  1035. if bare in quick_commands:
  1036. return self._run_quick_command(base_cmd, quick_commands[bare], user_args)
  1037. from hermes_cli import gateway_plugin_commands
  1038. try:
  1039. plugin = gateway_plugin_commands.lookup(self, bare) # the gateway's; None off the gateway
  1040. except gateway_plugin_commands.CatalogUnavailable:
  1041. return True # printed; an unreadable catalog never selects a skill, bundle or expansion
  1042. gone = False
  1043. skill_commands = _session_skill_commands(self) # after lookup: the catalog its miss re-read
  1044. if plugin or (plugin is None and bare in _get_plugin_cmd_handler_names()):
  1045. gone = self._run_plugin_slash_command(base_cmd, user_args) is gateway_plugin_commands.GONE
  1046. if not gone:
  1047. return True
  1048. skill_commands = _session_skill_commands(self) # the reload may have changed the skills
  1049. if base_cmd in skill_bundles: # also a name a gateway plugin reload just dropped (GONE)
  1050. self._run_skill_bundle_command(base_cmd, skill_bundles[base_cmd], user_args)
  1051. elif base_cmd in skill_commands:
  1052. self._run_skill_slash_command(base_cmd, skill_commands[base_cmd], user_args)
  1053. elif not (gone and gateway_plugin_commands.report_gone(bare, skill_commands, skill_bundles)):
  1054. return self._expand_slash_prefix(cmd_original, cmd_lower, skill_commands, skill_bundles)
  1055. return True
  1056. def _run_quick_command(self, base_cmd: str, qcmd: dict, user_args: str) -> bool:
  1057. """User-defined quick command (config.yaml): ``exec`` runs a shell snippet, ``alias`` re-dispatches."""
  1058. qtype = qcmd.get("type")
  1059. if qtype == "alias":
  1060. target = qcmd.get("target", "").strip()
  1061. if target:
  1062. target = target if target.startswith("/") else f"/{target}"
  1063. return self.process_command(f"{target} {user_args}".strip(), redispatch=True)
  1064. self._console_print(f"[bold red]{_t('cli.quick.no_target', command=base_cmd)}[/]")
  1065. return True
  1066. if qtype != "exec":
  1067. self._console_print(f"[bold red]{_t('cli.quick.unsupported_type', command=base_cmd)}[/]")
  1068. return True
  1069. import subprocess
  1070. exec_cmd = qcmd.get("command", "")
  1071. if not exec_cmd:
  1072. self._console_print(f"[bold red]{_t('cli.quick.no_command', command=base_cmd)}[/]")
  1073. return True
  1074. try:
  1075. # shell=True is intentional (user-authored config snippets, never LLM controlled);
  1076. # the env is sanitized because this process holds every API key.
  1077. from tools.environments.local import build_subprocess_env
  1078. from hermes_cli._subprocess_compat import windows_hide_flags
  1079. result = subprocess.run(
  1080. exec_cmd, shell=True, capture_output=True, text=True, encoding="utf-8", errors="replace",
  1081. timeout=30, env=build_subprocess_env(),
  1082. creationflags=windows_hide_flags(), # no console flash on Windows (#56747),
  1083. check=False,
  1084. )
  1085. # See #56747.
  1086. output = result.stdout.strip() or result.stderr.strip()
  1087. if output:
  1088. from agent.redact import redact_sensitive_text
  1089. self._console_print(_rich_text_from_ansi(redact_sensitive_text(output)))
  1090. else:
  1091. self._console_print(f"[dim]{_t('cli.quick.no_output')}[/]")
  1092. except subprocess.TimeoutExpired:
  1093. self._console_print(f"[bold red]{_t('cli.quick.timed_out')}[/]")
  1094. except Exception as e:
  1095. self._console_print(f"[bold red]{_t('cli.quick.error', error=str(e))}[/]")
  1096. return True
  1097. def _run_plugin_slash_command(self, base_cmd: str, user_args: str):
  1098. from hermes_cli import gateway_plugin_commands
  1099. answered = gateway_plugin_commands.run(self, base_cmd.lstrip("/"), user_args)
  1100. if answered:
  1101. return answered # ran beside the plugin's hooks, tools and MCP servers in the gateway, or GONE
  1102. from hermes_cli.plugin_command_dispatch import invoke_plugin_command
  1103. from hermes_cli.plugins import get_plugin_command_handler, resolve_plugin_command_result
  1104. plugin_handler = get_plugin_command_handler(base_cmd.lstrip("/"))
  1105. if not plugin_handler:
  1106. return
  1107. session_id = getattr(self, "session_id", None) or ""
  1108. from hermes_cli.plugin_choices import bind_asker, clarify_asker
  1109. try:
  1110. with bind_asker(clarify_asker(self._clarify_callback)): # ctx.ask_choice: the clarify panel
  1111. result = resolve_plugin_command_result(invoke_plugin_command(
  1112. plugin_handler, user_args, source=None, session_id=session_id, session_key=session_id,
  1113. platform="cli"))
  1114. if result:
  1115. _cprint(str(result))
  1116. except Exception as e:
  1117. _cprint(f"\033[1;31m{_t('cli.plugin.command_error', error=str(e))}{_RST}")
  1118. def _queue_skill_message(self, msg) -> None:
  1119. if hasattr(self, '_pending_input'):
  1120. self._pending_input.put(msg)
  1121. def _run_skill_bundle_command(self, base_cmd: str, bundle_info: dict, user_instruction: str) -> None:
  1122. """``/<bundle>`` loads several skills at once (bundles win over same-named skills)."""
  1123. bundle_result = build_bundle_invocation_message(base_cmd, user_instruction, task_id=self.session_id)
  1124. if not bundle_result:
  1125. ChatConsole().print(f"[bold red]{_t('cli.skills.bundle_load_failed', command=base_cmd)}[/]")
  1126. return
  1127. msg, loaded_names, missing = bundle_result
  1128. self._queue_loaded_skills(
  1129. msg, _t("cli.skills.loading_bundle", name=bundle_info['name'], count=str(len(loaded_names))), missing)
  1130. def _queue_loaded_skills(self, msg, label: str, missing) -> None:
  1131. print(f"\n⚡ {label}")
  1132. if missing:
  1133. ChatConsole().print(f"[yellow]{_t('cli.skills.skipped_missing', names=', '.join(missing))}[/]")
  1134. self._queue_skill_message(msg)
  1135. def _run_skill_slash_command(self, base_cmd: str, skill_info: dict, rest: str) -> None:
  1136. """``/<skill> ...``; stacked ``/skill-a /skill-b do XYZ`` loads every leading skill (up to 5)."""
  1137. from hermes_cli import gateway_plugin_commands
  1138. if gateway_plugin_commands.run_skill(self, base_cmd, rest):
  1139. return # the gateway session's skill, loaded there
  1140. from agent.skill_commands import build_stacked_skill_invocation_message, split_stacked_skill_commands
  1141. # Interactive surface: stacked tokens resolve against the interactive
  1142. # map so plugin skills stack in the CLI like native skills.
  1143. extra_keys, user_instruction = split_stacked_skill_commands(rest, interactive=True)
  1144. if extra_keys:
  1145. stacked_result = build_stacked_skill_invocation_message(
  1146. [base_cmd, *extra_keys], user_instruction, task_id=self.session_id,
  1147. )
  1148. if not stacked_result:
  1149. ChatConsole().print(f"[bold red]{_t('cli.skills.stacked_load_failed', command=base_cmd)}[/]")
  1150. return
  1151. msg, loaded_names, missing = stacked_result
  1152. self._queue_loaded_skills(
  1153. msg, _t("cli.skills.loading_stacked", count=str(len(loaded_names)), names=', '.join(loaded_names)),
  1154. missing,
  1155. )
  1156. return
  1157. msg = build_skill_invocation_message(base_cmd, rest, task_id=self.session_id)
  1158. if msg:
  1159. self._queue_loaded_skills(msg, _t("cli.skills.loading_skill", name=skill_info['name']), None)
  1160. else:
  1161. ChatConsole().print(f"[bold red]{_t('cli.skills.skill_load_failed', command=base_cmd)}[/]")
  1162. def _expand_slash_prefix(self, cmd_original: str, cmd_lower: str, skill_commands, skill_bundles) -> bool:
  1163. """Unique-prefix expansion against built-in COMMANDS + skill commands/bundles (agrees with tab-completion)."""
  1164. from hermes_cli.commands import COMMANDS
  1165. typed_base = cmd_lower.split()[0]
  1166. all_known = set(COMMANDS) | set(skill_commands) | set(skill_bundles)
  1167. matches = [c for c in all_known if c.startswith(typed_base)]
  1168. if len(matches) > 1:
  1169. if typed_base in matches:
  1170. matches = [typed_base]
  1171. else:
  1172. # Unique shortest match wins: /qui -> /quit (5) over /quint-pipeline (15)
  1173. min_len = min(len(c) for c in matches)
  1174. shortest = [c for c in matches if len(c) == min_len]
  1175. if len(shortest) == 1:
  1176. matches = shortest
  1177. if len(matches) == 1 and matches[0] != typed_base:
  1178. # Expand to the full name, preserving arguments.
  1179. return self.process_command(matches[0] + cmd_original.strip()[len(typed_base):], redispatch=True)
  1180. if len(matches) > 1:
  1181. _cprint(f"{_ACCENT}{_t('cli.command.ambiguous', command=cmd_lower)}{_RST}")
  1182. _cprint(f"{_DIM}{_t('cli.command.did_you_mean_many', candidates=', '.join(sorted(matches)))}{_RST}")
  1183. else:
  1184. # Exact token with no handler (never re-dispatch the same token: recursion), or no match.
  1185. from hermes_cli.cli_unknown_command import unknown_command_lines
  1186. lead, pointer = unknown_command_lines(cmd_lower, all_known)
  1187. _cprint(f"\033[1;31m{lead}{_RST}")
  1188. _cprint(f"{_DIM}{_ACCENT}{pointer}{_RST}")
  1189. return True
  1190. def _drain_interrupt_queue_to_pending_input(self) -> None:
  1191. """Move stray ``_interrupt_queue`` messages into ``_pending_input`` after every turn.
  1192. Busy-time input lands in ``_interrupt_queue`` and is only drained by the explicit
  1193. interrupt path; a turn that finishes naturally would otherwise strand it and the
  1194. CLI appears to hang. Never raises.
  1195. Called once at the end of every turn from ``process_loop``'s ``finally`` block. Catches and swallows
  1196. ``Exception`` because the drain must never break the main loop. (#20271)
  1197. """
  1198. try:
  1199. while not self._interrupt_queue.empty():
  1200. stray = self._interrupt_queue.get_nowait()
  1201. if stray:
  1202. self._pending_input.put(stray)
  1203. except Exception:
  1204. pass
  1205. def _on_reasoning(self, reasoning_text: str):
  1206. """Callback for intermediate reasoning display during tool-call loops."""
  1207. if not reasoning_text:
  1208. return
  1209. self._reasoning_preview_buf = getattr(self, "_reasoning_preview_buf", "") + reasoning_text
  1210. self._flush_reasoning_preview(force=False)
  1211. # Inline tokens that bypass the destructive-slash confirmation modal (scripting, or
  1212. # when the modal can't be marshaled onto the app loop).
  1213. # A general escape hatch for non-interactive use (scripting/automation) and for the degraded path where
  1214. # the modal can't be marshaled onto the app loop — lets users self-serve without flipping
  1215. # approvals.destructive_slash_confirm in config. (Native Windows now drives the modal normally — see
  1216. # #33961.)
  1217. _DESTRUCTIVE_SKIP_TOKENS = frozenset({"now", "--yes", "-y"})
  1218. def run(self):
  1219. """Run the interactive CLI loop with persistent input at bottom."""
  1220. if not self._claim_active_session("cli"):
  1221. return
  1222. self._tui_print_startup()
  1223. self._tui_init_run_state()
  1224. kb = self._tui_build_key_bindings()
  1225. layout, style = self._tui_build_layout(kb)
  1226. app = self._tui_build_application(layout, kb, style)
  1227. _disable_prompt_toolkit_cpr_warning(app)
  1228. app.after_render += self._pet_flush_kitty_frame
  1229. from hermes_cli.observability.shared_metrics_startup import cli_prompt_ready_handler
  1230. app.after_render += cli_prompt_ready_handler()
  1231. self._app = app
  1232. # Ghost status-bar lines on resize: pt's renderer scrolls the terminal after each
  1233. # paint, pushing chrome into scrollback where a column-shrink reflows it into
  1234. # duplicates. Wrapping _output_screen_diff keeps its reserve-space branch from firing.
  1235. try:
  1236. # Background: prompt_toolkit's renderer (renderer.py L232-242) explicitly moves the cursor to
  1237. # the bottom of the canvas after painting "to make sure the terminal scrolls up, even when the
  1238. # lower lines of the canvas just contain whitespace". In non-fullscreen mode this scrolls chrome
  1239. # content (status bar, input rules) into terminal scrollback on every render. When the terminal
  1240. # column-shrinks, the emulator reflows the previously rendered full-width rows into multiple
  1241. # narrower rows that get pushed up — leaving ghost duplicates AND polluting scrollback. Same
  1242. # issue as pt #29 (open since 2014), #1675, #1933. Surgical fix: wrap _output_screen_diff so
  1243. # that when its internal `if current_height > previous_screen.height` branch fires (the one that
  1244. # does the bottom-cursor-move), we make it fall through by inflating previous_screen.height
  1245. # first.
  1246. import prompt_toolkit.renderer as _pt_renderer
  1247. from prompt_toolkit.renderer import _output_screen_diff as _orig_osd
  1248. if not getattr(_pt_renderer, "_hermes_osd_patched", False):
  1249. _pt_renderer._output_screen_diff = functools.partial(
  1250. _hermes_call_output_screen_diff, _orig_osd
  1251. )
  1252. _pt_renderer._hermes_osd_patched = True
  1253. except Exception:
  1254. pass
  1255. _apply_bracketed_paste_timeout_patch()
  1256. self._install_resize_recovery(app)
  1257. threading.Thread(target=self._tui_spinner_loop, daemon=True).start()
  1258. threading.Thread(target=self._tui_process_loop, daemon=True).start()
  1259. # Wake word listener off-thread so a first-run engine install never blocks the prompt.
  1260. threading.Thread(target=self._tui_wake_startup, daemon=True, name="wake-startup").start()
  1261. atexit.register(_run_cleanup)
  1262. self._tui_install_signal_handlers()
  1263. if not self._tui_stdin_usable():
  1264. _run_cleanup()
  1265. self._print_exit_summary()
  1266. return
  1267. try:
  1268. with patch_stdout():
  1269. try:
  1270. # run_in_terminal() may return either: • a coroutine / Future (prompt_toolkit ≥ 3.0) —
  1271. # must be scheduled via ensure_future so the coroutine is actually awaited; calling it
  1272. # bare would leave it unawaited and silently drop the output (fixes #23185 Bug A). •
  1273. # None (some mocks / older PT builds) — just call the inner function directly since PT
  1274. # already executed it synchronously. Do NOT fall back to a bare _pt_print when
  1275. # ensure_future raises, because run_in_terminal already invoked the lambda in that case
  1276. # (the mock path), which would double-print the line.
  1277. import asyncio as _aio
  1278. _aio.get_running_loop().set_exception_handler(self._tui_suppress_closed_loop_errors)
  1279. except Exception:
  1280. pass # no running loop -- nothing to patch
  1281. # Record that the app enables focus reporting + mouse tracking so _run_cleanup
  1282. # resets them; extended key modes are popped by the same reset.
  1283. # When multiline shortcuts are on, also ask supported terminals (e.g. iTerm2) to report
  1284. # modified keys distinctly (kitty protocol + modifyOtherKeys); the cleanup reset pops both
  1285. # modes. See #36823.
  1286. _mark_tui_input_modes_active()
  1287. if self._tui_multiline_shortcuts:
  1288. _enable_extended_enter_keys(app.output)
  1289. self._pet_start_anim()
  1290. app.run()
  1291. except (EOFError, KeyboardInterrupt, BrokenPipeError):
  1292. pass
  1293. except (KeyError, OSError) as _stdin_err:
  1294. # Selector registration failures from broken stdin and I/O errors from a
  1295. # broken stdout during interrupt (EIO is suppressed).
  1296. _errno = getattr(_stdin_err, "errno", None) if isinstance(_stdin_err, OSError) else None
  1297. _msg = str(_stdin_err)
  1298. if _errno == errno.EIO:
  1299. pass
  1300. elif _errno in {errno.EINVAL, errno.EBADF} or any(
  1301. s in _msg for s in ("is not registered", "Bad file descriptor", "Invalid argument")
  1302. ):
  1303. print(_t("cli.startup.stdin_unusable", error=str(_stdin_err)))
  1304. else:
  1305. raise
  1306. finally:
  1307. # A resize right before exit leaves its recovery (and the paints it held) unrun.
  1308. _release_paints()
  1309. self._tui_shutdown()
  1310. # /update relaunch happens here, after prompt_toolkit restored terminal modes, on the
  1311. # main thread (the process_loop thread would skip cleanup / only exit itself on Windows).
  1312. if self._pending_relaunch:
  1313. from hermes_cli.relaunch import relaunch
  1314. relaunch(self._pending_relaunch, preserve_inherited=False)
  1315. def _build_cli_from_args(model, toolsets, provider, reasoning, api_key, base_url, max_turns, run_budget, verbose, compact, resume, checkpoints, pass_session_id, ignore_rules, skills):
  1316. """Resolve the toolset list (explicit / coding posture / platform default), construct HermesCLI, and start the background skills preload."""
  1317. toolsets_list = None
  1318. if isinstance(toolsets, str) and toolsets:
  1319. toolsets_list = [t.strip() for t in toolsets.split(",")]
  1320. elif isinstance(toolsets, (list, tuple)) and toolsets:
  1321. # Fire may pass multiple --toolsets as a tuple
  1322. toolsets_list = []
  1323. for t in toolsets:
  1324. toolsets_list.extend([x.strip() for x in t.split(",")] if isinstance(t, str) else [str(t)])
  1325. elif not toolsets:
  1326. # Coding posture inside a code workspace, else the profile default the gateway resolves (its
  1327. # platform resolver reads plugin toolsets, which only the gateway loads: adopted when the session
  1328. # opens). Neither is a pick: this list only feeds the display.
  1329. try:
  1330. from agent.coding_context import coding_selection
  1331. toolsets_list = coding_selection(platform="cli", config=CLI_CONFIG)
  1332. except Exception:
  1333. toolsets_list = None
  1334. parsed_skills = _parse_skills_argument(skills)
  1335. try:
  1336. cli = HermesCLI(
  1337. model=model,
  1338. toolsets=toolsets_list,
  1339. provider=provider,
  1340. reasoning=reasoning,
  1341. api_key=api_key,
  1342. base_url=base_url,
  1343. max_turns=max_turns,
  1344. run_budget=run_budget,
  1345. verbose=verbose,
  1346. compact=compact,
  1347. resume=resume,
  1348. checkpoints=checkpoints,
  1349. pass_session_id=pass_session_id,
  1350. ignore_rules=ignore_rules,
  1351. )
  1352. except ImportError as e:
  1353. # Direct `python cli.py` bypasses cmd_chat's partial-update ImportError handler.
  1354. from hermes_constants import emit_partial_update_hint
  1355. if emit_partial_update_hint(e):
  1356. sys.exit(1)
  1357. raise
  1358. if not toolsets:
  1359. cli._explicit_toolsets = False # the gateway resolves the default and coding posture itself
  1360. # Only a typed -t is checked against a resumed session's frozen toolsets.
  1361. cli._typed_toolsets = toolsets_list if toolsets else None
  1362. # skills.auto_load rides the same background preload as -s; --ignore-rules skips it with
  1363. # the rest of the auto-injected context. Resolved here (not lazily in the agent) so the
  1364. # session id is real for ${HERMES_SESSION_ID} and -s can dedupe against it.
  1365. from agent.skill_commands import build_auto_load_prompt, resolve_auto_load_skills
  1366. auto_load_names = [] if getattr(cli, "ignore_rules", ignore_rules) else resolve_auto_load_skills(CLI_CONFIG)
  1367. if not auto_load_names:
  1368. cli._auto_load_skills_result = ("", [], [])
  1369. if parsed_skills or auto_load_names:
  1370. cli._preload_skills_requested = [*auto_load_names, *(s for s in parsed_skills if s not in auto_load_names)]
  1371. from hermes_cli.gateway_session_store import GatewaySessionStore
  1372. if isinstance(getattr(cli, "_session_db", None), GatewaySessionStore):
  1373. # The gateway session renders -s at creation and its agent loads skills.auto_load (plugin
  1374. # skills included); this process's prompt never reaches it, so nothing is loaded here.
  1375. return cli
  1376. # Load the skill payloads in the background: skill_view walks the full skills
  1377. # tree per skill (~0.5s for a large library) and the result is only consumed
  1378. # at agent init, not by the banner. finalize_preloaded_skills() joins the
  1379. # thread before any consumer reads cli.system_prompt.
  1380. def _load_preloaded_skills() -> None:
  1381. try:
  1382. if auto_load_names:
  1383. cli._auto_load_skills_result = build_auto_load_prompt(task_id=cli.session_id, user_config=CLI_CONFIG)
  1384. if parsed_skills:
  1385. cli._preload_skills_result = build_preloaded_skills_prompt(
  1386. parsed_skills, task_id=cli.session_id, excluded_loaded_names=set(cli._auto_load_skills_result[1]))
  1387. except Exception as exc: # surfaced by finalize
  1388. cli._preload_skills_error = exc
  1389. cli._preload_skills_thread = threading.Thread(target=_load_preloaded_skills, name="skills-preload", daemon=True)
  1390. cli._preload_skills_thread.start()
  1391. return cli
  1392. def _run_legacy_gateway():
  1393. """Legacy `cli.py --gateway` entry: arm the startup watchdog (before importing the gateway graph), then run it."""
  1394. import asyncio
  1395. from hermes_cli.resource_limits import apply_malloc_arena_max
  1396. apply_malloc_arena_max() # before the watchdog thread: glibc latches its arena limit
  1397. with suppress(Exception):
  1398. from hermes_startup_watchdog import arm_startup_watchdog
  1399. arm_startup_watchdog()
  1400. from gateway.run import start_gateway
  1401. print(_t("cli.gateway.starting"))
  1402. asyncio.run(start_gateway())
  1403. def _start_worktree_setup(list_tools, list_toolsets, worktree, w):
  1404. """Start isolated-worktree creation (+ tool prewarm) in the background.
  1405. Returns a join callable that publishes ``_active_worktree``/TERMINAL_CWD and
  1406. schedules stale-worktree GC, or None when no worktree is wanted.
  1407. """
  1408. if list_tools or list_toolsets or not (worktree or w or CLI_CONFIG.get("worktree", False)):
  1409. return None
  1410. # Overlap tool discovery with the I/O-bound worktree setup so show_banner() hits a warm
  1411. # cache (~0.4s). Only on the -w path: plain `hermes` has no I/O wait to hide.
  1412. def _prewarm_tools() -> None:
  1413. try:
  1414. import model_tools as _mt
  1415. _mt.get_tool_definitions(quiet_mode=True)
  1416. except Exception:
  1417. logger.debug("tool prewarm failed", exc_info=True)
  1418. threading.Thread(target=_prewarm_tools, name="tool-prewarm", daemon=True).start()
  1419. _sync_base = CLI_CONFIG.get("worktree_sync", True)
  1420. _wt_result: dict = {}
  1421. def _create_worktree() -> None:
  1422. try:
  1423. # The session freezes this cwd: recorded so a resume recreates the tree quit removed (N8).
  1424. _wt_result["info"] = _setup_worktree(sync_base=_sync_base, retain_db=get_hermes_home() / "state.db")
  1425. except Exception:
  1426. logger.debug("worktree setup failed", exc_info=True)
  1427. _wt_result["info"] = None
  1428. _wt_thread = threading.Thread(target=_create_worktree, name="worktree-setup", daemon=True)
  1429. _wt_thread.start()
  1430. def _worktree_maintenance(repo: str) -> None:
  1431. _prune_stale_worktrees(repo)
  1432. _maintain_pack_health(repo)
  1433. def _join_worktree() -> Optional[dict[str, str]]:
  1434. _wt_thread.join(timeout=120)
  1435. info = _wt_result.get("info")
  1436. if not info:
  1437. return info
  1438. global _active_worktree
  1439. _active_worktree = info
  1440. os.environ["TERMINAL_CWD"] = info["path"]
  1441. atexit.register(_cleanup_worktree, info)
  1442. # GC stale worktrees AFTER _setup_worktree so they never race on git's worktree
  1443. # metadata (the new tree is immune: <24h age gate + live pid lock); then repack
  1444. # once refs are final so lookups stay fast on multi-agent boxes.
  1445. _repo = _git_repo_root()
  1446. if _repo:
  1447. threading.Thread(target=_worktree_maintenance, args=(_repo,), name="worktree-prune", daemon=True).start()
  1448. return info
  1449. return _join_worktree
  1450. def main(
  1451. query: str | None = None,
  1452. q: str | None = None,
  1453. oneshot: bool = False,
  1454. image: str | None = None,
  1455. toolsets: str | None = None,
  1456. skills: str | list[str] | tuple[str, ...] | None = None,
  1457. model: str | None = None,
  1458. provider: str | None = None,
  1459. reasoning: str | None = None,
  1460. api_key: str | None = None,
  1461. base_url: str | None = None,
  1462. max_turns: int | None = None,
  1463. run_budget: float | None = None,
  1464. verbose: Optional[bool] = None,
  1465. quiet: bool = False,
  1466. compact: bool = False,
  1467. list_tools: bool = False,
  1468. list_toolsets: bool = False,
  1469. gateway: bool = False,
  1470. resume: str | None = None,
  1471. worktree: bool = False,
  1472. w: bool = False,
  1473. checkpoints: bool = False,
  1474. pass_session_id: bool = False,
  1475. output_format: str = "text",
  1476. ignore_user_config: bool = False,
  1477. ignore_rules: bool = False,
  1478. ):
  1479. """
  1480. Hermes Agent CLI - Interactive AI Assistant
  1481. Args:
  1482. query: Query to run. On a real TTY this seeds an interactive session
  1483. (submitted literally as the first turn); with --oneshot/-Q or a
  1484. non-TTY it answers and exits. Alias: -q
  1485. q: Shorthand for --query
  1486. oneshot: With -q: force the legacy answer-and-exit single-query mode
  1487. even on a TTY.
  1488. image: Optional local image path to attach to a single query
  1489. toolsets: Comma-separated list of toolsets to enable (e.g., "web,terminal")
  1490. skills: Comma-separated or repeated list of skills to preload for the session
  1491. model: Model to use (default: anthropic/claude-opus-4-20250514)
  1492. provider: Inference provider ("auto", "openrouter", "nous", "openai-codex", "zai", "kimi-coding", "minimax", "minimax-cn")
  1493. reasoning: Reasoning effort for this run (none|minimal|low|medium|high|xhigh|max|ultra). Overrides agent.reasoning_effort.
  1494. api_key: API key for authentication
  1495. base_url: Base URL for the API
  1496. max_turns: Maximum tool-calling iterations (default: 60)
  1497. verbose: Enable verbose logging
  1498. compact: Use compact display mode
  1499. list_tools: List available tools and exit
  1500. list_toolsets: List available toolsets and exit
  1501. resume: Resume a previous session by its ID (e.g., 20260225_143052_a1b2c3)
  1502. worktree: Run in an isolated git worktree (for parallel agents). Alias: -w
  1503. w: Shorthand for --worktree
  1504. Examples:
  1505. python cli.py # Start interactive mode
  1506. python cli.py --toolsets web,terminal # Use specific toolsets
  1507. python cli.py --skills hermes-agent-dev,github-auth
  1508. python cli.py -q "What is Python?" # Single query mode
  1509. python cli.py -q "Describe this" --image ~/storage/shared/Pictures/cat.png
  1510. python cli.py --list-tools # List tools and exit
  1511. python cli.py --resume 20260225_143052_a1b2c3 # Resume session
  1512. python cli.py -w # Start in isolated git worktree
  1513. python cli.py -w -q "Fix issue #123" # Single query in worktree
  1514. """
  1515. # UTF-8 stdio on Windows before any print (Rich box-drawing would UnicodeEncodeError on cp1252).
  1516. with suppress(Exception):
  1517. from hermes_cli.stdio import configure_windows_stdio
  1518. configure_windows_stdio()
  1519. os.environ["HERMES_INTERACTIVE"] = "1" # terminal_tool: interactive sudo prompts with timeout
  1520. if gateway:
  1521. _run_legacy_gateway()
  1522. return
  1523. if not (list_tools or list_toolsets):
  1524. from hermes_cli.process_identity import register_self
  1525. from hermes_cli.shared_profile_warning import shared_profile_warning
  1526. register_self("cli")
  1527. warning = shared_profile_warning()
  1528. if warning:
  1529. print(_t("cli.startup.warning", warning=warning), file=sys.stderr)
  1530. _join_worktree = _start_worktree_setup(list_tools, list_toolsets, worktree, w)
  1531. query = query or q
  1532. # ``hermes chat`` already validated this; the direct Fire entry point gets the same contract.
  1533. if output_format == "stream-json":
  1534. if not query:
  1535. raise ValueError("--format stream-json requires -q/--query")
  1536. quiet = True
  1537. cli = _build_cli_from_args(model, toolsets, provider, reasoning, api_key, base_url, max_turns, run_budget,
  1538. verbose, compact, resume, checkpoints, pass_session_id, ignore_rules, skills)
  1539. # Join the background worktree creation before anything consumes TERMINAL_CWD.
  1540. # A requested worktree whose setup failed aborts: never silently run without isolation.
  1541. wt_info = _join_worktree() if _join_worktree is not None else None
  1542. if _join_worktree is not None and not wt_info:
  1543. return
  1544. # The worktree note is rendered by the gateway from the session's folder (agent/coding_context.py).
  1545. if list_tools or list_toolsets:
  1546. cli.show_banner()
  1547. (cli.show_tools if list_tools else cli.show_toolsets)()
  1548. sys.exit(0)
  1549. atexit.register(_run_cleanup) # interactive mode registers again in run() (idempotent)
  1550. _install_single_query_signal_handlers(cli)
  1551. if query or image:
  1552. _run_single_query_mode(cli, query, image, quiet, oneshot, stream_json=output_format == "stream-json")
  1553. return
  1554. cli.run()
  1555. if __name__ == "__main__":
  1556. import fire
  1557. fire.Fire(main)