cli_init_mixin.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. """HermesCLI constructor phases: display options, model/provider routing, turn limits, toolsets, checkpoints, prompt/reasoning, runtime state, session store and UI state.
  2. Mixin split out of ``cli.py``; bound onto ``HermesCLI`` via the MRO.
  3. """
  4. from __future__ import annotations
  5. from contextlib import contextmanager
  6. import logging
  7. import os
  8. import queue
  9. import threading
  10. from datetime import datetime
  11. from hermes_cli.fallback_config import get_fallback_chain
  12. from hermes_state_ids import new_session_id
  13. from pathlib import Path
  14. from rich.console import Console
  15. from typing import Any, Dict, List, Optional
  16. from utils import base_url_host_matches, base_url_hostname, is_truthy_value
  17. # Log-record parity with the origin module.
  18. logger = logging.getLogger("cli")
  19. # The launch flags that pick the model route: ``/new`` starts on the profile's default route.
  20. _ROUTE_FLAGS = ("model", "provider", "api_key", "base_url")
  21. def _adopt_gateway_toolsets(cli, store):
  22. """The profile default the gateway resolved for the opened session, when this process has no list to
  23. show (display only), and main's "Unknown toolsets" warning as the gateway judged it against its own
  24. plugins."""
  25. info = (store.current or {}).get("info") or {}
  26. if getattr(cli, "enabled_toolsets", None) is None and isinstance(info.get("enabled_toolsets"), list):
  27. cli.enabled_toolsets = list(info["enabled_toolsets"])
  28. if info.get("unknown_toolsets"):
  29. from agent.i18n import t as _t
  30. names = ", ".join(info["unknown_toolsets"])
  31. cli._console_print(f"[bold red]{_t('cli.startup.unknown_toolsets', names=names)}[/]")
  32. def _gateway_launch(cli):
  33. """This run's explicit launch flags as gateway ``session.create`` policy (main handed them to AIAgent)."""
  34. explicit_model = getattr(cli, "_explicit_model_override", False)
  35. provider = getattr(cli, "_explicit_provider", None)
  36. return {"model": cli.model if explicit_model else None,
  37. "provider": provider if explicit_model and provider not in {None, "", "auto"} else None,
  38. "api_key": getattr(cli, "_explicit_api_key", None),
  39. "base_url": getattr(cli, "_explicit_base_url", None),
  40. # Only a typed -t; the gateway resolves the profile default and the coding posture (#138670).
  41. "toolsets": getattr(cli, "enabled_toolsets", None) if getattr(cli, "_explicit_toolsets", False) else None,
  42. "reasoning": getattr(cli, "_explicit_reasoning", None),
  43. "max_turns": getattr(cli, "_explicit_max_turns", None),
  44. "checkpoints": getattr(cli, "_explicit_checkpoints", False) or None,
  45. "pass_session_id": getattr(cli, "pass_session_id", False) or None,
  46. "ignore_rules": getattr(cli, "ignore_rules", False) or None,
  47. "run_budget": getattr(cli, "_explicit_run_budget", None),
  48. "verbose": getattr(cli, "verbose", False) or None,
  49. "skills": _explicit_launch_skills(cli)}
  50. def _explicit_launch_skills(cli):
  51. """The `-s/--skills` names, which the gateway renders into the session once at creation (the CLI's
  52. own prompt never reaches it). ``skills.auto_load`` names are left out: the gateway's agent loads those."""
  53. requested = getattr(cli, "_preload_skills_requested", None) or []
  54. if not requested:
  55. return None
  56. from agent.skill_commands import resolve_auto_load_skills
  57. from cli import CLI_CONFIG
  58. auto = set() if getattr(cli, "ignore_rules", False) else set(resolve_auto_load_skills(CLI_CONFIG))
  59. return [name for name in requested if name not in auto] or None
  60. def _record_shell_hook_consent():
  61. """Main's first-use shell-hook prompt, on this terminal. The gateway that registers the hooks
  62. has no TTY; it reads the allowlist this writes when the session opens (create or resume).
  63. ``--accept-hooks`` / ``HERMES_ACCEPT_HOOKS`` / ``hooks_auto_accept`` approve without asking.
  64. A remote gateway has its own home and allowlist, and a bypass launch reads no profile hooks,
  65. so nothing is asked for either."""
  66. from hermes_cli.gateway_chat import env_launch_flags
  67. flags = env_launch_flags()
  68. if os.environ.get("HERMES_TUI_GATEWAY_URL", "").strip() or flags.get("safe_mode") or flags.get("ignore_user_config"):
  69. return
  70. try:
  71. from agent.shell_hooks import record_consent_from_config
  72. from hermes_cli.config import load_config
  73. record_consent_from_config(load_config())
  74. except Exception: # health: allow BLE001 -- consent is best effort; the gateway skips unapproved hooks
  75. logger.warning("shell-hook consent check failed", exc_info=True)
  76. @contextmanager
  77. def lease_handed_over(cli, held):
  78. """Run a gateway attach without this CLI's own active-session lease, then re-claim it.
  79. A row the gateway has not imported yet (a legacy / in-process session) is imported under the
  80. active-session registry lock, which refuses (``runtime_coordination_required``) while ANY live
  81. lease holds the id, including this process's own. The block may move ``cli.session_id`` to the
  82. id the gateway returned: the lease is re-claimed for that id (main's exclusivity is kept), or
  83. for the unchanged id when the block raises."""
  84. if not held:
  85. yield
  86. return
  87. cli._release_active_session()
  88. try:
  89. yield
  90. except BaseException:
  91. cli._claim_active_session("cli", stderr=True)
  92. raise
  93. if not cli._claim_active_session("cli", stderr=True):
  94. raise RuntimeError("session_already_owned")
  95. class CLIInitMixin:
  96. """HermesCLI constructor phases: display options, model/provider routing, turn limits, toolsets, checkpoints, prompt/reasoning, runtime state, session store and UI state."""
  97. def _init_display_options(self, verbose, compact):
  98. """Display-related config: compact/tool-progress/focus view, bells, streaming, previews, stream buffers."""
  99. from cli import CLI_CONFIG, _configure_output_history, _int_or
  100. self.console = Console()
  101. self.config = CLI_CONFIG
  102. # A local /reasoning show|hide or /footer saves the per-platform ``cli`` key: read it (T7).
  103. from gateway.display_config import local_display_config
  104. display = local_display_config(CLI_CONFIG["display"])
  105. self.compact = compact if compact is not None else display.get("compact", False)
  106. # tool_progress: "off" | "new" | "all" | "verbose"; YAML 1.1 parses bare `off` as False.
  107. _raw_tp = display.get("tool_progress", "all")
  108. self.tool_progress_mode = "off" if _raw_tp is False else str(_raw_tp)
  109. # focus_view (/focus) is display-only: snaps tool_progress to "off" (stashing the
  110. # pre-focus mode for /focus off); never changes what is sent to the model.
  111. self._focus_view_enabled = bool(display.get("focus_view", False))
  112. self._focus_saved_tool_progress = self._focus_last_counted_tool = None
  113. self._focus_hidden_lines = 0
  114. if self._focus_view_enabled:
  115. from hermes_cli.focus_view import FOCUS_TOOL_PROGRESS_MODE, normalize_tool_progress_mode
  116. self._focus_saved_tool_progress = normalize_tool_progress_mode(self.tool_progress_mode)
  117. self.tool_progress_mode = FOCUS_TOOL_PROGRESS_MODE
  118. self.resume_display = display.get("resume_display", "full") # "full" | "minimal"
  119. self.bell_on_complete = display.get("bell_on_complete", False)
  120. self.bell_on_prompt = display.get("bell_on_prompt", False) # bell when a blocking modal opens
  121. self.show_reasoning = display.get("show_reasoning", True)
  122. self.reasoning_full = display.get("reasoning_full", False)
  123. _configure_output_history(
  124. enabled=display.get("persistent_output", True),
  125. max_lines=display.get("persistent_output_max_lines", 200),
  126. )
  127. from hermes_cli.cli_modern_layout import busy_input_mode_from_config, layout_from_config, set_active
  128. self._modern_layout = layout_from_config(display) # display.cli_layout: modern | classic
  129. set_active(self._modern_layout)
  130. # busy_input_mode: "interrupt" (redirect the run) | "queue" (next turn) | "steer" (inject mid-run).
  131. _bim = busy_input_mode_from_config(display)
  132. self.busy_input_mode = _bim if _bim in ("queue", "steer") else "interrupt"
  133. # verbose ONLY controls global DEBUG logging; tool_progress="verbose" is independent
  134. # (coupling them spewed every module's DEBUG logs to the console).
  135. self.verbose = bool(verbose) if verbose is not None else False
  136. self.streaming_enabled = display.get("streaming", False)
  137. self.show_timestamps = display.get("timestamps", False)
  138. self.timestamp_format = display.get("timestamp_format", "%H:%M")
  139. _frm = str(display.get("final_response_markdown", "strip")).strip().lower()
  140. self.final_response_markdown = _frm if _frm in {"render", "strip", "raw"} else "strip"
  141. self._inline_diffs_enabled = display.get("inline_diffs", True)
  142. self._inline_images_mode = display.get("inline_images", "auto")
  143. # Per-turn accounting: CLI-only chrome riding the tool-progress feed.
  144. self._turn_summary_enabled = bool(display.get("turn_summary", True))
  145. self._spinner_token_flow_enabled = bool(display.get("spinner_token_flow", True))
  146. self._turn_summary_collector = None
  147. self._turn_summary_start = 0.0
  148. self._turn_token_baseline = 0
  149. self._interactive_turn = False # only run()-loop turns; keeps the summary line off -Q
  150. _ump = display.get("user_message_preview", {})
  151. _ump = _ump if isinstance(_ump, dict) else {}
  152. self.user_message_preview_first_lines = max(1, _int_or(_ump.get("first_lines", 2), 2))
  153. self.user_message_preview_last_lines = max(0, _int_or(_ump.get("last_lines", 2), 2))
  154. # Streaming display state
  155. self._stream_buf = "" # partial line buffer
  156. self._reasoning_preview_buf = "" # coalesces tiny reasoning chunks
  157. self._stream_started = self._stream_box_opened = self._stream_box_live = False
  158. self._streamed_text_this_turn = ""
  159. self._held_status_lines: list[str] = [] # agent status lines parked while a box streams
  160. # Possible markdown-table lines held until the block ends for wcwidth-aware re-padding.
  161. self._stream_table_buf: list[str] = []
  162. self._in_stream_table = False
  163. self._pending_edit_snapshots = {}
  164. self._last_input_mode_recovery = self._last_termios_drift_check = None # None = never; monotonic epoch is arbitrary
  165. self._input_mode_recovery_notice_shown = self._termios_drift_notice_shown = False
  166. def _init_model_routing(self, model, toolsets, provider, reasoning, api_key, base_url, max_turns, run_budget, checkpoints, pass_session_id, ignore_rules):
  167. """Resolve model/provider/base_url, turn limits, toolsets, checkpoints, prompt/personality, reasoning + routing config."""
  168. self._init_model_and_provider(model, provider, api_key, base_url)
  169. self._init_turn_limits(max_turns, run_budget)
  170. self._init_toolsets(toolsets)
  171. self._init_checkpoints_and_rules(checkpoints, pass_session_id, ignore_rules)
  172. self._init_prompt_and_reasoning(reasoning)
  173. def _init_model_and_provider(self, model, provider, api_key, base_url):
  174. """Priority: CLI args > env vars > config file."""
  175. from cli import CLI_CONFIG, _normalize_moa_model, _split_model_config_default
  176. # LLM_MODEL/OPENAI_MODEL env vars are deliberately NOT checked (multi-agent setups
  177. # would stomp each other through the environment).
  178. _model_config = CLI_CONFIG["model"]
  179. # A dict-valued default carries its own provider, which must feed requested_provider
  180. # instead of being replaced by the merged model.provider (typically "auto").
  181. _config_model, _nested_provider = _split_model_config_default(
  182. _model_config.get("default") or _model_config.get("model") or ""
  183. )
  184. # resume must not clobber an explicit -m with the session's stored model.
  185. self._explicit_model_override = bool(model)
  186. self.model = model or _config_model or ""
  187. _cfg_provider = _model_config.get("provider") or os.getenv("HERMES_INFERENCE_PROVIDER")
  188. _startup_provider_override = _startup_base_url_override = _startup_api_key_override = ""
  189. if self.model:
  190. from hermes_cli.model_switch import resolve_startup_model_route
  191. _startup_route = resolve_startup_model_route(
  192. self.model,
  193. explicit_provider=provider or "",
  194. current_provider=(provider or _nested_provider or _cfg_provider or ""),
  195. user_providers=CLI_CONFIG.get("providers"),
  196. custom_providers=CLI_CONFIG.get("custom_providers"),
  197. )
  198. if _startup_route is not None:
  199. self.model = _startup_route.model
  200. _startup_provider_override = _startup_route.provider
  201. _startup_base_url_override = _startup_route.base_url
  202. _startup_api_key_override = _startup_route.api_key
  203. # ``moa:<preset>`` selects the MoA virtual provider before provider resolution so the
  204. # real provider never sees the unknown model; the prefix wins over --provider.
  205. # A ``moa:<preset>`` model string selects the MoA virtual provider in one shot (parity with
  206. # interactive ``/moa`` and the model picker). See #56828.
  207. _moa_provider_override, self.model = _normalize_moa_model(self.model)
  208. if self.model == "": # auto-detect from a local server
  209. _base_url = _model_config.get("base_url") or ""
  210. if base_url_hostname(_base_url) in ("localhost", "127.0.0.1"):
  211. from hermes_cli.runtime_provider import _auto_detect_local_model
  212. self.model = _auto_detect_local_model(_base_url) or self.model
  213. # Provider normalisation may silently override the default but must warn for an
  214. # explicit choice (a config model equal to the global fallback is NOT explicit).
  215. self._model_is_default = not model and not _config_model
  216. # --api-key wins; otherwise a URL-bearing startup alias carries its own credential.
  217. # See #28660.
  218. self._explicit_api_key = api_key or _startup_api_key_override or None
  219. self._typed_api_key = api_key or None # a startup resume it cannot bind is refused; an alias's falls back
  220. self._explicit_base_url = base_url or _startup_base_url_override or None
  221. # Resolved lazily at use-time via _ensure_runtime_credentials().
  222. self.requested_provider = (
  223. _moa_provider_override or provider or _startup_provider_override or _nested_provider
  224. or _cfg_provider or "auto"
  225. )
  226. # Only a provider the command line chose is gateway launch policy: the config default is the
  227. # gateway's to resolve, and a resume compares launch policy against the session's frozen route.
  228. self._explicit_provider = _moa_provider_override or provider or _startup_provider_override or None
  229. # `--provider <custom>` without `-m` uses that entry's default_model, else the global
  230. # default goes to the custom endpoint and the compressor gets the wrong context length.
  231. # Explicit `-m` still wins. See #86978.
  232. if not model and provider:
  233. try:
  234. from hermes_cli.runtime_provider import _get_named_custom_provider
  235. _named_custom = _get_named_custom_provider(provider)
  236. except Exception as exc:
  237. logger.warning(
  238. "Could not resolve --provider %s default model; keeping global model.default (%s)",
  239. provider, exc,
  240. )
  241. _named_custom = None
  242. _provider_default = str((_named_custom or {}).get("model") or "").strip()
  243. if _provider_default:
  244. self.model = _provider_default
  245. self._model_is_default = False
  246. self._provider_source: Optional[str] = None
  247. self.provider = self.requested_provider
  248. self.api_mode = "chat_completions"
  249. self.acp_command: Optional[str] = None
  250. self.acp_args: list[str] = []
  251. self.base_url = (
  252. base_url or _startup_base_url_override or _model_config.get("base_url", "")
  253. or os.getenv("OPENROUTER_BASE_URL", "")
  254. ) or None
  255. # Key matches the resolved base_url; re-resolved by _ensure_runtime_credentials().
  256. # This seed can reach /model before the first turn, so openrouter.ai never gets a real OpenAI key here.
  257. _keys = [os.getenv("OPENROUTER_API_KEY"), os.getenv("OPENAI_API_KEY")]
  258. if not (self.base_url and base_url_host_matches(self.base_url, "openrouter.ai")):
  259. _keys = _keys[::-1]
  260. else:
  261. from hermes_cli.auth import looks_like_openrouter_key
  262. _keys[1] = _keys[1] if looks_like_openrouter_key(_keys[1]) else None
  263. self.api_key = api_key or _keys[0] or _keys[1]
  264. def _init_turn_limits(self, max_turns, run_budget):
  265. """max_turns: CLI arg > config > env var > default; run budget: CLI flag > config."""
  266. from cli import CLI_CONFIG
  267. # resolve_turn_limit() accepts "none"/"unlimited" (-> sys.maxsize) alongside ints.
  268. # KEEP the root-level CLI_CONFIG["max_turns"] fallback: it is never migrated on disk
  269. # and other config paths may bypass the load-time fold.
  270. from hermes_cli.config import resolve_turn_limit as _resolve_turn_limit
  271. self.max_turns = _resolve_turn_limit(next(
  272. (v for v in (max_turns, CLI_CONFIG["agent"].get("max_turns"), CLI_CONFIG.get("max_turns")) if v is not None),
  273. os.getenv("HERMES_MAX_ITERATIONS"),
  274. ))
  275. self.run_budget_seconds = run_budget if run_budget is not None else CLI_CONFIG["agent"].get("run_budget_seconds")
  276. self._explicit_run_budget = run_budget # `--run-budget`: session.create policy (the gateway runs the turn)
  277. # The gateway builds the agent now: the explicit flag (not the resolved value) rides session.create.
  278. self._explicit_max_turns = max_turns
  279. def _init_toolsets(self, toolsets):
  280. from cli import CLI_CONFIG
  281. self.enabled_toolsets = toolsets
  282. # Only a picked list rides session.create; _build_cli_from_args clears this unless -t was typed (the
  283. # gateway resolves the profile default and coding posture itself; a stale explicit name is refused, #138670).
  284. self._explicit_toolsets = toolsets is not None
  285. from agent.skill_utils import parse_config_string_list
  286. self.disabled_toolsets = parse_config_string_list(CLI_CONFIG["agent"].get("disabled_toolsets"))
  287. # No local "Unknown toolsets" check: plugin toolsets are only known where plugins load. The gateway
  288. # refuses an unknown picked name at session.create and reports a stale profile one with the session
  289. # (``_adopt_gateway_toolsets``), so this process never discovers plugins to tell them apart (PLG-7).
  290. def _init_checkpoints_and_rules(self, checkpoints, pass_session_id, ignore_rules):
  291. from cli import CLI_CONFIG
  292. cp_cfg = CLI_CONFIG.get("checkpoints", {})
  293. if isinstance(cp_cfg, bool):
  294. cp_cfg = {"enabled": cp_cfg}
  295. self.checkpoints_enabled = checkpoints or cp_cfg.get("enabled", False)
  296. self._explicit_checkpoints = bool(checkpoints)
  297. self.checkpoint_max_snapshots = cp_cfg.get("max_snapshots", 20)
  298. self.checkpoint_max_total_size_mb = cp_cfg.get("max_total_size_mb", 500)
  299. self.checkpoint_max_file_size_mb = cp_cfg.get("max_file_size_mb", 10)
  300. self.pass_session_id = pass_session_id
  301. # --ignore-rules: AIAgent skips context files (AGENTS.md/SOUL.md/...) and memory.
  302. self.ignore_rules = ignore_rules or is_truthy_value(os.environ.get("HERMES_IGNORE_RULES"))
  303. # The env opt-in is creation policy only: a resume checks just a typed --ignore-rules (the thin client's rule).
  304. self._explicit_ignore_rules = bool(ignore_rules)
  305. def _init_prompt_and_reasoning(self, reasoning):
  306. """Ephemeral system prompt/prefill, reasoning + service tier, OpenRouter routing knobs, fallback chain."""
  307. from cli import CLI_CONFIG, _load_prefill_messages, _parse_reasoning_config, _parse_service_tier_config, _resolve_prefill_messages_file
  308. # Env var wins, then hermes_cli.personality (single owner of overlay resolution).
  309. from hermes_cli.personality import available_personalities, resolve_ephemeral_system_prompt
  310. self.system_prompt = os.getenv("HERMES_EPHEMERAL_SYSTEM_PROMPT", "") or resolve_ephemeral_system_prompt(CLI_CONFIG)
  311. self.personalities = available_personalities(CLI_CONFIG)
  312. self.prefill_messages = _load_prefill_messages(_resolve_prefill_messages_file(CLI_CONFIG))
  313. # Per-model override > global reasoning_effort.
  314. # Reasoning config (OpenRouter reasoning effort level) Per-model override > global reasoning_effort
  315. # — resolved through the shared chokepoint in hermes_constants (Closes #21256).
  316. from hermes_constants import resolve_reasoning_config
  317. self.reasoning_config = resolve_reasoning_config(CLI_CONFIG, self.model)
  318. self._explicit_reasoning_config = None
  319. self._explicit_reasoning = None
  320. # --reasoning wins for this run only (never persisted); unparseable -> warn and ignore.
  321. if reasoning is not None and str(reasoning).strip():
  322. _cli_reasoning = _parse_reasoning_config(reasoning)
  323. if _cli_reasoning is None:
  324. logger.warning("Unknown --reasoning '%s', keeping the configured level", reasoning)
  325. else:
  326. self.reasoning_config = _cli_reasoning
  327. self._explicit_reasoning_config = _cli_reasoning
  328. self._explicit_reasoning = str(reasoning).strip()
  329. self.service_tier = _parse_service_tier_config(CLI_CONFIG["agent"].get("service_tier", ""))
  330. pr = CLI_CONFIG.get("provider_routing", {}) or {}
  331. self._provider_sort = pr.get("sort")
  332. self._providers_only = pr.get("only")
  333. self._providers_ignore = pr.get("ignore")
  334. self._providers_order = pr.get("order")
  335. self._provider_require_params = pr.get("require_parameters", False)
  336. self._provider_data_collection = pr.get("data_collection")
  337. # OpenRouter Pareto Code router coding-score floor; out-of-range = unset.
  338. _raw_score = (CLI_CONFIG.get("openrouter", {}) or {}).get("min_coding_score")
  339. self._openrouter_min_coding_score: Optional[float] = None
  340. if _raw_score not in {None, ""}:
  341. try:
  342. _f = float(_raw_score)
  343. if 0.0 <= _f <= 1.0:
  344. self._openrouter_min_coding_score = _f
  345. except (TypeError, ValueError):
  346. pass
  347. self._fallback_model = get_fallback_chain(CLI_CONFIG)
  348. def _init_runtime_state(self, resume):
  349. """Session store + all per-run mutable state (queues, overlays, pet/voice/status-bar fields)."""
  350. from cli import _hermes_home
  351. from hermes_cli.left_core_migration import serve_notices_on_stderr
  352. serve_notices_on_stderr()
  353. # A signature change across turns (/model, credential rotation) rebuilds the agent.
  354. self._active_agent_route_signature = None
  355. self.agent: Optional[Any] = None # initialized on first use
  356. self._tool_callbacks_installed = False
  357. self._app = None # prompt_toolkit Application (set in run())
  358. self.conversation_history: list[dict[str, Any]] = []
  359. self.session_start = datetime.now()
  360. # Per-prompt elapsed timer shown in the status bar.
  361. self._prompt_start_time: Optional[float] = None
  362. self._prompt_duration: float = 0.0
  363. self._last_turn_finished_at: Optional[float] = None
  364. self._init_session_store()
  365. self._pending_title: Optional[str] = None
  366. self._resumed = bool(resume)
  367. self.session_id = resume or new_session_id(self.session_start)
  368. getattr(self, "_write_terminal_breadcrumb", lambda: None)()
  369. self._history_file = _hermes_home / ".hermes_history"
  370. self._last_invalidate: float | None = None # throttles UI repaints (None = never; monotonic epoch is arbitrary)
  371. self._init_ui_state()
  372. def _init_session_store(self):
  373. """Open the session store early (so /title works before the first message)."""
  374. self._session_db = None
  375. self._session_db_unavailable = False
  376. try:
  377. # Registry handle, not a bare SessionDB(): goals/loops/heartbeat acquire the same
  378. # path a moment later from the REPL thread, and a second writer repeats the full
  379. # open (the /proc-wide deleted-WAL scan, ~4k readlinks) while the render thread
  380. # holds the GIL — that repeat was the post-banner freeze before the first prompt.
  381. from hermes_cli.gateway_session_store import session_store
  382. self._session_db = session_store() # the gateway is the single writer
  383. except Exception as e:
  384. # Without a store the transcript is NOT persisted while the chat looks healthy,
  385. # so surface it prominently rather than only logging.
  386. # #41386: a failed session store means the transcript is NOT persisted to state.db — the live
  387. # chat looks healthy but resume later shows a truncated/empty session. A buried log line is not
  388. # enough; surface it prominently so the user knows persistence is off for this run and can fix
  389. # the store before relying on resume.
  390. self._session_db_unavailable = True
  391. logger.warning("Failed to initialize SessionDB — session will NOT be indexed for search: %s", e)
  392. from hermes_state_user_copy import describe_storage_failure, storage_failure_details
  393. from agent.i18n import t
  394. failure = describe_storage_failure(e)
  395. def _present_store_warning():
  396. try:
  397. Console(stderr=True).print(t(
  398. "cli.session_store.unavailable_rich",
  399. reason=failure.gloss, action=failure.action, details=storage_failure_details(e)))
  400. except Exception:
  401. print(t("cli.session_store.unavailable_plain", reason=failure.gloss, action=failure.action))
  402. # Same automatic diagnostic the gateway gates for its home channel (run_notifications).
  403. from gateway.warning_notifications import render_notification
  404. render_notification(_present_store_warning, platform="cli")
  405. # No state.db / checkpoint maintenance here: the gateway (the single writer) runs both.
  406. def _ensure_gateway_session(self):
  407. """Create (or resume) this CLI's gateway session and adopt the id it returns, before the banner
  408. and the first turn. Idempotent; a store without the gateway facade (tests) is left alone."""
  409. from hermes_cli.gateway_session_store import GatewaySessionStore
  410. store = getattr(self, "_session_db", None)
  411. if getattr(self, "_gateway_session_open", False) or not isinstance(store, GatewaySessionStore):
  412. return
  413. launch = _gateway_launch(self)
  414. held = getattr(self, "_resumed", False) and getattr(self, "_active_session_lease", None) is not None
  415. _record_shell_hook_consent()
  416. with lease_handed_over(self, held):
  417. sid = store.open_session(self, launch)
  418. self._gateway_session_open = True
  419. from hermes_cli import gateway_plugin_commands, tools_config
  420. tools_config._gateway_plugin_toolsets = lambda: gateway_plugin_commands.toolsets(self)
  421. _adopt_gateway_toolsets(self, store)
  422. from hermes_cli.gateway_tools import bind_session
  423. bind_session(self, store.connection) # the session's processes, before _init_agent's chat proxy
  424. if sid and sid != self.session_id:
  425. self.session_id = sid
  426. getattr(self, "_write_terminal_breadcrumb", lambda: None)()
  427. def _new_session_id(self, now, *, branch_of=None, title=None):
  428. """The id main mints for /new (``new_session_id``) and /branch (``mint_session_id``). On a gateway
  429. store it is a session the gateway created: /new is a fresh ``session.create`` on the profile's
  430. default model (an explicit -m was for the previous session only) with the run's other launch
  431. flags, /branch the child of
  432. ``session.mutate branch``. Before this CLI opened its gateway session (or off the gateway) it is
  433. main's local mint, which ``_ensure_gateway_session`` replaces on first use, as at startup."""
  434. from hermes_cli.gateway_session_store import GatewaySessionStore
  435. store = getattr(self, "_session_db", None)
  436. if not isinstance(store, GatewaySessionStore) or not getattr(self, "_gateway_session_open", False):
  437. from hermes_state_ids import new_session_id
  438. return new_session_id(now)
  439. if branch_of:
  440. child = store.branch(branch_of, title)
  441. # Main's with_session_yolo: a live /yolo carries onto the branch. The gateway's child starts
  442. # without the parent's toggle, so set it there too (/branch moves the CLI's own flag over).
  443. # Approvals run on the gateway, so this write is not toggle_session_yolo's best-effort persist:
  444. # a failure raises before the child shows YOLO locally.
  445. from tools.approval import enable_session_yolo, is_session_yolo_enabled
  446. if is_session_yolo_enabled(branch_of):
  447. store.set_session_yolo(child, True)
  448. enable_session_yolo(child)
  449. return child
  450. # The run's other launch flags hold for every session it opens, as main's one AIAgent did across /new.
  451. launch = {key: value for key, value in _gateway_launch(self).items() if key not in _ROUTE_FLAGS}
  452. sid = store.create(launch, record_cwd=False)
  453. self.session_id = sid
  454. return sid
  455. def _init_ui_state(self):
  456. """Per-run mutable UI state; must exist before any chat() call since -q never goes through run()."""
  457. from cli import CLI_CONFIG, _status_bar_visible_from_display_config
  458. self._pending_input = queue.Queue()
  459. self._interrupt_queue = queue.Queue()
  460. self._agent_running = self._should_exit = False
  461. self._detach_on_exit = False # Ctrl+D mid-turn: leave the gateway turn running (LC-6b)
  462. self._last_turn_interrupted = False # /goal never auto-queues on a Ctrl+C'd turn
  463. self._terminal_io_broken = False # stdout EIO: freeze UI paints instead of spinning
  464. self._delete_session_on_exit = False # /exit --delete
  465. # /update: relaunch() runs from run() after prompt_toolkit restored terminal modes.
  466. # /exit --delete: when True, the current session's SQLite history and on-disk transcripts are
  467. # deleted during shutdown. Set by process_command() when the user runs /exit --delete or /quit
  468. # --delete. Ported from google-gemini/gemini-cli#19332.
  469. self._pending_relaunch: list[str] | None = None
  470. self._last_ctrl_c_time = 0
  471. # Blocking-prompt overlays (clarify / sudo / approval / slash-confirm / model picker).
  472. self._clarify_state = self._clarify_multi_base = None
  473. self._clarify_freetext = False
  474. self._clarify_prefill = ""
  475. self._sudo_state = self._modal_input_snapshot = self._approval_state = None
  476. self._slash_confirm_state = self._model_picker_state = None
  477. self._clarify_deadline = self._sudo_deadline = self._approval_deadline = self._slash_confirm_deadline = 0
  478. self._approval_lock = threading.Lock()
  479. try: # composer placeholder chosen once so it stays stable on screen
  480. from hermes_cli.tips import get_random_composer_placeholder
  481. self._composer_placeholder = get_random_composer_placeholder()
  482. except Exception:
  483. self._composer_placeholder = ""
  484. self._command_palette_state = self._secret_state = None
  485. self._pending_resume_sessions = None # armed by a bare `/resume`; the next bare number selects
  486. self._pending_agent_seed = None # one-shot seed from a slash handler
  487. self._secret_deadline = 0
  488. self._tool_start_time: float = 0.0
  489. self._pending_tool_info: dict = {} # function_name -> [(preview, args)] for stacked scrollback
  490. self._spinner_text = self._command_status = ""
  491. self._last_scrollback_tool: str = "" # "new" mode dedup
  492. self._command_running = self._command_blocks_input = False
  493. # Petdex mascot (display.pet): kitty placeholders on kitty/Ghostty, half-blocks elsewhere.
  494. self._pet_renderer = self._pet_anim_thread = None
  495. self._pet_slug = self._pet_kitty_pending = ""
  496. self._pet_enabled = self._pet_anim_running = False
  497. self._pet_cols: int = 18
  498. self._pet_scale: float = 0.7
  499. self._pet_frames_cache: dict = {}
  500. self._pet_kitty_cache: dict = {}
  501. self._pet_kitty_image_id = self._pet_frame_idx = 0
  502. self._pet_lock = threading.Lock()
  503. self._pet_cfg_checked = self._pet_event_until = 0.0
  504. self._pet_event: str = ""
  505. self._pet_reasoning = self._pet_turn_error = False
  506. self._attached_images: list[Path] = []
  507. self._image_counter = 0
  508. # Ctrl+S prompt stash; in-memory only because drafts routinely contain secrets.
  509. from hermes_cli.prompt_stash import PromptStash as _PromptStash
  510. self._prompt_stash = _PromptStash()
  511. self.preloaded_skills: list[str] = []
  512. self._startup_skills_line_shown = False
  513. # skills.auto_load rendered in the preload thread; None until joined. Handed to every
  514. # agent this CLI builds so the prompt bytes never depend on when the agent was created.
  515. self._auto_load_skills_result: Optional[tuple] = None
  516. # Background --skills preload, joined by finalize_preloaded_skills before any agent is built.
  517. self._preload_skills_thread: Optional[threading.Thread] = None
  518. self._preload_skills_result: Optional[tuple] = None
  519. self._preload_skills_error: Optional[BaseException] = None
  520. self._preload_skills_requested: list = []
  521. self._preload_skills_finalized = False
  522. self._active_session_lease = None
  523. # Voice mode state (also reinitialized inside run() for interactive TUI).
  524. self._voice_lock = threading.Lock()
  525. self._voice_mode = self._voice_tts = self._voice_recording = False
  526. self._voice_processing = self._voice_continuous = False
  527. self._voice_recorder = self._voice_tts_stop = None
  528. self._voice_live_text = "" # live STT partial (stt.streaming) shown in the placeholder
  529. self._voice_tts_done = threading.Event()
  530. self._voice_tts_done.set()
  531. self._voice_barge_capture = threading.Event() # barge monitor is capturing the interruption
  532. self._voice_last_tts_text = "" # echo guard
  533. self._voice_barge_phase = None # "generation" | "playback"
  534. self._status_bar_visible = _status_bar_visible_from_display_config(CLI_CONFIG.get("display"))
  535. self._battery_visible = bool(CLI_CONFIG["display"].get("battery", False))
  536. # Vi/vim editing mode for the input composer (display.vim_mode, config-only).
  537. # Off by default: prompt_toolkit's standard emacs bindings.
  538. self._vim_mode = bool(CLI_CONFIG["display"].get("vim_mode", False))
  539. # Hide rules + status bar until the next input after a resize, so SIGWINCH cannot
  540. # stamp a fresh status bar over one the terminal just reflowed into scrollback.
  541. self._status_bar_suppressed_after_resize = self._resize_recovery_pending = False
  542. self._resize_recovery_lock = threading.Lock()
  543. self._resize_recovery_timer = self._status_bar_unsuppress_timer = None # latter: debounced un-suppress
  544. self._last_resize_width = None # width change (reflow, needs viewport clear) vs rows-only
  545. self._background_tasks: dict[str, threading.Thread] = {}
  546. self._background_task_counter = 0
  547. # Cache-hit baseline, reset on model switch / compression so the bar shows the current regime.
  548. self._cache_hit_baseline_prompt = self._cache_hit_baseline_read = self._cache_hit_baseline_compressions = 0
  549. self._cache_hit_baseline_model: Optional[str] = None