cli_agent_setup_mixin.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. """Agent construction + session-resume display for ``HermesCLI``: credential resolution,
  2. per-turn agent config, first-use build, resume preload + recap. ``cli.py`` helpers are
  3. imported lazily inside each method (import cycle)."""
  4. from __future__ import annotations
  5. import sys
  6. from rich.markup import escape as _escape
  7. from agent.i18n import t
  8. from utils import base_url_host_matches
  9. def _single_query_clarify_callback(questions: list) -> dict:
  10. """Headless clarify answer for ``hermes chat -q``.
  11. A -q turn never builds the prompt_toolkit app, so the interactive clarify modal
  12. can never be painted or answered — the CLI callback would poll until
  13. ``agent.clarify_timeout`` while the caller sees a silent hang. Mirror the oneshot
  14. path and answer immediately instead.
  15. The oneshot path answers immediately via ``_oneshot_clarify_callback``; single-query turns need the same
  16. headless behavior (#94943).
  17. """
  18. return {"answers": {}, "outcome": "undelivered", "notice": (
  19. "single-query mode: no user available to answer. Pick the best choices using your own "
  20. "judgment, or make the most reasonable assumption you can, and continue.")}
  21. def _current_runtime(cli) -> dict:
  22. """Snapshot the CLI's resolved provider routing as an AIAgent runtime dict.
  23. getattr guards stay: tests build minimal shells lacking these attributes."""
  24. return {
  25. "api_key": cli.api_key,
  26. "base_url": cli.base_url,
  27. "provider": cli.provider,
  28. "requested_provider": getattr(cli, "requested_provider", cli.provider),
  29. "api_mode": cli.api_mode,
  30. "command": cli.acp_command,
  31. "args": list(cli.acp_args or []),
  32. "credential_pool": getattr(cli, "_credential_pool", None)}
  33. def _route_signature(model, runtime: dict) -> tuple:
  34. """Hashable identity of (model, routing) used to detect when the agent must be rebuilt."""
  35. return (
  36. model, runtime.get("provider"), runtime.get("requested_provider"), runtime.get("base_url"),
  37. runtime.get("api_mode"), runtime.get("command"), tuple(runtime.get("args") or ()))
  38. def _cooldown_cause(entry) -> str:
  39. """Why a benched (exhausted) row is cooling down, from what the pool recorded: a rate-limit or
  40. quota response, a failed token refresh, or another HTTP failure."""
  41. reason = (entry.last_error_reason or "").lower()
  42. if entry.last_error_code in (402, 429) or any(k in reason for k in ("rate", "quota", "insufficient")):
  43. return t("cli.startup.cooldown_cause_rate_limit")
  44. if entry.last_error_code is None or "refresh" in reason:
  45. return t("cli.startup.cooldown_cause_token_refresh")
  46. return t("cli.startup.cooldown_cause_http", code=entry.last_error_code)
  47. def _credential_pool_notice(provider: str) -> tuple:
  48. """``(cooling, lines)`` on why *provider*'s pool has nothing selectable right now, for the
  49. startup notice. *cooling* is True when the first line is a live cooldown with its remaining
  50. time; a dead (quarantined) sign-in adds a line naming the re-login."""
  51. import time
  52. from agent.credential_pool import STATUS_DEAD, STATUS_EXHAUSTED, load_pool
  53. try:
  54. pool = load_pool(provider)
  55. if not pool.has_credentials() or pool.has_available():
  56. return False, []
  57. next_at = pool.next_available_at()
  58. entries = pool.entries()
  59. except Exception:
  60. return False, []
  61. lines = []
  62. if next_at is not None:
  63. minutes = max(1, int((next_at - time.time() + 59) // 60))
  64. benched = [e for e in entries if e.last_status == STATUS_EXHAUSTED]
  65. cause = _cooldown_cause(benched[0]) if benched else t("cli.startup.cooldown_cause_failed_request")
  66. lines.append(t("cli.startup.credential_cooling_down", provider=provider, cause=cause, minutes=minutes))
  67. dead = [e for e in entries if e.last_status == STATUS_DEAD]
  68. if dead:
  69. reason = dead[0].last_error_message or dead[0].last_error_reason or t("cli.startup.sign_in_lost")
  70. lines.append(t("cli.startup.sign_in_was_lost", provider=provider, reason=reason))
  71. return next_at is not None, lines
  72. def _resume_counts(user_count: int, total: int) -> str:
  73. """``(N user message(s), M total messages)`` suffix of the resumed-session line."""
  74. key = "cli.resume.counts_one" if user_count == 1 else "cli.resume.counts_other"
  75. return t(key, count=user_count, total=total)
  76. def _keyless_custom_base(base_url) -> bool:
  77. """Custom/local endpoints (llama.cpp, ollama, vLLM) often need no auth; only a
  78. non-OpenRouter base_url qualifies."""
  79. return bool(
  80. isinstance(base_url, str)
  81. and base_url
  82. and not base_url_host_matches(base_url, "openrouter.ai"))
  83. def _compression_descendant(session_db, session_id):
  84. """If ``session_id`` is the (empty) head of a compression chain, return the
  85. descendant that actually holds the messages; else None. Fails open on DB errors."""
  86. try:
  87. resolved_id = session_db.resolve_resume_session_id(session_id)
  88. except Exception:
  89. return None
  90. return resolved_id if resolved_id and resolved_id != session_id else None
  91. def _gateway_owned_id(session_db, session_id):
  92. """The id the gateway answers for physical row *session_id*: ``session.resume``'s
  93. ``stored_session_id``. A canonical local compression segment holds the transcript, but its creation
  94. receipt lives on the conversation's logical owner, which every turn and mutation must name (as Ink
  95. and ``session.resume`` do). Unchanged off the gateway store or when the resume is refused."""
  96. return _gateway_open(session_db, session_id)[0]
  97. def _gateway_open(session_db, session_id):
  98. """``(owner_id, refusal)`` from one ``session.resume`` of *session_id* on this viewer: the attach
  99. subscribes it and names its receipt owner (:func:`_gateway_owned_id`). ``refusal`` is the reason
  100. code when the owner answered that this viewer may not open it (``RESUME_GONE``), else ``None``:
  101. off the gateway store, a transient refusal, or no answer, the caller proceeds on its local reads."""
  102. from hermes_cli.gateway_client import GatewayRPCError
  103. from hermes_cli.gateway_connection import RESUME_GONE
  104. from hermes_cli.gateway_session_store import GatewaySessionStore
  105. if not isinstance(session_db, GatewaySessionStore):
  106. return session_id, None
  107. try:
  108. return session_db.attach(session_id).get("stored_session_id") or session_id, None
  109. except GatewayRPCError as exc:
  110. return session_id, (str(exc) if str(exc) in RESUME_GONE else None)
  111. except Exception: # health: allow BLE001 -- no answer: the turn reports the lost connection itself
  112. return session_id, None
  113. def _user_display_text(content) -> str:
  114. """Recap text for a user row; multimodal lists become text parts + ``[image]`` markers."""
  115. if isinstance(content, list):
  116. return " ".join(
  117. part.get("text", "") if part.get("type") == "text" else "[image]"
  118. for part in content
  119. if isinstance(part, dict) and part.get("type") in ("text", "image_url"))
  120. return "" if content is None else str(content)
  121. def _tool_calls_summary(tool_calls) -> str:
  122. """``[N tool call(s): name, ...]`` with up to 4 distinct names."""
  123. names = []
  124. for tc in tool_calls:
  125. fn = tc.get("function", {})
  126. name = fn.get("name", "unknown") if isinstance(fn, dict) else "unknown"
  127. if name not in names:
  128. names.append(name)
  129. names_str = ", ".join(names[:4]) + (", ..." if len(names) > 4 else "")
  130. key = "cli.resume.tool_calls_one" if len(tool_calls) == 1 else "cli.resume.tool_calls_other"
  131. return t(key, count=len(tool_calls), names=names_str)
  132. # display_kind -> catalog key of the recap event line (resolved at call time); ``hidden`` rows
  133. # are skipped before this lookup.
  134. _RESUME_EVENT_KEYS = {
  135. "model_switch": "cli.resume.event_model_changed",
  136. "async_delegation_complete": "cli.resume.event_delegation_completed",
  137. "process_complete": "cli.resume.event_process_finished",
  138. "auto_continue": "cli.resume.event_resumed_interrupted"}
  139. def _collect_resume_entries(display_history, disp: dict, clean_assistant):
  140. """Displayable ``(role, text)`` recap entries from stored history, truncated per the
  141. ``display.resume_*`` config; system and tool-result rows are skipped. Returns
  142. ``(entries, index of last assistant entry, its un-truncated text)``.
  143. Stored history is untrusted for display: text is sanitized so replay can't clear the
  144. screen, retitle the window or restyle the panel. Pure-reasoning assistant rows with no
  145. visible output are skipped, as are tool-call-only rows when ``resume_skip_tool_only``.
  146. """
  147. from agent.message_metadata import withheld_prompt_text
  148. from tools.ansi_strip import sanitize_display_text as _sanitize_display_text
  149. max_user_len = int(disp.get("resume_max_user_chars", 300))
  150. max_asst_len = int(disp.get("resume_max_assistant_chars", 200))
  151. max_asst_lines = int(disp.get("resume_max_assistant_lines", 3))
  152. skip_tool_only = disp.get("resume_skip_tool_only", True)
  153. entries: list = []
  154. last_asst_idx = None
  155. last_asst_full = None
  156. for msg in display_history:
  157. role = msg.get("role", "")
  158. display_kind = msg.get("display_kind")
  159. content = msg.get("content")
  160. tool_calls = msg.get("tool_calls") or []
  161. if display_kind == "hidden":
  162. continue
  163. if display_kind in _RESUME_EVENT_KEYS:
  164. metadata = msg.get("display_metadata") or {}
  165. label = metadata.get("display_text") if display_kind in ("async_delegation_complete", "process_complete") else None
  166. entries.append(("event", _sanitize_display_text(label or t(_RESUME_EVENT_KEYS[display_kind]))))
  167. continue
  168. if role == "user":
  169. text = _sanitize_display_text(withheld_prompt_text(msg) or _user_display_text(content))
  170. if len(text) > max_user_len:
  171. text = text[:max_user_len] + "..."
  172. entries.append(("user", text))
  173. elif role == "assistant":
  174. text = clean_assistant("" if content is None else str(content))
  175. parts, full_parts = [], []
  176. if text:
  177. full_parts.append(text)
  178. lines = text.splitlines()
  179. if len(lines) > max_asst_lines:
  180. text = "\n".join(lines[:max_asst_lines]) + " ..."
  181. if len(text) > max_asst_len:
  182. text = text[:max_asst_len] + "..."
  183. parts.append(text)
  184. if tool_calls:
  185. parts.append(_tool_calls_summary(tool_calls))
  186. full_parts.append(parts[-1])
  187. if not text and (skip_tool_only or not tool_calls):
  188. continue
  189. entries.append(("assistant", " ".join(parts)))
  190. last_asst_idx = len(entries) - 1
  191. last_asst_full = " ".join(full_parts)
  192. return entries, last_asst_idx, last_asst_full
  193. # (skin key, fallback) for recap panel colors: body text, session label, border, assistant label.
  194. _RESUME_SKIN_COLORS = (
  195. ("banner_text", "#FFF8DC"), ("session_label", "#DAA520"), ("session_border", "#8B8682"),
  196. ("ui_ok", "#8FBC8F"))
  197. def _resume_panel_colors() -> tuple:
  198. """Active-skin colors for ``_RESUME_SKIN_COLORS`` (fallbacks when no skin loads)."""
  199. try:
  200. from hermes_cli.skin_engine import get_active_skin
  201. _skin = get_active_skin()
  202. return tuple(_skin.get_color(key, default) for key, default in _RESUME_SKIN_COLORS)
  203. except Exception:
  204. return tuple(default for _, default in _RESUME_SKIN_COLORS)
  205. def _retire_agent(cli) -> None:
  206. """Drop ``cli.agent`` so the next turn rebuilds it, releasing its LLM clients first: the Codex
  207. app-server child (and MCP descendants) belongs to the instance, so ``self.agent = None`` alone
  208. orphans it for the CLI process lifetime (#72548). Session tool state is kept (soft release)."""
  209. agent = cli.agent
  210. if agent is not None and hasattr(agent, "release_clients"):
  211. agent.release_clients()
  212. cli.agent = None
  213. class CLIAgentSetupMixin:
  214. """Agent construction + session-resume display methods for ``HermesCLI``."""
  215. def _ensure_runtime_credentials(self) -> bool:
  216. """Re-resolve provider credentials before agent use so key rotation / token
  217. refresh are picked up without restarting the CLI. False on auth failure."""
  218. from cli import ChatConsole, logger
  219. from hermes_cli.runtime_provider import (
  220. deferred_token_mint, format_runtime_provider_error, resolve_runtime_provider)
  221. _primary_exc = None
  222. runtime = None
  223. _model_at_entry = self.model
  224. self._credentials_rate_limited = False
  225. self._credentials_terminal = False
  226. # The gateway session runs the turn and mints its own short-lived OAuth token (Vertex); this
  227. # process only routes, so it must not run a second JWT exchange per launch.
  228. with deferred_token_mint():
  229. try:
  230. # target_model: the ladder's model-keyed rungs (Zen/Go api_mode, per-model
  231. # api_mode) must see the model this CLI will actually send, not config's `default`,
  232. # or `hermes -m mimo-v2.5 --provider opencode-go` resolves an api_mode/base_url the
  233. # sent model cannot use (#112600).
  234. runtime = resolve_runtime_provider(
  235. requested=self.requested_provider, explicit_api_key=self._explicit_api_key,
  236. explicit_base_url=self._explicit_base_url, target_model=self.model or None)
  237. except Exception as exc:
  238. _primary_exc = exc
  239. if _primary_exc is not None:
  240. runtime = self._resolve_fallback_runtime(_primary_exc)
  241. if runtime is not None:
  242. _primary_exc = None
  243. if runtime is None:
  244. from hermes_cli.auth import AuthError, is_rate_limited_auth_error
  245. self._credentials_rate_limited = bool(_primary_exc) and is_rate_limited_auth_error(_primary_exc)
  246. # Only an explicit re-authentication requirement is terminal. Unknown
  247. # resolver/network failures must not acquire the sticky Kanban block.
  248. self._credentials_terminal = isinstance(_primary_exc, AuthError) and _primary_exc.relogin_required
  249. message = format_runtime_provider_error(_primary_exc) if _primary_exc else t("cli.startup.provider_resolution_failed")
  250. if getattr(self, "tool_progress_mode", "full") == "off":
  251. print(message, file=sys.stderr) # quiet/stream-json: stdout is machine-readable
  252. else:
  253. ChatConsole().print(f"[bold red]{message}[/]")
  254. return False
  255. api_key = runtime.get("api_key")
  256. base_url = runtime.get("base_url")
  257. resolved_provider = runtime.get("provider", "openrouter")
  258. resolved_routing = (
  259. resolved_provider, runtime.get("api_mode", self.api_mode), runtime.get("command"),
  260. list(runtime.get("args") or []))
  261. # A callable api_key is a bearer-token provider (Azure Entra ID): the OpenAI SDK
  262. # invokes it per request, so skip string validation / placeholder substitution.
  263. if not callable(api_key) and not (isinstance(api_key, str) and api_key):
  264. if _keyless_custom_base(base_url):
  265. # Placeholder key so the SDK doesn't reject the keyless local endpoint.
  266. api_key = "no-key-required"
  267. logger.debug(
  268. "No API key for custom endpoint %s (source=%s), "
  269. "using placeholder — local servers typically ignore auth",
  270. base_url, runtime.get("source", ""))
  271. else:
  272. _prov = (resolved_provider or self.requested_provider or "").strip()
  273. if _prov and _prov != "auto":
  274. print(f"\n{t('cli.startup.no_api_key_for_provider', provider=_prov)}")
  275. else:
  276. print(f"\n{t('cli.startup.no_provider_configured')}")
  277. print(f" {t('cli.startup.run_model_or_setup')}")
  278. return False
  279. if not isinstance(base_url, str) or not base_url:
  280. print(f"\n{t('cli.startup.empty_base_url')}")
  281. return False
  282. credentials_changed = api_key != self.api_key or base_url != self.base_url
  283. routing_changed = resolved_routing != (self.provider, self.api_mode, self.acp_command, self.acp_args)
  284. self.provider, self.api_mode, self.acp_command, self.acp_args = resolved_routing
  285. self._credential_pool = runtime.get("credential_pool")
  286. self._provider_source = runtime.get("source")
  287. self.api_key = api_key
  288. self.base_url = base_url
  289. # A custom_provider entry's explicit `model` wins when the CLI model is unset or
  290. # is just the provider slug/display name (`hermes chat --model <provider-name>`
  291. # would otherwise send the provider name as the model string -> 400).
  292. runtime_model = runtime.get("model")
  293. if runtime_model and isinstance(runtime_model, str) and (
  294. not self.model or self.model == self.provider or self.model == runtime.get("name")):
  295. self.model = runtime_model
  296. # Still empty (e.g. `hermes auth add` without `hermes model`): fall back to the
  297. # provider's first catalog model so the API doesn't reject an empty model.
  298. if not self.model and resolved_provider:
  299. try:
  300. from hermes_cli.models import get_default_model_for_provider
  301. _default = get_default_model_for_provider(resolved_provider)
  302. if _default:
  303. self.model = _default
  304. logger.info(
  305. "No model configured — defaulting to %s for provider %s",
  306. _default, resolved_provider)
  307. except Exception:
  308. pass
  309. # Normalize model for the resolved provider (e.g. swap non-Codex models on openai-codex).
  310. # Fixes #651.
  311. model_changed = self._normalize_model_for_provider(resolved_provider)
  312. # Startup resolved reasoning_config for the launch model; whichever path above moved
  313. # self.model (auth fallback, custom-entry model, provider default, normalization) leaves a
  314. # per-model contract the lazily built agent would otherwise miss (an always-thinking model
  315. # 400s on the primary's effort). Same chokepoint as /model, /new and --resume; an explicit
  316. # --reasoning is the user's intent for this run and outranks the new model's config.
  317. if self.model != _model_at_entry and getattr(self, "_explicit_reasoning_config", None) is None:
  318. from hermes_cli.cli_model_switch_mixin import _resolve_cli_reasoning
  319. _resolve_cli_reasoning(self)
  320. logger.info("Model moved to %s: reasoning_config resolved: %s", self.model, self.reasoning_config)
  321. # AIAgent/OpenAI client holds auth at init, so rebuild on key/routing/model change.
  322. if (credentials_changed or routing_changed or model_changed) and self.agent is not None:
  323. _retire_agent(self)
  324. self._active_agent_route_signature = None
  325. return True
  326. def _resolve_fallback_runtime(self, primary_exc):
  327. """Primary provider resolution failed: on an AuthError try each fallback entry in
  328. order and switch the CLI's requested_provider/model to the first that resolves.
  329. None when the error is not auth-related or no fallback resolves."""
  330. from cli import _cprint, logger
  331. from hermes_cli.auth import AuthError, primary_failure_wording
  332. from hermes_cli.runtime_provider import resolve_runtime_provider
  333. if not isinstance(primary_exc, AuthError):
  334. return None
  335. _fb_chain = self._fallback_model if isinstance(self._fallback_model, list) else []
  336. for _fb in _fb_chain:
  337. _fb_provider = (_fb.get("provider") or "").strip().lower()
  338. _fb_model = (_fb.get("model") or "").strip()
  339. if not _fb_provider or not _fb_model:
  340. continue
  341. try:
  342. from hermes_cli.fallback_config import resolve_entry_api_key
  343. # target_model: the fallback entry names the model that will be sent; without it the
  344. # ladder keys off config `default` (see _ensure_runtime_credentials, #112600).
  345. _fb_kwargs = {"requested": _fb_provider, "target_model": _fb_model}
  346. if _fb.get("base_url"):
  347. _fb_kwargs["explicit_base_url"] = _fb["base_url"]
  348. _fb_api_key = resolve_entry_api_key(_fb)
  349. if _fb_api_key:
  350. _fb_kwargs["explicit_api_key"] = _fb_api_key
  351. runtime = resolve_runtime_provider(**_fb_kwargs)
  352. _why_log, _why = primary_failure_wording(primary_exc) # #117482: quota is not auth
  353. logger.warning(
  354. "Primary provider %s (%s). Falling through to fallback: %s/%s",
  355. _why_log, primary_exc, _fb_provider, _fb_model)
  356. from gateway.warning_notifications import render_notification
  357. render_notification(
  358. lambda: _cprint(t("cli.startup.switching_to_fallback", reason=_why, provider=_fb_provider, model=_fb_model)),
  359. platform="cli")
  360. self.requested_provider = _fb_provider
  361. self.model = _fb_model
  362. # reasoning_config follows the swap in _ensure_runtime_credentials (the only caller).
  363. return runtime
  364. except Exception:
  365. continue
  366. return None
  367. def _runtime_credentials_ready(self) -> bool:
  368. """Silently probe whether any inference provider can be resolved.
  369. Never prints or mutates CLI state, so the interactive first-run path can route a
  370. keyless install into onboarding before the user types into a chat that can't work.
  371. See #62935.
  372. """
  373. return self._probe_runtime_credentials()[0]
  374. def _probe_runtime_credentials(self) -> tuple:
  375. """``(ready, error)``: *error* is the exception that stopped resolution — raised, or
  376. swallowed by the "auto" ladder and stamped on a keyless fallback — ``None`` when a provider
  377. resolved (usable or merely keyless). Never prints or mutates CLI state."""
  378. from hermes_cli.runtime_provider import deferred_token_mint, resolve_runtime_provider
  379. try:
  380. with deferred_token_mint(): # a readiness probe never needs a live token
  381. runtime = resolve_runtime_provider(
  382. requested=self.requested_provider, explicit_api_key=self._explicit_api_key,
  383. explicit_base_url=self._explicit_base_url)
  384. except Exception as exc:
  385. return False, exc
  386. if not isinstance(runtime, dict):
  387. return False, None
  388. api_key = runtime.get("api_key")
  389. base_url = runtime.get("base_url")
  390. if callable(api_key) or (isinstance(api_key, str) and api_key):
  391. return bool(base_url), None
  392. return _keyless_custom_base(base_url), runtime.get("auth_error")
  393. def _maybe_offer_first_run_setup(self) -> None:
  394. """Interactive startup gate: a blank install goes to the provider wizard; a configured
  395. profile whose credential is benched or signed out gets the reason instead (#113720)."""
  396. if not sys.stdin.isatty():
  397. return
  398. ready, error = self._probe_runtime_credentials()
  399. if not ready and not self._explain_unusable_credentials(error):
  400. self._offer_first_run_setup()
  401. def _explain_unusable_credentials(self, error) -> bool:
  402. """A configured profile whose credential is benched, quarantined or signed out is not a
  403. blank install: print what is wrong (and the remaining cooldown) instead of the first-run
  404. wizard, whose "nothing is configured" claim sends operators into a second login that can
  405. rotate a single-use OAuth grant away from the session that was working (#113720).
  406. True when the failure was explained; False when nothing is configured (the wizard's case).
  407. """
  408. from cli import _cprint
  409. from hermes_cli.auth import format_auth_error
  410. if error is None or getattr(error, "code", None) == "no_provider_configured":
  411. return False
  412. provider = getattr(error, "provider", None) or self.requested_provider
  413. cooling, lines = _credential_pool_notice(provider) if provider and provider != "auto" else (False, [])
  414. _cprint("")
  415. if cooling:
  416. # A live cooldown is a wait, not a lost login: lead with it and skip the re-auth hint.
  417. _cprint(f"⚠️ {_escape(lines.pop(0))}")
  418. _cprint(f" {_escape(str(error))}")
  419. else:
  420. _cprint(f"⚠️ {_escape(format_auth_error(error))}")
  421. for line in lines:
  422. _cprint(f" {_escape(line)}")
  423. return True
  424. def _offer_first_run_setup(self) -> bool:
  425. """Offer the provider picker when no provider is configured at all (interactive
  426. startup, TTY). Runs the same flow as ``hermes model`` so onboarding has a single
  427. source of truth. True when a provider was configured."""
  428. from cli import _cprint, logger
  429. _cprint("")
  430. _cprint(t("cli.startup.first_run_no_provider"))
  431. _cprint(f" {t('cli.startup.first_run_pick_provider')}")
  432. try:
  433. answer = input(f" {t('cli.startup.first_run_prompt')} ").strip().lower()
  434. except (KeyboardInterrupt, EOFError):
  435. print()
  436. answer = "n"
  437. if answer in {"n", "no"}:
  438. _cprint(f" {t('cli.startup.first_run_skipped')}")
  439. return False
  440. try:
  441. from hermes_cli.main import select_provider_and_model
  442. from hermes_cli.observability.shared_metrics_setup import provider_setup_surface
  443. with provider_setup_surface("cli_setup"):
  444. select_provider_and_model()
  445. except (KeyboardInterrupt, EOFError, SystemExit):
  446. print()
  447. _cprint(f" {t('cli.startup.first_run_cancelled')}")
  448. return False
  449. except Exception as exc:
  450. logger.debug("first-run provider setup failed: %s", exc)
  451. _cprint(f" {t('cli.startup.provider_setup_failed', error=exc)}")
  452. _cprint(f" {t('cli.startup.run_model_to_retry')}")
  453. return False
  454. # Re-sync CLI state from what the picker persisted so the next turn uses it without a restart.
  455. try:
  456. from hermes_cli.config import load_config
  457. _model_cfg = (load_config().get("model") or {})
  458. if isinstance(_model_cfg, dict):
  459. self.requested_provider = (_model_cfg.get("provider") or "").strip() or self.requested_provider
  460. _new_model = (_model_cfg.get("default") or _model_cfg.get("model") or "").strip()
  461. self.model = _new_model or self.model
  462. # The picker's model has its own per-model reasoning contract (see
  463. # _resolve_cli_reasoning); an explicit --reasoning stays the user's intent.
  464. if _new_model and getattr(self, "_explicit_reasoning_config", None) is None:
  465. from hermes_cli.cli_model_switch_mixin import _resolve_cli_reasoning
  466. _resolve_cli_reasoning(self)
  467. except Exception as exc:
  468. logger.debug("first-run config re-sync failed: %s", exc)
  469. # Force credential re-resolution + agent rebuild on next use.
  470. _retire_agent(self)
  471. self._active_agent_route_signature = None
  472. if self._runtime_credentials_ready():
  473. _cprint(f" {t('cli.startup.provider_configured')}")
  474. return True
  475. _cprint(f" {t('cli.startup.provider_setup_incomplete')}")
  476. return False
  477. def _resolve_turn_agent_config(self, user_message: str) -> dict:
  478. """Effective model/runtime config for one turn — always the session's primary
  479. provider. With a static `/fast` tier (fast / ultrafast) attach request_overrides;
  480. auto/cold tiers are applied per request by agent.fast_mode instead."""
  481. from agent.fast_mode import STATIC_TIERS
  482. from hermes_cli.models import resolve_fast_mode_overrides
  483. runtime = _current_runtime(self)
  484. route = {"model": self.model, "runtime": runtime, "signature": _route_signature(self.model, runtime)}
  485. overrides = None
  486. tier = getattr(self, "service_tier", None)
  487. if tier in STATIC_TIERS:
  488. try:
  489. overrides = resolve_fast_mode_overrides(
  490. route["model"], provider=runtime["provider"], base_url=runtime["base_url"], tier=tier)
  491. except Exception:
  492. pass
  493. route["request_overrides"] = overrides
  494. return route
  495. def _follow_compression_chain(self, session_meta, announce):
  496. """If the resumed id is an empty compression-chain head, announce and switch to
  497. the descendant holding the messages; returns the (possibly refreshed) meta."""
  498. self._resume_read_id = self.session_id
  499. resolved_id = _compression_descendant(self._session_db, self.session_id)
  500. if resolved_id:
  501. session_meta = self._session_db.get_session(resolved_id) or session_meta
  502. self._resume_read_id = resolved_id
  503. owner = _gateway_owned_id(self._session_db, resolved_id)
  504. if owner != resolved_id:
  505. # The transcript is read from the tip segment; the session stays addressed by the
  506. # id the gateway holds its receipt for (a segment id is refused storage_unavailable).
  507. self.session_id = owner
  508. else:
  509. announce(resolved_id)
  510. self.session_id = resolved_id
  511. return session_meta
  512. def _restore_session_state(self, session_meta, *, quiet: bool = False) -> None:
  513. """Restore cwd / yolo / model from the resumed session's metadata."""
  514. self._restore_session_cwd(session_meta, quiet=quiet)
  515. self._restore_session_yolo(session_meta, quiet=quiet)
  516. self._restore_session_model(session_meta, quiet=quiet)
  517. def _reopen_session(self) -> None:
  518. """Clear ended_at so the resumed session is active again (best effort)."""
  519. try:
  520. self._session_db.reopen_session(self.session_id)
  521. except Exception:
  522. pass
  523. def _load_resumed_history_late(self) -> bool:
  524. """Late resume path: validate the session and load its history from the DB when
  525. _preload_resumed_session() (called from run()) did not already populate it.
  526. False when the resume must abort (missing session / over the safe-resume limit)."""
  527. from cli import ChatConsole, _DIM, _RST, _accent_hex, _cprint
  528. session_meta = self._session_db.get_session(self.session_id)
  529. # Quiet mode (tool_progress_mode == "off") routes resume status lines to
  530. # stderr so stdout stays machine-readable for `$(hermes chat -Q --resume ...)`.
  531. # Without this, the resume banner pollutes captured stdout. See #11793.
  532. _quiet_mode = getattr(self, "tool_progress_mode", "full") == "off"
  533. def _say(plain: str, rich: str) -> None:
  534. if _quiet_mode:
  535. print(plain, file=sys.stderr)
  536. else:
  537. ChatConsole().print(rich)
  538. if not session_meta:
  539. hint = t("cli.resume.session_id_hint")
  540. not_found = t("cli.resume.session_not_found", session_id=self.session_id)
  541. if _quiet_mode:
  542. print(not_found, file=sys.stderr)
  543. print(hint, file=sys.stderr)
  544. else:
  545. _cprint(f"\033[1;31m{not_found}{_RST}")
  546. _cprint(f"{_DIM}{hint}{_RST}")
  547. return False
  548. session_meta = self._follow_compression_chain(
  549. session_meta,
  550. lambda rid: ChatConsole().print(
  551. f"[dim]{_escape(t('cli.resume.compressed_into', session_id=self.session_id, descendant=rid))}[/dim]"))
  552. if getattr(self, "_resume_history_error", None):
  553. return False
  554. # Only the TIP session's rows are loaded here (no ancestors), so use the
  555. # tip-only count — the full-lineage count would over-reject compressed sessions.
  556. resume_limit_error = self._resume_history_limit_error(tip_only=True)
  557. if resume_limit_error:
  558. self._resume_history_error = resume_limit_error
  559. _say(
  560. t("cli.resume.cannot_resume", error=resume_limit_error),
  561. f"[bold red]{_escape(t('cli.resume.cannot_resume_prefix'))}[/] {_escape(resume_limit_error)}")
  562. return False
  563. restored = self._session_db.get_messages_as_conversation(self._resume_read_id, repair_alternation=True)
  564. if restored:
  565. restored = [m for m in restored if m.get("role") != "session_meta"]
  566. self.conversation_history = restored
  567. msg_count = len([m for m in restored if m.get("role") == "user"])
  568. title_part = f" \"{session_meta['title']}\"" if session_meta.get("title") else ""
  569. counts = _resume_counts(msg_count, len(restored))
  570. _say(
  571. f"{t('cli.resume.resumed_session')} {self.session_id}{title_part} {counts}",
  572. f"[bold {_accent_hex()}]{_escape(t('cli.resume.resumed_session'))}[/] [bold]{_escape(self.session_id)}[/]"
  573. f"[bold {_accent_hex()}]{_escape(title_part)}[/] {counts}")
  574. self._restore_session_state(session_meta, quiet=_quiet_mode)
  575. else:
  576. no_messages = t("cli.resume.session_no_messages", session_id=self.session_id)
  577. _say(no_messages, f"[bold {_accent_hex()}]{_escape(no_messages)}[/]")
  578. self._reopen_session()
  579. return True
  580. def _init_agent(self, *, model_override: str | None = None, runtime_override: dict | None = None, request_overrides: dict | None = None) -> bool:
  581. """Build the agent on first use; when resuming, restore history from SQLite.
  582. Returns True on success."""
  583. from cli import ChatConsole, _cprint, logger
  584. from hermes_cli.gateway_agent import GatewayAgent as AIAgent # the gateway runs the turn
  585. if self.agent is not None:
  586. return True
  587. # Join the background preloaded-skills load (--skills/-s) BEFORE the agent
  588. # snapshots self.system_prompt below. No-op when nothing was requested.
  589. self.finalize_preloaded_skills()
  590. # No deferred plugin discovery either: the gateway that runs the turn loads the plugins (PLG-7).
  591. self._install_tool_callbacks()
  592. if not self._ensure_runtime_credentials():
  593. return False
  594. # No MCP discovery here: the gateway session that runs the turn owns its MCP servers.
  595. from hermes_cli.cli_chat_error_copy import agent_init_failure_message
  596. if self._session_db is None:
  597. try:
  598. from hermes_cli.gateway_session_store import session_store
  599. self._session_db = session_store()
  600. except Exception as e:
  601. logger.warning("SQLite session store not available — session will NOT be indexed: %s", e)
  602. try:
  603. self._ensure_gateway_session()
  604. except Exception as e: # health: allow BLE001 -- any session.create/resume failure is main's agent-init failure copy, never a traceback
  605. from hermes_cli.gateway_chat import exit_on_resume_refusal
  606. exit_on_resume_refusal(e) # -q: a changed flag on --resume is interactive startup's `Error:` + exit 2
  607. ChatConsole().print(f"[bold red]{_escape(agent_init_failure_message(e))}[/]")
  608. return False
  609. if (
  610. self._resumed and self._session_db and not self.conversation_history
  611. and not self._load_resumed_history_late()):
  612. return False
  613. try:
  614. runtime = runtime_override or _current_runtime(self)
  615. effective_model = model_override or self.model
  616. # ``/model --once`` has already staged the pick on the CLI and saved the restore
  617. # snapshot. chat retires the previous agent, so the pick has to be on this one.
  618. pending_one_turn = getattr(self, "_pending_one_turn_model_restore", None)
  619. one_turn = pending_one_turn is not None
  620. # -q never builds the prompt_toolkit app, so the clarify modal can't be
  621. # answered — answer headless instead of polling until clarify_timeout.
  622. single_query_mode = getattr(self, "_single_query_mode", False)
  623. clarify_callback = (
  624. # See #94943.
  625. _single_query_clarify_callback
  626. if single_query_mode
  627. else self._clarify_callback)
  628. connection_callback = None if single_query_mode else self._connection_callback
  629. self.agent = AIAgent(
  630. model=effective_model, api_key=runtime.get("api_key"),
  631. base_url=runtime.get("base_url"), provider=runtime.get("provider"),
  632. requested_provider=runtime.get("requested_provider"),
  633. api_mode=runtime.get("api_mode"), acp_command=runtime.get("command"),
  634. acp_args=runtime.get("args"), credential_pool=runtime.get("credential_pool"),
  635. max_iterations=self.max_turns,
  636. run_budget_seconds=getattr(self, "run_budget_seconds", None),
  637. enabled_toolsets=self.enabled_toolsets, disabled_toolsets=self.disabled_toolsets,
  638. verbose_logging=self.verbose, quiet_mode=not self.verbose,
  639. tool_progress_mode=getattr(self, "tool_progress_mode", "all"),
  640. ephemeral_system_prompt=self.system_prompt if self.system_prompt else None,
  641. prefill_messages=self.prefill_messages or None,
  642. reasoning_config=self.reasoning_config, service_tier=self.service_tier,
  643. # A --once level rides the admission; a session /reasoning is committed by the next rebuild.
  644. push_reasoning=getattr(self, "_reasoning_user_set", False) and not one_turn,
  645. request_overrides=request_overrides, providers_allowed=self._providers_only,
  646. providers_ignored=self._providers_ignore, providers_order=self._providers_order,
  647. provider_sort=self._provider_sort,
  648. provider_require_parameters=self._provider_require_params,
  649. provider_data_collection=self._provider_data_collection,
  650. openrouter_min_coding_score=self._openrouter_min_coding_score,
  651. session_id=self.session_id, platform="cli", session_db=self._session_db,
  652. clarify_callback=clarify_callback, connection_callback=connection_callback,
  653. connection_update_callback=None if single_query_mode else self._connection_on_change,
  654. # The gateway's model-guard refusal is asked like main's own guard; -q cannot answer it.
  655. model_confirm_callback=None if single_query_mode else self._confirm_owner_model_switch,
  656. # Another viewer answering the gateway's clarify/sudo/secret request closes this modal.
  657. modal_withdraw_callback=None if single_query_mode else self._withdraw_gateway_modal,
  658. one_turn=one_turn,
  659. one_turn_reasoning=(pending_one_turn or {}).get("one_turn_reasoning") if one_turn else None,
  660. one_turn_alias=(pending_one_turn or {}).get("one_turn_alias", "") if one_turn else "",
  661. reasoning_callback=self._current_reasoning_callback(),
  662. fallback_model=self._fallback_model, thinking_callback=self._on_thinking,
  663. checkpoints_enabled=self.checkpoints_enabled,
  664. checkpoint_max_snapshots=self.checkpoint_max_snapshots,
  665. checkpoint_max_total_size_mb=self.checkpoint_max_total_size_mb,
  666. checkpoint_max_file_size_mb=self.checkpoint_max_file_size_mb,
  667. pass_session_id=self.pass_session_id, skip_context_files=self.ignore_rules,
  668. skip_memory=self.ignore_rules, tool_progress_callback=self._on_tool_progress,
  669. tool_start_callback=self._on_tool_start if self._inline_diffs_enabled else None,
  670. tool_complete_callback=self._on_tool_complete if self._inline_diffs_enabled else None,
  671. stream_delta_callback=self._stream_delta if self.streaming_enabled else None,
  672. tool_gen_callback=self._on_tool_gen_start if self.streaming_enabled else None,
  673. notice_callback=self._on_notice, notice_clear_callback=self._on_notice_clear,
  674. reaction_callback=self._on_reaction)
  675. # Reference for atexit memory-provider shutdown: ``_run_cleanup`` in cli.py
  676. # reads ``cli._active_agent_ref``, so this MUST write the ``cli`` module's
  677. # global — a ``global`` statement here would bind this module's namespace.
  678. # When this code lived in cli.py a bare ``global _active_agent_ref`` worked; after the god-file
  679. # extraction into this mixin a ``global`` here would bind *this module's* namespace, leaving
  680. # ``cli._active_agent_ref`` None forever — so memory shutdown never ran on /exit (#49287).
  681. import cli as _cli
  682. _cli._active_agent_ref = self.agent
  683. self.agent.control_update_callback = self._mark_automation_stale
  684. # Seed the agent's once-per-lifecycle auto_load cache with the bytes the preload
  685. # thread rendered, so the shared prompt path never re-reads config or skill files.
  686. _auto_result = getattr(self, "_auto_load_skills_result", None)
  687. if _auto_result is not None:
  688. self.agent._auto_load_skills_result = _auto_result
  689. self.agent._auto_load_skills_resolved = True
  690. # Route agent status output through prompt_toolkit so ANSI escapes aren't garbled by
  691. # patch_stdout's StdoutProxy (#2262), holding lines while a response box streams so a
  692. # subagent/background completion notice never splits the reply mid-paragraph.
  693. self.agent._print_fn = self._agent_status_print
  694. self.agent._finite = single_query_mode # -q/-Q: a finite gateway admission (headless clarify)
  695. from hermes_cli.gateway_tools import bind
  696. bind(self.agent) # main's dock / status bar / /stop read this session's gateway processes
  697. # Hydrate credits notices at session OPEN (parity with the TUI) so a depletion
  698. # warning shows before the first message. Idempotent + fail-open in the helper.
  699. try:
  700. from agent.credits_tracker import seed_credits_at_session_start
  701. seed_credits_at_session_start(self.agent)
  702. except Exception:
  703. pass
  704. self._active_agent_route_signature = _route_signature(effective_model, runtime)
  705. if getattr(self.agent, "reasoning_pushed", False):
  706. # The session holds the pick now; later rebuilds (/fast, /personality, a route change)
  707. # must not re-commit it (a resume, a prepare+commit, a receipt, an agent eviction each).
  708. self._reasoning_user_set = False
  709. # Force-create DB row on /title intent, then apply title.
  710. if self._pending_title and self._session_db:
  711. try:
  712. self.agent._ensure_db_session()
  713. if self.agent._session_db_created:
  714. self._session_db.set_session_title(self.session_id, self._pending_title)
  715. _cprint(f" {t('cli.resume.title_applied', title=self._pending_title)}")
  716. self._pending_title = None
  717. # else: row creation failed transiently — keep _pending_title for retry
  718. except Exception as e:
  719. _cprint(f" {t('cli.resume.title_apply_failed', error=e)}")
  720. # Keep _pending_title so it can be retried after row creation succeeds
  721. return True
  722. except Exception as e:
  723. console = ChatConsole()
  724. from hermes_cli.cli_chat_error_copy import agent_init_failure_message
  725. console.print(f"[bold red]{_escape(agent_init_failure_message(e))}[/]")
  726. from hermes_constants import partial_update_hint
  727. for line in partial_update_hint(e):
  728. console.print(line)
  729. return False
  730. def _resume_history_limit_error(self, tip_only: bool = False):
  731. """Return a safe-resume error without materializing transcript rows.
  732. ``tip_only`` matches call sites that load only the tip session's rows — counting
  733. the full lineage there would over-reject heavily-compressed sessions with a small
  734. tip. Generic guard failures fail OPEN; only a genuine over-limit result blocks."""
  735. if not self._session_db:
  736. return None
  737. from cli import logger
  738. from hermes_state import SessionResumeTooLargeError
  739. try:
  740. safety_check = getattr(self._session_db, "assert_resume_safe", None)
  741. if not callable(safety_check):
  742. return None
  743. safety_check(getattr(self, "_resume_read_id", None) or self.session_id,
  744. **({"tip_only": True} if tip_only else {}))
  745. except SessionResumeTooLargeError as exc:
  746. return str(exc)
  747. except Exception as exc:
  748. logger.warning(
  749. "Resume safety check failed for %s (proceeding without guard): %s",
  750. self.session_id, exc)
  751. return None
  752. def _preload_resumed_session(self) -> bool:
  753. """Load a resumed session's history early (from run(), before the first chat) so
  754. it can be displayed; ``_init_agent()`` then skips its own DB round-trip. Sets
  755. ``self.conversation_history`` and prints the status line. True if history loaded."""
  756. from cli import _accent_hex
  757. if not self._resumed or not self._session_db:
  758. return False
  759. session_meta = self._session_db.get_session(self.session_id)
  760. if not session_meta:
  761. self._console_print(f"[bold red]{_escape(t('cli.resume.session_not_found', session_id=self.session_id))}[/]")
  762. self._console_print(f"[dim]{_escape(t('cli.resume.session_id_hint'))}[/]")
  763. return False
  764. session_meta = self._follow_compression_chain(
  765. session_meta,
  766. lambda rid: self._console_print(
  767. f"[dim]{_escape(t('cli.resume.compressed_into', session_id=self.session_id, descendant=rid))}[/]"))
  768. # A Kanban worker transcript resumes only through a dispatcher-owned run (#68779) —
  769. # an ordinary CLI resume would be a live writer the board cannot observe. Refuse AND
  770. # fall back to a fresh session id, so this process never appends to the worker row.
  771. from hermes_cli.kanban_resume_guard import kanban_resume_refusal
  772. if (kanban_refusal := kanban_resume_refusal(self._session_db, self._resume_read_id)):
  773. self._console_print(f"[bold red]{_escape(kanban_refusal)}[/]")
  774. self._resumed = False
  775. from hermes_state_ids import new_session_id
  776. self.session_id = new_session_id(self.session_start)
  777. return False
  778. resume_limit_error = self._resume_history_limit_error()
  779. if resume_limit_error:
  780. self._resume_history_error = resume_limit_error
  781. self._console_print(f"[bold red]{_escape(t('cli.resume.cannot_resume_prefix'))}[/] {resume_limit_error}")
  782. return False
  783. restored, display_history = self._session_db.get_resume_conversations(self._resume_read_id)
  784. accent_color = _accent_hex()
  785. if not restored:
  786. self._console_print(
  787. f"[{accent_color}]{_escape(t('cli.resume.session_no_messages', session_id=self.session_id))}[/]")
  788. return False
  789. restored = [m for m in restored if m.get("role") != "session_meta"]
  790. self.conversation_history = restored
  791. self._resume_display_history = [m for m in display_history if m.get("role") != "session_meta"]
  792. from agent.context_compressor import is_user_originated_turn
  793. # Count only user-originated turns: legacy compaction handoffs are durable
  794. # role=user rows without display_kind.
  795. msg_count = len([m for m in self._resume_display_history if is_user_originated_turn(m)])
  796. title_part = f' "{session_meta["title"]}"' if session_meta.get("title") else ""
  797. self._console_print(
  798. f"[{accent_color}]{_escape(t('cli.resume.resumed_session'))} [bold]{self.session_id}[/bold]"
  799. f"{title_part} {_resume_counts(msg_count, len(restored))}[/]")
  800. self._restore_session_state(session_meta)
  801. self._reopen_session()
  802. return True
  803. def _display_resumed_history(self):
  804. """Render a dim Rich-panel recap of the previous conversation, capped at the last
  805. ``resume_exchanges`` user/assistant exchanges with a hidden-count indicator."""
  806. from cli import CLI_CONFIG, _record_output_history_entry, _strip_reasoning_tags, _suspend_output_history
  807. from tools.ansi_strip import sanitize_display_text as _sanitize_display_text
  808. display_history = getattr(self, "_resume_display_history", self.conversation_history)
  809. if not display_history or self.resume_display == "minimal":
  810. return
  811. _disp = CLI_CONFIG.get("display", {})
  812. entries, _last_asst_idx, _last_asst_full = _collect_resume_entries(
  813. display_history, _disp, lambda t: _sanitize_display_text(_strip_reasoning_tags(t)))
  814. if not entries:
  815. return
  816. skipped = max(0, len(entries) - int(_disp.get("resume_exchanges", 10)) * 2)
  817. entries = entries[skipped:]
  818. # Show the last assistant entry in full so the user sees where they left off.
  819. if _last_asst_idx is not None and _last_asst_full:
  820. adj_idx = _last_asst_idx - skipped
  821. if 0 <= adj_idx < len(entries):
  822. entries[adj_idx] = ("assistant_last", _last_asst_full)
  823. from rich.panel import Panel
  824. from rich.text import Text
  825. _history_text_c, _session_label_c, _session_border_c, _assistant_label_c = (
  826. _resume_panel_colors())
  827. # role -> (label, label style, body style, continuation indent)
  828. you_label = f" {t('cli.resume.label_you')} "
  829. assistant_label = f" {t('cli.resume.label_assistant', agent_name='Hermes')} "
  830. role_styles = {
  831. "user": (you_label, f"dim bold {_session_label_c}", "dim", " " * len(you_label)),
  832. "assistant": (assistant_label, f"dim bold {_assistant_label_c}", "dim", " " * len(assistant_label)),
  833. "assistant_last": (assistant_label, f"bold {_assistant_label_c}", "", " " * len(assistant_label)), # full, non-dim
  834. }
  835. lines = Text()
  836. if skipped:
  837. lines.append(f" {t('cli.resume.earlier_messages', count=skipped)}\n\n", style="dim italic")
  838. for i, (role, text) in enumerate(entries):
  839. if role == "event":
  840. lines.append(f" ◈ {text}\n", style="dim italic")
  841. else:
  842. label, label_style, body_style, indent = role_styles[role]
  843. lines.append(label, style=label_style)
  844. first, *rest = text.splitlines() or [""] # first line inline, rest indented
  845. lines.append(first + "\n", style=body_style)
  846. for ml in rest:
  847. lines.append(f"{indent}{ml}\n", style=body_style)
  848. if i < len(entries) - 1:
  849. lines.append("") # small gap
  850. panel = Panel(
  851. lines, title=f"[dim {_session_label_c}]{_escape(t('cli.resume.panel_title'))}[/]",
  852. border_style=f"dim {_session_border_c}", padding=(0, 1), style=_history_text_c)
  853. _record_output_history_entry(lambda: self._render_resume_history_panel_lines(panel))
  854. with _suspend_output_history():
  855. self._console_print(panel)