cli_session_mixin.py 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  1. """Session lifecycle for the interactive CLI: new/resume/save, undo/retry rewinds, yolo
  2. persistence, manual compression, and exit summary.
  3. Mixin bound onto ``HermesCLI`` via the MRO. cli.py-internal symbols are imported LAZILY
  4. inside each method (``from cli import ...``) — never at module load time (import cycle).
  5. """
  6. from __future__ import annotations
  7. import contextlib
  8. import os
  9. import shutil
  10. import sys
  11. from agent.i18n import t
  12. from hermes_constants import get_hermes_home
  13. from hermes_state_ids import new_session_id
  14. from pathlib import Path
  15. from rich.console import Console
  16. from rich.markup import escape as _escape
  17. from typing import Any, Dict, List, Optional
  18. def _user_turn_indices(history: list) -> list[int]:
  19. """Indices of *real* user turns: excludes ephemeral scaffolding, display_kind timeline
  20. rows and compaction handoffs — the same predicate as resume turn counting."""
  21. from agent.context_compressor import user_originated_turn_view
  22. from agent.session_persistence import _is_ephemeral_scaffolding
  23. return [
  24. i for i, m in enumerate(history)
  25. if not _is_ephemeral_scaffolding(m) and user_originated_turn_view(m) is not None]
  26. def _timestamp_or(value, default):
  27. """``datetime.fromtimestamp(value)`` or *default* when the value is missing/unparseable."""
  28. from cli import datetime
  29. if not value:
  30. return default
  31. try:
  32. return datetime.fromtimestamp(float(value))
  33. except Exception:
  34. return default
  35. def _squash(text: str, limit: int = 120) -> str:
  36. """Collapse whitespace and cap to *limit* cells with an ellipsis."""
  37. text = " ".join(text.split())
  38. return text[: limit - 1] + "…" if len(text) > limit else text
  39. def _dim_notice(cli, msg: str, quiet: bool) -> None:
  40. """Print a dim notice — raw to stderr on quiet (pre-TUI) paths. Module-level so tests can
  41. call the resume helpers unbound against a minimal stand-in."""
  42. if quiet:
  43. print(msg, file=sys.stderr)
  44. else:
  45. cli._console_print(f"[dim]{_escape(msg)}[/dim]")
  46. def _reset_model_to_config_default(cli, silent: bool) -> None:
  47. """/new is a full boundary: re-derive model/provider from config.yaml so a
  48. session-only ``/model --session`` switch never leaks into the next session.
  49. Best-effort — an unreachable default must never block /new. Module-level helper (like
  50. ``_apply_new_session_title``): tests drive ``new_session`` unbound on a SimpleNamespace."""
  51. from cli import CLI_CONFIG, _cprint, _split_model_config_default, logger
  52. _model_config = CLI_CONFIG.get("model", {})
  53. if isinstance(_model_config, dict):
  54. _raw_default = _model_config.get("default") or _model_config.get("model") or ""
  55. _config_provider = _model_config.get("provider", "")
  56. else:
  57. _raw_default, _config_provider = (_model_config or ""), ""
  58. _config_model, _ = _split_model_config_default(_raw_default)
  59. if not _config_model or _config_model == getattr(cli, "model", None):
  60. return
  61. try:
  62. from hermes_cli.model_switch import switch_model as _switch_model
  63. r = _switch_model(
  64. raw_input=_config_model,
  65. current_provider=cli.provider or "",
  66. current_model=cli.model or "",
  67. current_base_url=cli.base_url or "",
  68. current_api_key=cli.api_key or "",
  69. is_global=False,
  70. explicit_provider=_config_provider or "")
  71. if not r.success:
  72. return
  73. # A gateway /new already opened the next session on the profile's default (``session.create``
  74. # without a model); the stand-in still points at the ended session, which a switch would rewrite.
  75. if cli.agent and not getattr(cli, "_gateway_session_open", False):
  76. cli.agent.switch_model(
  77. new_model=r.new_model, new_provider=r.target_provider, api_key=r.api_key,
  78. base_url=r.base_url, api_mode=r.api_mode,
  79. capabilities=getattr(r, "runtime_capabilities", None))
  80. cli.model = r.new_model
  81. cli.provider = r.target_provider
  82. cli.requested_provider = r.target_provider
  83. cli._explicit_api_key = r.api_key
  84. cli._explicit_base_url = r.base_url
  85. if r.api_key:
  86. cli.api_key = r.api_key
  87. if r.base_url:
  88. cli.base_url = r.base_url
  89. if r.api_mode:
  90. cli.api_mode = r.api_mode
  91. if not silent:
  92. _cprint(f" {t('cli.session.model_reset_default', model=r.new_model)}")
  93. except Exception:
  94. logger.debug("/new model reset to config default failed", exc_info=True)
  95. def _apply_new_session_title(cli, title: str) -> Optional[str]:
  96. """Sanitize + persist a /new title; returns the stored title or None (untitled)."""
  97. from cli import _cprint
  98. from hermes_state import SessionDB
  99. try:
  100. sanitized = SessionDB.sanitize_title(title)
  101. except ValueError as e:
  102. _cprint(f" {t('cli.session.title_rejected', error=e)}")
  103. return None
  104. if not sanitized:
  105. _cprint(f" {t('cli.session.title_empty_untitled')}")
  106. return None
  107. try:
  108. cli._session_db.set_session_title(cli.session_id, sanitized)
  109. except ValueError as e:
  110. _cprint(f" {t('cli.session.title_error_untitled', error=e)}")
  111. return None
  112. except Exception:
  113. return None
  114. cli._pending_title = None
  115. cli._status_bar_title_checked_at = 0.0
  116. return sanitized
  117. def _print_save_refusal(error) -> None:
  118. """A gateway's ``/save`` refusal: ``not_found`` (no stored conversation yet) is main's nothing-to-save."""
  119. print(t("cli.session.save_nothing") if str(error) == "not_found" else t("cli.session.save_failed", error=error))
  120. def _export_on_gateway(connection, session_id, fmt, filename, redact):
  121. """The owner's ``/save`` rendering of its stored row (``session.export``: the snapshot ``hermes
  122. sessions export`` writes, with title, metadata and archived rows), never this process's
  123. in-memory history. Nothing is written on the gateway host, so a remote owner's disk is never
  124. taken for this machine's. None when refused (printed), and also None when an older gateway
  125. without ``session.export`` was handed to ``_save_on_older_gateway`` (which may save on the
  126. gateway host and prints its own outcome)."""
  127. from hermes_cli.gateway_client import GatewayClientError, GatewayRPCError
  128. try:
  129. content = (connection.call("session.export", session_id=session_id, format=fmt,
  130. redact=redact) or {}).get("content")
  131. except GatewayClientError as e:
  132. if not (isinstance(e, GatewayRPCError) and (e.code == -32601 or str(e) == "unknown_method")):
  133. _print_save_refusal(e)
  134. return None
  135. _save_on_older_gateway(connection, session_id, fmt, filename, redact)
  136. return None
  137. if not isinstance(content, str):
  138. print(t("cli.session.save_failed", error="the gateway returned no export"))
  139. return None
  140. return content
  141. def _save_on_older_gateway(connection, session_id, fmt, filename, redact):
  142. """An owner without ``session.export``: its ``session.save`` writes default-named, unredacted
  143. JSON on the gateway host, so only a plain ``/save json`` may use it (as Desktop does)."""
  144. from hermes_cli.gateway_client import GatewayClientError
  145. if redact or fmt != "json" or filename:
  146. print("(._.) This gateway predates this CLI: only a plain /save json works until it restarts "
  147. "(it saves on the gateway host).")
  148. return
  149. try:
  150. saved = (connection.call("session.save", session_id=session_id) or {}).get("file")
  151. except GatewayClientError as e:
  152. _print_save_refusal(e)
  153. return
  154. print(f"(^_^)v Conversation saved on the gateway host: {saved}" if saved
  155. else t("cli.session.save_failed", error="the gateway returned no file"))
  156. def _write_save(session_id, fmt, filename, render):
  157. """Write a ``/save`` export on this machine: ``filename`` as typed (relative to the cwd), else
  158. ``sessions/saved/hermes_conversation_<ts>.<fmt>`` under this CLI's home."""
  159. from cli import datetime
  160. saved_dir = get_hermes_home() / "sessions" / "saved"
  161. try:
  162. saved_dir.mkdir(parents=True, exist_ok=True)
  163. except OSError as e:
  164. print(t("cli.session.save_dir_failed", path=saved_dir, error=e))
  165. return
  166. if filename:
  167. path = Path(filename).expanduser()
  168. if not path.is_absolute():
  169. path = Path.cwd() / path
  170. else:
  171. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  172. path = saved_dir / f"hermes_conversation_{timestamp}.{fmt}"
  173. try:
  174. content = render()
  175. with open(path, "w", encoding="utf-8") as f:
  176. f.write(content)
  177. label = {"json": "JSON", "md": t("cli.session.format_markdown"), "html": "HTML"}[fmt]
  178. print(t("cli.session.save_ok", path=path, label=label))
  179. if session_id:
  180. print(f" {t('cli.session.save_resume_hint', session_id=session_id)}")
  181. except Exception as e: # health: allow BLE001 -- /save's user boundary (main's, moved here): any render/write failure is printed
  182. print(t("cli.session.save_failed", error=e))
  183. class CLISessionMixin:
  184. """Session lifecycle for the interactive CLI: new/resume/save, undo/retry rewinds, yolo
  185. persistence, manual compression, and exit summary."""
  186. def _restore_session_cwd(self, session_meta: dict, *, quiet: bool = False) -> None:
  187. """Relaunch a resumed session in the directory it was started from.
  188. Idempotent; called from every resume path. Both ``os.chdir()`` and ``TERMINAL_CWD``
  189. are retargeted so the process and the terminal/code-exec tools agree (the local
  190. terminal backend snapshots cwd on first use, after this). No-op when no cwd was
  191. recorded, the directory is gone (dim warning, never a crash), or we're already there.
  192. """
  193. recorded = (session_meta or {}).get("cwd")
  194. if not recorded:
  195. return
  196. recorded = os.path.expanduser(str(recorded))
  197. try:
  198. current = os.getcwd()
  199. except OSError:
  200. current = None
  201. if current and os.path.realpath(recorded) == os.path.realpath(current):
  202. return
  203. if not os.path.isdir(recorded):
  204. msg = t("cli.session.cwd_gone", recorded=recorded, current=current or ".")
  205. else:
  206. try:
  207. os.chdir(recorded)
  208. os.environ["TERMINAL_CWD"] = recorded
  209. msg = t("cli.session.cwd_restored", path=recorded)
  210. except OSError as e:
  211. msg = t("cli.session.cwd_enter_failed", path=recorded, error=e)
  212. _dim_notice(self, msg, quiet)
  213. def _restore_session_yolo(self, session_meta: dict, *, quiet: bool = False) -> None:
  214. """Re-arm the session row's persisted /yolo on every resume path (``tools.approval_yolo``)."""
  215. from hermes_state import SessionDB
  216. from tools.approval_yolo import restore_session_yolo
  217. if restore_session_yolo(self.session_id or "default", SessionDB.session_yolo_enabled(session_meta)):
  218. _dim_notice(self, t("cli.session.yolo_restored"), quiet)
  219. def _render_resume_history_panel_lines(self, panel) -> list[str]:
  220. """Render the resume panel at the current terminal width for resize replay."""
  221. from cli import _suspend_output_history
  222. from io import StringIO
  223. buf = StringIO()
  224. console = Console(
  225. file=buf, force_terminal=True, color_system="truecolor", highlight=False,
  226. width=shutil.get_terminal_size((80, 24)).columns)
  227. with _suspend_output_history():
  228. console.print(panel)
  229. return buf.getvalue().rstrip("\n").splitlines()
  230. def _resolve_checkpoint_ref(self, ref: str, checkpoints: list) -> str | None:
  231. """Resolve a 1-indexed checkpoint number (or pass through a git hash)."""
  232. try:
  233. idx = int(ref) - 1
  234. except ValueError:
  235. return ref
  236. if 0 <= idx < len(checkpoints):
  237. return checkpoints[idx]["hash"]
  238. print(f" {t('cli.session.invalid_checkpoint', count=len(checkpoints))}")
  239. return None
  240. def _show_status(self):
  241. """Show compact startup status line."""
  242. from cli import get_tool_definitions
  243. from hermes_cli.gateway_tools_notify import gateway_store
  244. store = gateway_store(self) # a gateway session's tools are the gateway's: never enumerated here
  245. inventory = store.banner_inventory() if store is not None else None
  246. # Avoid pulling the full tool registry into the bare Termux prompt path.
  247. if os.environ.get("HERMES_DEFER_AGENT_STARTUP") == "1" or (store is not None and inventory is None):
  248. tool_status = t("cli.session.status_tools_deferred")
  249. elif inventory is not None:
  250. tool_status = t("cli.session.status_tools_count", count=len(inventory["tools"] or []))
  251. else:
  252. tools = get_tool_definitions(enabled_toolsets=self.enabled_toolsets,
  253. disabled_toolsets=self.disabled_toolsets, quiet_mode=True)
  254. tool_status = t("cli.session.status_tools_count", count=len(tools) if tools else 0)
  255. model_short = self.model.split("/")[-1] if "/" in self.model else self.model
  256. if len(model_short) > 30:
  257. model_short = model_short[:27] + "..."
  258. api_indicator = "[green bold]●[/]" if self.api_key else "[red bold]●[/]"
  259. try:
  260. from hermes_cli.skin_engine import get_active_skin
  261. skin = get_active_skin()
  262. separator_color = skin.get_color("banner_dim", "#B8860B")
  263. accent_color = skin.get_color("ui_accent", "#FFBF00")
  264. label_color = skin.get_color("ui_label", "#DAA520")
  265. except Exception:
  266. separator_color, accent_color, label_color = "#B8860B", "#FFBF00", "cyan"
  267. sep = f" [dim {separator_color}]·[/] "
  268. toolsets_info = ""
  269. if self.enabled_toolsets and "all" not in self.enabled_toolsets:
  270. toolsets_info = f"{sep}[{label_color}]{_escape(t('cli.session.status_toolsets', toolsets=', '.join(self.enabled_toolsets)))}[/]"
  271. provider_info = f"{sep}[dim]{_escape(t('cli.session.status_provider', provider=self.provider))}[/]"
  272. if self._provider_source:
  273. provider_info += f"{sep}[dim]{_escape(t('cli.session.status_auth', source=self._provider_source))}[/]"
  274. self._console_print(
  275. f" {api_indicator} [{accent_color}]{model_short}[/]{sep}"
  276. f"[bold {label_color}]{tool_status}[/]{toolsets_info}{provider_info}")
  277. def _show_session_status(self):
  278. """Show gateway-style status for the current CLI session."""
  279. from hermes_cli.status_report import build_status_fields, status_lines
  280. session_meta = {}
  281. if self._session_db:
  282. with contextlib.suppress(Exception):
  283. session_meta = self._session_db.get_session(self.session_id) or {}
  284. agent = getattr(self, "agent", None)
  285. fields = build_status_fields(
  286. self.session_id, agent, session_meta,
  287. model=getattr(self, "model", None), provider=getattr(self, "provider", None),
  288. created_fallback=self.session_start, agent_running=bool(getattr(self, "_agent_running", False)),
  289. )
  290. reasoning_label = None
  291. rc = getattr(agent, "reasoning_config", None) or getattr(self, "reasoning_config", None)
  292. if isinstance(rc, dict):
  293. if rc.get("enabled") is False:
  294. reasoning_label = t("cli.shared.label_off")
  295. elif rc.get("effort"):
  296. reasoning_label = str(rc.get("effort"))
  297. show_r = getattr(self, "show_reasoning", None)
  298. if reasoning_label and show_r is not None:
  299. state = t("cli.shared.label_on") if show_r else t("cli.shared.label_off")
  300. reasoning_label += t("cli.session.reasoning_display_suffix", state=state)
  301. approval_label = None
  302. try:
  303. from tools.approval import is_approval_bypass_active_for_session
  304. from tools.approval_context import _get_approval_mode
  305. approval_label = _get_approval_mode()
  306. if is_approval_bypass_active_for_session(getattr(self, "session_key", "") or ""):
  307. approval_label += t("cli.session.yolo_bypass_suffix")
  308. except Exception:
  309. pass
  310. # Context window usage: reuse the status-bar snapshot (tokens / max / percent).
  311. ctx_label = None
  312. try:
  313. snap = self._get_status_bar_snapshot()
  314. ctx_max = snap.get("context_length")
  315. ctx_pct = snap.get("context_percent")
  316. if ctx_max:
  317. left = ""
  318. if isinstance(ctx_pct, (int, float)):
  319. left = t("cli.session.ctx_left_prefix", percent=max(0, 100 - int(ctx_pct)))
  320. ctx_label = t("cli.session.ctx_tokens_used", left=left, used=f"{snap.get('context_tokens') or 0:,}",
  321. max=f"{ctx_max:,}")
  322. except Exception:
  323. ctx_label = None
  324. lines = [t("cli.session.status_title"), "", *status_lines(fields, "session_id", "path", "title", "model")]
  325. optional = ((t("cli.session.label_reasoning"), reasoning_label),
  326. (t("cli.session.label_approvals"), approval_label),
  327. (t("cli.session.label_context"), ctx_label))
  328. for label, value in optional:
  329. if value:
  330. lines.append(t("cli.shared.label_value", label=label, value=value))
  331. lines.extend(status_lines(fields, "created", "last_activity", "tokens", "agent_running"))
  332. self._console_print("\n".join(lines), highlight=False, markup=False)
  333. def _list_recent_sessions(self, limit: int = 10) -> list[dict[str, Any]]:
  334. """Return recent CLI sessions for in-chat browsing/resume affordances."""
  335. if not self._session_db:
  336. return []
  337. try:
  338. from hermes_cli.session_listing import query_session_listing
  339. from hermes_state_sessions import INTERNAL_LISTING_SOURCES
  340. return query_session_listing(
  341. self._session_db, source="cli", current_session_id=self.session_id,
  342. include_all_sources=False, include_unnamed=True, limit=limit,
  343. exclude_sources=list(INTERNAL_LISTING_SOURCES))
  344. except Exception:
  345. return []
  346. def _show_recent_sessions(self, *, reason: str = "history", limit: int = 10) -> bool:
  347. """Render recent sessions inline from the active chat TUI.
  348. Returns True when something was shown, False if no session list was available.
  349. """
  350. from cli import _cli_visible_print
  351. sessions = self._list_recent_sessions(limit=limit)
  352. if not sessions:
  353. return False
  354. from hermes_cli.timefmt import relative_time as _relative_time
  355. _cli_visible_print()
  356. if reason == "history":
  357. _cli_visible_print(t("cli.session.recent_intro"))
  358. else:
  359. _cli_visible_print(f" {t('cli.session.recent_header')}")
  360. _cli_visible_print()
  361. _cli_visible_print(
  362. f" {'#':<3} {t('cli.session.column_title'):<32} {t('cli.session.column_preview'):<40} "
  363. f"{t('cli.session.column_last_active'):<13} {t('cli.session.column_id')}")
  364. _cli_visible_print(f" {'─' * 3} {'─' * 32} {'─' * 40} {'─' * 13} {'─' * 24}")
  365. for idx, session in enumerate(sessions, start=1):
  366. title = session.get("title") or "—"
  367. preview = (session.get("preview") or "")[:38]
  368. last_active = _relative_time(session.get("last_active"), session_id=session.get("id"))
  369. _cli_visible_print(f" {idx:<3} {title:<32} {preview:<40} {last_active:<13} {session['id']}")
  370. _cli_visible_print()
  371. _cli_visible_print(f" {t('cli.session.resume_usage')}")
  372. _cli_visible_print(f" {t('cli.session.resume_example')}")
  373. _cli_visible_print()
  374. return True
  375. def show_history(self):
  376. """Display conversation history."""
  377. from cli import _cli_visible_print
  378. if not self.conversation_history:
  379. if not self._show_recent_sessions(reason="history"):
  380. _cli_visible_print(t("cli.session.history_empty"))
  381. return
  382. preview_limit = 400
  383. visible_index = 0
  384. hidden_tool_messages = 0
  385. show_ts = bool(getattr(self, "show_timestamps", False))
  386. def _ts_suffix(message: dict) -> str:
  387. # Only annotate when the toggle is on AND the turn has a stored unix
  388. # `timestamp` (SessionDB-restored rows do; live turns may not) — never fabricate.
  389. ts = message.get("timestamp") if show_ts else None
  390. if not ts:
  391. return ""
  392. try:
  393. stamp = _timestamp_or(ts, None)
  394. return f" [{stamp.strftime(getattr(self, 'timestamp_format', '%H:%M'))}]" if stamp else ""
  395. except (ValueError, OSError, TypeError):
  396. return ""
  397. def flush_tool_summary():
  398. nonlocal hidden_tool_messages
  399. if not hidden_tool_messages:
  400. return
  401. key = "cli.session.history_tools_hidden_one" if hidden_tool_messages == 1 else "cli.session.history_tools_hidden_other"
  402. _cli_visible_print(f"\n {t('cli.session.history_tools_header')}")
  403. _cli_visible_print(f" {t(key, count=hidden_tool_messages)}")
  404. hidden_tool_messages = 0
  405. rule = "+" + "-" * 50 + "+"
  406. for line in ("", rule, "|" + t("cli.session.history_title").center(50) + "|", rule):
  407. _cli_visible_print(line)
  408. for msg in self.conversation_history:
  409. role = msg.get("role", "unknown")
  410. if role == "tool":
  411. hidden_tool_messages += 1
  412. continue
  413. if role not in {"user", "assistant"}:
  414. continue
  415. flush_tool_summary()
  416. visible_index += 1
  417. content = msg.get("content")
  418. content_text = "" if content is None else str(content)
  419. preview = content_text[:preview_limit]
  420. suffix = "..." if len(content_text) > preview_limit else ""
  421. if role == "user":
  422. _cli_visible_print(f"\n {t('cli.session.history_you_header', index=visible_index)}{_ts_suffix(msg)}")
  423. _cli_visible_print(f" {preview}{suffix}")
  424. continue
  425. _cli_visible_print(
  426. f"\n {t('cli.session.history_assistant_header', agent_name='Hermes', index=visible_index)}{_ts_suffix(msg)}")
  427. n_calls = len(msg.get("tool_calls") or [])
  428. if not content_text:
  429. suffix = ""
  430. preview = t("cli.session.history_no_text")
  431. if n_calls:
  432. key = "cli.session.history_tool_calls_one" if n_calls == 1 else "cli.session.history_tool_calls_other"
  433. preview = t(key, count=n_calls)
  434. _cli_visible_print(f" {preview}{suffix}")
  435. flush_tool_summary()
  436. _cli_visible_print()
  437. def _notify_session_boundary(self, event_type: str) -> None:
  438. """Fire a session-boundary plugin hook (on_session_finalize / on_session_reset).
  439. Non-blocking; errors swallowed. Safe from shutdown, /new, /reset."""
  440. with contextlib.suppress(Exception):
  441. from hermes_cli.lifecycle import finalize_session, invoke_hook
  442. context = {
  443. "session_id": self.agent.session_id if self.agent else None,
  444. "platform": getattr(self, "platform", None) or "cli",
  445. "reason": "new_session" if event_type == "on_session_reset" else "session_boundary"}
  446. if event_type == "on_session_finalize":
  447. from cli import _cli_visible_print
  448. from hermes_cli.lifecycle import session_end_messages
  449. for message in session_end_messages(finalize_session(**context)):
  450. _cli_visible_print(message)
  451. else:
  452. invoke_hook(event_type, **context)
  453. def _discard_session_if_empty(self, session_id: Optional[str]) -> bool:
  454. """Drop a just-ended session row that never gained content (quit-immediately, /new,
  455. /clear) so it doesn't clutter ``/resume``. ``SessionDB.delete_session_if_empty`` only
  456. removes rows with no messages, no title and no children (gemini-cli#27770 port)."""
  457. from cli import logger
  458. if not self._session_db or not session_id:
  459. return False
  460. # In-memory transcript is authoritative: a real conversation whose DB flush failed
  461. # or hasn't happened yet must never be pruned.
  462. if getattr(self, "conversation_history", None):
  463. return False
  464. try:
  465. from hermes_constants import get_hermes_home as _ghh
  466. return self._session_db.delete_session_if_empty(
  467. session_id, sessions_dir=_ghh() / "sessions")
  468. except Exception:
  469. logger.debug("Could not prune empty session %s", session_id, exc_info=True)
  470. return False
  471. def _launch_session_boundary_memory_flush(
  472. self, history_snapshot: list, *, session_id: Optional[str] = None) -> Optional[list]:
  473. """Stage old-session memory extraction so /new stays responsive.
  474. The context-engine ``on_session_end`` is delivered synchronously here: cheap (no LLM)
  475. and ordering-sensitive — it must land before ``reset_session_state()`` rebinds the
  476. engine. The memory-provider half (LLM-bound, seconds) is NOT run here: the returned
  477. snapshot goes to ``MemoryManager.commit_session_boundary_async`` as one end→switch
  478. task on the serialized worker, so a late ``on_session_end`` can never run after
  479. ``on_session_switch`` and misattribute the old transcript to the new session.
  480. Returns the snapshot to queue, or ``None`` when there is nothing to extract.
  481. """
  482. from cli import logger
  483. agent = getattr(self, "agent", None)
  484. if not agent or not history_snapshot:
  485. return None
  486. engine = getattr(agent, "context_compressor", None)
  487. if engine is not None and hasattr(engine, "on_session_end"):
  488. try:
  489. engine.on_session_end(session_id or "", history_snapshot)
  490. except Exception:
  491. logger.debug("Context engine on_session_end failed at /new boundary", exc_info=True)
  492. # No memory manager → new_session() falls back to the inline switch path.
  493. if getattr(agent, "_memory_manager", None) is None:
  494. return None
  495. return history_snapshot
  496. def new_session(self, silent=False, title=None):
  497. """Start a fresh session with a new session ID and cleared agent state."""
  498. from cli import (
  499. CLI_CONFIG, _parse_service_tier_config,
  500. _sync_process_session_id, datetime)
  501. from hermes_cli.cli_model_switch_mixin import _resolve_cli_reasoning
  502. old_session_id = self.session_id
  503. _boundary_snapshot = None
  504. if self.agent:
  505. if self.conversation_history:
  506. # Context-engine boundary now; provider extraction is queued below (after
  507. # rotation) so /new never blocks on the LLM-bound call.
  508. _boundary_snapshot = self._launch_session_boundary_memory_flush(
  509. list(self.conversation_history), session_id=old_session_id)
  510. from hermes_cli.cli_shutdown import _gateway_owns_session_end
  511. if not _gateway_owns_session_end(self.agent): # the gateway finalizes at end_session below
  512. self._notify_session_boundary("on_session_finalize")
  513. if self._session_db and old_session_id:
  514. # /new can arrive mid-turn before _flush_messages_to_session_db() ran — flush
  515. # the current turn to the OLD session before rotating or it is silently lost.
  516. if self.agent:
  517. with contextlib.suppress(Exception):
  518. # Flush any un-persisted messages from the current turn to the old session *before*
  519. # rotating. /new can be called mid-turn when _flush_messages_to_session_db() has not
  520. # yet run — without this, messages generated during the current turn are silently lost
  521. # on session rotation (#47202).
  522. # See #47202.
  523. # See #47202.
  524. self.agent._flush_messages_to_session_db(
  525. self.conversation_history, conversation_history=self.conversation_history)
  526. with contextlib.suppress(Exception):
  527. self._session_db.end_session(old_session_id, "new_session")
  528. self._discard_session_if_empty(old_session_id)
  529. self.session_start = datetime.now()
  530. # The gateway's new session; getattr: tests drive new_session unbound (main's mint then).
  531. self.session_id = getattr(self, "_new_session_id", lambda now: new_session_id(now))(self.session_start)
  532. # getattr: tests drive new_session unbound against a SimpleNamespace stand-in.
  533. getattr(self, "_write_terminal_breadcrumb", lambda: None)()
  534. self.conversation_history = []
  535. self._pending_title = None
  536. self._resumed = False
  537. # An explicit -m/--model was for the previous session only.
  538. self._explicit_model_override = False
  539. # Session-scoped overrides (/model --session, /fast, one-turn restores) don't carry over.
  540. # Re-derive model/provider and service tier from config.yaml so a session-only switch never leaks
  541. # into the next session (#48055, #23131).
  542. self._pending_one_turn_model_restore = None
  543. self.service_tier = _parse_service_tier_config(CLI_CONFIG["agent"].get("service_tier", ""))
  544. _reset_model_to_config_default(self, silent)
  545. # After the model reset: the effort belongs to the model the fresh session lands on (a /reasoning
  546. # session override is dropped, the default model's per-model override is kept).
  547. _resolve_cli_reasoning(self)
  548. _sync_process_session_id(self.session_id)
  549. if self.agent:
  550. self.agent.session_id = self.session_id
  551. self.agent.session_start = self.session_start
  552. self.agent.reasoning_config = self.reasoning_config
  553. self.agent.reset_session_state()
  554. if hasattr(self.agent, "_last_flushed_db_idx"):
  555. self.agent._last_flushed_db_idx = 0
  556. if hasattr(self.agent, "_todo_store"):
  557. with contextlib.suppress(Exception):
  558. from tools.todo_tool import TodoStore
  559. self.agent._todo_store = TodoStore()
  560. if hasattr(self.agent, "_invalidate_system_prompt"):
  561. self.agent._invalidate_system_prompt()
  562. if self._session_db:
  563. with contextlib.suppress(Exception):
  564. self.agent._session_db_created = False
  565. self._session_db.create_session(
  566. session_id=self.session_id,
  567. source=os.environ.get("HERMES_SESSION_SOURCE", "cli"),
  568. model=self.model,
  569. model_config={
  570. "max_iterations": self.max_turns, "reasoning_config": self.reasoning_config,
  571. })
  572. self.agent._session_db_created = True
  573. if title:
  574. title = _apply_new_session_title(self, title)
  575. # Tell memory providers the session_id rotated (reset=True flushes per-session
  576. # state) BEFORE the plugin on_session_reset hook. With old history, end-of-session
  577. # extraction and this switch are queued as ONE task on the serialized worker —
  578. # end strictly before switch, without blocking /new. No history → switch inline.
  579. _mm = getattr(self.agent, "_memory_manager", None)
  580. with contextlib.suppress(Exception):
  581. if _mm is not None and _boundary_snapshot:
  582. _mm.commit_session_boundary_async(
  583. _boundary_snapshot, new_session_id=self.session_id,
  584. parent_session_id=old_session_id or "", reason="new_session")
  585. elif _mm is not None:
  586. _mm.on_session_switch(
  587. self.session_id, parent_session_id=old_session_id or "",
  588. reset=True, reason="new_session")
  589. from hermes_cli.cli_shutdown import _gateway_owns_session_end
  590. if not _gateway_owns_session_end(self.agent): # the gateway resets when end_session closes it
  591. self._notify_session_boundary("on_session_reset")
  592. if not silent:
  593. if title:
  594. print(t("cli.session.new_session_titled", title=title))
  595. else:
  596. print(t("cli.session.new_session"))
  597. def _consume_pending_resume_selection(self, text: str) -> bool:
  598. """Resolve a bare numeric reply following a bare ``/resume`` prompt.
  599. ``/resume`` (no args) arms ``self._pending_resume_sessions``; the next input gets one
  600. chance to be a bare session number. The pending state is one-shot — cleared on the
  601. first input regardless of outcome, so a stray later number is never hijacked.
  602. Returns True if the input was consumed (caller must not treat it as chat).
  603. See #34584.
  604. """
  605. from cli import _cprint
  606. pending = self._pending_resume_sessions
  607. if not pending:
  608. return False
  609. self._pending_resume_sessions = None
  610. if not isinstance(text, str):
  611. return False
  612. # Only a pure number selects; "/resume 3", titles etc. fall through.
  613. if not text.strip().isdigit():
  614. return False
  615. index = int(text.strip())
  616. if not 1 <= index <= len(pending):
  617. _cprint(f" {t('cli.session.resume_index_out_of_range', index=index)}")
  618. _cprint(f" {t('cli.session.resume_no_args_hint')}")
  619. return True
  620. self._handle_resume_command(f"/resume {index}")
  621. return True
  622. def save_conversation(self, cmd: str = "/save"):
  623. """Handle ``/save [json|md|html] [filename] [redact]``.
  624. A convenience export only — every message is already persisted to the session DB, so
  625. the live session stays resumable regardless. ``redact`` runs the force-mode secret
  626. redaction pass before writing.
  627. """
  628. from hermes_cli.session_export import (
  629. SAVE_USAGE, load_save_snapshot, normalize_save_format, render_session_for_save)
  630. parts = cmd.split()[1:]
  631. redact = bool(parts) and parts[-1].lower() in ("redact", "--redact")
  632. if redact:
  633. parts = parts[:-1]
  634. if not parts:
  635. print(SAVE_USAGE)
  636. return
  637. try:
  638. fmt = normalize_save_format(parts[0])
  639. except ValueError as e:
  640. print(f"(._.) {e}")
  641. print(SAVE_USAGE)
  642. return
  643. filename = parts[1] if len(parts) > 1 else None
  644. from hermes_cli.gateway_tools_notify import gateway_store
  645. store = gateway_store(self)
  646. if store is not None: # the gateway owns the session: it renders its stored row, this machine writes it
  647. if not self.conversation_history: # as Ink: nothing said yet, nothing exported
  648. print(t("cli.session.save_nothing"))
  649. return
  650. content = _export_on_gateway(store.connection, self.session_id, fmt, filename, redact)
  651. if content is not None:
  652. _write_save(self.session_id, fmt, filename, lambda: content)
  653. return
  654. # Prefer the durable DB row (metadata + tool calls); fall back to in-memory history.
  655. # getattr: test doubles may not carry _session_db / session_id.
  656. session_data = None
  657. _db = getattr(self, "_session_db", None)
  658. _sid = getattr(self, "session_id", None)
  659. if _db and _sid:
  660. from hermes_state import SessionExportTooLargeError
  661. try:
  662. session_data = load_save_snapshot(_db, _sid, fmt)
  663. except SessionExportTooLargeError as e:
  664. print(f"(._.) {e}")
  665. return
  666. except Exception:
  667. session_data = None
  668. if not session_data:
  669. if not self.conversation_history:
  670. print(t("cli.session.save_nothing"))
  671. return
  672. session_data = {
  673. "id": self.session_id, "model": self.model,
  674. "started_at": self.session_start.timestamp(), "messages": self.conversation_history}
  675. if redact:
  676. from hermes_cli.session_export_md import redact_session_data
  677. session_data = redact_session_data(session_data)
  678. _write_save(self.session_id, fmt, filename, lambda: render_session_for_save(session_data, fmt))
  679. def _publish_truncated_history(self, truncated: list, *, invalidate_prompt: bool) -> None:
  680. """Install a rewound history and mirror it onto the agent (flush index reset so the
  681. next turn re-flushes from the truncated head)."""
  682. self.conversation_history = truncated
  683. agent = self.agent
  684. if agent is None:
  685. return
  686. if invalidate_prompt and hasattr(agent, "_invalidate_system_prompt"):
  687. with contextlib.suppress(Exception):
  688. agent._invalidate_system_prompt()
  689. if hasattr(agent, "_last_flushed_db_idx"):
  690. with contextlib.suppress(Exception):
  691. agent._last_flushed_db_idx = len(self.conversation_history)
  692. if hasattr(agent, "_session_messages"):
  693. agent._session_messages = self.conversation_history
  694. if hasattr(agent, "_db_flush_scan_prefix"):
  695. agent._db_flush_scan_prefix = self.conversation_history[:]
  696. def retry_last(self):
  697. """Retry the last user message: drop the last exchange and return the text to re-send
  698. (None when there is nothing to retry)."""
  699. if not self.conversation_history:
  700. print(t("cli.session.retry_no_messages"))
  701. return None
  702. from agent.context_compressor import (
  703. history_before_user_originated_turn, retryable_user_text)
  704. from agent.memory_context import sanitize_context
  705. warm_history = list(self.conversation_history)
  706. user_indices = _user_turn_indices(warm_history)
  707. if not user_indices:
  708. print(t("cli.session.retry_no_user_message"))
  709. return None
  710. # Resolve a lossless live payload before touching persistence or memory. A
  711. # force-user-leading compaction row is one physical carrier: its handoff stays in
  712. # the prefix while only the embedded human ask is retried. Media cannot be replayed
  713. # by /retry, so fail closed before archiving anything.
  714. try:
  715. truncated, live_view = history_before_user_originated_turn(
  716. warm_history, user_indices[-1])
  717. live_content = live_view.get("content")
  718. if isinstance(live_content, str):
  719. live_content = sanitize_context(live_content).strip()
  720. last_message = retryable_user_text(live_content)
  721. except ValueError as exc:
  722. print(t("cli.session.retry_unsafe", error=exc))
  723. return None
  724. # Persist the rewind before publishing the shorter in-memory view: the DB owns the
  725. # physical carrier split so archived original + retained scaffold commit atomically.
  726. if self._session_db is not None and self.session_id:
  727. try:
  728. truncated = self._session_db.rewind_user_turn(
  729. self.session_id, -1, warm_history=warm_history, require_retryable=True).prefix
  730. except Exception as exc:
  731. print(t("cli.session.retry_rewind_failed", error=exc))
  732. return None
  733. self._publish_truncated_history(truncated, invalidate_prompt=False)
  734. print(t("cli.session.retrying", preview=f"{last_message[:60]}{'...' if len(last_message) > 60 else ''}"))
  735. return last_message
  736. def undo_last(self, n: int = 1, prefill: bool = True):
  737. """Back up N user turns: truncate history, soft-delete on disk, prefill the composer.
  738. Discards everything from the Nth-from-last user message onward (clamped to the oldest
  739. turn). Rows are soft-deleted in SessionDB (``active=0``, kept for audit), memory
  740. providers get ``on_session_switch(rewound=True)``, and the agent is patched like
  741. /branch does. ``prefill=False`` is for programmatic callers (checkpoint rollback)
  742. that must not touch the input buffer. Returns the number of user turns undone (None when
  743. nothing changed).
  744. """
  745. if not self.conversation_history:
  746. print(t("cli.session.undo_no_messages"))
  747. return
  748. n = max(n, 1)
  749. user_indices = _user_turn_indices(self.conversation_history)
  750. if not user_indices:
  751. print(t("cli.session.undo_no_user_message"))
  752. return
  753. turns_undone = min(n, len(user_indices))
  754. rewound = self._rewind_to_user_ordinal(len(user_indices) - turns_undone)
  755. if rewound is None:
  756. return
  757. removed_text, removed_count = rewound
  758. key = "cli.session.undo_ok_one" if turns_undone == 1 else "cli.session.undo_ok_other"
  759. print(t(key, count=turns_undone, messages=removed_count,
  760. backup=f"{removed_text[:60]}{'...' if len(removed_text) > 60 else ''}"))
  761. print(f" {t('cli.session.undo_remaining', count=len(self.conversation_history))}")
  762. # Editable, not auto-sent (Claude-Code-style).
  763. if prefill and removed_text:
  764. self._prefill_input_buffer(removed_text)
  765. return turns_undone
  766. def _rewind_to_user_ordinal(self, target_ordinal: int, *, failure_key: str = "cli.session.undo_failed"):
  767. """Cut the session back to just before real user turn ``target_ordinal`` (0 = oldest).
  768. The shared /undo and /rewind primitive: soft-deletes the rows on disk (``active=0``) via
  769. ``SessionDB.rewind_user_turn`` before publishing the shorter history, patches the agent,
  770. and fires the memory providers' ``rewound`` hook. Returns ``(live_text, archived_count)``,
  771. or None after printing ``failure_key`` when the durable rewind refused (history untouched).
  772. """
  773. from cli import logger
  774. from agent.context_compressor import history_before_user_originated_turn
  775. warm_history = list(self.conversation_history)
  776. cut_idx = _user_turn_indices(warm_history)[target_ordinal]
  777. removed_count = len(warm_history) - cut_idx
  778. truncated, live_view = history_before_user_originated_turn(warm_history, cut_idx)
  779. removed_text = self._undo_content_to_text(live_view.get("content"))
  780. if self._session_db is not None and self.session_id:
  781. try:
  782. outcome = self._session_db.rewind_user_turn(
  783. self.session_id, target_ordinal, warm_history=warm_history)
  784. except Exception as e: # health: allow BLE001 -- moved from undo_last: any refusal (local SessionDB or the gateway store) must leave history untouched and be shown
  785. logger.debug("rewind: durable rewind failed: %s", e, exc_info=True)
  786. print(t(failure_key, error=e))
  787. return None
  788. truncated = outcome.prefix
  789. # Canonical editable prefill: the raw carrier holds the reference-summary wrapper.
  790. removed_text = outcome.live_text or removed_text
  791. removed_count = outcome.rewound_count or removed_count
  792. # Publish only after the durable rewind succeeds (or no store exists).
  793. self._publish_truncated_history(truncated, invalidate_prompt=True)
  794. # Same hook /branch fires; rewound=True invalidates per-turn document caches (#21910, #6672).
  795. _mm = getattr(self.agent, "_memory_manager", None)
  796. if _mm is not None and self.session_id:
  797. with contextlib.suppress(Exception):
  798. _mm.on_session_switch(self.session_id, parent_session_id="", reset=False, rewound=True)
  799. return removed_text, removed_count
  800. @staticmethod
  801. def _undo_content_to_text(content) -> str:
  802. """Flatten message content (str or content-part list) to plain text."""
  803. if isinstance(content, str):
  804. return content
  805. if isinstance(content, list):
  806. parts = [
  807. p.get("text", "") for p in content if isinstance(p, dict) and p.get("type") == "text"
  808. ]
  809. return "\n".join(t for t in parts if t)
  810. return ""
  811. def _write_terminal_breadcrumb(self) -> None:
  812. """Record this terminal's live session for bare ``hermes -c``. Called whenever
  813. ``self.session_id`` is (re)assigned so a later bare ``-c`` in THIS terminal resumes
  814. this conversation's live tip. Best-effort; no-op without a terminal identity."""
  815. with contextlib.suppress(Exception):
  816. from hermes_cli.terminal_breadcrumbs import write_breadcrumb
  817. write_breadcrumb(self.session_id)
  818. def _is_session_yolo_active(self) -> bool:
  819. """Whether YOLO bypass is on for this session: reads ``tools.approval._session_yolo``
  820. (not a stale env var) and honors the frozen process-start ``--yolo`` flag."""
  821. try:
  822. from tools.approval import _YOLO_MODE_FROZEN, is_session_yolo_enabled
  823. except Exception:
  824. return False
  825. if _YOLO_MODE_FROZEN:
  826. return True
  827. # getattr: __new__-built test fixtures skip __init__; the status-bar builders
  828. # swallow exceptions but would lose every field after the failure.
  829. return is_session_yolo_enabled(getattr(self, "session_id", None) or "default")
  830. def _toggle_yolo(self):
  831. """Toggle per-session YOLO mode (skip dangerous-command approvals).
  832. Mirrors the gateway/TUI ``/yolo`` handlers. Deliberately does NOT touch
  833. ``HERMES_YOLO_MODE``: that env var is frozen into ``tools.approval._YOLO_MODE_FROZEN``
  834. at import (so prompt-injected skills can't flip the bypass), making a later set a
  835. silent no-op. ``run_conversation`` binds ``self.session_id`` as the active approval
  836. key, so the bypass applies to the very next dangerous command.
  837. """
  838. from cli import _cprint
  839. from hermes_cli.colors import Colors as _Colors
  840. from tools.approval import _YOLO_MODE_FROZEN
  841. # A frozen process-level bypass short-circuits the approval gate ahead of the session
  842. # check — toggling "OFF" would be a false safety claim. Say so instead.
  843. if _YOLO_MODE_FROZEN:
  844. state = f"{_Colors.BOLD}{_Colors.RED}{t('cli.session.yolo_state_locked_on')}{_Colors.RESET}"
  845. _cprint(f" {t('cli.session.yolo_locked', state=state)}")
  846. return
  847. from tools.approval_yolo import toggle_session_yolo
  848. session_key = self.session_id or "default"
  849. db = getattr(self, "_session_db", None) # getattr: tests call this unbound against a stand-in
  850. # The row is created lazily on the first turn; until then with_session_yolo records the toggle.
  851. persist = (lambda on: db.set_session_yolo(session_key, on)) if db and session_key != "default" else None
  852. if toggle_session_yolo(session_key, persist=persist):
  853. state = f"{_Colors.BOLD}{_Colors.GREEN}{t('cli.shared.label_on_upper')}{_Colors.RESET}"
  854. _cprint(f" {t('cli.session.yolo_on', state=state)}")
  855. else:
  856. state = f"{_Colors.BOLD}{_Colors.RED}{t('cli.shared.label_off_upper')}{_Colors.RESET}"
  857. _cprint(f" {t('cli.session.yolo_off', state=state)}")
  858. def _manual_compress(self, cmd_original: str = ""):
  859. """Manually trigger context compression.
  860. * ``/compress [<focus>]`` — compress the whole history; an optional focus topic tells
  861. the summariser what to preserve while discarding the rest more aggressively.
  862. * ``/compress here [N]`` — boundary-aware: summarize everything except the most recent
  863. ``N`` exchanges (default 2), kept verbatim.
  864. * ``--preview`` reports what would happen and changes nothing.
  865. No ``compression_enabled`` gate: that flag disables *automatic* compaction only, and
  866. the context-overflow error path directs users here when it is off.
  867. """
  868. from agent.conversation_compression import finalize_context_engine_compression_notification
  869. from agent.conversation_compression_manual import (
  870. AGGRESSIVE_UNSUPPORTED, MIN_MESSAGES, compress_now, parse_compress_args, render_compress_result)
  871. if len(self.conversation_history or ()) < MIN_MESSAGES:
  872. print(t("cli.session.compress_too_short", min=MIN_MESSAGES))
  873. return
  874. if not self.agent:
  875. print(t("cli.session.compress_no_agent"))
  876. return
  877. _parts = (cmd_original or "").strip().split(None, 1)
  878. request = parse_compress_args(_parts[1] if len(_parts) > 1 else "")
  879. if request.aggressive:
  880. print(f"(._.) {AGGRESSIVE_UNSUPPORTED}")
  881. if not request.preview:
  882. return
  883. if request.preview:
  884. for line in render_compress_result(compress_now(self.agent, self.conversation_history, request)):
  885. print(f"🗜️ {line}")
  886. return
  887. original_count = len(self.conversation_history)
  888. with self._busy_command(t("cli.session.compress_busy"), blocks_input=False):
  889. try:
  890. if request.partial:
  891. print(t("cli.session.compress_summarizing", count=original_count, keep_last=request.keep_last))
  892. elif request.focus_topic:
  893. print(t("cli.session.compress_focus", count=original_count, focus=request.focus_topic))
  894. else:
  895. print(t("cli.session.compress_plain", count=original_count))
  896. result = compress_now(self.agent, self.conversation_history, request,
  897. task_id=self.session_id or "default")
  898. if result.status != "compressed":
  899. for line in render_compress_result(result):
  900. print(f" {line}")
  901. return
  902. self.conversation_history = result.after_messages
  903. # _compress_context ends the old session and creates a child session on the
  904. # agent. Sync the CLI's session_id so /status, /resume, exit summary and title
  905. # generation point at the live continuation, not the ended parent.
  906. agent_sid = getattr(self.agent, "session_id", None)
  907. if agent_sid and agent_sid != self.session_id:
  908. from tools.approval_yolo import transfer_session_yolo
  909. transfer_session_yolo(self.session_id, agent_sid)
  910. self.session_id = self.agent.session_id
  911. self._write_terminal_breadcrumb()
  912. self._pending_title = None
  913. # Persist the new handoff from offset 0 so resume can recover it after exit.
  914. self.agent._flush_messages_to_session_db(self.conversation_history, None)
  915. finalize_context_engine_compression_notification(self.agent, committed=True)
  916. summary = result.summary
  917. if summary.get("aborted") or summary.get("fallback_used") or summary.get("refused_would_grow"):
  918. icon = "⚠️"
  919. else:
  920. icon = "🗜️" if summary["noop"] else "✅"
  921. print(f" {icon} {summary['headline']}")
  922. print(f" {summary['token_line']}")
  923. if summary["note"]:
  924. print(f" {summary['note']}")
  925. except Exception as e:
  926. finalize_context_engine_compression_notification(self.agent, committed=False)
  927. from hermes_cli.cli_chat_error_copy import refusal_text
  928. print(f" {t('cli.session.compress_failed', error=refusal_text(e))}")
  929. def _persist_prompt_summary(self, icon: str, label: str, detail: str, outcome: str) -> None:
  930. """Print a one-line scrollback summary of a resolved modal prompt (approval/clarify
  931. panels vanish on repaint); gated by ``display.persist_prompts``."""
  932. from cli import CLI_CONFIG, _DIM, _RST, _cprint
  933. if not CLI_CONFIG.get("display", {}).get("persist_prompts", True):
  934. return
  935. detail, outcome = (_squash(s) for s in (detail, outcome))
  936. _cprint(f"\n{_DIM}{t('cli.session.persist_prompt_summary', icon=icon, label=label, detail=detail, outcome=outcome)}{_RST}")
  937. def _clear_terminal_on_exit(self):
  938. """Clear screen + scrollback (``ESC[3J ESC[2J ESC[H``) so nothing is stranded above
  939. the exit summary. Only safe after ``app.run()`` returned and prompt_toolkit restored
  940. terminal modes. Skips when stdout isn't a console; falls back to ``clear``/``cls``."""
  941. try:
  942. stream = sys.stdout
  943. if stream is None or not stream.isatty():
  944. return
  945. except Exception:
  946. return
  947. try:
  948. stream.write("\033[3J\033[2J\033[H")
  949. stream.flush()
  950. except Exception:
  951. # Fallback for terminals that reject the escape sequence. Never os.system():
  952. # it spawns a cmd.exe/shell window that flashes on Windows (#116904) and a
  953. # minimal container without `clear` on PATH just no-ops through the shell.
  954. try:
  955. import subprocess
  956. from hermes_cli._subprocess_compat import windows_hide_flags
  957. if os.name == "nt":
  958. argv = ["cmd", "/c", "cls"] # `cls` is a cmd builtin, not an exe
  959. else:
  960. clear_bin = shutil.which("clear")
  961. argv = [clear_bin] if clear_bin else []
  962. if argv:
  963. subprocess.run(
  964. argv,
  965. stdin=subprocess.DEVNULL,
  966. creationflags=windows_hide_flags(),
  967. check=False,
  968. )
  969. except Exception:
  970. pass
  971. def _persist_active_session_before_close(self):
  972. """Best-effort flush of the agent's live ``_session_messages`` before ``end_session()``
  973. — a terminal close/SIGHUP can unwind the app while the agent thread still holds the
  974. current turn only in memory."""
  975. from cli import logger
  976. agent = getattr(self, "agent", None)
  977. if not agent or not hasattr(agent, "_persist_session"):
  978. return
  979. persist_lock = getattr(agent, "_session_persist_lock", None)
  980. def _snapshot_and_persist() -> None:
  981. # Must share the staging lock with ``chat()``: otherwise close can retain a
  982. # history baseline just before chat appends its pending dict, and the later flush
  983. # stamps that dict durable without writing a row.
  984. messages = getattr(agent, "_session_messages", None)
  985. pending_cli_message = getattr(agent, "_pending_cli_user_message", None)
  986. if not isinstance(messages, list):
  987. messages = getattr(self, "conversation_history", None)
  988. if not isinstance(messages, list):
  989. return
  990. if isinstance(pending_cli_message, dict) and not any(
  991. m is pending_cli_message for m in messages):
  992. # The UI accepted a new input but the worker still exposes its prior snapshot.
  993. messages = [*messages, pending_cli_message]
  994. if not messages:
  995. return
  996. # Baseline: the CLI history a normal turn built its new list from, so a signal
  997. # between assigning ``_session_messages`` and the DB flush cannot append the
  998. # durable prefix twice. When both names alias the same live list, marker-only
  999. # persistence would mark an unflushed tail durable — pass None instead.
  1000. conversation_history = getattr(self, "conversation_history", None)
  1001. if (
  1002. isinstance(conversation_history, list)
  1003. and conversation_history
  1004. and conversation_history[-1] is pending_cli_message):
  1005. # Accepted but not yet durable: exclude it from the resumed-history baseline.
  1006. conversation_history = conversation_history[:-1]
  1007. elif not isinstance(conversation_history, list) or conversation_history is messages:
  1008. conversation_history = None
  1009. # A first-turn close can precede the cached prompt; build it so the durable
  1010. # transcript never gets a NULL system_prompt cache entry.
  1011. if getattr(agent, "_cached_system_prompt", None) is None:
  1012. try:
  1013. from agent.conversation_loop import _restore_or_build_system_prompt
  1014. _restore_or_build_system_prompt(agent, None, conversation_history)
  1015. except Exception:
  1016. logger.debug("Could not build system prompt during CLI close", exc_info=True)
  1017. return
  1018. if getattr(agent, "_cached_system_prompt", None) is None:
  1019. return
  1020. agent._ensure_db_session()
  1021. agent._persist_session(messages, conversation_history)
  1022. if getattr(agent, "session_id", None):
  1023. self.session_id = agent.session_id
  1024. self._write_terminal_breadcrumb()
  1025. try:
  1026. # Create the DB session row now that _cached_system_prompt is populated, so the persisted
  1027. # snapshot is written non-NULL on the first turn (Issue #45499). Idempotent:
  1028. # _ensure_db_session() no-ops once the row exists. Must run BEFORE preflight compression:
  1029. # in-place compaction inserts message rows referencing this session (archive_and_compact), and
  1030. # rotation creates a child with parent_session_id pointing at it — with PRAGMA foreign_keys=ON,
  1031. # a missing parent row fails both INSERTs on a fresh oversized first turn. The user-turn crash
  1032. # persist itself runs LATER (after memory prefetch / pre_llm_call), so the row is written once
  1033. # with its final api_content — both steps take the same per-agent persist lock as CLI close
  1034. # persistence.
  1035. if persist_lock is None:
  1036. _snapshot_and_persist()
  1037. else:
  1038. with persist_lock:
  1039. _snapshot_and_persist()
  1040. except (Exception, KeyboardInterrupt) as e:
  1041. logger.debug("Could not persist active CLI session before close: %s", e)
  1042. def _print_exit_summary(self, clear_screen: bool = True):
  1043. """Print session resume info on exit. ``clear_screen`` (interactive TUI teardown)
  1044. wipes screen + scrollback first; single-query mode passes False to keep the answer.
  1045. Args: clear_screen: When True (default), clear the terminal screen and scrollback before printing
  1046. the summary. See #38252, #53009.
  1047. """
  1048. from cli import datetime
  1049. if clear_screen:
  1050. # Clear the screen + scrollback before printing the summary so the live bottom chrome (status
  1051. # bar, input box, separator rules) and the rest of the session transcript don't get stranded
  1052. # above the exit summary (#38252). By this point app.run() has returned and prompt_toolkit has
  1053. # restored terminal modes, so writing raw escapes to stdout is safe. ESC[3J clears scrollback,
  1054. # ESC[2J clears the visible screen, ESC[H homes the cursor — so the summary prints at a clean
  1055. # top-left. Falls back to the platform clear command if stdout isn't a TTY-capable stream.
  1056. # Honors NO_COLOR/dumb terminals by skipping silently when there's no real console.
  1057. self._clear_terminal_on_exit()
  1058. print()
  1059. import cli as _cli_module
  1060. # Plugin on_session_finalize messages from _run_cleanup: printed after the clear so they survive.
  1061. for message in _cli_module._session_end_messages:
  1062. print(message)
  1063. _cli_module._session_end_messages.clear()
  1064. msg_count = len(self.conversation_history)
  1065. if not msg_count:
  1066. try:
  1067. from hermes_cli.skin_engine import get_active_goodbye
  1068. goodbye = get_active_goodbye(t("cli.session.goodbye"))
  1069. except Exception:
  1070. goodbye = t("cli.session.goodbye")
  1071. print(goodbye)
  1072. return
  1073. user_msgs = len([m for m in self.conversation_history if m.get("role") == "user"])
  1074. tool_calls = len([
  1075. m for m in self.conversation_history if m.get("role") == "tool" or m.get("tool_calls")])
  1076. elapsed = datetime.now() - self.session_start
  1077. hours, remainder = divmod(int(elapsed.total_seconds()), 3600)
  1078. minutes, seconds = divmod(remainder, 60)
  1079. duration_str = t("cli.shared.duration_s", seconds=seconds)
  1080. if hours > 0:
  1081. duration_str = t("cli.shared.duration_hm_rest", hours=hours, minutes=minutes, rest=duration_str)
  1082. elif minutes > 0:
  1083. duration_str = t("cli.shared.duration_m_rest", minutes=minutes, rest=duration_str)
  1084. session_title = None
  1085. if self._session_db:
  1086. with contextlib.suppress(Exception):
  1087. session_title = self._session_db.get_session_title(self.session_id)
  1088. print(t("cli.session.exit_resume_hint"))
  1089. # Session IDs are profile-constrained: non-default profiles need `-p <profile>` in
  1090. # the hint ("default"/"custom" use the standard HERMES_HOME).
  1091. try:
  1092. from hermes_cli.profiles import get_active_profile_name
  1093. _active_profile = get_active_profile_name()
  1094. except Exception:
  1095. _active_profile = "default"
  1096. profile_flag = "" if _active_profile in ("default", "custom") else f" -p {_active_profile}"
  1097. print(f" hermes --resume {self.session_id}{profile_flag}")
  1098. if session_title:
  1099. print(f" hermes -c \"{session_title}\"{profile_flag}")
  1100. print()
  1101. print(t("cli.session.exit_label_session", session_id=self.session_id))
  1102. if session_title:
  1103. print(t("cli.session.exit_label_title", title=session_title))
  1104. print(t("cli.session.exit_label_duration", duration=duration_str))
  1105. print(t("cli.session.exit_label_messages", count=msg_count, user=user_msgs, tool_calls=tool_calls))