The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(cli): simplify CLI mixins (billing, agent-setup, commands) — dedupe helpers, dispatch tables, god-method splits
Teknium150ee2a35d30
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.pyindex 46eae97b0d0..5edf0c89cb0 100644--- a/hermes_cli/cli_agent_setup_mixin.py+++ b/hermes_cli/cli_agent_setup_mixin.py@@ -1,15 +1,10 @@"""Agent-construction and session-resume display methods for ``HermesCLI``.-Extracted from ``cli.py`` as part of the god-file decomposition campaign-(``~/.hermes/plans/god-file-decomposition.md``, Phase 4 step 2). This mixin holds-the agent lifecycle/setup cluster: runtime-credential resolution, per-turn agent-config, first-use agent construction, and resumed-session preload + history recap.--Behavior-neutral: every method is lifted verbatim from ``HermesCLI``. ``self.*``-calls resolve unchanged via the MRO. Neutral dependencies are imported at module-top level; ``cli.py``-internal helpers/constants are imported lazily inside each-method (``from cli import ...`` resolves at call time, when ``cli`` is fully-loaded) so this module never imports ``cli`` at import time -> no import cycle.+Holds the agent lifecycle cluster lifted from ``cli.py``: runtime-credential+resolution, per-turn agent config, first-use agent construction, and resumed-session+preload + history recap. ``cli.py``-internal helpers are imported lazily inside each+method (``from cli import ...`` resolves once ``cli`` is fully loaded) so this module+never imports ``cli`` at import time -> no import cycle."""from __future__ import annotations@@ -22,48 +17,82 @@ from utils import base_url_host_matchesdef _single_query_clarify_callback(question: str, choices=None, multi_select=False) -> str:- """Clarify has no interactive surface in a single-query (-q) turn.-- ``hermes chat -q`` runs one turn without ever building the- prompt_toolkit application, so the interactive clarify modal can never- be painted or answered — the CLI callback would poll its response queue- until ``agent.clarify_timeout`` expires (default 3600 s, 0 = unlimited)- while the gateway/cron/kanban-dispatcher caller sees a silent hang. The- oneshot path answers immediately via ``_oneshot_clarify_callback``;- single-query turns need the same headless behavior (#94943)."""+ """Headless clarify answer for ``hermes chat -q``.++ A -q turn never builds the prompt_toolkit app, so the interactive clarify modal+ can never be painted or answered — the CLI callback would poll until+ ``agent.clarify_timeout`` while the caller sees a silent hang. Mirror the oneshot+ path and answer immediately instead."""+ prefix = f"[single-query mode: no user available to answer {question!r}. "if choices:- if multi_select:- return (- f"[single-query mode: no user available to answer {question!r}. "- f"Pick the best subset from {choices} using your own judgment "- f"and continue.]"- )- return (- f"[single-query mode: no user available to answer {question!r}. "- f"Pick the best option from {choices} using your own judgment "- f"and continue.]"- )+ what = "subset" if multi_select else "option"+ return f"{prefix}Pick the best {what} from {choices} using your own judgment and continue.]"+ return f"{prefix}Make the most reasonable assumption you can and continue.]"+++def _current_runtime(cli) -> dict:+ """Snapshot the CLI's resolved provider routing as an AIAgent runtime dict.++ getattr guards stay: tests build minimal shells lacking these attributes."""+ return {+ "api_key": cli.api_key,+ "base_url": cli.base_url,+ "provider": cli.provider,+ "requested_provider": getattr(cli, "requested_provider", cli.provider),+ "api_mode": cli.api_mode,+ "command": cli.acp_command,+ "args": list(cli.acp_args or []),+ "credential_pool": getattr(cli, "_credential_pool", None),+ }+++def _route_signature(model, runtime: dict) -> tuple:+ """Hashable identity of (model, routing) used to detect when the agent must be rebuilt."""return (- f"[single-query mode: no user available to answer {question!r}. Make "- f"the most reasonable assumption you can and continue.]"+ model,+ runtime.get("provider"),+ runtime.get("requested_provider"),+ runtime.get("base_url"),+ runtime.get("api_mode"),+ runtime.get("command"),+ tuple(runtime.get("args") or ()),)+def _compression_descendant(session_db, session_id):+ """If ``session_id`` is the (empty) head of a compression chain, return the+ descendant that actually holds the messages; else None. Fails open on DB errors."""+ try:+ resolved_id = session_db.resolve_resume_session_id(session_id)+ except Exception:+ return None+ return resolved_id if resolved_id and resolved_id != session_id else None+++# display_kind -> recap event line; ``hidden`` rows are skipped before this lookup.+_RESUME_EVENT_TEXT = {+ "model_switch": "model changed",+ "async_delegation_complete": "background delegation completed",+ "auto_continue": "resumed interrupted turn",+}++# (skin key, fallback) for recap panel colors: body text, session label, border, assistant label.+_RESUME_SKIN_COLORS = (+ ("banner_text", "#FFF8DC"),+ ("session_label", "#DAA520"),+ ("session_border", "#8B8682"),+ ("ui_ok", "#8FBC8F"),+)++class CLIAgentSetupMixin:"""Agent construction + session-resume display methods for ``HermesCLI``."""def _ensure_runtime_credentials(self) -> bool:- """- Ensure runtime credentials are resolved before agent use.- Re-resolves provider credentials so key rotation and token refresh- are picked up without restarting the CLI.- Returns True if credentials are ready, False on auth failure.- """+ """Re-resolve provider credentials before agent use so key rotation / token+ refresh are picked up without restarting the CLI. False on auth failure."""from cli import ChatConsole, _cprint, logger- from hermes_cli.runtime_provider import (- resolve_runtime_provider,- format_runtime_provider_error,- )+ from hermes_cli.runtime_provider import resolve_runtime_provider, format_runtime_provider_error_primary_exc = Noneruntime = None@@ -119,18 +148,12 @@ class CLIAgentSetupMixin:resolved_api_mode = runtime.get("api_mode", self.api_mode)resolved_acp_command = runtime.get("command")resolved_acp_args = list(runtime.get("args") or [])- resolved_credential_pool = runtime.get("credential_pool")- # A callable api_key is a bearer-token provider (Azure Foundry- # Entra ID — ``azure_identity_adapter.build_token_provider``).- # The OpenAI SDK accepts ``Callable[[], str]`` for ``api_key`` and- # invokes it before every request. Skip the string-only validation- # and placeholder substitution for callables.+ # A callable api_key is a bearer-token provider (Azure Entra ID): the OpenAI SDK+ # invokes it per request, so skip string validation / placeholder substitution._is_callable_provider = callable(api_key) and not isinstance(api_key, str)if not _is_callable_provider and (not isinstance(api_key, str) or not api_key):- # Custom / local endpoints (llama.cpp, ollama, vLLM, etc.) often- # don't require authentication. When a base_url IS configured but- # no API key was found, use a placeholder so the OpenAI SDK- # doesn't reject the request and local servers just ignore it.+ # Custom/local endpoints (llama.cpp, ollama, vLLM) often need no auth: with a+ # non-OpenRouter base_url use a placeholder key so the SDK doesn't reject it._source = runtime.get("source", "")_has_custom_base = (isinstance(base_url, str)@@ -169,30 +192,22 @@ class CLIAgentSetupMixin:self.api_mode = resolved_api_modeself.acp_command = resolved_acp_commandself.acp_args = resolved_acp_args- self._credential_pool = resolved_credential_pool+ self._credential_pool = runtime.get("credential_pool")self._provider_source = runtime.get("source")self.api_key = api_keyself.base_url = base_url- # When a custom_provider entry carries an explicit `model` field,- # use it as the effective model name. Without this, running- # `hermes chat --model <provider-name>` sends the provider name- # (e.g. "my-provider") as the model string to the API instead of- # the configured model (e.g. "qwen3.6-plus"), causing 400 errors.+ # A custom_provider entry's explicit `model` wins when the CLI model is unset or+ # is just the provider slug/display name (`hermes chat --model <provider-name>`+ # would otherwise send the provider name as the model string -> 400).runtime_model = runtime.get("model")- if runtime_model and isinstance(runtime_model, str):- # Only use runtime model if: model is unset, or model equals provider name- should_use_runtime_model = (- not self.model or # No model configured yet- self.model == self.provider or # Model is the provider slug- self.model == runtime.get("name") # Model matches provider display name- )- if should_use_runtime_model:- self.model = runtime_model+ if runtime_model and isinstance(runtime_model, str) and (+ not self.model or self.model == self.provider or self.model == runtime.get("name")+ ):+ self.model = runtime_model- # If model is still empty (e.g. user ran `hermes auth add openai-codex`- # without `hermes model`), fall back to the provider's first catalog- # model so the API call doesn't fail with "model must be non-empty".+ # Still empty (e.g. `hermes auth add` without `hermes model`): fall back to the+ # provider's first catalog model so the API doesn't reject an empty model.if not self.model and resolved_provider:try:from hermes_cli.models import get_default_model_for_provider@@ -206,12 +221,10 @@ class CLIAgentSetupMixin:except Exception:pass- # Normalize model for the resolved provider (e.g. swap non-Codex- # models when provider is openai-codex). Fixes #651.+ # Normalize model for the resolved provider (e.g. swap non-Codex models on openai-codex).model_changed = self._normalize_model_for_provider(resolved_provider)- # AIAgent/OpenAI client holds auth at init time, so rebuild if key,- # routing, or the effective model changed.+ # AIAgent/OpenAI client holds auth at init, so rebuild on key/routing/model change.if (credentials_changed or routing_changed or model_changed) and self.agent is not None:self.agent = Noneself._active_agent_route_signature = None@@ -221,12 +234,8 @@ class CLIAgentSetupMixin:def _runtime_credentials_ready(self) -> bool:"""Silently probe whether any inference provider can be resolved.- Unlike ``_ensure_runtime_credentials`` this never prints and never- mutates CLI state — it exists so the interactive first-run path can- detect a completely unconfigured install *before* the user types a- message into a chat that cannot work (#62935-adjacent UX class:- keyless first run must route into onboarding, not a broken chat).- """+ Never prints or mutates CLI state, so the interactive first-run path can route a+ keyless install into onboarding before the user types into a chat that can't work."""from hermes_cli.runtime_provider import resolve_runtime_providertry:@@ -241,9 +250,7 @@ class CLIAgentSetupMixin:return Falseapi_key = runtime.get("api_key")base_url = runtime.get("base_url")- if callable(api_key) and not isinstance(api_key, str):- return bool(base_url)- if isinstance(api_key, str) and api_key:+ if (callable(api_key) and not isinstance(api_key, str)) or (isinstance(api_key, str) and api_key):return bool(base_url)# Keyless custom/local endpoints (ollama, llama.cpp, vLLM…) are fine.return bool(@@ -253,15 +260,9 @@ class CLIAgentSetupMixin:)def _offer_first_run_setup(self) -> bool:- """Offer the provider picker when no provider is configured at all.-- Called from the interactive startup path when- ``_runtime_credentials_ready()`` is False and stdin is a TTY. Runs the- exact same flow as ``hermes model`` (which fronts Quick Setup / Nous- Portal OAuth as the first, recommended option) so there is a single- source of truth for provider onboarding. Returns True when a provider- was configured.- """+ """Offer the provider picker when no provider is configured at all (interactive+ startup, TTY). Runs the same flow as ``hermes model`` so onboarding has a single+ source of truth. True when a provider was configured."""from cli import _cprint, logger_cprint("")@@ -290,8 +291,7 @@ class CLIAgentSetupMixin:_cprint(" Run 'hermes model' to try again.")return False- # Re-sync CLI state from what the picker persisted so the very next- # turn uses the new provider without a restart.+ # Re-sync CLI state from what the picker persisted so the next turn uses it without a restart.try:from hermes_cli.config import load_config_model_cfg = (load_config().get("model") or {})@@ -299,9 +299,7 @@ class CLIAgentSetupMixin:_new_provider = (_model_cfg.get("provider") or "").strip()if _new_provider:self.requested_provider = _new_provider- _new_model = (- _model_cfg.get("default") or _model_cfg.get("model") or ""- ).strip()+ _new_model = (_model_cfg.get("default") or _model_cfg.get("model") or "").strip()if _new_model:self.model = _new_modelexcept Exception as exc:@@ -317,74 +315,108 @@ class CLIAgentSetupMixin:return Falsedef _resolve_turn_agent_config(self, user_message: str) -> dict:- """Build the effective model/runtime config for a single user turn.-- Always uses the session's primary model/provider. If the user has- toggled `/fast` on and the current model supports Priority- Processing / Anthropic fast mode, attach `request_overrides` so the- API call is marked accordingly.- """+ """Effective model/runtime config for one turn — always the session's primary+ provider. With `/fast` on (service_tier == "priority") attach request_overrides;+ auto/cold tiers are applied per request by agent.fast_mode instead."""from hermes_cli.models import resolve_fast_mode_overrides- runtime = {- "api_key": self.api_key,- "base_url": self.base_url,- "provider": self.provider,- "requested_provider": getattr(- self, "requested_provider", self.provider- ),- "api_mode": self.api_mode,- "command": self.acp_command,- "args": list(self.acp_args or []),- "credential_pool": getattr(self, "_credential_pool", None),- }- route = {- "model": self.model,- "runtime": runtime,- "signature": (- self.model,- runtime["provider"],- runtime["requested_provider"],- runtime["base_url"],- runtime["api_mode"],- runtime["command"],- tuple(runtime["args"]),- ),- }+ runtime = _current_runtime(self)+ route = {"model": self.model, "runtime": runtime, "signature": _route_signature(self.model, runtime)}- service_tier = getattr(self, "service_tier", None)- if service_tier != "priority":- # None (normal) or auto/cold — the bounded window is applied per- # request by agent.fast_mode, not pinned into request_overrides.+ if getattr(self, "service_tier", None) != "priority":route["request_overrides"] = Nonereturn routetry:overrides = resolve_fast_mode_overrides(- route["model"],- provider=runtime["provider"],- base_url=runtime["base_url"],+ route["model"], provider=runtime["provider"], base_url=runtime["base_url"],)except Exception:overrides = Noneroute["request_overrides"] = overridesreturn route+ def _load_resumed_history_late(self) -> bool:+ """Late resume path: validate the session and load its history from the DB when+ _preload_resumed_session() (called from run()) did not already populate it.+ False when the resume must abort (missing session / over the safe-resume limit)."""+ from cli import ChatConsole, _DIM, _RST, _accent_hex, _cprint+ session_meta = self._session_db.get_session(self.session_id)+ # Quiet mode (tool_progress_mode == "off") routes resume status lines to+ # stderr so stdout stays machine-readable for `$(hermes chat -Q --resume ...)`.+ _quiet_mode = getattr(self, "tool_progress_mode", "full") == "off"++ def _say(plain: str, rich: str) -> None:+ if _quiet_mode:+ print(plain, file=sys.stderr)+ else:+ ChatConsole().print(rich)++ if not session_meta:+ if _quiet_mode:+ print(f"Session not found: {self.session_id}", file=sys.stderr)+ print("Use a session ID from a previous CLI run (hermes sessions list).", file=sys.stderr)+ else:+ _cprint(f"\033[1;31mSession not found: {self.session_id}{_RST}")+ _cprint(f"{_DIM}Use a session ID from a previous CLI run (hermes sessions list).{_RST}")+ return False+ resolved_id = _compression_descendant(self._session_db, self.session_id)+ if resolved_id:+ ChatConsole().print(+ f"[dim]Session {_escape(self.session_id)} was compressed into "+ f"{_escape(resolved_id)}; resuming the descendant with your "+ f"transcript.[/dim]"+ )+ self.session_id = resolved_id+ session_meta = self._session_db.get_session(self.session_id) or session_meta+ if getattr(self, "_resume_history_error", None):+ return False+ # Only the TIP session's rows are loaded here (no ancestors), so use the+ # tip-only count — the full-lineage count would over-reject compressed sessions.+ resume_limit_error = self._resume_history_limit_error(tip_only=True)+ if resume_limit_error:+ self._resume_history_error = resume_limit_error+ _say(+ f"Cannot resume session: {resume_limit_error}",+ f"[bold red]Cannot resume session:[/] {_escape(resume_limit_error)}",+ )+ return False+ restored = self._session_db.get_messages_as_conversation(self.session_id, repair_alternation=True)+ if restored:+ restored = [m for m in restored if m.get("role") != "session_meta"]+ self.conversation_history = restored+ msg_count = len([m for m in restored if m.get("role") == "user"])+ title_part = f" \"{session_meta['title']}\"" if session_meta.get("title") else ""+ counts = f"({msg_count} user message{'s' if msg_count != 1 else ''}, {len(restored)} total messages)"+ _say(+ f"↻ Resumed session {self.session_id}{title_part} {counts}",+ f"[bold {_accent_hex()}]↻ Resumed session[/] [bold]{_escape(self.session_id)}[/]"+ f"[bold {_accent_hex()}]{_escape(title_part)}[/] {counts}",+ )+ self._restore_session_cwd(session_meta, quiet=_quiet_mode)+ self._restore_session_yolo(session_meta, quiet=_quiet_mode)+ self._restore_session_model(session_meta, quiet=_quiet_mode)+ else:+ _say(+ f"Session {self.session_id} found but has no messages. Starting fresh.",+ f"[bold {_accent_hex()}]Session {_escape(self.session_id)} found but has no messages. Starting fresh.[/]",+ )+ # Re-open the session (clear ended_at so it's active again)+ try:+ self._session_db.reopen_session(self.session_id)+ except Exception:+ pass+ return True+def _init_agent(self, *, model_override: str = None, runtime_override: dict = None, request_overrides: dict | None = None) -> bool:- """- Initialize the agent on first use.- When resuming a session, restores conversation history from SQLite.-- Returns:- bool: True if successful, False otherwise- """- from cli import AIAgent, ChatConsole, _DIM, _RST, _accent_hex, _cprint, _prepare_deferred_agent_startup, logger+ """Build the agent on first use; when resuming, restore history from SQLite.+ Returns True on success."""+ from cli import AIAgent, ChatConsole, _cprint, _prepare_deferred_agent_startup, loggerif self.agent is not None:return True- # Join the background preloaded-skills load (cli.py cmd_chat starts- # it when --skills/-s is passed) BEFORE the agent snapshots- # self.system_prompt below. No-op when nothing was requested.+ # Join the background preloaded-skills load (--skills/-s) BEFORE the agent+ # snapshots self.system_prompt below. No-op when nothing was requested.self.finalize_preloaded_skills()_prepare_deferred_agent_startup()@@ -401,126 +433,21 @@ class CLIAgentSetupMixin:single_query=getattr(self, "_single_query_mode", False),)- # Initialize SQLite session store for CLI sessions (if not already done in __init__)if self._session_db is None:try:from hermes_state import SessionDBself._session_db = SessionDB()except Exception as e:logger.warning("SQLite session store not available — session will NOT be indexed: %s", e)-- # If resuming, validate the session exists and load its history.- # _preload_resumed_session() may have already loaded it (called from- # run() for immediate display). In that case, conversation_history- # is non-empty and we skip the DB round-trip.- if self._resumed and self._session_db and not self.conversation_history:- session_meta = self._session_db.get_session(self.session_id)- # In quiet mode (`hermes chat -Q` / --quiet, surfaced via- # tool_progress_mode == "off"), resume status lines go to stderr- # so stdout stays machine-readable for automation wrappers that- # do `$(hermes chat -Q --resume <id> -q "...")`. Without this,- # the resume banner pollutes captured stdout. See #11793.- _quiet_mode = getattr(self, "tool_progress_mode", "full") == "off"- if not session_meta:- if _quiet_mode:- print(f"Session not found: {self.session_id}", file=sys.stderr)- print(- "Use a session ID from a previous CLI run (hermes sessions list).",- file=sys.stderr,- )- else:- _cprint(f"\033[1;31mSession not found: {self.session_id}{_RST}")- _cprint(f"{_DIM}Use a session ID from a previous CLI run (hermes sessions list).{_RST}")- return False- # If the requested session is the (empty) head of a compression- # chain, walk to the descendant that actually holds the messages.- # See #15000 and SessionDB.resolve_resume_session_id.- try:- resolved_id = self._session_db.resolve_resume_session_id(self.session_id)- except Exception:- resolved_id = self.session_id- if resolved_id and resolved_id != self.session_id:- ChatConsole().print(- f"[dim]Session {_escape(self.session_id)} was compressed into "- f"{_escape(resolved_id)}; resuming the descendant with your "- f"transcript.[/dim]"- )- self.session_id = resolved_id- resolved_meta = self._session_db.get_session(self.session_id)- if resolved_meta:- session_meta = resolved_meta- prior_resume_error = getattr(self, "_resume_history_error", None)- if prior_resume_error:- return False- # This path loads only the TIP session's rows (no ancestors),- # so guard with a tip-only count — the full-lineage count would- # over-reject heavily-compressed sessions with a small tip.- resume_limit_error = self._resume_history_limit_error(tip_only=True)- if resume_limit_error:- self._resume_history_error = resume_limit_error- if _quiet_mode:- print(f"Cannot resume session: {resume_limit_error}", file=sys.stderr)- else:- ChatConsole().print(- f"[bold red]Cannot resume session:[/] {_escape(resume_limit_error)}"- )- return False- restored = self._session_db.get_messages_as_conversation(- self.session_id, repair_alternation=True- )- if restored:- restored = [m for m in restored if m.get("role") != "session_meta"]- self.conversation_history = restored- msg_count = len([m for m in restored if m.get("role") == "user"])- title_part = ""- if session_meta.get("title"):- title_part = f" \"{session_meta['title']}\""- if _quiet_mode:- print(- f"↻ Resumed session {self.session_id}{title_part} "- f"({msg_count} user message{'s' if msg_count != 1 else ''}, "- f"{len(restored)} total messages)",- file=sys.stderr,- )- else:- ChatConsole().print(- f"[bold {_accent_hex()}]↻ Resumed session[/] "- f"[bold]{_escape(self.session_id)}[/]"- f"[bold {_accent_hex()}]{_escape(title_part)}[/] "- f"({msg_count} user message{'s' if msg_count != 1 else ''}, {len(restored)} total messages)"- )- self._restore_session_cwd(session_meta, quiet=_quiet_mode)- self._restore_session_yolo(session_meta, quiet=_quiet_mode)- self._restore_session_model(session_meta, quiet=_quiet_mode)- else:- if _quiet_mode:- print(- f"Session {self.session_id} found but has no messages. Starting fresh.",- file=sys.stderr,- )- else:- ChatConsole().print(- f"[bold {_accent_hex()}]Session {_escape(self.session_id)} found but has no messages. Starting fresh.[/]"- )- # Re-open the session (clear ended_at so it's active again)- try:- self._session_db.reopen_session(self.session_id)- except Exception:- pass-++ if (+ self._resumed and self._session_db and not self.conversation_history+ and not self._load_resumed_history_late()+ ):+ return False+try:- runtime = runtime_override or {- "api_key": self.api_key,- "base_url": self.base_url,- "provider": self.provider,- "requested_provider": getattr(- self, "requested_provider", self.provider- ),- "api_mode": self.api_mode,- "command": self.acp_command,- "args": list(self.acp_args or []),- "credential_pool": getattr(self, "_credential_pool", None),- }+ runtime = runtime_override or _current_runtime(self)effective_model = model_override or self.modelself.agent = AIAgent(model=effective_model,@@ -555,17 +482,14 @@ class CLIAgentSetupMixin:session_id=self.session_id,platform="cli",session_db=self._session_db,- # A -q turn never builds the prompt_toolkit application, so- # the interactive modal can never be painted or answered —- # answer headless instead of polling until clarify_timeout- # (#94943; mirrors _oneshot_clarify_callback on the -z path).+ # -q never builds the prompt_toolkit app, so the clarify modal can't be+ # answered — answer headless instead of polling until clarify_timeout.clarify_callback=(_single_query_clarify_callbackif getattr(self, "_single_query_mode", False)else self._clarify_callback),reasoning_callback=self._current_reasoning_callback(),-fallback_model=self._fallback_model,thinking_callback=self._on_thinking,checkpoints_enabled=self.checkpoints_enabled,@@ -584,39 +508,23 @@ class CLIAgentSetupMixin:notice_clear_callback=self._on_notice_clear,reaction_callback=self._on_reaction,)- # Store reference for atexit memory provider shutdown.- # NOTE: this MUST write to the ``cli`` module's global, not a- # local module global. ``_run_cleanup`` (in cli.py) reads- # ``cli._active_agent_ref`` to decide whether to fire the memory- # provider's ``on_session_end`` hook. When this code lived in- # cli.py a bare ``global _active_agent_ref`` worked; after the- # god-file extraction into this mixin a ``global`` here would bind- # *this module's* namespace, leaving ``cli._active_agent_ref`` None- # forever — so memory shutdown never ran on /exit (#49287).+ # Reference for atexit memory-provider shutdown: ``_run_cleanup`` in cli.py+ # reads ``cli._active_agent_ref``, so this MUST write the ``cli`` module's+ # global — a ``global`` statement here would bind this module's namespace.import cli as _cli_cli._active_agent_ref = self.agent- # Route agent status output through prompt_toolkit so ANSI escape- # sequences aren't garbled by patch_stdout's StdoutProxy (#2262).+ # Route agent status output through prompt_toolkit so ANSI escapes+ # aren't garbled by patch_stdout's StdoutProxy.self.agent._print_fn = _cprint- # Hydrate credits notices at session OPEN (parity with the TUI), so a- # depletion / usage-band warning shows before the first message. The- # notice_callback is bound above → _on_notice renders the line. Idempotent- # + fail-open inside the helper; harmless for non-Nous providers.+ # Hydrate credits notices at session OPEN (parity with the TUI) so a depletion+ # warning shows before the first message. Idempotent + fail-open in the helper.try:from agent.credits_tracker import seed_credits_at_session_startseed_credits_at_session_start(self.agent)except Exception:pass- self._active_agent_route_signature = (- effective_model,- runtime.get("provider"),- runtime.get("requested_provider"),- runtime.get("base_url"),- runtime.get("api_mode"),- runtime.get("command"),- tuple(runtime.get("args") or ()),- )+ self._active_agent_route_signature = _route_signature(effective_model, runtime)# Force-create DB row on /title intent, then apply title.if self._pending_title and self._session_db and self.agent:@@ -643,17 +551,13 @@ class CLIAgentSetupMixin:def _resume_history_limit_error(self, tip_only: bool = False):"""Return a safe-resume error without materializing transcript rows.- ``tip_only`` matches call sites that load only the tip session's rows- (``get_messages_as_conversation`` without ancestors) — counting the- full lineage there would over-reject heavily-compressed sessions- whose tip is small. Generic guard failures fail OPEN (resume- proceeds) — only a genuine over-limit result blocks.- """+ ``tip_only`` matches call sites that load only the tip session's rows — counting+ the full lineage there would over-reject heavily-compressed sessions with a small+ tip. Generic guard failures fail OPEN; only a genuine over-limit result blocks."""if not self._session_db:return None- from hermes_state import (- SessionResumeTooLargeError,- )+ from cli import logger+ from hermes_state import SessionResumeTooLargeErrortry:safety_check = getattr(self._session_db, "assert_resume_safe", None)@@ -674,95 +578,63 @@ class CLIAgentSetupMixin:return Nonedef _preload_resumed_session(self) -> bool:- """Load a resumed session's history from the DB early (before first chat).-- Called from run() so the conversation history is available for display- before the user sends their first message. Sets- ``self.conversation_history`` and prints the one-liner status. Returns- True if history was loaded, False otherwise.-- The corresponding block in ``_init_agent()`` checks whether history is- already populated and skips the DB round-trip.- """+ """Load a resumed session's history early (from run(), before the first chat) so+ it can be displayed; ``_init_agent()`` then skips its own DB round-trip. Sets+ ``self.conversation_history`` and prints the status line. True if history loaded."""from cli import _accent_hexif not self._resumed or not self._session_db:return Falsesession_meta = self._session_db.get_session(self.session_id)if not session_meta:- self._console_print(- f"[bold red]Session not found: {self.session_id}[/]"- )- self._console_print(- "[dim]Use a session ID from a previous CLI run "- "(hermes sessions list).[/]"- )+ self._console_print(f"[bold red]Session not found: {self.session_id}[/]")+ self._console_print("[dim]Use a session ID from a previous CLI run (hermes sessions list).[/]")return False- # If the requested session is the (empty) head of a compression chain,- # walk to the descendant that actually holds the messages. See #15000.- try:- resolved_id = self._session_db.resolve_resume_session_id(self.session_id)- except Exception:- resolved_id = self.session_id- if resolved_id and resolved_id != self.session_id:+ resolved_id = _compression_descendant(self._session_db, self.session_id)+ if resolved_id:self._console_print(f"[dim]Session {self.session_id} was compressed into "f"{resolved_id}; resuming the descendant with your transcript.[/]")self.session_id = resolved_id- resolved_meta = self._session_db.get_session(self.session_id)- if resolved_meta:- session_meta = resolved_meta+ session_meta = self._session_db.get_session(self.session_id) or session_metaresume_limit_error = self._resume_history_limit_error()if resume_limit_error:self._resume_history_error = resume_limit_error- self._console_print(- f"[bold red]Cannot resume session:[/] {resume_limit_error}"- )+ self._console_print(f"[bold red]Cannot resume session:[/] {resume_limit_error}")return Falsemodel_history, display_history = self._session_db.get_resume_conversations(self.session_id)restored = model_history- if restored:- restored = [m for m in restored if m.get("role") != "session_meta"]- self.conversation_history = restored- self._resume_display_history = [- m for m in display_history if m.get("role") != "session_meta"- ]- from agent.context_compressor import is_user_originated_turn-- # Count only user-originated turns (#80622): legacy compaction- # handoffs are durable role=user rows without display_kind.- msg_count = len(- [- m- for m in self._resume_display_history- if is_user_originated_turn(m)- ]- )- title_part = ""- if session_meta.get("title"):- title_part = f' "{session_meta["title"]}"'- accent_color = _accent_hex()- self._console_print(- f"[{accent_color}]↻ Resumed session [bold]{self.session_id}[/bold]"- f"{title_part} "- f"({msg_count} user message{'s' if msg_count != 1 else ''}, "- f"{len(restored)} total messages)[/]"- )- self._restore_session_cwd(session_meta)- self._restore_session_yolo(session_meta)- self._restore_session_model(session_meta)- else:- accent_color = _accent_hex()+ accent_color = _accent_hex()+ if not restored:self._console_print(f"[{accent_color}]Session {self.session_id} found but has no "f"messages. Starting fresh.[/]")return False+ restored = [m for m in restored if m.get("role") != "session_meta"]+ self.conversation_history = restored+ self._resume_display_history = [m for m in display_history if m.get("role") != "session_meta"]+ from agent.context_compressor import is_user_originated_turn++ # Count only user-originated turns: legacy compaction handoffs are durable+ # role=user rows without display_kind.+ msg_count = len([m for m in self._resume_display_history if is_user_originated_turn(m)])+ title_part = f' "{session_meta["title"]}"' if session_meta.get("title") else ""+ self._console_print(+ f"[{accent_color}]↻ Resumed session [bold]{self.session_id}[/bold]"+ f"{title_part} "+ f"({msg_count} user message{'s' if msg_count != 1 else ''}, "+ f"{len(restored)} total messages)[/]"+ )+ self._restore_session_cwd(session_meta)+ self._restore_session_yolo(session_meta)+ self._restore_session_model(session_meta)+# Re-open the session (clear ended_at so it's active again)try:self._session_db.reopen_session(self.session_id)@@ -772,24 +644,14 @@ class CLIAgentSetupMixin:return Truedef _display_resumed_history(self):- """Render a compact recap of previous conversation messages.-- Uses Rich markup with dim/muted styling so the recap is visually- distinct from the active conversation. Caps the display at the- last ``MAX_DISPLAY_EXCHANGES`` user/assistant exchanges and shows- an indicator for earlier hidden messages.- """+ """Render a dim Rich-panel recap of the previous conversation, capped at the last+ ``resume_exchanges`` user/assistant exchanges with a hidden-count indicator."""from cli import CLI_CONFIG, _record_output_history_entry, _strip_reasoning_tags, _suspend_output_historyfrom tools.ansi_strip import sanitize_display_text as _sanitize_display_textdisplay_history = getattr(self, "_resume_display_history", self.conversation_history)- if not display_history:+ if not display_history or self.resume_display == "minimal":return- # Check config: resume_display setting- if self.resume_display == "minimal":- return-- # Read limits from config (with hardcoded defaults)_disp = CLI_CONFIG.get("display", {})MAX_DISPLAY_EXCHANGES = int(_disp.get("resume_exchanges", 10))MAX_USER_LEN = int(_disp.get("resume_max_user_chars", 300))@@ -797,8 +659,8 @@ class CLIAgentSetupMixin:MAX_ASST_LINES = int(_disp.get("resume_max_assistant_lines", 3))SKIP_TOOL_ONLY = _disp.get("resume_skip_tool_only", True)- # Collect displayable entries (skip system, tool-result messages)- entries = [] # list of (role, display_text)+ # Collect displayable (role, text) entries; system and tool-result rows are skipped.+ entries = []_last_asst_idx = None # index of last assistant entry_last_asst_full = None # un-truncated display text for last assistantfor msg in display_history:@@ -809,36 +671,22 @@ class CLIAgentSetupMixin:if display_kind == "hidden":continue- if display_kind == "model_switch":- entries.append(("event", "model changed"))+ if display_kind in _RESUME_EVENT_TEXT:+ entries.append(("event", _RESUME_EVENT_TEXT[display_kind]))continue- if display_kind == "async_delegation_complete":- entries.append(("event", "background delegation completed"))- continue- if display_kind == "auto_continue":- entries.append(("event", "resumed interrupted turn"))- continue-- if role == "system":- continue- if role == "tool":+ if role in ("system", "tool"):continueif role == "user":text = "" if content is None else str(content)- # Handle multimodal content (list of dicts)- if isinstance(content, list):- parts = []- for part in content:- if isinstance(part, dict) and part.get("type") == "text":- parts.append(part.get("text", ""))- elif isinstance(part, dict) and part.get("type") == "image_url":- parts.append("[image]")- text = " ".join(parts)- # Stored history is untrusted for display: strip escape- # sequences/control chars so replaying a message can't- # clear the screen, retitle the window, or restyle the- # recap panel (see tools/ansi_strip.sanitize_display_text).+ if isinstance(content, list): # multimodal: text parts + [image] markers+ text = " ".join(+ part.get("text", "") if part.get("type") == "text" else "[image]"+ for part in content+ if isinstance(part, dict) and part.get("type") in ("text", "image_url")+ )+ # Stored history is untrusted for display: strip escape sequences/control+ # chars so replay can't clear the screen, retitle the window or restyle the panel.text = _sanitize_display_text(text)if len(text) > MAX_USER_LEN:text = text[:MAX_USER_LEN] + "..."@@ -858,27 +706,20 @@ class CLIAgentSetupMixin:text = text[:MAX_ASST_LEN] + "..."parts.append(text)if tool_calls:- tc_count = len(tool_calls)- # Extract tool namesnames = []for tc in tool_calls:fn = tc.get("function", {})name = fn.get("name", "unknown") if isinstance(fn, dict) else "unknown"if name not in names:names.append(name)- names_str = ", ".join(names[:4])- if len(names) > 4:- names_str += ", ..."- noun = "call" if tc_count == 1 else "calls"- tc_summary = f"[{tc_count} tool {noun}: {names_str}]"+ names_str = ", ".join(names[:4]) + (", ..." if len(names) > 4 else "")+ noun = "call" if len(tool_calls) == 1 else "calls"+ tc_summary = f"[{len(tool_calls)} tool {noun}: {names_str}]"parts.append(tc_summary)full_parts.append(tc_summary)- if not parts:- # Skip pure-reasoning messages that have no visible output- continue- # Skip tool-call-only entries when SKIP_TOOL_ONLY is enabled- has_text = bool(text)- if SKIP_TOOL_ONLY and not has_text and tool_calls:+ # Skip pure-reasoning messages with no visible output, and tool-call-only+ # entries when SKIP_TOOL_ONLY is enabled.+ if not text and (SKIP_TOOL_ONLY or not tool_calls):continueentries.append(("assistant", " ".join(parts)))_last_asst_idx = len(entries) - 1@@ -887,66 +728,52 @@ class CLIAgentSetupMixin:if not entries:return- # Determine if we need to truncateskipped = 0if len(entries) > MAX_DISPLAY_EXCHANGES * 2:skipped = len(entries) - MAX_DISPLAY_EXCHANGES * 2entries = entries[skipped:]- # Replace last assistant entry with full (un-truncated) text- # so the user can see where they left off without wasting tokens.+ # Show the last assistant entry in full so the user sees where they left off.if _last_asst_idx is not None and _last_asst_full:adj_idx = _last_asst_idx - skippedif 0 <= adj_idx < len(entries):entries[adj_idx] = ("assistant_last", _last_asst_full)- # Build the display using Richfrom rich.panel import Panelfrom rich.text import Texttry:from hermes_cli.skin_engine import get_active_skin_skin = get_active_skin()- _history_text_c = _skin.get_color("banner_text", "#FFF8DC")- _session_label_c = _skin.get_color("session_label", "#DAA520")- _session_border_c = _skin.get_color("session_border", "#8B8682")- _assistant_label_c = _skin.get_color("ui_ok", "#8FBC8F")+ _history_text_c, _session_label_c, _session_border_c, _assistant_label_c = (+ _skin.get_color(key, default) for key, default in _RESUME_SKIN_COLORS+ )except Exception:- _history_text_c = "#FFF8DC"- _session_label_c = "#DAA520"- _session_border_c = "#8B8682"- _assistant_label_c = "#8FBC8F"+ _history_text_c, _session_label_c, _session_border_c, _assistant_label_c = (+ default for _, default in _RESUME_SKIN_COLORS+ )++ # role -> (label, label style, body style, continuation indent)+ role_styles = {+ "user": (" ● You: ", f"dim bold {_session_label_c}", "dim", " " * 9),+ "assistant": (" ◆ Hermes: ", f"dim bold {_assistant_label_c}", "dim", " " * 12),+ "assistant_last": (" ◆ Hermes: ", f"bold {_assistant_label_c}", "", " " * 12), # full, non-dim+ }lines = Text()if skipped:- lines.append(- f" ... {skipped} earlier messages ...\n\n",- style="dim italic",- )+ lines.append(f" ... {skipped} earlier messages ...\n\n", style="dim italic")for i, (role, text) in enumerate(entries):if role == "event":lines.append(f" ◈ {text}\n", style="dim italic")- elif role == "user":- lines.append(" ● You: ", style=f"dim bold {_session_label_c}")- # Show first line inline, indent rest- msg_lines = text.splitlines() or [""]- lines.append(msg_lines[0] + "\n", style="dim")- for ml in msg_lines[1:]:- lines.append(f" {ml}\n", style="dim")- elif role == "assistant_last":- # Last assistant response shown in full, non-dim- lines.append(" ◆ Hermes: ", style=f"bold {_assistant_label_c}")- msg_lines = text.splitlines() or [""]- lines.append(msg_lines[0] + "\n", style="")- for ml in msg_lines[1:]:- lines.append(f" {ml}\n", style="")else:- lines.append(" ◆ Hermes: ", style=f"dim bold {_assistant_label_c}")- msg_lines = text.splitlines() or [""]- lines.append(msg_lines[0] + "\n", style="dim")- for ml in msg_lines[1:]:- lines.append(f" {ml}\n", style="dim")+ label, label_style, body_style, indent = role_styles[role]+ lines.append(label, style=label_style)+ first, *rest = text.splitlines() or [""] # first line inline, rest indented+ lines.append(first + "\n", style=body_style)+ for ml in rest:+ lines.append(f"{indent}{ml}\n", style=body_style)if i < len(entries) - 1:lines.append("") # small gapdiff --git a/hermes_cli/cli_billing_mixin.py b/hermes_cli/cli_billing_mixin.pyindex b0ec388a3b4..23e0ce24c08 100644--- a/hermes_cli/cli_billing_mixin.py+++ b/hermes_cli/cli_billing_mixin.py@@ -1,42 +1,137 @@-"""Billing and subscription handlers for the interactive CLI (god-file decomposition).--This module hosts the Nous billing/subscription methods lifted out of-``cli.py``'s ``HermesCLI`` class. ``HermesCLI`` inherits-``CLIBillingMixin`` so every ``self.<handler>`` call resolves unchanged-via the MRO — behavior-neutral apart from focused billing fixes.--Import discipline mirrors ``hermes_cli.cli_commands_mixin``:- * Neutral, non-cyclic dependencies are imported at module top level below.- * cli.py-internal symbols (the ``_cprint``/``_b``/``_d`` helpers and- display constants) are imported LAZILY inside each method via- ``from cli import ...``. The mixin never imports ``cli`` at module load- time, avoiding the cycle created when ``cli.py`` imports this mixin.+"""Billing and subscription handlers for the interactive CLI, lifted out of ``cli.py``.++``HermesCLI`` inherits ``CLIBillingMixin`` so every ``self.<handler>`` resolves via the MRO.+cli.py-internal symbols (``_cprint``/``_b``/``_d``, display constants) are imported LAZILY+inside each method — the mixin never imports ``cli`` at module load time (import cycle)."""from __future__ import annotations+_RULE = "─" * 41++# Poll `failed` reasons → copy (default: generic line carrying the raw reason).+_CHARGE_FAILED_COPY = {+ "authentication_required": " 🔴 Your bank requires verification (3DS). Complete it on the portal to finish this purchase.",+ "payment_method_expired": " 🔴 Your card has expired. Update it on the portal.",+ "card_declined": " 🔴 Your card was declined. Try another card on the portal.",+}++# Submit-time BillingError codes with a fixed copy (no payload/type inspection).+_CHARGE_ERROR_COPY = {+ "no_payment_method": " 💳 No card on file — top up and manage billing on the portal.",+ "cli_billing_disabled": " Remote spending is off for this account — a billing admin can turn it on from the portal's Hermes Agent page.",+ "role_required": " Adding funds needs an org admin/owner. Ask an admin, or manage on the portal.",+ "idempotency_conflict": " 🔴 That charge key was already used for a different amount. Start a fresh top-up.",+}+_CHARGE_ERROR_COPY["remote_spending_disabled"] = _CHARGE_ERROR_COPY["cli_billing_disabled"]++# Upgrade 2xx `status` → (line, echo recoveryUrl as "Portal:"). Missing status → ambiguous.+_UPGRADE_STATUS_COPY = {+ "requires_action": (" 🟡 This upgrade needs extra verification (3DS). Finish it on the portal.", True),+ "payment_failed": (" 🔴 Your card was declined. Update your payment method on the portal and try again.", True),+}++_ALLOW_REMOTE_SPENDING_CHOICES = [+ ("yes", "Allow Remote Spending", "open your browser to authorize"),+ ("no", "Not now", "cancel"),+]class CLIBillingMixin:"""Mixin holding interactive-CLI billing and subscription handlers."""+ # ------------------------------------------------------------------+ # Shared helpers+ # ------------------------------------------------------------------++ def _modal_choice(self, title, detail, choices):+ """Run the choice modal and return the normalized choice value."""+ raw = self._prompt_text_input_modal(title=title, detail=detail, choices=choices)+ return self._normalize_slash_confirm_choice(raw, choices)++ def _print_org_line(self, state) -> None:+ """Dim ``Org: <name> · <Role>`` line (skipped when there is no org)."""+ from cli import _cprint, _d+ if state.org_name:+ role = (state.role or "").title()+ _org_line = f"Org: {state.org_name}{f' · {role}' if role else ''}"+ _cprint(f" {_d(_org_line)}")++ def _try_usage_model(self):+ """Shared dollar usage model (the only source with top-up dollars); None on any failure."""+ try:+ from agent.billing_usage import build_usage_model+ return build_usage_model()+ except Exception:+ return None++ def _usage_bar_lines(self, usage, plan_name) -> list:+ """The plan + top-up dollar bars as ready-to-print lines (filled = remaining); [] when+ nothing to draw. The caller picks its print fn — block ordering differs per surface+ (``_cprint`` vs ``print`` under patch_stdout). One source of truth for /usage, /subscription, /topup."""+ lines: list = []+ pb = getattr(usage, "plan_bar", None) if usage else None+ if pb is not None and pb.total_usd > 0:+ filled = max(0, min(10, round(pb.fill_fraction * 10)))+ bar = ("█" * filled) + ("░" * (10 - filled))+ pct_s = f" · {pb.pct_used}% used" if pb.pct_used is not None else ""+ label = (plan_name or "plan").ljust(8)[:8]+ lines.append(f" {label}[{bar}] ${pb.remaining_usd:,.2f} left of ${pb.total_usd:,.2f}{pct_s}")+ tb = getattr(usage, "topup_bar", None) if usage else None+ if tb is not None and tb.remaining_usd > 0:+ lines.append(f" {'top-up'.ljust(8)}[{'█' * 10}] ${tb.remaining_usd:,.2f} · never expires")+ return lines++ def _print_total_spendable(self, usage, print_fn) -> None:+ if usage and getattr(usage, "has_topup", False) and getattr(usage, "total_spendable_usd", None) is not None:+ print_fn(f" Total spendable: ${usage.total_spendable_usd:,.2f}")++ def _step_up_remote_spending(self, *, explain, noninteractive_msg, declined_msg, not_granted_msg) -> bool:+ """The "! One-time setup" step-up: explain, confirm in the modal, then run the browser+ device-flow via ``step_up_nous_billing_scope``. Returns True only when the scope was granted;+ every refusal/failure path has already printed its own line."""+ from cli import _cprint, _d+ print()+ print(" ! One-time setup")+ _cprint(f" {_d(explain)}")+ if not self._app:+ print(noninteractive_msg)+ return False+ choice = self._modal_choice("Allow Remote Spending", "Opens your browser to authorize this terminal.", _ALLOW_REMOTE_SPENDING_CHOICES)+ if choice != "yes":+ print(declined_msg)+ return False+ print(" Opening your browser to allow Remote Spending…")+ try:+ from hermes_cli.auth import step_up_nous_billing_scope+ granted = step_up_nous_billing_scope(open_browser=True)+ except Exception as exc:+ print(f" Couldn't allow Remote Spending: {exc}")+ return False+ if not granted:+ print(not_granted_msg)+ return False+ return True++ def _print_portal_line(self, exc) -> None:+ """``Portal: <url>`` via _cprint when the error carries a portal deep-link."""+ from cli import _cprint+ _url = getattr(exc, "portal_url", None) if exc is not None else None+ if _url:+ _cprint(f" Portal: {_url}")++ # ------------------------------------------------------------------+ # /usage — Nous balance block+ # ------------------------------------------------------------------+def _print_nous_credits_block(self) -> bool:- """Print the Nous dollar balance block (two-bar view) when a Nous account- is logged in. Returns True if it printed anything.-- Prefers the shared dollar usage model (``agent.billing_usage`` — two-bar- plan/top-up view, dollars-only, the /usage + /subscription source of- truth). Falls back to the legacy ``nous_credits_lines`` text only when the- model is unavailable. Agent-independent (a portal fetch gated on "a Nous- account is logged in"), so /usage shows the block even in the TUI- slash-worker subprocess that resumes WITHOUT a live agent. Fail-open and- wall-clock-bounded; honors HERMES_DEV_CREDITS_FIXTURE for offline testing.- """+ """Print the Nous dollar balance block (two-bar view) when a Nous account is logged in;+ True if anything printed. Prefers the shared dollar model (``agent.billing_usage``, the+ /usage + /subscription source of truth), falling back to legacy ``nous_credits_lines`` text.+ Agent-independent so the TUI slash-worker (no live agent) still shows it. Fail-open."""from cli import _cprint, _b, _d-try:from agent.billing_usage import build_usage_model, format_renews-usage = build_usage_model()except Exception:usage = None@@ -51,32 +146,23 @@ class CLIBillingMixin:print()_cprint(f" {_b(f'Plan: {plan}{renews}')}")printed_any = True-- # All lines below go through _cprint (same renderer as the Plan line) so- # ordering is deterministic: raw print() and _cprint() flush to different- # buffers under patch_stdout and interleave nondeterministically (the bar- # would race above/below the Plan line across states). Keep one path.+ # Everything below goes through _cprint like the Plan line: raw print() and _cprint()+ # flush to different buffers under patch_stdout and would interleave nondeterministically.for _bar_ln in self._usage_bar_lines(usage, usage.plan_name):_cprint(_bar_ln)printed_any = True- if usage.has_topup and usage.total_spendable_usd is not None:- _cprint(f" Total spendable: ${usage.total_spendable_usd:,.2f}")-+ self._print_total_spendable(usage, _cprint)if usage.status == "free":_cprint(f" {_d('> Free · free models only. Run /subscription to reach paid models.')}")printed_any = Trueelif usage.status == "low":_amt = f"${usage.total_spendable_usd:,.2f}" if usage.total_spendable_usd is not None else "under $5"- _low = f"! Low balance · {_amt} left. Run /topup or /subscription."- _cprint(f" {_low}")+ _cprint(f" ! Low balance · {_amt} left. Run /topup or /subscription.")printed_any = True-if printed_any:return True- # Fallback: legacy text lines (only when the model is unavailable).from agent.account_usage import nous_credits_lines-lines = nous_credits_lines()if not lines:return False@@ -86,38 +172,23 @@ class CLIBillingMixin:return Truedef _print_usage_cta(self) -> None:- """Print the `/usage` call-to-action pointing at /subscription + /topup.-- Mirrors the TUI's ``USAGE_CTA`` (``session.ts``) so every surface ends a- usage read with the same nudge. Only called when a Nous account is logged- in (the balance block printed), since both commands are Nous-account only.- """+ """The `/usage` call-to-action; mirrors the TUI's ``USAGE_CTA``. Only printed when a Nous+ account is logged in (both commands are Nous-account only)."""from cli import _cprint, _d-_cprint(f" {_d('Run /subscription to change plan · /topup to add to your balance')}")# ------------------------------------------------------------------- # /subscription — view plan + change it in the browser (CLI surface)+ # /subscription — view plan + change it (CLI surface)# ------------------------------------------------------------------def _show_subscription(self):- """`/subscription` (alias `/upgrade`) — view the Nous plan + browser hand-off.-- The CLI mirror of the TUI ``SubscriptionOverlay``: a read of the current- plan, this cycle's subscription credits, renewal date, and the plans you- could switch to — then a deep-link to NAS's own ``/manage-subscription``- page (NOT the Stripe portal; that page routes upgrade→Checkout /- downgrade→scheduled internally). The terminal NEVER charges for a- subscription. Fail-open: logged-out / portal hiccup degrades to a clear- message, never a crash. Mirrors ``_show_billing``- discipline for the interactive-vs-text split.- """+ """`/subscription` (alias `/upgrade`) — CLI mirror of the TUI ``SubscriptionOverlay``.+ Deep-links to NAS's own ``/manage-subscription`` page (NOT the Stripe portal). The terminal+ NEVER charges for a subscription. Fail-open: logged-out / portal hiccup → clear message."""from cli import _cprint, _b, _d-from agent.subscription_view import build_subscription_state, subscription_manage_urlstate = build_subscription_state()-if not state.logged_in:print()if state.error:@@ -127,15 +198,11 @@ class CLIBillingMixin:print(" Run `hermes portal` to log in, then /subscription.")return- # Team context: no personal plan — teams run on a shared balance.- if state.context == "team":+ if state.context == "team": # no personal plan — teams run on a shared balanceprint()_cprint(f" ⚕ {_b('Team subscription')}")- print(f" {'─' * 41}")- if state.org_name:- role = (state.role or "").title()- _org_line = f"Org: {state.org_name}{f' · {role}' if role else ''}"- _cprint(f" {_d(_org_line)}")+ print(f" {_RULE}")+ self._print_org_line(state)org = state.org_name or "a team org"print(f" This terminal is connected to {org}. Teams run on a shared")print(" balance · use /topup to add funds.")@@ -145,37 +212,22 @@ class CLIBillingMixin:self._subscription_overview(state, subscription_manage_url(state))def _subscription_overview(self, state, manage_url):- """Print the plan read block, then the browser hand-off to manage it.-- Dollars-only (no "credits") — mirrors the TUI overlay: a status line, the- shared two-bar dollar usage view (plan + top-up) with the plan name on- the bar, and state-matched free/low nudges. No in-terminal tier picker —- the only action is managing the subscription on the portal.- """+ """Print the plan read block (dollars-only, two-bar view, state-matched nudges), then the+ action: portal hand-off for members / non-interactive, catalog for Free, change menu for paid admins."""from cli import _cprint, _b, _d-- # Shared dollar usage model (the only source with top-up dollars).from agent.billing_usage import format_renews- try:- from agent.billing_usage import build_usage_model-- usage = build_usage_model()- except Exception:- usage = None+ usage = self._try_usage_model()c = state.currentis_free = not (c and c.tier_id)can_change = state.can_change_plan-plan_name = (c.tier_name or c.tier_id) if c else (usage.plan_name if usage else None)u_status = getattr(usage, "status", None) if usage else None- view_only = not can_changerenews_display = getattr(usage, "renews_display", None) if usage else Noneif not renews_display and c and c.cycle_ends_at:renews_display = format_renews(c.cycle_ends_at)- # Status line — dollars-only, with a "→ Plus" echo of a pending change so- # the headline itself carries a scheduled downgrade/cancellation.+ # Status line carries a pending change ("→ Plus" / "→ cancels") so the headline itself flags it._flip = ""if c and c.cancel_at_period_end:_flip = " → cancels"@@ -184,24 +236,20 @@ class CLIBillingMixin:if not plan_name:status = "Plan: Free · free models only"elif usage is not None and u_status == "low" and usage.total_spendable_usd is not None:- _tot = f"${usage.total_spendable_usd:,.2f}"- status = f"Plan: {plan_name}{_flip} · {_tot} left"+ status = f"Plan: {plan_name}{_flip} · ${usage.total_spendable_usd:,.2f} left"else:_spend = getattr(usage, "total_spendable_usd", None) if usage else None_left = f" · ${_spend:,.2f} left" if _spend is not None else ""- _tail = " · view only" if view_only else (f" · renews {renews_display}" if renews_display else "")+ _tail = " · view only" if not can_change else (f" · renews {renews_display}" if renews_display else "")status = f"Plan: {plan_name}{_flip}{_left}{_tail}"- # Lead with the scheduled change (cancel > downgrade) so it can't read as- # "nothing happened" — mirrors the TUI banner. All-`_cprint` (blanks- # included) so the block orders deterministically even when piped.+ # Lead with the scheduled change (cancel > downgrade) so it can't read as "nothing happened".+ # All-_cprint (blanks included) so the block orders deterministically even when piped._trans = Noneif c and c.cancel_at_period_end:- _when = format_renews(c.cancellation_effective_at) or "the end of the billing period"- _trans = ((c.tier_name or "your plan"), "cancels", _when)+ _trans = ((c.tier_name or "your plan"), "cancels", format_renews(c.cancellation_effective_at) or "the end of the billing period")elif c and c.pending_downgrade_tier_name:- _when = format_renews(c.pending_downgrade_at) or "the end of the cycle"- _trans = ((c.tier_name or "your plan"), c.pending_downgrade_tier_name, _when)+ _trans = ((c.tier_name or "your plan"), c.pending_downgrade_tier_name, format_renews(c.pending_downgrade_at) or "the end of the cycle")_cprint("")if _trans:_from, _to, _when = _trans@@ -211,125 +259,78 @@ class CLIBillingMixin:_cprint("")_cprint(f" ⚕ {_b(status)}")- print(f" {'─' * 41}")-- # Two-bar dollar usage view — plan name labels the plan bar.+ print(f" {_RULE}")for _bar_ln in self._usage_bar_lines(usage, plan_name):print(_bar_ln)- if usage and getattr(usage, "has_topup", False) and getattr(usage, "total_spendable_usd", None) is not None:- print(f" Total spendable: ${usage.total_spendable_usd:,.2f}")-- # State-matched nudge (free upsell / low alert; healthy stays silent).+ self._print_total_spendable(usage, print)if is_free:_cprint(f" {_d('> Paid models need a subscription. Start one to reach them.')}")elif u_status == "low":_amt = f"${usage.total_spendable_usd:,.2f}" if usage is not None and usage.total_spendable_usd is not None else "under $5"- _low = f"! Low balance · {_amt} left. Top up or upgrade before a mid-run cutoff."- _cprint(f" {_low}")+ _cprint(f" ! Low balance · {_amt} left. Top up or upgrade before a mid-run cutoff.")+ self._print_org_line(state)+ print(f" {_RULE}")- if state.org_name:- role = (state.role or "").title()- _org_line = f"Org: {state.org_name}{f' · {role}' if role else ''}"- _cprint(f" {_d(_org_line)}")- print(f" {'─' * 41}")-- # ── Actions ── Members (non-admin) and non-interactive contexts fall back- # to the portal hand-off; a paid admin/owner gets the full in-terminal- # change flow (parity with the TUI overlay).if not can_change:print()_cprint(f" {_d('Plan changes need an org admin/owner.')}")if manage_url:print(f" Manage on portal: {manage_url}")return-- if not getattr(self, "_app", None):- # Non-interactive (TUI slash-worker / piped): the modal can't run.+ if not self._app: # non-interactive (TUI slash-worker / piped): the modal can't runprint()if manage_url:print(f" Manage your subscription: {manage_url}")print(" Open it in your browser, then re-run /subscription.")return-- if is_free:- # Starting a NEW subscription needs a fresh card — deep-link only.- # Show the plan catalog, let the user pick, and carry ``plan=<tier_id>``- # into the portal deep-link so it preselects the chosen plan.+ if is_free: # a NEW subscription needs a fresh card → catalog + portal deep-link onlyself._subscription_free_catalog(state, manage_url)return-- # Paid + admin/owner + interactive → the in-terminal change flow.self._subscription_change_menu(state, manage_url)def _open_url_in_browser(self, url: str) -> bool:- """Open ``url`` in a REAL graphical browser; return whether one opened.-- The one opener behind every "open the portal" path in this mixin. Applies- the same console-browser / remote-session guard the device-code auth flows- use (``hermes_cli.auth``): ``webbrowser.open()`` returns ``True`` even when- it launched a text-mode browser (w3m/lynx over SSH) that hijacks the TTY,- so we refuse those and let the caller print the URL instead. Returns- ``False`` on any guard refusal or open failure, ``True`` only when a real- graphical browser launched.- """+ """Open ``url`` in a REAL graphical browser; the one opener behind every portal hand-off.+ Applies the console-browser / remote-session guard from ``hermes_cli.auth``:+ ``webbrowser.open()`` returns True even for a text-mode browser (w3m/lynx over SSH) that+ hijacks the TTY, so those are refused and the caller prints the URL instead."""if not url:return Falsetry:from hermes_cli.auth import _can_open_graphical_browser, _is_remote_session-if _is_remote_session() or not _can_open_graphical_browser():return Falseexcept Exception:- # Guard unavailable → fall through to a plain best-effort open.- pass+ pass # guard unavailable → plain best-effort opentry:import webbrowser-return bool(webbrowser.open(url))except Exception:return Falsedef _subscription_free_catalog(self, state, manage_url):- """Free + admin/owner + interactive: print the plan catalog, pick one, then- open the portal manage-subscription deep-link with ``plan=<tier_id>``.-- The catalog mirrors the TUI Free rows (name · $/mo · $credits/mo, from the- same ``tiers[]`` data via the shared ``selectable_tiers`` / ``format_tier_row``- helpers). Monthly credits are DOLLARS — rendered ``$X credits/mo`` (hidden- when absent/zero). Starting a NEW subscription needs a fresh card, so the- only action is the portal hand-off (the terminal never charges here); the- picked tier rides along as ``plan=`` so the portal preselects it.- """+ """Free + admin/owner + interactive: print the plan catalog, pick one, open the portal+ manage-subscription deep-link with ``plan=<tier_id>`` so it preselects the plan.+ Monthly credits are DOLLARS. The terminal never charges here (a new sub needs a fresh card)."""from cli import _cprint, _b, _d-- from agent.subscription_view import (- format_tier_row,- selectable_tiers,- subscription_manage_url,- )+ from agent.subscription_view import format_tier_row, selectable_tiers, subscription_manage_urltiers = selectable_tiers(state)if not tiers:- # No catalog to show → the plain portal hand-off (no plan= to append).self._subscription_open_portal(state, manage_url, verb="Start a subscription")returnprint()_cprint(f" ⚕ {_b('Choose a plan')}")- print(f" {'─' * 41}")+ print(f" {_RULE}")for i, t in enumerate(tiers, 1):print(f" {i}. {format_tier_row(t)}")_cprint(f" {_d('Starting a subscription opens the portal to add your card.')}")choices = [(t.tier_id, format_tier_row(t), f"start {t.name} on the portal") for t in tiers]choices.append(("cancel", "Cancel", "do nothing"))- raw = self._prompt_text_input_modal(- title="Start a subscription",- detail="Pick a plan to open it on the portal.",- choices=choices,- )- # The rows are printed numbered, so accept a bare number as a pick (the- # shared normalizer only knows the confirm-dialog digit aliases).+ raw = self._prompt_text_input_modal(title="Start a subscription", detail="Pick a plan to open it on the portal.", choices=choices)+ # Rows are printed numbered → accept a bare number as a pick (the shared normalizer+ # only knows the confirm-dialog digit aliases)._digit = (raw or "").strip()if _digit.isdigit() and 1 <= int(_digit) <= len(tiers):choice = tiers[int(_digit) - 1].tier_id@@ -338,8 +339,6 @@ class CLIBillingMixin:if not choice or choice == "cancel":print(" 🟡 Cancelled. No plan started.")return- # Numbered pick → open the portal deep-link directly, with the picked tier's- # plan= param so the portal preselects it (spec: pick → opens the portal).tier_url = subscription_manage_url(state, tier_id=choice) or manage_urlif not tier_url:_cprint(f" {_d('No manage URL available — is your portal configured?')}")@@ -349,15 +348,12 @@ class CLIBillingMixin:if self._open_url_in_browser(tier_url):print(f" Opening the portal to start {label}…")else:- # No graphical browser (headless / SSH / console browser): print the- # link so it stays actionable.print(f" Open this URL to start {label}: {tier_url}")print(" Finish in your browser, then re-run /subscription.")def _subscription_open_portal(self, state, manage_url, *, verb="Manage your subscription"):"""Open / copy the manage-subscription URL — the portal hand-off."""from cli import _cprint, _d-if not manage_url:print()_cprint(f" {_d('No manage URL available — is your portal configured?')}")@@ -368,8 +364,7 @@ class CLIBillingMixin:("copy", "Copy link", "copy the manage-subscription URL to your clipboard"),("cancel", "Cancel", "do nothing"),]- raw = self._prompt_text_input_modal(title=verb, detail="", choices=choices)- choice = self._normalize_slash_confirm_choice(raw, choices)+ choice = self._modal_choice(verb, "", choices)if choice == "open":if not self._open_url_in_browser(manage_url):print(f" Open this URL: {manage_url}")@@ -389,10 +384,8 @@ class CLIBillingMixin:c = state.currenthas_pending = bool(c and (c.cancel_at_period_end or c.pending_downgrade_tier_name))keep_name = (c.tier_name if c else None) or "your plan"- # When a change is already scheduled, undo is the most likely next intent →- # promote it first (parity with the TUI). The Close row uses value "close"- # (not "cancel") so typing the word "cancel" — which the alias table would- # map to a Close row — can't be confused with "Cancel subscription".+ # A scheduled change makes undo the likeliest intent → promote it first. The Close row uses+ # value "close" (not "cancel") so typing "cancel" can't be confused with "Cancel subscription".if has_pending:choices = [("keep", f"Keep {keep_name} (undo the scheduled change)", "cancel the pending change"),@@ -405,8 +398,7 @@ class CLIBillingMixin:]choices.append(("portal", "Manage on portal", "open the billing page in your browser"))choices.append(("close", "Close", "do nothing"))- raw = self._prompt_text_input_modal(title="Manage your subscription", detail="", choices=choices)- choice = self._normalize_slash_confirm_choice(raw, choices)+ choice = self._modal_choice("Manage your subscription", "", choices)if choice == "change":self._subscription_pick_tier(state)elif choice == "keep":@@ -419,13 +411,11 @@ class CLIBillingMixin:print(" 🟡 Closed. No plan change.")def _subscription_pick_tier(self, state):- """Tier picker → preview → confirm (mirrors the TUI picker screen)."""+ """Tier picker → preview → confirm (mirrors the TUI picker screen). Selectable = enabled paid+ tiers other than current (dropping to free is a cancellation, on the change menu)."""from agent.subscription_view import format_tier_row, is_upgrade, selectable_tiersc = state.current- # Selectable = enabled paid tiers other than current (free/no-sub excluded;- # dropping to free is a cancellation, on the change menu). Sorted by price.- # Shared with the Free catalog + blocked-preview branch (one derivation).selectable = selectable_tiers(state)if not selectable:print(" No other plans are available to switch to right now.")@@ -435,12 +425,7 @@ class CLIBillingMixin:direction = "upgrade" if is_upgrade(state, t.tier_id) else "downgrade"choices.append((t.tier_id, f"{format_tier_row(t)} · {direction}", f"switch to {t.name}"))choices.append(("cancel", "Back", "do nothing"))- raw = self._prompt_text_input_modal(- title="Change plan",- detail=f"Current: {c.tier_name if c else 'Free'}. Pick a plan to preview the effect.",- choices=choices,- )- choice = self._normalize_slash_confirm_choice(raw, choices)+ choice = self._modal_choice("Change plan", f"Current: {c.tier_name if c else 'Free'}. Pick a plan to preview the effect.", choices)if not choice or choice == "cancel":print(" 🟡 Cancelled. No plan change.")return@@ -448,14 +433,10 @@ class CLIBillingMixin:def _subscription_preview_and_confirm(self, state, tier_id, *, allow_stepup=True):"""Preview the change (chargeless quote), show the effect, then confirm+apply.-- ``allow_stepup=False`` (a post-grant replay) declines a second step-up on a- repeated scope denial so the flow can't re-prompt/re-open the browser in a- loop.- """+ ``allow_stepup=False`` (a post-grant replay) declines a second step-up on a repeated scope+ denial so the flow can't re-prompt/re-open the browser in a loop."""from cli import _cprint, _b, _d-- from agent.subscription_view import subscription_change_preview_from_payload+ from agent.subscription_view import is_upgrade, subscription_change_preview_from_payload, subscription_manage_urlfrom hermes_cli.nous_billing import BillingError, BillingScopeRequired, post_subscription_preview_cprint(f" {_d('Checking the change…')}")@@ -478,14 +459,9 @@ class CLIBillingMixin:_cprint(f" {_d(f'You are already on {target} — nothing to change.')}")returnif effect not in ("charge_now", "scheduled"):- # blocked OR an unknown/unexpected effect → fail SAFE (never schedule a- # real change on an unrecognized string, unlike a bare `else`), and- # re-offer the portal hand-off like the TUI's blocked branch. The picked- # tier rides along as plan= only for an UPGRADE hand-off — new-sub /- # upgrade deep-links carry the plan; downgrades stay native (binding- # ruling), so a blocked downgrade keeps the generic manage link.- from agent.subscription_view import is_upgrade, subscription_manage_url-+ # blocked OR unknown effect → fail SAFE (never schedule a real change on an unrecognized+ # string) and re-offer the portal. plan= rides along only for an UPGRADE hand-off —+ # downgrades stay native, so a blocked downgrade keeps the generic manage link._plan = tier_id if is_upgrade(state, tier_id) else None_cprint(f" 🟡 {p.reason or 'This change cannot be confirmed here — manage it on the portal.'}")_mu = subscription_manage_url(state, tier_id=_plan)@@ -499,14 +475,11 @@ class CLIBillingMixin:_cprint(f" Upgrade to {target}. You will be charged {_amt} now (prorated).")else:_cprint(f" Upgrade to {target}. You will be charged the prorated amount now.")- # Best-effort: name the exact card (billing.state), but only when the- # resolver rung matches what a subscription charge actually uses- # (subPin / customerDefault — Stripe's own precedence). Any failure or- # older NAS → the generic line stands.+ # Best-effort: name the exact card, but only when the resolver rung matches what a+ # subscription charge actually uses (subPin / customerDefault — Stripe's precedence)._card_line = "The card on your subscription will be charged."try:from agent.billing_view import build_billing_state-_bs = build_billing_state(timeout=6.0)_c = _bs.card if _bs.logged_in else Noneif _c is not None and _c.resolved_via in ("subPin", "customerDefault"):@@ -516,8 +489,7 @@ class CLIBillingMixin:_cprint(f" {_d(_card_line)}")pay_label = f"Pay {_amt} & upgrade now" if _amt else "Upgrade now (prorated charge)"action = ("upgrade", tier_id)- # The money-moving row is NOT the default — a bare Enter hits "Go back",- # so a single stray keystroke can't charge the card.+ # The money-moving row is NOT the default — a bare Enter hits "Go back", so a stray keystroke can't charge.confirm_choices = [("cancel", "Go back", "do not charge"),("yes", pay_label, "charge + upgrade now"),@@ -534,8 +506,7 @@ class CLIBillingMixin:]if p.monthly_credits_delta:_cprint(f" {_d(f'Monthly credits change: {p.monthly_credits_delta}.')}")- raw = self._prompt_text_input_modal(title=pay_label, detail="", choices=confirm_choices)- if self._normalize_slash_confirm_choice(raw, confirm_choices) != "yes":+ if self._modal_choice(pay_label, "", confirm_choices) != "yes":print(" 🟡 Cancelled. No plan change.")returnself._subscription_apply(state, action, allow_stepup=allow_stepup)@@ -543,7 +514,6 @@ class CLIBillingMixin:def _subscription_confirm_cancel(self, state):"""Confirm, then schedule a cancellation at period end."""from cli import _cprint, _b, _d-from agent.billing_usage import format_renewsc = state.current@@ -556,39 +526,26 @@ class CLIBillingMixin:("yes", "Cancel subscription", "schedule cancellation at period end"),("cancel", "Go back", "keep your plan"),]- raw = self._prompt_text_input_modal(title="Cancel subscription?", detail="", choices=confirm_choices)- if self._normalize_slash_confirm_choice(raw, confirm_choices) != "yes":+ if self._modal_choice("Cancel subscription?", "", confirm_choices) != "yes":print(" 🟡 Cancelled. Your plan is unchanged.")returnself._subscription_apply(state, ("cancel", None))def _subscription_apply(self, state, action, idempotency_key=None, *, allow_stepup=True):- """Run the mutation for `action`, handling the scope step-up + the result.-- `action` is one of ("upgrade", tier_id) / ("schedule", tier_id) /- ("cancel", None) / ("resume", None). insufficient_scope routes to the- step-up and replays; the upgrade idempotency key is reused across the replay.- ``allow_stepup=False`` (a post-grant replay) declines a second step-up on a- repeated scope denial so the flow can't re-prompt/re-open the browser in a loop.- """+ """Run the mutation for `action` — ("upgrade"|"schedule", tier_id) / ("cancel"|"resume", None) —+ handling the scope step-up + the result. insufficient_scope routes to the step-up and replays;+ the upgrade idempotency key is reused across the replay. ``allow_stepup=False`` (post-grant+ replay) declines a second step-up so the flow can't re-prompt/re-open the browser in a loop."""from cli import _cprint, _d, _DIM, _RST-from hermes_cli.nous_billing import (- BillingError,- BillingTransient,- BillingRemoteSpendingRevoked,- BillingScopeRequired,- BillingSessionRevoked,- delete_subscription_pending_change,- post_subscription_upgrade,- put_subscription_pending_change,+ BillingError, BillingTransient, BillingRemoteSpendingRevoked, BillingScopeRequired, BillingSessionRevoked,+ delete_subscription_pending_change, post_subscription_upgrade, put_subscription_pending_change,)kind, arg = actionkey = Noneif kind == "upgrade":from agent.billing_view import new_idempotency_key-key = idempotency_key or new_idempotency_key()try:if kind == "upgrade":@@ -597,23 +554,18 @@ class CLIBillingMixin:except BillingScopeRequired:raise # a scope denial rejects BEFORE charging → route to the step-upexcept (BillingTransient, BillingSessionRevoked, BillingRemoteSpendingRevoked) as exc:- # Deterministic PRE-charge typed rejections (429 / 401 / 403) never- # reached Stripe → surface the CORRECT recovery (retry_after / re-login /- # reconnect), NOT the "maybe charged" ambiguity copy.+ # Deterministic PRE-charge rejections (429/401/403) never reached Stripe →+ # the correct recovery copy, NOT the "maybe charged" ambiguity.self._subscription_render_error(state, exc)returnexcept BillingError as exc:_status = getattr(exc, "status", None)_code = getattr(exc, "error", None)if _code in ("network_error", "endpoint_unavailable") or _status is None or _status >= 500:- # Genuinely INDETERMINATE — transport / unparseable 2xx / a 5xx the- # server hit mid-request: NAS may have already prorated + charged.- # Steer to a re-check, never a blind retry (a fresh key can't dedup →- # a real second charge).+ # Genuinely INDETERMINATE (transport / unparseable 2xx / 5xx): NAS may already have+ # charged. Steer to a re-check, never a blind retry (a fresh key can't dedup).self._subscription_render_upgrade_ambiguous(exc)- else:- # A deterministic 4xx (role_required / no_payment_method / …) → the- # normal error copy, not "maybe charged".+ else: # deterministic 4xx (role_required / no_payment_method / …)self._subscription_render_error(state, exc)returnstatus = res.get("status")@@ -623,16 +575,12 @@ class CLIBillingMixin:_cprint(f" {_DIM}✓ You are already on {name}.{_RST}")elif status == "upgraded":_cprint(f" {_DIM}✓ Upgraded to {name}. Your new monthly credits land in a moment.{_RST}")- elif status == "requires_action":- _cprint(" 🟡 This upgrade needs extra verification (3DS). Finish it on the portal.")- if _url:- _cprint(f" Portal: {_url}")- elif status == "payment_failed":- _cprint(" 🔴 Your card was declined. Update your payment method on the portal and try again.")- if _url:+ elif status in _UPGRADE_STATUS_COPY:+ line, echo_url = _UPGRADE_STATUS_COPY[status]+ _cprint(line)+ if echo_url and _url:_cprint(f" Portal: {_url}")- else:- # Unknown / absent 2xx status → also ambiguous, not a flat failure.+ else: # unknown / absent 2xx status → also ambiguous, not a flat failureself._subscription_render_upgrade_ambiguous(None)returnif kind == "schedule":@@ -654,58 +602,27 @@ class CLIBillingMixin:self._subscription_render_error(state, exc)def _subscription_handle_scope_required(self, state, *, retry, idempotency_key=None):- """insufficient_scope → allow remote spending (step-up), then replay `retry`.-- Mirrors _billing_handle_scope_required: the classic CLI calls- step_up_nous_billing_scope directly (it opens the browser + blocks), then- replays the held preview/mutation so the user never re-runs the command.- """- from cli import _cprint, _d, _DIM, _RST-- print()- print(" ! One-time setup")- _cprint(f" {_d('To change your plan from the terminal, allow Remote Spending once. It opens your browser to authorize, then your change picks up right here.')}")- if not getattr(self, "_app", None):- print(" Run `hermes portal` and allow Remote Spending, then re-run /subscription.")- return- confirm_choices = [- ("yes", "Allow Remote Spending", "open your browser to authorize"),- ("no", "Not now", "cancel"),- ]- raw = self._prompt_text_input_modal(- title="Allow Remote Spending",- detail="Opens your browser to authorize this terminal.",- choices=confirm_choices,+ """insufficient_scope → allow remote spending (step-up), then replay `retry` ONCE so the+ user never re-runs the command."""+ from cli import _cprint, _DIM, _RST+ granted = self._step_up_remote_spending(+ explain="To change your plan from the terminal, allow Remote Spending once. It opens your browser to authorize, then your change picks up right here.",+ noninteractive_msg=" Run `hermes portal` and allow Remote Spending, then re-run /subscription.",+ declined_msg=" No change made. Allow Remote Spending when you're ready.",+ not_granted_msg=" Couldn't allow Remote Spending — an org admin or owner has to approve it for this org.",)- if self._normalize_slash_confirm_choice(raw, confirm_choices) != "yes":- print(" No change made. Allow Remote Spending when you're ready.")- return- print(" Opening your browser to allow Remote Spending…")- try:- from hermes_cli.auth import step_up_nous_billing_scope-- granted = step_up_nous_billing_scope(open_browser=True)- except Exception as exc:- print(f" Couldn't allow Remote Spending: {exc}")- returnif not granted:- print(" Couldn't allow Remote Spending — an org admin or owner has to approve it for this org.")return_cprint(f" {_DIM}✓ Remote Spending allowed.{_RST}")- # Bust the 30s token cache so the replay uses the freshly-scoped token. The- # cache still holds the pre-grant unscoped token, and _request only busts it- # on a 401 (not a 403 scope denial) — without this, the replay would 403- # again and (before the allow_stepup guard) re-prompt in a loop.+ # Bust the 30s token cache: it still holds the pre-grant unscoped token and _request only+ # busts on a 401 (not a 403 scope denial) — without this the replay would 403 again.try:from hermes_cli import nous_billing as _nb-_nb.invalidate_cached_token()except Exception:pass- # Re-fetch fresh state, then replay the held action ONCE (allow_stepup=False- # so a repeated scope denial can't re-enter the step-up).+ # Re-fetch fresh state, then replay the held action ONCE (allow_stepup=False).from agent.subscription_view import build_subscription_state-try:fresh = build_subscription_state()except Exception:@@ -719,54 +636,35 @@ class CLIBillingMixin:def _subscription_render_error(self, state, exc):"""Render a subscription BillingError (a lighter _billing_render_charge_error)."""from cli import _cprint-code = getattr(exc, "error", None)msg = str(exc) or "Something went wrong."- if code == "insufficient_scope":- # Defensive: the flow routes scope to the step-up before reaching here.+ if code == "insufficient_scope": # defensive: the flow routes scope to the step-up before here_cprint(" 🟡 Remote Spending isn't allowed yet. Allow it, then retry.")elif code in ("subscription_mutation_rejected", "preview_rejected"):_cprint(f" 🟡 {msg}")else:_cprint(f" 🔴 {msg}")- _url = getattr(exc, "portal_url", None)- if _url:- _cprint(f" Portal: {_url}")+ self._print_portal_line(exc)def _subscription_render_upgrade_ambiguous(self, exc):- """A charge-route failure (transport / timeout / 500 / unknown status) is- AMBIGUOUS — NAS may have already prorated + charged. Steer to a re-check,- never a flat failure that invites a blind retry (mirrors the TUI's- upgradeResult(null) — the CLI can't persist the key across a command re-run,- so a re-check is the safe path)."""+ """A charge-route failure (transport / timeout / 500 / unknown status) is AMBIGUOUS — NAS may+ already have charged. Steer to a re-check, never a flat failure that invites a blind retry+ (the CLI can't persist the key across a command re-run)."""from cli import _cprint, _d-_cprint(" 🟡 Couldn't confirm the upgrade — your card may or may not have been charged.")_cprint(f" {_d('Re-run /subscription to check your plan before trying again.')}")- _url = getattr(exc, "portal_url", None) if exc is not None else None- if _url:- _cprint(f" Portal: {_url}")+ self._print_portal_line(exc)# ------------------------------------------------------------------- # /billing — Phase 2b Remote Spending (CLI surface, all 5 screens)+ # /topup — Remote Spending (CLI surface, all 5 screens)# ------------------------------------------------------------------def _show_billing(self, command: str = "/topup"):- """`/topup` — Remote Spending for Nous (one interactive modal).-- ZERO sub-commands: any argument is ignored. Bare ``/topup`` always- opens the Overview (Screen 1), whose numbered menu is the *only* way to- reach the Buy / Auto-reload / Monthly-limit sub-screens. (Per the unified- UX spec §0.4 — ``/topup buy`` etc. are gone; we don't error on a stray- arg, we just open the menu.)-- Interactive CLI uses the prompt_toolkit modal; non-interactive contexts- (TUI slash-worker / no live app) render text + the portal deep-link, never- prompting (the URL is the affordance), same discipline as ``_show_subscription``.- All money is Decimal end-to-end; the terminal never collects card details.- """+ """`/topup` — Remote Spending for Nous. ZERO sub-commands: any argument is ignored and the+ Overview menu is the only way to reach Buy / Auto-reload / Monthly-limit. Non-interactive+ contexts render text + the portal deep-link, never prompting. All money is Decimal end-to-end;+ the terminal never collects card details."""from cli import _cprint, _d-from agent.billing_view import build_billing_statestate = build_billing_state()@@ -779,8 +677,6 @@ class CLIBillingMixin:_cprint(f" 💳 {_d('Not logged into Nous Portal.')}")print(" Run `hermes portal` to log in, then /topup.")return-- # Any sub-arg is intentionally ignored — always open the menu.self._billing_overview(state)def _billing_portal_hint(self, state, *, reason: str = "") -> None:@@ -793,55 +689,32 @@ class CLIBillingMixin:print(f" Manage on portal: {url}")def _billing_overview(self, state):- """Screen 1 — overview: balance in title, two-bar dollar usage, action menu.-- Dollars-only (no "credits") — mirrors the TUI /topup overlay: balance- leads in the title, the shared plan + top-up bars render below, then the- reordered menu (Add funds first). No scope preflight — remote spending- is discovered reactively when a charge 403s insufficient_scope.- """+ """Screen 1 — balance in title, two-bar dollar usage, action menu (Add funds first).+ No scope preflight — remote spending is discovered reactively when a charge 403s. A missing+ card does NOT gate the overview either: it only matters at CHARGE time (the buy flow hands off)."""from cli import _cprint, _b, _d-from agent.billing_view import format_money- # Shared dollar usage model (plan + top-up bars), same source as /usage.- try:- from agent.billing_usage import build_usage_model-- usage = build_usage_model()- except Exception:- usage = None-+ usage = self._try_usage_model()print()_cprint(f" 💳 {_b(f'Top up · balance {format_money(state.balance_usd)}')}")- if state.org_name:- role = (state.role or "").title()- _org_line = f"Org: {state.org_name}{f' · {role}' if role else ''}"- _cprint(f" {_d(_org_line)}")- print(f" {'─' * 41}")-- # Two-bar dollar usage view (plan name on the plan bar; top-up below).+ self._print_org_line(state)+ print(f" {_RULE}")for _bar_ln in self._usage_bar_lines(usage, getattr(usage, "plan_name", None)):print(_bar_ln)ar = state.auto_reloadif ar is not None:if ar.enabled:- print(- f" Auto-reload: on — below {format_money(ar.threshold_usd)} "- f"→ reload to {format_money(ar.reload_to_usd)}"- )+ print(f" Auto-reload: on — below {format_money(ar.threshold_usd)} → reload to {format_money(ar.reload_to_usd)}")else:print(" Auto-reload: off")- # Card presence at a glance: which card a charge would use (with why —- # "the card on your subscription"), or that none is saved. Only for the- # full-menu case (admin + billing on) — others get the portal note below.- if state.can_change_plan and state.cli_billing_enabled:+ if state.can_change_plan and state.cli_billing_enabled: # card at a glance, full-menu case onlyif state.card is not None:print(f" Card: {state.card.display}")else:_cprint(f" {_d('No saved card on file — “Add funds” walks you through adding one.')}")- print(f" {'─' * 41}")+ print(f" {_RULE}")# Action gating: admin + kill-switch for charge/auto-reload; everyone gets portal.if not state.can_change_plan:@@ -850,54 +723,27 @@ class CLIBillingMixin:returnif not state.cli_billing_enabled:_cprint(f" {_d('Remote spending is off for this org.')}")- self._billing_portal_hint(- state,- reason="A billing admin can turn it on from the portal's Hermes Agent page to add funds here.",- )+ self._billing_portal_hint(state, reason="A billing admin can turn it on from the portal's Hermes Agent page to add funds here.")return-- # A missing card does NOT gate the whole overview — the org may already have- # balance, auto-reload, or a limit to view/manage. The card only matters at- # CHARGE time: "Add funds" -> _billing_buy_flow, which detects no card and- # hands off to the portal there. So always show the full menu below.-- # Non-interactive (slash-worker / no live app): no modal, no sub-command- # advertising — just the portal funnel (the URL is the affordance).- if not getattr(self, "_app", None):+ if not self._app: # non-interactive: no modal, just the portal funnelself._billing_portal_hint(state)return- # One-time vs automatic — the two ways to add funds, the distinction stated- # up front in each first sentence (parity with the desktop revamp's split- # copy). "credits" stays out of the dollars-only /topup surface: "Add funds- # now" carries the one-time meaning without it.+ # One-time vs automatic — the distinction stated up front in each first sentence._cprint(f" {_d('Add funds now — a single charge, added to your balance today.')}")if (- ar is not None- and ar.enabled- and ar.reload_to_usd is not None- and ar.reload_to_usd.is_finite()- and ar.threshold_usd is not None- and ar.threshold_usd.is_finite()+ ar is not None and ar.enabled+ and ar.reload_to_usd is not None and ar.reload_to_usd.is_finite()+ and ar.threshold_usd is not None and ar.threshold_usd.is_finite()):- _auto_line = (- f"Refill when low — charges {format_money(ar.reload_to_usd)} automatically "- f"when your balance falls below {format_money(ar.threshold_usd)}."- )+ _auto_line = f"Refill when low — charges {format_money(ar.reload_to_usd)} automatically when your balance falls below {format_money(ar.threshold_usd)}."else:- _auto_line = (- "Refill when low — charges your card automatically when your balance "- "falls below the amount you set."- )+ _auto_line = "Refill when low — charges your card automatically when your balance falls below the amount you set."_cprint(f" {_d(_auto_line)}")- print(f" {'─' * 41}")-- # Add funds first, then settings, then the scopeless browser handoff.- # No "Allow Remote Spending" item — that's discovered at pay time.- # "Add funds" charges in-terminal against the org's portal-saved card- # (server-held via POST /charge — no card ref leaves the client). A- # missing card is NOT gated here: the buy flow reacts to the server's- # no_payment_method 403 and hands off to the portal at charge time.+ print(f" {_RULE}")++ # No "Allow Remote Spending" item — discovered at pay time. "Add funds" charges in-terminal+ # against the org's portal-saved card (server-held; no card ref leaves the client).choices = [("buy", "Add funds", "a single charge, added to your balance today"),("auto", "Auto-reload", "refill automatically when your balance runs low"),@@ -905,13 +751,7 @@ class CLIBillingMixin:("portal", "Manage on portal", "open the billing page in your browser"),("cancel", "Cancel", "do nothing"),]- # The overview summary is already printed above; the modal only needs to- # present the action menu — repeating the title/balance reads as a dupe.- raw = self._prompt_text_input_modal(- title="Top up your balance", detail="",- choices=choices,- )- choice = self._normalize_slash_confirm_choice(raw, choices)+ choice = self._modal_choice("Top up your balance", "", choices)if choice == "buy":self._billing_buy_flow(state)elif choice == "auto":@@ -923,27 +763,6 @@ class CLIBillingMixin:else:print(" Cancelled.")- def _usage_bar_lines(self, usage, plan_name) -> list:- """The plan + top-up dollar bars as ready-to-print lines (filled = remaining).-- Returns [] when there's nothing to draw. The caller resolves ``plan_name``- (the plan-bar label) and picks its own print fn — block ordering differs- per surface (``_cprint`` vs ``print`` under patch_stdout). One source of- truth for the bar format across /usage, /subscription, and /topup.- """- lines: list = []- pb = getattr(usage, "plan_bar", None) if usage else None- if pb is not None and pb.total_usd > 0:- filled = max(0, min(10, round(pb.fill_fraction * 10)))- bar = ("█" * filled) + ("░" * (10 - filled))- pct_s = f" · {pb.pct_used}% used" if pb.pct_used is not None else ""- label = (plan_name or "plan").ljust(8)[:8]- lines.append(f" {label}[{bar}] ${pb.remaining_usd:,.2f} left of ${pb.total_usd:,.2f}{pct_s}")- tb = getattr(usage, "topup_bar", None) if usage else None- if tb is not None and tb.remaining_usd > 0:- lines.append(f" {'top-up'.ljust(8)}[{'█' * 10}] ${tb.remaining_usd:,.2f} · never expires")- return lines-def _billing_open_portal(self, state):url = getattr(state, "portal_url", None)if not url:@@ -956,7 +775,6 @@ class CLIBillingMixin:def _billing_require_admin(self, state) -> bool:"""Guard charge/auto-reload entry points; print + return False if blocked."""from cli import _cprint, _d-if not state.can_change_plan:print()_cprint(f" 💳 {_d('Billing actions require an org admin/owner.')}")@@ -965,23 +783,15 @@ class CLIBillingMixin:if not state.cli_billing_enabled:print()_cprint(f" 💳 {_d('Remote spending is off for this org.')}")- self._billing_portal_hint(- state,- reason="A billing admin can turn it on from the portal's Hermes Agent page before adding funds.",- )+ self._billing_portal_hint(state, reason="A billing admin can turn it on from the portal's Hermes Agent page before adding funds.")return Falsereturn Truedef _billing_add_card_flow(self, state):- """No saved card → guide adding one on the portal, with a re-check loop.-- Cards are added on the portal (never in-terminal). "I've added it" re-fetches- billing state so the purchase continues right here once the card is saved —- this also recovers a transient miss (the card display is best-effort- server-side). Returns the refreshed state (card present), or None to abandon.- """+ """No saved card → guide adding one on the portal (never in-terminal), with a bounded re-check+ loop so the purchase continues right here once the card is saved (also recovers a transient+ miss — the card display is best-effort server-side). Returns refreshed state, or None to abandon."""from cli import _cprint, _b, _d, _DIM, _RST-print()_cprint(f" 💳 {_b('Add a card first')}")_cprint(" No saved card on file.")@@ -992,15 +802,13 @@ class CLIBillingMixin:("cancel", "Back", "do nothing"),]for _ in range(8): # bounded: portal-open plus a handful of re-checks- raw = self._prompt_text_input_modal(title="Add a card", detail="", choices=choices)- choice = self._normalize_slash_confirm_choice(raw, choices)+ choice = self._modal_choice("Add a card", "", choices)if choice == "portal":self._billing_open_portal(state)_cprint(f" {_d('Add the card on the billing page, then pick “check again” here.')}")continueif choice == "recheck":from agent.billing_view import build_billing_state-try:fresh = build_billing_state()except Exception:@@ -1017,22 +825,15 @@ class CLIBillingMixin:return Nonedef _billing_buy_flow(self, state):- """Screen 2 (preset select) → Screen 3 (confirm + charge + poll)."""+ """Screen 2 (preset select) → Screen 3 (confirm + charge + poll). No scope preflight: the+ charge flies and we react to the server's 403 order (insufficient_scope → in-flight reauth,+ no_payment_method → portal hand-off)."""from cli import _cprint, _b-from agent.billing_view import format_money, validate_charge_amountif not self._billing_require_admin(state):return-- # No card / scope preflight here — that's the rejected anti-pattern. We let- # the charge fly and react to whatever 403 the server returns: scope first- # (insufficient_scope → in-flight reauth), then card (no_payment_method →- # portal handoff via _billing_render_charge_error). Mirrors the server's gate- # order; the user only hits the flow they actually need.-- # Screen 3 — preset selection.- if not getattr(self, "_app", None):+ if not self._app:presets = ", ".join(format_money(p) for p in state.charge_presets)print()_cprint(f" 💳 {_b('Add funds')}")@@ -1040,42 +841,27 @@ class CLIBillingMixin:print(" Run this in the interactive CLI to complete a purchase.")self._billing_portal_hint(state)return-- # No card on file → the guided ADD-CARD path first (portal + re-check),- # so the user isn't walked through picking an amount that will 403.- # Returns refreshed state with a card, or None (abandoned).- if state.card is None:+ if state.card is None: # guided add-card path first, so the amount pick can't 403state = self._billing_add_card_flow(state)if state is None or state.card is None:return- preset_choices = []- for p in state.charge_presets:- preset_choices.append((str(p), format_money(p), "one-time credit purchase"))+ preset_choices = [(str(p), format_money(p), "one-time credit purchase") for p in state.charge_presets]preset_choices.append(("custom", "Custom amount…", "enter your own amount"))preset_choices.append(("cancel", "Cancel", "do nothing"))-card = state.card- detail = f"Payment: {card.display}" if card else "No saved card on file"- raw = self._prompt_text_input_modal(- title="Add funds", detail=detail, choices=preset_choices,- )- choice = self._normalize_slash_confirm_choice(raw, preset_choices)+ choice = self._modal_choice("Add funds", f"Payment: {card.display}" if card else "No saved card on file", preset_choices)if not choice or choice == "cancel":print(" Cancelled. No funds added.")returnfrom decimal import Decimal-if choice == "custom":entered = self._prompt_text_input(" Amount (USD): ")- if entered is None:- # None = cancelled (e.g. slash-worker can't prompt off-thread).+ if entered is None: # cancelled (e.g. slash-worker can't prompt off-thread)print(" Cancelled. No funds added.")return- v = validate_charge_amount(- entered or "", min_usd=state.min_usd, max_usd=state.max_usd- )+ v = validate_charge_amount(entered or "", min_usd=state.min_usd, max_usd=state.max_usd)if not v.ok:print(f" 🔴 {v.error}")return@@ -1086,46 +872,35 @@ class CLIBillingMixin:except Exception:print(" 🔴 Invalid selection.")return-self._billing_confirm_and_charge(state, amount)def _billing_confirm_and_charge(self, state, amount):"""Screen 3 — confirm total + consent, charge, then poll to settlement."""from cli import _cprint, _b, _d-from agent.billing_view import format_money, new_idempotency_key+ from hermes_cli.nous_billing import BillingError, BillingScopeRequired, post_chargecard = state.cardprint()_cprint(f" 💳 {_b('Confirm purchase')}")- print(f" {'─' * 41}")+ print(f" {_RULE}")print(f" Total: {format_money(amount)}")if card:print(f" Payment: {card.display}")- # Provenance-less payloads (older NAS) keep the generic line; when- # the resolver says WHY this card, the Payment line carries it.- if card.provenance is None:+ if card.provenance is None: # older NAS without provenance → generic line_cprint(f" {_d('Your card saved on the portal will be charged.')}")- print(f" {'─' * 41}")- _consent = (- "By confirming, you allow Nous Research to charge your card."- )- _cprint(f" {_d(_consent)}")+ print(f" {_RULE}")+ _cprint(f" {_d('By confirming, you allow Nous Research to charge your card.')}")confirm_choices = [("pay", f"Pay {format_money(amount)} now", "submit the charge"),("portal", "Manage on portal", "manage your card / billing in the browser"),("cancel", "Go back", "do not charge"),]- if not getattr(self, "_app", None):+ if not self._app:print(" Run in the interactive CLI to confirm a purchase.")return- raw = self._prompt_text_input_modal(- title=f"Pay {format_money(amount)}?",- detail=(card.display if card else "no saved card"),- choices=confirm_choices,- )- choice = self._normalize_slash_confirm_choice(raw, confirm_choices)+ choice = self._modal_choice(f"Pay {format_money(amount)}?", card.display if card else "no saved card", confirm_choices)if choice == "portal":self._billing_open_portal(state)return@@ -1133,25 +908,15 @@ class CLIBillingMixin:print(" Cancelled. No funds added.")return- # Submit the charge with a fresh idempotency key (reused on retry).- from hermes_cli.nous_billing import (- BillingError,- BillingScopeRequired,- post_charge,- )-- key = new_idempotency_key()+ key = new_idempotency_key() # reused on the post-step-up resume so a double-submit collapsestry:result = post_charge(amount_usd=amount, idempotency_key=key)except BillingScopeRequired:- # In-flight reauth: allow remote spending, then resume THIS charge- # (press-Enter beat) — no command re-run. Reuses the same idem key.self._billing_handle_scope_required(state, amount=amount, idempotency_key=key)returnexcept BillingError as exc:self._billing_render_charge_error(state, exc)return-charge_id = result.get("chargeId")if not charge_id:print(" 🔴 No charge id returned; please check the portal.")@@ -1162,102 +927,66 @@ class CLIBillingMixin:def _billing_poll_charge(self, state, charge_id, amount):"""Poll loop: 2s interval, 5-min cap, cancellable. settled = ledger truth."""import time as _time+ from agent.billing_view import format_money, parse_money+ from hermes_cli.nous_billing import BillingError, BillingTransient, get_charge_status- from agent.billing_view import format_money- from hermes_cli.nous_billing import (- BillingError,- BillingTransient,- get_charge_status,- )-- deadline = _time.time() + 300 # 5-minute cap- interval = 2.0+ deadline = _time.time() + 300while _time.time() < deadline:try:status = get_charge_status(charge_id)- except BillingTransient as exc:- # Retry-after, NOT a failure — back off and keep polling.- wait = exc.retry_after or 5- _time.sleep(min(wait, 30))+ except BillingTransient as exc: # retry-after, NOT a failure — back off and keep polling+ _time.sleep(min(exc.retry_after or 5, 30))continueexcept BillingError as exc:print(f" 🔴 Could not check the charge: {exc}")return-state_str = status.get("status")if state_str == "settled":amt = status.get("amountUsd")- from agent.billing_view import parse_money-shown = format_money(parse_money(amt)) if amt else format_money(amount)print(f" ✓ {shown} added to your balance.")returnif state_str == "failed":self._billing_render_charge_failed(state, status.get("reason"))return- # pending → wait and poll again- _time.sleep(interval)-- # Past the cap with no terminal state = timeout (not an error).- print(" 🟡 Still processing after 5 minutes — this is a timeout, not a "- "failure. Check /billing or the portal shortly.")+ _time.sleep(2.0) # pending+ print(" 🟡 Still processing after 5 minutes — this is a timeout, not a failure. Check /billing or the portal shortly.")self._billing_portal_hint(state)def _billing_render_charge_failed(self, state, reason):- """Branch the poll `failed` reasons to the right copy + portal funnel."""+ """Poll `failed` reasons → the right copy + portal funnel."""reason = (reason or "").strip()- if reason == "authentication_required":- print(" 🔴 Your bank requires verification (3DS). Complete it on the "- "portal to finish this purchase.")- elif reason == "payment_method_expired":- print(" 🔴 Your card has expired. Update it on the portal.")- elif reason == "card_declined":- print(" 🔴 Your card was declined. Try another card on the portal.")- else:- print(f" 🔴 The charge didn't go through ({reason or 'processing_error'}).")+ print(_CHARGE_FAILED_COPY.get(reason) or f" 🔴 The charge didn't go through ({reason or 'processing_error'}).")self._billing_portal_hint(state)def _billing_render_charge_error(self, state, exc):- """Render a typed BillingError at submit time (pre-poll)."""- from hermes_cli.nous_billing import (- BillingTransient,- BillingRemoteSpendingRevoked,- BillingSessionRevoked,- )+ """Render a typed BillingError at submit time (pre-poll). Order matters: revoked/session+ checks precede code lookups, and Transient precedes the insufficient_scope fallback."""+ from hermes_cli.nous_billing import BillingTransient, BillingRemoteSpendingRevoked, BillingSessionRevokedcode = getattr(exc, "error", None)- actor = getattr(exc, "actor", None)portal_url = getattr(exc, "portal_url", None) or getattr(state, "portal_url", None)if isinstance(exc, BillingRemoteSpendingRevoked) or code == "remote_spending_revoked":- # CF-4: this terminal's spend was revoked. Recovery is reconnect.- who = ("An admin stopped this terminal's spending."- if actor == "admin"- else "You stopped this terminal's spending.")+ # This terminal's spend was revoked; recovery is reconnect.+ who = "An admin stopped this terminal's spending." if getattr(exc, "actor", None) == "admin" else "You stopped this terminal's spending."print(f" 🔴 {who} Reconnect to restore — run `hermes portal` to re-authorize.")elif isinstance(exc, BillingSessionRevoked) or code == "session_revoked":print(" 🔴 Your session was logged out. Run `hermes portal` to log in again.")elif code == "no_payment_method":- print(" 💳 No card on file — top up and manage billing on the portal.")- elif code in ("cli_billing_disabled", "remote_spending_disabled") or \- getattr(exc, "code", None) == "remote_spending_disabled":- print(" Remote spending is off for this account — a billing admin can turn it on from the portal's Hermes Agent page.")- elif code == "role_required":- print(" Adding funds needs an org admin/owner. Ask an admin, or manage on the portal.")- elif code == "idempotency_conflict":- print(" 🔴 That charge key was already used for a different amount. Start a fresh top-up.")+ print(_CHARGE_ERROR_COPY[code])+ elif code in ("cli_billing_disabled", "remote_spending_disabled") or getattr(exc, "code", None) == "remote_spending_disabled":+ print(_CHARGE_ERROR_COPY["cli_billing_disabled"]) # dual error/code gate payload+ elif code in _CHARGE_ERROR_COPY: # role_required / idempotency_conflict+ print(_CHARGE_ERROR_COPY[code])elif code == "monthly_cap_exceeded":remaining = (getattr(exc, "payload", {}) or {}).get("remainingUsd")- if remaining is not None:- print(f" 🔴 Monthly spend cap reached — ${remaining} headroom left.")- else:- print(" 🔴 Monthly spend cap reached.")+ print(f" 🔴 Monthly spend cap reached — ${remaining} headroom left." if remaining is not None else " 🔴 Monthly spend cap reached.")elif isinstance(exc, BillingTransient):wait = getattr(exc, "retry_after", None)mins = f" (try again in ~{max(1, round(wait / 60))} min)" if wait else ""print(f" 🟡 Too many charges right now{mins}. This isn't a payment failure.")elif code == "insufficient_scope":- # Never leak the raw billing:manage scope (the post-grant replay can- # re-raise it if the grant raced) — the concept is "Remote Spending".+ # Never leak the raw billing:manage scope (a raced post-grant replay can re-raise it).print(" 🔴 Remote Spending needs approval — run /topup to allow it, then retry.")else:print(f" 🔴 {exc}")@@ -1265,99 +994,48 @@ class CLIBillingMixin:print(f" Portal: {portal_url}")def _billing_handle_scope_required(self, state, *, amount=None, idempotency_key=None):- """403 insufficient_scope → in-flight reauth, then resume the held charge.-- The buy path discovers remote spending isn't allowed only when the- charge 403s — there is no preflight. We allow it in-flight ("Allow- Remote Spending" → browser device-flow), then on return ask the user to- press Enter to resume the held ``amount`` (reusing ``idempotency_key`` so- the resumed charge collapses with the original). Never leaks the raw- billing:manage scope.- """+ """403 insufficient_scope → in-flight reauth, then resume the held ``amount`` on an explicit+ press-Enter confirm, reusing ``idempotency_key`` so the resumed charge collapses with the+ original. Never leaks the raw billing:manage scope."""from cli import _cprint, _d-- from agent.billing_view import format_money+ from agent.billing_view import build_billing_state, format_money, new_idempotency_keyamount_str = format_money(amount) if amount is not None else "your top-up"- print()- print(" ! One-time setup")- _cprint(f" {_d(f'To charge from this terminal, allow Remote Spending once. It opens your browser to authorize, then {amount_str} picks up right here.')}")- if not getattr(self, "_app", None):- print(" Run `hermes portal` and allow Remote Spending, then retry.")- return- confirm_choices = [- ("yes", "Allow Remote Spending", "open your browser to authorize"),- ("no", "Not now", "cancel"),- ]- raw = self._prompt_text_input_modal(- title="Allow Remote Spending",- detail="Opens your browser to authorize this terminal.",- choices=confirm_choices,+ granted = self._step_up_remote_spending(+ explain=f"To charge from this terminal, allow Remote Spending once. It opens your browser to authorize, then {amount_str} picks up right here.",+ noninteractive_msg=" Run `hermes portal` and allow Remote Spending, then retry.",+ declined_msg=" No charge made. Run /topup when you want to allow Remote Spending.",+ not_granted_msg=" Couldn't allow Remote Spending — an org admin or owner has to approve it. Your card was not charged.",)- choice = self._normalize_slash_confirm_choice(raw, confirm_choices)- if choice != "yes":- print(" No charge made. Run /topup when you want to allow Remote Spending.")- return- print(" Opening your browser to allow Remote Spending…")- try:- from hermes_cli.auth import step_up_nous_billing_scope-- granted = step_up_nous_billing_scope(open_browser=True)- except Exception as exc:- print(f" Couldn't allow Remote Spending: {exc}")- returnif not granted:- print(" Couldn't allow Remote Spending — an org admin or owner has to approve it. Your card was not charged.")return- # Granted. The token now carries the scope, but the ORG kill-switch- # (cli_billing_enabled) is a separate gate — re-fetch /state so we don't- # over-promise when a charge would still hit cli_billing_disabled.- from agent.billing_view import build_billing_state-+ # The token now carries the scope, but the ORG kill-switch (cli_billing_enabled) is a separate+ # gate — re-fetch /state so we don't over-promise.fresh = build_billing_state()if not (fresh.logged_in and fresh.cli_billing_enabled):print(" Remote Spending is allowed for this terminal, but it's still off for this org. A billing admin can turn it on from the portal's Hermes Agent page, then run /topup again.")self._billing_portal_hint(fresh)return-- # Scope granted + org kill-switch on — but a charge still needs a card on- # file. If there's none, this is a half-done state: say so and route to the- # portal to top up / manage billing, rather than a bare "✓ enabled" that reads as done.- if fresh.card is None:+ if fresh.card is None: # half-done state: say so rather than a bare "✓ enabled"print(" ✓ Remote Spending allowed — but there's no card on file yet.")_cprint(f" {_d('Top up and manage billing on the portal to continue.')}")self._billing_portal_hint(fresh)return-- # Nothing to resume (scope-required hit outside a charge, e.g. auto-reload- # config) → just tell the user it's ready.- if amount is None:+ if amount is None: # scope-required hit outside a charge (e.g. auto-reload config)print(" ✓ Remote Spending allowed. Run /topup to continue.")return- # Press-Enter beat: the user is back from the browser; resume the held- # purchase on an explicit confirm (reassuring, not silent).print(" ✓ Remote Spending allowed.")resume_choices = [("resume", f"Resume {format_money(amount)} top-up", "finish the held purchase"),("cancel", "Cancel", "do not charge"),]- raw = self._prompt_text_input_modal(- title="Resume your top-up",- detail=f"{format_money(amount)} is ready to finish — press Enter to resume.",- choices=resume_choices,- )- if self._normalize_slash_confirm_choice(raw, resume_choices) != "resume":+ if self._modal_choice("Resume your top-up", f"{format_money(amount)} is ready to finish — press Enter to resume.", resume_choices) != "resume":print(" Cancelled. No funds added.")return- # Replay the held charge, reusing the original idempotency key so a- # double-submit collapses to one charge.from hermes_cli.nous_billing import BillingError, post_charge-- from agent.billing_view import new_idempotency_key-key = idempotency_key or new_idempotency_key()try:result = post_charge(amount_usd=amount, idempotency_key=key)@@ -1372,26 +1050,20 @@ class CLIBillingMixin:self._billing_poll_charge(fresh, charge_id, amount)def _billing_auto_reload_flow(self, state):- """Screen 4 — auto-reload config: threshold + reload-to → PATCH.-- Prefills the current values from ``state.auto_reload``. Validates both- amounts (2dp, within bounds, ``reload_to > threshold``). When auto-reload- is already on, offers a "Turn off" path (PATCH ``enabled:false``).- """+ """Screen 4 — auto-reload config: threshold + reload-to → PATCH. Prefills current values;+ validates both (2dp, within bounds, ``reload_to > threshold``); offers "Turn off" when already on."""from cli import _cprint, _b, _d-from agent.billing_view import format_money, validate_charge_amountif not self._billing_require_admin(state):return-card = state.cardar = state.auto_reloadcurrently_on = bool(ar and ar.enabled)print()_cprint(f" 💳 {_b('Auto-reload')}")- print(f" {'─' * 41}")+ print(f" {_RULE}")_cprint(f" {_d('Automatically add funds when your balance is low.')}")if card:print(f" Card on file: {card.masked}")@@ -1400,32 +1072,19 @@ class CLIBillingMixin:self._billing_portal_hint(state)returnif currently_on:- print(- f" Currently: below {format_money(ar.threshold_usd)} → "- f"reload to {format_money(ar.reload_to_usd)}"- )-- if not getattr(self, "_app", None):+ print(f" Currently: below {format_money(ar.threshold_usd)} → reload to {format_money(ar.reload_to_usd)}")+ if not self._app:print(" Run in the interactive CLI to configure auto-reload.")self._billing_portal_hint(state)return- # When already enabled, let the user turn it off without re-entering values.- if currently_on:+ if currently_on: # let the user turn it off without re-entering valuestop_choices = [("edit", "Edit thresholds", "change when / how much to reload"),("off", "Turn off", "disable auto-reload"),("cancel", "Cancel", "do nothing"),]- raw = self._prompt_text_input_modal(- title="Auto-reload",- detail=(- f"On — below {format_money(ar.threshold_usd)} → "- f"reload to {format_money(ar.reload_to_usd)}"- ),- choices=top_choices,- )- top = self._normalize_slash_confirm_choice(raw, top_choices)+ top = self._modal_choice("Auto-reload", f"On — below {format_money(ar.threshold_usd)} → reload to {format_money(ar.reload_to_usd)}", top_choices)if top == "off":self._billing_auto_reload_disable(state)return@@ -1433,134 +1092,82 @@ class CLIBillingMixin:print(" 🟡 Cancelled.")return- # Field 1 — threshold (prefilled when editing an existing config).- cur_thr = format_money(ar.threshold_usd) if currently_on else None- thr_prompt = " When balance falls below (USD)"- thr_prompt += f" [{cur_thr}]: " if cur_thr else ": "- threshold_raw = self._prompt_text_input(thr_prompt)- if threshold_raw is None:- # None = cancelled (e.g. slash-worker can't prompt off-thread).- print(" 🟡 Cancelled.")+ _CANCELLED = object()++ def _ask_amount(label, current):+ """Prompt one amount; empty input keeps `current` when editing. Returns the Decimal (or the+ kept current value, possibly None), or _CANCELLED after printing the cancel/validation message."""+ cur = format_money(current) if currently_on else None+ raw = self._prompt_text_input(f" {label} (USD)" + (f" [{cur}]: " if cur else ": "))+ if raw is None: # cancelled (e.g. slash-worker can't prompt off-thread)+ print(" 🟡 Cancelled.")+ return _CANCELLED+ if not (raw or "").strip() and currently_on:+ return current+ v = validate_charge_amount(raw or "", min_usd=state.min_usd, max_usd=state.max_usd)+ if not v.ok or v.amount is None:+ print(f" 🔴 {v.error}")+ return _CANCELLED+ return v.amount++ threshold_amt = _ask_amount("When balance falls below", ar.threshold_usd if currently_on else None)+ if threshold_amt is _CANCELLED:return- if not (threshold_raw or "").strip() and currently_on:- threshold_amt = ar.threshold_usd # keep current value on empty input- else:- tv = validate_charge_amount(- threshold_raw or "", min_usd=state.min_usd, max_usd=state.max_usd- )- if not tv.ok or tv.amount is None:- print(f" 🔴 {tv.error}")- return- threshold_amt = tv.amount-- # Field 2 — reload-to (prefilled when editing an existing config).- cur_rel = format_money(ar.reload_to_usd) if currently_on else None- rel_prompt = " Reload balance to (USD)"- rel_prompt += f" [{cur_rel}]: " if cur_rel else ": "- reload_raw = self._prompt_text_input(rel_prompt)- if reload_raw is None:- print(" 🟡 Cancelled.")+ reload_amt = _ask_amount("Reload balance to", ar.reload_to_usd if currently_on else None)+ if reload_amt is _CANCELLED:return- if not (reload_raw or "").strip() and currently_on:- reload_amt = ar.reload_to_usd # keep current value on empty input- else:- rv = validate_charge_amount(- reload_raw or "", min_usd=state.min_usd, max_usd=state.max_usd- )- if not rv.ok or rv.amount is None:- print(f" 🔴 {rv.error}")- return- reload_amt = rv.amount-if reload_amt is None or threshold_amt is None or reload_amt <= threshold_amt:print(" 🔴 Reload-to amount must be greater than the threshold.")returnprint()- _ar_consent = (- f"By confirming, you authorize Nous Research to charge {card.masked} "- f"whenever your balance reaches {format_money(threshold_amt)}. "- f"Turn off any time here or on the portal."- )- _cprint(f" {_d(_ar_consent)}")+ _cprint(f" {_d(f'By confirming, you authorize Nous Research to charge {card.masked} whenever your balance reaches {format_money(threshold_amt)}. Turn off any time here or on the portal.')}")confirm_choices = [("agree", "Agree and turn on", "enable auto-reload"),("cancel", "Cancel", "do nothing"),]- raw = self._prompt_text_input_modal(- title="Turn on auto-reload?",- detail=f"Below {format_money(threshold_amt)} → reload to {format_money(reload_amt)}",- choices=confirm_choices,- )- choice = self._normalize_slash_confirm_choice(raw, confirm_choices)- if choice != "agree":+ if self._modal_choice("Turn on auto-reload?", f"Below {format_money(threshold_amt)} → reload to {format_money(reload_amt)}", confirm_choices) != "agree":print(" 🟡 Cancelled.")return+ if self._billing_patch_auto_top_up(state, enabled=True, threshold=float(threshold_amt), top_up_amount=float(reload_amt)):+ print(f" ✅ Auto-reload on: below {format_money(threshold_amt)} → reload to {format_money(reload_amt)}.")- from hermes_cli.nous_billing import (- BillingError,- BillingScopeRequired,- patch_auto_top_up,- )-+ def _billing_patch_auto_top_up(self, state, **kwargs) -> bool:+ """PATCH auto-top-up, routing scope denials to the step-up and other errors to the renderer.+ True on success."""+ from hermes_cli.nous_billing import BillingError, BillingScopeRequired, patch_auto_top_uptry:- patch_auto_top_up(- enabled=True, threshold=float(threshold_amt), top_up_amount=float(reload_amt)- )+ patch_auto_top_up(**kwargs)except BillingScopeRequired:self._billing_handle_scope_required(state)- return+ return Falseexcept BillingError as exc:self._billing_render_charge_error(state, exc)- return- print(f" ✅ Auto-reload on: below {format_money(threshold_amt)} → "- f"reload to {format_money(reload_amt)}.")+ return False+ return Truedef _billing_auto_reload_disable(self, state):- """Turn off auto-reload (PATCH ``enabled:false``).-- The endpoint requires ``threshold``/``topUpAmount`` in the body even when- disabling, so we echo back the current values (falling back to 0).- """- from hermes_cli.nous_billing import (- BillingError,- BillingScopeRequired,- patch_auto_top_up,- )-+ """Turn off auto-reload (PATCH ``enabled:false``). The endpoint requires ``threshold``/+ ``topUpAmount`` even when disabling, so echo back the current values (fallback 0)."""ar = state.auto_reloadthr = float(ar.threshold_usd) if ar and ar.threshold_usd is not None else 0.0rel = float(ar.reload_to_usd) if ar and ar.reload_to_usd is not None else 0.0- try:- patch_auto_top_up(enabled=False, threshold=thr, top_up_amount=rel)- except BillingScopeRequired:- self._billing_handle_scope_required(state)- return- except BillingError as exc:- self._billing_render_charge_error(state, exc)- return- print(" ✅ Auto-reload turned off.")+ if self._billing_patch_auto_top_up(state, enabled=False, threshold=thr, top_up_amount=rel):+ print(" ✅ Auto-reload turned off.")def _billing_limit_screen(self, state):"""Screen 5 — monthly spend limit (read-only; cap is portal-only)."""from cli import _cprint, _b, _d-from agent.billing_view import format_moneyprint()_cprint(f" 💳 {_b('Monthly spend limit')}")- print(f" {'─' * 41}")+ print(f" {_RULE}")cap = state.monthly_capif cap is None or cap.limit_usd is None:_cprint(f" {_d('No monthly cap visible (managed on the portal).')}")else:- spent = format_money(cap.spent_this_month_usd)- limit = format_money(cap.limit_usd)ceiling = " (default ceiling)" if cap.is_default_ceiling else ""- print(f" {spent} of {limit} used this month{ceiling}")- _limit_note = (- "The monthly limit is set on the portal — the terminal shows "- "it read-only."- )- _cprint(f" {_d(_limit_note)}")+ print(f" {format_money(cap.spent_this_month_usd)} of {format_money(cap.limit_usd)} used this month{ceiling}")+ _cprint(f" {_d('The monthly limit is set on the portal — the terminal shows it read-only.')}")self._billing_portal_hint(state)diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex b78ff6157c1..9d9b597159c 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -1,15 +1,9 @@-"""Slash-command handlers for the interactive CLI (god-file decomposition Phase 4).--This module hosts the ``_handle_*_command`` slash-command handlers lifted out of-``cli.py``'s ``HermesCLI`` class. ``HermesCLI`` inherits ``CLICommandsMixin`` so-every ``self.<handler>`` call resolves unchanged via the MRO — behavior-neutral.--Import discipline (mirrors gateway/slash_commands.py, PR #41886):- * Neutral, non-cyclic deps are imported at module top-level below.- * cli.py-internal symbols (the ``_cprint``/``_ACCENT``/``save_config_value``…- module-level helpers and constants) are imported LAZILY inside each handler- via ``from cli import ...`` — that resolves at call time when ``cli`` is fully- loaded, so the mixin module never imports ``cli`` at top level (no cycle).+"""Slash-command handlers for the interactive CLI, lifted out of ``cli.py``'s ``HermesCLI``.++``HermesCLI`` inherits ``CLICommandsMixin`` so every ``self.<handler>`` resolves via the MRO.+cli.py-internal symbols (``_cprint``/``_ACCENT``/``save_config_value``…) are imported LAZILY+inside each handler via ``from cli import ...`` — the mixin never imports ``cli`` at top level+(import cycle)."""from __future__ import annotations@@ -41,12 +35,8 @@ from hermes_cli.browser_connect import (def _print_lightpanda_engine_status() -> None:- """One or two ``/browser status`` lines about ``browser.engine: lightpanda``.-- Silent unless the engine is set to lightpanda. Says whether it is in use- (and by which driver) or which setting shadows it — the engine is the- lowest-precedence browser knob and used to be ignored silently.- """+ """``/browser status`` line(s) about ``browser.engine: lightpanda`` — silent unless set;+ says whether it is in use or which higher-precedence setting shadows it."""try:from tools.browser_tool import lightpanda_engine_status, _using_lightpanda_engine@@ -71,26 +61,235 @@ def _print_lightpanda_engine_status() -> None:print(f" ⚠ lightpanda binary not found — {LIGHTPANDA_INSTALL_HINT}")-class CLICommandsMixin:- """Mixin holding the interactive-CLI slash-command handlers.+# /cron flag tables: flag -> opts key. Order-sensitive in _parse_flags: bool flags never consume+# a value; --repeat is int-validated separately.+_CRON_BOOL_FLAGS = {"--clear-skills": "clear_skills", "--all": "all"}+_CRON_LIST_FLAGS = {"--skill": "skills", "--add-skill": "add_skills", "--remove-skill": "remove_skills"}+_CRON_VALUE_FLAGS = {"--name": "name", "--deliver": "deliver", "--prompt": "prompt", "--schedule": "schedule"}++_ON_WORDS = {"on", "enable", "true", "1"}+_OFF_WORDS = {"off", "disable", "false", "0"}++# /busy mode -> what Enter does while Hermes is working (status line / post-set explanation).+_BUSY_MODE_SHORT = {+ "queue": "queues for next turn",+ "steer": "steers into current run (after next tool call)",+ "interrupt": "redirects current run immediately",+}+_BUSY_MODE_LONG = {+ "queue": "Enter will queue follow-up input while Hermes is busy.",+ "steer": "Enter will steer your message into the current run (after the next tool call).",+ "interrupt": "Enter will redirect the current run while Hermes is busy; /stop still cancels it.",+}+++# /fast argument -> (service_tier value, persisted config value)+_FAST_TIERS = {+ "fast": ("priority", "fast"), "on": ("priority", "fast"),+ "normal": (None, "normal"), "off": (None, "normal"),+ "auto": ("auto", "auto"), "cold": ("cold", "cold"),+}+++def _split_scope_flags(raw: str):+ """``(arg, explicit_global)`` for /reasoning + /fast: session scope by default, ``--global``+ persists to config.yaml, ``--session`` is an explicit no-op (parity with /model)."""+ tokens = raw.strip().lower().split()+ return " ".join(t for t in tokens if t not in ("--global", "--session")), "--global" in tokens+++def _scope_outcome(explicit_global: bool, saved: bool) -> str:+ """Parenthetical tail for a scoped setting change."""+ if saved:+ return "(saved to config)"+ if explicit_global:+ return "(session only; config save failed)"+ return "(this session — use --global to persist)"+++def _toggle_target(arg: str, current: bool):+ """Resolve a ``/x [on|off|status]`` argument: "status" for a status query, a bool for the+ new state (bare arg toggles), or None when the argument is unrecognized."""+ if arg in {"status", "?"}:+ return "status"+ if arg in _ON_WORDS:+ return True+ if arg in _OFF_WORDS:+ return False+ if arg == "":+ return not current+ return None+++def _command_arg(cmd: str, *, lower: bool = False) -> str:+ """Everything after the slash-command word, stripped (optionally lowercased)."""+ parts = (cmd or "").strip().split(None, 1)+ arg = parts[1].strip() if len(parts) > 1 else ""+ return arg.lower() if lower else arg+++def _summarize_paths(paths, limit: int = 5) -> str:+ """``a, b, c (+N more)`` for a list of paths."""+ more = f" (+{len(paths) - limit} more)" if len(paths) > limit else ""+ return ", ".join(paths[:limit]) + more+++def _cron_api(**kwargs) -> dict:+ """Call the cronjob model tool and decode its JSON reply."""+ from tools.cronjob_tools import cronjob as cronjob_tool+ return json.loads(cronjob_tool(**kwargs))+++def _normalize_skills(values) -> list:+ """Strip, drop empties, and dedupe (order-preserving)."""+ normalized = []+ for value in values:+ text = str(value or "").strip()+ if text and text not in normalized:+ normalized.append(text)+ return normalized+++def _parse_cron_flags(tokens):+ """Parse /cron flags into an opts dict (None after printing an error for a bad --repeat)."""+ opts = {+ "name": None, "deliver": None, "repeat": None, "prompt": None, "schedule": None,+ "skills": [], "add_skills": [], "remove_skills": [],+ "clear_skills": False, "all": False, "positionals": [],+ }+ i = 0+ while i < len(tokens):+ token = tokens[i]+ has_value = i + 1 < len(tokens)+ if token in _CRON_BOOL_FLAGS:+ opts[_CRON_BOOL_FLAGS[token]] = True+ i += 1+ elif token in _CRON_LIST_FLAGS and has_value:+ opts[_CRON_LIST_FLAGS[token]].append(tokens[i + 1])+ i += 2+ elif token == "--repeat" and has_value:+ try:+ opts["repeat"] = int(tokens[i + 1])+ except ValueError:+ print("(._.) --repeat must be an integer")+ return None+ i += 2+ elif token in _CRON_VALUE_FLAGS and has_value:+ opts[_CRON_VALUE_FLAGS[token]] = tokens[i + 1]+ i += 2+ else:+ opts["positionals"].append(token)+ i += 1+ return opts+++# /cron subcommand -> CLICommandsMixin handler (bound late, after the class body).+_CRON_SUBCOMMANDS: dict = {}+++def _say_block(*lines: str) -> None:+ """print() the lines framed by a blank line above and below (the /browser output style)."""+ print()+ for line in lines:+ print(line)+ print()+++def _end_current_session(cli, reason: str) -> None:+ """Flush un-persisted messages, then end the current session row with ``reason``.+ Best-effort on both steps (the switch proceeds even if the DB write fails)."""+ if cli.agent:+ try:+ cli.agent._flush_messages_to_session_db(+ cli.conversation_history, conversation_history=cli.conversation_history,+ )+ except Exception:+ pass+ try:+ cli._session_db.end_session(cli.session_id, reason)+ except Exception:+ pass+++def _sync_agent_to_session(cli, session_id: str, *, parent_session_id: str, reason: str) -> None:+ """Point an already-built agent at ``session_id`` after a /resume or /branch switch.++ Resets per-session agent state, re-anchors the DB flush index to the loaded history,+ and notifies memory providers with reset=False — their accumulated state stays valid+ and just targets the new session_id (the parent link keeps the lineage)."""+ if not cli.agent:+ return+ cli.agent.session_id = session_id+ cli.agent.reset_session_state()+ if hasattr(cli.agent, "_last_flushed_db_idx"):+ cli.agent._last_flushed_db_idx = len(cli.conversation_history)+ if hasattr(cli.agent, "_todo_store"):+ try:+ from tools.todo_tool import TodoStore+ cli.agent._todo_store = TodoStore()+ except Exception:+ pass+ if hasattr(cli.agent, "_invalidate_system_prompt"):+ cli.agent._invalidate_system_prompt()+ try:+ _mm = getattr(cli.agent, "_memory_manager", None)+ if _mm is not None:+ _mm.on_session_switch(+ session_id, parent_session_id=parent_session_id or "", reset=False, reason=reason,+ )+ except Exception:+ pass+++def _print_side_result_panel(cli, *, header_lines, body, title_suffix, empty_note) -> None:+ """Print a worker-thread result (/bg, /btw) into the scrollback: accent rules around+ ``header_lines``, then ``body`` in a skinned Rich panel (or ``empty_note``).+ Forces a TUI refresh first so the spinner/status bar don't overlap the output."""+ from cli import ChatConsole, _accent_hex, _cprint, _maybe_remap_for_light_mode, _render_final_assistant_content+ if cli._app:+ cli._app.invalidate()+ time.sleep(0.05) # brief pause for refresh+ print()+ ChatConsole().print(f"[{_accent_hex()}]{'─' * 40}[/]")+ for line in header_lines:+ _cprint(line)+ ChatConsole().print(f"[{_accent_hex()}]{'─' * 40}[/]")+ if not body:+ _cprint(empty_note)+ return+ try:+ from hermes_cli.skin_engine import get_active_skin+ _skin = get_active_skin()+ label = _skin.get_branding("response_label", "⚕ Hermes")+ _resp_color = _maybe_remap_for_light_mode(_skin.get_color("response_border", "#CD7F32"))+ _resp_text = _maybe_remap_for_light_mode(_skin.get_color("banner_text", "#FFF8DC"))+ except Exception:+ label, _resp_color, _resp_text = "⚕ Hermes", "#CD7F32", "#FFF8DC"+ ChatConsole().print(Panel(+ _render_final_assistant_content(body, mode=cli.final_response_markdown),+ title=f"[{_resp_color} bold]{label} {title_suffix}[/]",+ title_align="left",+ border_style=_resp_color,+ style=_resp_text,+ box=rich_box.HORIZONTALS,+ padding=(1, 4),+ width=cli._scrollback_box_width(),+ ))+- All methods use only ``self`` state plus the imports above and per-method- lazy ``from cli import ...`` lines, so they compose cleanly onto- ``HermesCLI`` via the MRO.- """+class CLICommandsMixin:+ """Mixin holding the interactive-CLI slash-command handlers."""def _handle_rollback_command(self, command: str):"""Handle /rollback — list, diff, or restore filesystem checkpoints.Syntax:/rollback — list checkpoints- /rollback <N> — restore checkpoint N, preserving user- hand-edits (also undoes last chat turn)- /rollback <N> --all — classic full restore (may overwrite- files you edited after Hermes did)+ /rollback <N> — restore checkpoint N, preserving user hand-edits+ (also undoes last chat turn)+ /rollback <N> --all — classic full restore (may overwrite your later edits)/rollback diff <N> — preview changes since checkpoint N- /rollback <N> <file> — restore a single file from checkpoint N- """+ /rollback <N> <file> — restore a single file from checkpoint N"""from tools.checkpoint_manager import format_checkpoint_listif not hasattr(self, 'agent') or not self.agent:@@ -119,12 +318,8 @@ class CLICommandsMixin:args = filteredif not args:- # List checkpoints — fall back to the cross-project view when the- # current directory has none (#10505, reapply of PR #10633 by- # @nightq). The Aug 2026 QA sweep hit this live: writes landed- # checkpoints under the session cwd (/tmp/qa-repo) while bare- # /rollback searched only TERMINAL_CWD's project and reported- # "No checkpoints found" despite fresh checkpoints existing.+ # List checkpoints — fall back to the cross-project view when the current+ # directory has none (writes may have landed under the session cwd, not TERMINAL_CWD).checkpoints = mgr.list_checkpoints(cwd)if not checkpoints:all_checkpoints = mgr.list_all_checkpoints()@@ -192,20 +387,14 @@ class CLICommandsMixin:print(f" ✅ Restored to checkpoint {result['restored_to']}: {result['reason']}")skipped = result.get("skipped_user_edits") or []if skipped:- shown = ", ".join(skipped[:5])- more = f" (+{len(skipped) - 5} more)" if len(skipped) > 5 else ""- print(f" ↷ Kept your hand-edits: {shown}{more}")+ print(f" ↷ Kept your hand-edits: {_summarize_paths(skipped)}")print(" Use /rollback <N> --all to restore those too.")oversize = result.get("skipped_oversize") or []if oversize:- shown = ", ".join(oversize[:5])- more = f" (+{len(oversize) - 5} more)" if len(oversize) > 5 else ""- print(f" ↷ Kept (too large for checkpoints, no stored copy to revert to): {shown}{more}")+ print(f" ↷ Kept (too large for checkpoints, no stored copy to revert to): {_summarize_paths(oversize)}")failed = result.get("failed_deletes") or []if failed:- shown = ", ".join(failed[:5])- more = f" (+{len(failed) - 5} more)" if len(failed) > 5 else ""- print(f" ⚠️ Could not remove (left in place): {shown}{more}")+ print(f" ⚠️ Could not remove (left in place): {_summarize_paths(failed)}")print(" A pre-rollback snapshot was saved automatically.")# Also undo the last conversation turn so the agent's context@@ -219,14 +408,8 @@ class CLICommandsMixin:def _handle_diff_command(self, command: str):"""Handle /diff — show git changes in the working directory.- Syntax:- /diff — unstaged changes + untracked files- /diff staged — staged changes (git diff --cached)- /diff all — staged + unstaged + untracked (vs HEAD)- /diff session — everything Hermes changed (checkpoint baseline)- /diff [mode] --stat — summary only (changed files + counts)- /diff [mode] <path...> — restrict to specific paths- """+ Syntax: ``/diff`` (unstaged + untracked), ``staged``, ``all`` (vs HEAD), ``session``+ (everything Hermes changed since the checkpoint baseline), ``[mode] --stat``, ``[mode] <path...>``."""import shlextry:@@ -282,15 +465,15 @@ class CLICommandsMixin:print(f" ... and {len(untracked) - 20} more")if stat_only or not diff:return+ self._print_diff_body(diff, "run /diff --stat for a summary")+ def _print_diff_body(self, diff: str, stat_hint: str, limit: int = 400) -> None:+ """Print a diff, capped at ``limit`` lines with a pointer to the --stat form."""diff_lines = diff.splitlines()print("")- if len(diff_lines) > 400:- self._print_diff_text("\n".join(diff_lines[:400]))- print(- f"\n ... ({len(diff_lines) - 400} more lines — "- "run /diff --stat for a summary)"- )+ if len(diff_lines) > limit:+ self._print_diff_text("\n".join(diff_lines[:limit]))+ print(f"\n ... ({len(diff_lines) - limit} more lines — {stat_hint})")else:self._print_diff_text(diff)@@ -323,23 +506,11 @@ class CLICommandsMixin:self._print_diff_text(f"\n{stat}")if stat_only or not diff:return- diff_lines = diff.splitlines()- print("")- if len(diff_lines) > 400:- self._print_diff_text("\n".join(diff_lines[:400]))- print(- f"\n ... ({len(diff_lines) - 400} more lines — "- "run /diff session --stat for a summary)"- )- else:- self._print_diff_text(diff)+ self._print_diff_body(diff, "run /diff session --stat for a summary")def _print_diff_text(self, text: str) -> None:- """Render diff/stat text with color when a rich console is present.-- Falls back to plain print when the console isn't available (e.g. unit- tests instantiating the mixin standalone).- """+ """Render diff/stat text with color when a rich console is present; plain print otherwise+ (e.g. unit tests instantiating the mixin standalone)."""console = getattr(self, "console", None)if console is not None:try:@@ -353,12 +524,7 @@ class CLICommandsMixin:def _handle_snapshot_command(self, command: str):"""Handle /snapshot — lightweight state snapshots for Hermes config/state.- Syntax:- /snapshot — list recent snapshots- /snapshot create [label] — create a snapshot- /snapshot restore <id> — restore state from snapshot- /snapshot prune [N] — prune to N snapshots (default 20)- """+ Syntax: ``/snapshot`` (list), ``create [label]``, ``restore <id>``, ``prune [N]`` (default 20)."""from hermes_cli.backup import (create_quick_snapshot, list_quick_snapshots,restore_quick_snapshot, prune_quick_snapshots,@@ -399,7 +565,6 @@ class CLICommandsMixin:elif subcmd in {"restore", "rewind"}:if len(parts) < 3:print(" Usage: /snapshot restore <snapshot-id>")- # Show hint with most recent snapshotsnaps = list_quick_snapshots(limit=1)if snaps:print(f" Most recent: {snaps[0]['id']}")@@ -417,9 +582,7 @@ class CLICommandsMixin:except ValueError:pass- # Close our local SessionDB connection before restore so the- # backup-API restore doesn't contend with a live connection to- # state.db from this same process (issue #65942).+ # Close our SessionDB first so the restore doesn't contend with this process's live connection.local_session_db = getattr(self, "_session_db", None)if local_session_db is not None:try:@@ -453,13 +616,7 @@ class CLICommandsMixin:print(" Usage: /snapshot [list|create [label]|restore <id>|prune [N]]")def _handle_export_command(self, command: str):- """Handle /export — export a profile to a shareable .tar.gz archive.-- Syntax:- /export — export the active profile- /export <profile> — export a named profile- /export [profile] -o <path> — choose the output path- """+ """Handle /export [profile] [-o path] — export a profile to a shareable .tar.gz archive."""from hermes_cli.profiles import (export_profile,get_active_profile_name,@@ -531,19 +688,14 @@ class CLICommandsMixin:print(f" Use it: hermes -p {imported}")def _handle_stop_command(self):- """Handle /stop — kill all running background processes and- background (async) delegations.-- Inspired by OpenAI Codex's separation of interrupt (stop current turn)- from /stop (clean up background processes). See openai/codex#14602.- """+ """Handle /stop — kill all running background processes and background (async) delegations.+ Separate from interrupt (stop the current turn), as in Codex."""from tools.process_registry import process_registryprocesses = process_registry.list_sessions()running = [p for p in processes if p.get("status") == "running"]- # Background subagents dispatched via delegate_task(background=true)- # live in their own registry, not the process registry.+ # Background subagents live in their own registry, not the process registry.try:from tools.async_delegation import active_count, interrupt_alln_async = active_count()@@ -630,13 +782,9 @@ class CLICommandsMixin:_cprint(f" Agent: {'running' if agent_running else 'idle'}")def _handle_journey_command(self, cmd_original: str) -> None:- """Handle /journey — the learning timeline (see `hermes journey`).-- The read-only views (default + ``list``) render Rich color, which- patch_stdout would swallow as raw escapes; capture with forced ANSI and- re-emit through ``_cprint``. ``delete``/``edit`` are interactive- (confirm prompt / ``$EDITOR``) so they keep the real stdio.- """+ """Handle /journey — the learning timeline (see `hermes journey`). Read-only views render+ Rich color that patch_stdout would swallow, so capture with forced ANSI and re-emit via+ ``_cprint``; ``delete``/``edit`` are interactive and keep real stdio."""import argparseimport ioimport shlex@@ -667,12 +815,8 @@ class CLICommandsMixin:_cprint(f" /journey failed: {exc}")def _handle_paste_command(self):- """Handle /paste — explicitly check clipboard for an image.-- This is the reliable fallback for terminals where BracketedPaste- doesn't fire for image-only clipboard content (e.g., VSCode terminal,- Windows Terminal with WSL2).- """+ """Handle /paste — explicitly check the clipboard for an image; the reliable fallback where+ BracketedPaste doesn't fire for image-only clipboards (VSCode terminal, Windows Terminal/WSL2)."""from cli import _DIM, _RST, _cprint, _termux_example_image_pathif _is_termux_environment():_cprint(@@ -731,9 +875,7 @@ class CLICommandsMixin:write_clipboard_text,)if is_remote_shell_session():- # Over SSH, native tools would write the REMOTE clipboard- # (or an X-forwarded one) — OSC 52 reaches the terminal- # the user is actually sitting at. Fixes #31528.+ # Over SSH native tools write the REMOTE clipboard; OSC 52 reaches the user's terminal.self._write_osc52_clipboard(text)_cprint(f" Copied assistant response #{idx + 1} via OSC 52 "@@ -743,8 +885,7 @@ class CLICommandsMixin:if write_clipboard_text(text):_cprint(f" Copied assistant response #{idx + 1} to clipboard")return- # Native tools unavailable/failed — fall back to OSC 52 so- # SSH/tmux sessions can still copy via the terminal emulator.+ # Native tools unavailable/failed — OSC 52 fallback (SSH/tmux via the emulator).self._write_osc52_clipboard(text)_cprint(f" Copied assistant response #{idx + 1} via OSC 52 "@@ -779,14 +920,9 @@ class CLICommandsMixin:_cprint(f" {_DIM}Tip: type your next message, or run hermes chat -q --image {_termux_example_image_path(image_path.name)} \"What do you see?\"{_RST}")def _handle_tools_command(self, cmd: str):- """Handle /tools [list|disable|enable] slash commands.-- /tools (no args) shows the tool list.- /tools list shows enabled/disabled status per toolset.- /tools disable/enable saves the change to config and resets- the session so the new tool set takes effect cleanly (no- prompt-cache breakage mid-conversation).- """+ """Handle /tools [list|disable|enable]. Bare shows the tool list; ``list`` shows per-toolset+ status; disable/enable save to config and reset the session so the new tool set takes+ effect cleanly (no prompt-cache breakage mid-conversation)."""from cli import _ACCENT, _DIM, _RST, _cprintimport shlexfrom argparse import Namespace@@ -795,22 +931,15 @@ class CLICommandsMixin:from hermes_cli.tools_config import tools_disable_enable_commanddef _run_capture(ns: Namespace) -> None:- """Run tools_disable_enable_command, routing its ANSI-colored- print() output through _cprint when inside the interactive TUI- so escapes aren't mangled by patch_stdout's StdoutProxy into- garbled '?[32m...?[0m' text.-- Outside the TUI (standalone mode, tests), call straight through- so real stdout / pytest capture works as expected.- """+ """Run tools_disable_enable_command, routing its ANSI print() output through _cprint+ inside the interactive TUI so patch_stdout's StdoutProxy doesn't garble the escapes.+ Standalone/tests call straight through so real stdout / pytest capture works."""# Standalone/tests, run as usualif getattr(self, "_app", None) is None:tools_disable_enable_command(ns)return- # Buffer reports isatty()=True so color() in hermes_cli/colors.py- # still emits ANSI escapes. StringIO.isatty() is False, which- # would otherwise strip all colors before we re-render them.+ # isatty()=True so color() in hermes_cli/colors.py still emits ANSI escapes.class _TTYBuf(StringIO):def isatty(self) -> bool:return True@@ -842,16 +971,13 @@ class CLICommandsMixin:print(f" MCP tool: /tools {subcommand} github:create_issue")return- # Apply the change directly — the user typing the command is implicit- # consent. Do NOT use input() here; it hangs inside prompt_toolkit's- # TUI event loop (known pitfall).+ # Typing the command is consent. Do NOT use input() — it hangs in prompt_toolkit's loop.verb = "Disabling" if subcommand == "disable" else "Enabling"label = ", ".join(names)_cprint(f"{_ACCENT}{verb} {label}...{_RST}")_run_capture(Namespace(tools_action=subcommand, names=names, platform="cli"))- # Reset session so the new tool config is picked up from a clean statefrom hermes_cli.tools_config import _get_platform_toolsfrom hermes_cli.config import load_configself.enabled_toolsets = _get_platform_tools(load_config(), "cli")@@ -874,23 +1000,12 @@ class CLICommandsMixin:def _handle_handoff_command(self, cmd_original: str) -> bool:"""Handle ``/handoff <platform>`` — transfer this CLI session to a gateway platform.- Flow:- 1. Validate platform name + the gateway has a home channel for it.- 2. Reject if the agent is currently running (the in-flight turn- would race with the gateway's switch_session).- 3. Write ``handoff_state='pending'`` on this session row.- 4. Block-poll ``state.db``: 60s for the gateway to CLAIM the row- (pending), then up to 15 min for the claimed dispatch to reach a- terminal state (running → completed/failed) with heartbeats.- 5. On ``completed`` → print resume hint and signal CLI exit by- returning False (the caller honors that like ``/quit``).- 6. On ``failed`` / pending-timeout → print error and return True so- the user keeps their CLI session. A running-timeout leaves the- row untouched (the gateway owns it) and returns True.-- Returns:- False to signal CLI exit, True to keep going.- """+ Validates the platform + home channel, refuses mid-turn (an in-flight run would race the+ gateway's switch_session), writes ``handoff_state='pending'``, then block-polls state.db:+ 60s for the gateway to CLAIM the row, then up to 15 min (with heartbeats) for the claimed+ dispatch to finish. ``completed`` → resume hint + return False (caller exits like /quit).+ ``failed`` / pending-timeout → error + True (session kept). A running-timeout leaves the+ row untouched (the gateway owns it) and returns True."""from cli import _cprintfrom hermes_state import format_session_db_unavailable@@ -924,14 +1039,9 @@ class CLICommandsMixin:pcfg = gw_config.platforms.get(platform)if not pcfg or not pcfg.enabled:- # Relay aliasing: a relay-fronted gateway has no per-platform- # config block for the logical platform ("discord" etc.) — only a- # RELAY entry — yet /handoff discord is deliverable when the relay- # fronts it. The fronted set is deploy config- # (GATEWAY_RELAY_PLATFORMS), readable here without the live- # adapter; the gateway watcher re-checks against the authenticated- # transport (resolve_delivery_transport) before dispatch, so this- # is a UX pre-check, not the security gate.+ # Relay aliasing: a relay-fronted gateway has only a RELAY config block, yet+ # /handoff discord is deliverable when the relay fronts it. UX pre-check only —+ # the gateway watcher re-checks against the authenticated transport before dispatch.relay_fronts = Falsetry:from gateway.relay import relay_platform_identities@@ -968,17 +1078,12 @@ class CLICommandsMixin:_cprint(f" {format_session_db_unavailable()}")return True- # Make sure the session row exists in state.db. Most CLI sessions- # are written via _flush_messages_to_session_db on the first turn- # already, but if the user tries to hand off an empty session we- # still want a row to mark.+ # Ensure the session row exists (an empty session has flushed nothing yet): the+ # gateway needs a row to switch_session onto; set_session_title's INSERT OR IGNORE+ # creates it.try:row = self._session_db.get_session(self.session_id)if not row:- # Nothing has flushed yet. Create a stub so the gateway has- # something to switch_session onto. Inserting via title-set- # is the simplest path because set_session_title's INSERT OR- # IGNORE creates the row.placeholder_title = f"handoff-{self.session_id[:8]}"self._session_db.set_session_title(self.session_id, placeholder_title)except Exception as exc:@@ -1005,25 +1110,12 @@ class CLICommandsMixin:_cprint(f" Queued handoff of '{session_title}' → {platform_name} (home: {home.name}).")_cprint(" Waiting for the gateway to pick it up...")- # Two-phase poll, tick every 0.5s.- #- # PENDING (nobody claimed the row): 60s deadline. A timeout here- # genuinely means no gateway watcher is looking at this state.db —- # "Is `hermes gateway` running?" is the correct diagnosis, and the- # CAS fail (only_states=("pending",)) can't stomp a claim that lands- # in the same instant.- #- # RUNNING (gateway claimed it): the gateway owns the row and is- # replaying the full transcript through a synthetic agent turn —- # routinely slower than 60s on long sessions with reasoning models.- # Timing out here and failing the row is the bug this replaces: the- # CLI printed "Is `hermes gateway` running?" while the gateway was- # mid-delivery, then the watcher overwrote failed → completed- # (split-brain; the session HAD been switched under the CLI). So in- # this phase we wait with a much longer bound and a periodic- # heartbeat, and on timeout we do NOT touch the row — the gateway- # reaches its own terminal state (or the next gateway startup- # reclaims a stranded 'running' row).+ # Two-phase poll, tick every 0.5s. PENDING (unclaimed): 60s — a timeout means no+ # gateway watcher is looking at this state.db, and the CAS fail can't stomp a claim+ # landing the same instant. RUNNING (claimed): the gateway replays the full+ # transcript via a synthetic turn (routinely >60s), so wait much longer with a+ # heartbeat and on timeout do NOT touch the row — failing it here was the+ # split-brain bug (CLI said "failed" while the gateway completed the switch).import time as _time_PENDING_TIMEOUT = 60.0_RUNNING_TIMEOUT = 900.0 # full synthetic agent turn + delivery@@ -1049,12 +1141,9 @@ class CLICommandsMixin:_cprint(f" ↻ Handoff complete. The session is now active on {platform_name}.")_cprint(f" Resume it on this CLI later with: /resume {session_title}")_cprint("")- # Mark this session as handed off so _run_cleanup does NOT- # finalize it on CLI exit. The gateway reopened the session- # row and now owns its lifecycle; a CLI cleanup finalize would- # set end_reason on the row the gateway is actively writing- # to, causing the handoff leg to vanish from session history- # and session_search (#88234).+ # Mark handed off so _run_cleanup does NOT finalize it on exit: the gateway+ # owns the row now, and setting end_reason under it would drop the handoff+ # leg from session history / session_search.from cli import _handed_off_session_ids_handed_off_session_ids.add(self.session_id)# End the CLI cleanly — same exit semantics as /quit.@@ -1074,9 +1163,7 @@ class CLICommandsMixin:_cprint(" Still transferring (the agent is replaying your session on the destination)...")next_heartbeat = now + _HEARTBEAT_EVERYif running_deadline is not None and now >= running_deadline:- # Do NOT fail the row: the gateway owns it and will record- # its own terminal state (or startup reclaim handles a- # dead gateway). Stomping it here is the split-brain bug.+ # Do NOT fail the row: the gateway owns it (split-brain bug otherwise)._cprint(" The gateway is taking unusually long to finish the transfer.")_cprint(f" Check {platform_name} — the session may still arrive there.")_cprint(" This CLI is no longer waiting. Avoid continuing this session here;")@@ -1084,9 +1171,8 @@ class CLICommandsMixin:return True_time.sleep(0.5)- # Pending timed out: nothing ever claimed the row. Clear the pending- # flag (CAS — a claim racing this exact moment wins and we just lose- # the retry convenience, never the handoff) so the user can retry.+ # Pending timed out: clear the flag so the user can retry (CAS — a claim racing this+ # instant wins; we lose only the retry convenience, never the handoff).try:self._session_db.fail_handoff(self.session_id,@@ -1094,8 +1180,7 @@ class CLICommandsMixin:only_states=("pending",),)except TypeError:- # Older SessionDB without only_states (downgrade/mixed installs):- # fall back to the legacy unconditional fail.+ # Older SessionDB without only_states (mixed installs): legacy unconditional fail.try:self._session_db.fail_handoff(self.session_id, "timed out waiting for gateway")except Exception:@@ -1112,28 +1197,16 @@ class CLICommandsMixin:parts = cmd_original.split(None, 1)target = parts[1].strip() if len(parts) > 1 else ""- # Strip common outer brackets/quotes users may type literally from the- # usage hint (e.g. ``/resume <abc123>`` or ``/resume [abc123]``). The- # `/resume` help text shows angle brackets as a placeholder and a few- # users copy them through verbatim. Stripping them keeps the lookup- # working without changing the help string.- if len(target) >= 2 and (- (target[0] == "<" and target[-1] == ">")- or (target[0] == "[" and target[-1] == "]")- or (target[0] == '"' and target[-1] == '"')- or (target[0] == "'" and target[-1] == "'")- ):+ # Users copy the help text's placeholder brackets/quotes verbatim (``/resume <abc123>``).+ if len(target) >= 2 and (target[0], target[-1]) in {("<", ">"), ("[", "]"), ('"', '"'), ("'", "'")}:target = target[1:-1].strip()if not target:_cprint(" Usage: /resume <number|session_id_or_title>")if self._show_recent_sessions(reason="resume"):- # Arm a one-shot pending-resume selection so the user can type- # just the number (`3`) on the next line instead of having to- # retype `/resume 3`. The list here must match the one shown by- # _show_recent_sessions and used for index resolution below —- # all three go through _list_recent_sessions(limit=10). See- # #34584.+ # Arm a one-shot pending-resume selection so a bare number on the next line+ # works. Must be the same list _show_recent_sessions showed and the numbered+ # branch below resolves — all three use _list_recent_sessions(limit=10).self._pending_resume_sessions = self._list_recent_sessions(limit=10)return_cprint(" Tip: Use /history or `hermes sessions list` to find sessions.")@@ -1190,20 +1263,7 @@ class CLICommandsMixin:returnold_session_id = self.session_id- # Flush un-persisted messages before ending the old session (#47202).- if self.agent:- try:- self.agent._flush_messages_to_session_db(- self.conversation_history,- conversation_history=self.conversation_history,- )- except Exception:- pass- # End current session- try:- self._session_db.end_session(self.session_id, "resumed_other")- except Exception:- pass+ _end_current_session(self, "resumed_other")# Switch to the target sessionself.session_id = target_id@@ -1211,25 +1271,13 @@ class CLICommandsMixin:self._pending_title = None_sync_process_session_id(target_id)- # Load conversation history (strip transcript-only metadata entries).- # repair_alternation: this /resume feeds LIVE REPLAY — ``restored``- # becomes ``self.conversation_history`` for subsequent turns. Heal a- # durable ``user;user`` violation once here instead of re-firing the- # pre-request repair on every request for the rest of the session.- ## Both projections come from one lineage SELECT: model_history is- # alternation-repaired for live replay; display_history is the full- # lineage verbatim, used by _display_resumed_history() so timeline- # events and ancestor rows render correctly (matching the startup- # --resume path in _preload_resumed_session).- model_history, display_history = self._session_db.get_resume_conversations(- target_id- )- restored = [m for m in (model_history or []) if m.get("role") != "session_meta"]- self.conversation_history = restored- self._resume_display_history = [- m for m in (display_history or []) if m.get("role") != "session_meta"- ]+ # alternation-repaired for LIVE REPLAY (heals a durable ``user;user`` violation+ # once instead of on every request); display_history is the full lineage+ # verbatim for _display_resumed_history() (matches startup --resume).+ model_history, display_history = self._session_db.get_resume_conversations(target_id)+ self.conversation_history = [m for m in (model_history or []) if m.get("role") != "session_meta"]+ self._resume_display_history = [m for m in (display_history or []) if m.get("role") != "session_meta"]# Re-open the target session so it's not marked as endedtry:@@ -1237,42 +1285,13 @@ class CLICommandsMixin:except Exception:pass- # Sync the agent if already initialised- if self.agent:- self.agent.session_id = target_id- self.agent.reset_session_state()- if hasattr(self.agent, "_last_flushed_db_idx"):- self.agent._last_flushed_db_idx = len(self.conversation_history)- if hasattr(self.agent, "_todo_store"):- try:- from tools.todo_tool import TodoStore- self.agent._todo_store = TodoStore()- except Exception:- pass- if hasattr(self.agent, "_invalidate_system_prompt"):- self.agent._invalidate_system_prompt()-- # Notify memory providers that session_id rotated to a resumed- # session. reset=False — the provider's accumulated state is- # still valid; it just needs to target the new session_id for- # subsequent writes. See #6672.- try:- _mm = getattr(self.agent, "_memory_manager", None)- if _mm is not None:- _mm.on_session_switch(- target_id,- parent_session_id=old_session_id or "",- reset=False,- reason="resume",- )- except Exception:- pass+ _sync_agent_to_session(self, target_id, parent_session_id=old_session_id, reason="resume")title_part = f" \"{session_meta['title']}\"" if session_meta.get("title") else ""from agent.context_compressor import is_user_originated_turn- # Count only user-originated turns (#80622): legacy compaction- # handoffs are durable role=user rows without display_kind.+ # Count only user-originated turns: legacy compaction handoffs are durable+ # role=user rows without display_kind.msg_count = len([m for m in self._resume_display_history if is_user_originated_turn(m)])if self.conversation_history:_cprint(@@ -1284,40 +1303,20 @@ class CLICommandsMixin:else:_cprint(f" ↻ Resumed session {target_id}{title_part} — no messages, starting fresh.")- # Retarget the process + tool cwd to where the session was started, so a- # mid-chat /resume (and /sessions <id>, which delegates here) lands in the- # same directory as a startup `hermes -c`/`--resume`. The startup resume- # paths already call this; without it, the terminal/code-exec tools and- # relative-path resolution keep operating in the wrong repo. Idempotent- # and a no-op when the session recorded no cwd. See #38562.+ # Same contract as a startup --resume: retarget the process/tool cwd (else the+ # terminal tools keep operating in the wrong repo), restore the target session's+ # persisted YOLO bypass (the previous session's stops applying — the approval+ # session key changed), and its model/provider (else it reverts to config default).self._restore_session_cwd(session_meta)-- # Restore the target session's persisted YOLO bypass. Any bypass the- # PREVIOUS session had toggled on stops applying automatically because- # the approval session key just changed. Same contract as a startup- # --resume.self._restore_session_yolo(session_meta)-- # Restore the target session's model/provider so a mid-chat /resume- # doesn't silently revert to the config default. Same contract as a- # startup --resume (_preload_resumed_session / _init_agent path).self._restore_session_model(session_meta)def _handle_sessions_command(self, cmd_original: str) -> None:"""Handle /sessions [list|<id_or_title>] — browse or resume previous sessions.- Without arguments, prints the same recent-sessions table that /resume- shows when called without a target, and tells the user how to resume.- With an explicit subcommand or target, delegates to the resume flow so- ``/sessions <id>`` and ``/resume <id>`` behave identically.-- The TUI ships an interactive picker overlay for this command; the- classic CLI prints an inline list because there is no equivalent- overlay primitive here. Without this handler the canonical name- ``sessions`` falls through ``process_command``'s elif chain and- prints ``Unknown command: sessions`` even though the command is- registered in the central COMMAND_REGISTRY.- """+ Bare/``list`` prints the same recent-sessions table /resume shows; an explicit target+ delegates to the resume flow so ``/sessions <id>`` and ``/resume <id>`` behave identically.+ (The TUI has a picker overlay; the classic CLI prints inline.)"""from cli import _cprintparts = cmd_original.split(None, 1)arg = parts[1].strip() if len(parts) > 1 else ""@@ -1345,16 +1344,10 @@ class CLICommandsMixin:/worktree list — list worktrees under the repo's .worktrees//worktree prune [--dry-run] — reclaim safe trees + merged branches- Inspired by Copilot CLI's ``/worktree new``: start isolated work in a- fresh worktree without leaving the session. Creating one retargets the- terminal/file tools (``TERMINAL_CWD`` + process cwd) at the new tree;- the launcher's exit cleanup applies (kept only when it has unpushed- commits, same as ``hermes -w``).-- ``prune`` is the same attended reclaim as ``hermes worktree prune``- (hermes_cli/worktree_gc.py): never deletes tracked changes, unique- unpushed commits, or in-use trees; archives untracked-only scratch.- """+ ``new`` retargets the terminal/file tools (``TERMINAL_CWD`` + process cwd) at the new+ tree; the launcher's exit cleanup applies (kept only with unpushed commits, as ``hermes -w``).+ ``prune`` is the attended reclaim from hermes_cli/worktree_gc.py: never deletes tracked+ changes, unique unpushed commits, or in-use trees."""import subprocessimport cli as _cli@@ -1389,8 +1382,7 @@ class CLICommandsMixin:active = _cli._active_worktreetree_records = worktree_gc.audit_worktrees(repo_root, with_sizes=False)if active:- # Never reap the tree this very session is sitting in, even- # if a concurrent audit would judge it clean+merged.+ # Never reap the tree this session is sitting in, even if judged clean+merged.active_path = str(active.get("path") or "")tree_records = [record for record in tree_records@@ -1452,16 +1444,14 @@ class CLICommandsMixin:)if not wt_info:return # _setup_worktree already printed the failure- # Retarget the session's terminal/file tools at the new tree, the- # same way `hermes -w` and session-resume cwd restore do.+ # Retarget the session's terminal/file tools at the new tree (as `hermes -w` does).try:os.chdir(wt_info["path"])except OSError as e:print(f" ⚠ Created worktree but could not enter it: {e}")os.environ["TERMINAL_CWD"] = wt_info["path"]- # Register for the same keep-if-unpushed cleanup as `hermes -w`.- # Only one worktree is tracked as "active" per process; an earlier- # one keeps its own atexit registration (explicit info arg).+ # Same keep-if-unpushed cleanup as `hermes -w`. Only one tree is "active" per+ # process; an earlier one keeps its own atexit registration (explicit info arg).import atexit_cli._active_worktree = wt_infoatexit.register(_cli._cleanup_worktree, wt_info)@@ -1474,12 +1464,8 @@ class CLICommandsMixin:print(" Usage: /worktree [new [name] | list]")def _handle_branch_command(self, cmd_original: str) -> None:- """Handle /branch [name] — fork the current session into a new independent copy.-- Copies the full conversation history to a new session so the user can- explore a different approach without losing the original session state.- Inspired by Claude Code's /branch command.- """+ """Handle /branch [name] — fork the current session into a new independent copy of the+ full history so a different approach can be explored without losing the original."""from cli import _cprint, _sync_process_session_idif not self.conversation_history:_cprint(" No conversation to branch — send a message first.")@@ -1512,28 +1498,11 @@ class CLICommandsMixin:# Save the current session's state before branchingparent_session_id = self.session_id+ _end_current_session(self, "branched")- # Flush un-persisted messages before ending the old session (#47202).- if self.agent:- try:- self.agent._flush_messages_to_session_db(- self.conversation_history,- conversation_history=self.conversation_history,- )- except Exception:- pass-- # End the old session- try:- self._session_db.end_session(self.session_id, "branched")- except Exception:- pass-- # Create the new session with parent link.- # Persist a stable ``_branched_from`` marker in model_config so- # list_sessions_rich() can keep the branch visible in /resume and- # /sessions even after the parent is reopened and re-ended with a- # different end_reason (e.g. tui_shutdown overwriting 'branched').+ # Create the new session with parent link. The stable ``_branched_from`` marker keeps+ # the branch visible in /resume + /sessions even after the parent is re-ended with a+ # different end_reason.try:self._session_db.create_session(session_id=new_session_id,@@ -1550,9 +1519,7 @@ class CLICommandsMixin:_cprint(f" Failed to create branch session: {e}")return- # Copy conversation history to the new session in bounded-chunk- # transactions (see #23254) instead of one txn per row. Best-effort- # like the old loop — a failed copy still yields a usable branch.+ # Copy history in bounded-chunk transactions. Best-effort: a failed copy still yields a usable branch.try:self._session_db.append_messages_batch(new_session_id,@@ -1567,9 +1534,8 @@ class CLICommandsMixin:"reasoning_details": msg.get("reasoning_details"),"codex_reasoning_items": msg.get("codex_reasoning_items"),"codex_message_items": msg.get("codex_message_items"),- # Keep the api_content sidecar so the branch's first turn- # replays the parent's exact wire bytes (warm provider- # prompt cache) instead of a full cold prefill.+ # api_content sidecar: the branch's first turn replays the parent's exact+ # wire bytes (warm prompt cache) instead of a cold prefill."api_content": extract_api_content_sidecar(msg),"timestamp": msg.get("timestamp"),}@@ -1596,35 +1562,8 @@ class CLICommandsMixin:# Sync the agentif self.agent:- self.agent.session_id = new_session_idself.agent.session_start = now- self.agent.reset_session_state()- if hasattr(self.agent, "_last_flushed_db_idx"):- self.agent._last_flushed_db_idx = len(self.conversation_history)- if hasattr(self.agent, "_todo_store"):- try:- from tools.todo_tool import TodoStore- self.agent._todo_store = TodoStore()- except Exception:- pass- if hasattr(self.agent, "_invalidate_system_prompt"):- self.agent._invalidate_system_prompt()-- # Notify memory providers that session_id forked to a new branch.- # reset=False — the branched session carries the transcript- # forward, so provider state tracks the lineage. parent_session_id- # links the branch back to the original. See #6672.- try:- _mm = getattr(self.agent, "_memory_manager", None)- if _mm is not None:- _mm.on_session_switch(- new_session_id,- parent_session_id=parent_session_id or "",- reset=False,- reason="branch",- )- except Exception:- pass+ _sync_agent_to_session(self, new_session_id, parent_session_id=parent_session_id, reason="branch")msg_count = len([m for m in self.conversation_history if m.get("role") == "user"])_cprint(@@ -1714,15 +1653,9 @@ class CLICommandsMixin:def _handle_pet_command(self, cmd: str):"""Toggle, browse, or adopt a petdex mascot.- ``/pet`` / ``/pet toggle`` → flip ``display.pet.enabled`` on/off- ``/pet list`` → browse the petdex gallery- ``/pet scale <n>`` → resize the pet everywhere (e.g. 0.5)- ``/pet <slug>`` → adopt (install if needed) + make active- ``/pet off`` → disable (alias for toggle-off)-- Writes ``display.pet.*`` to config; the CLI/TUI/desktop pet surfaces- pick the change up on their next poll, so the pet appears shortly.- """+ ``/pet`` / ``/pet toggle`` flips ``display.pet.enabled``; ``list`` browses the gallery;+ ``scale <n>`` resizes; ``<slug>`` adopts (installs if needed); ``off`` disables.+ Writes ``display.pet.*`` to config; pet surfaces pick it up on their next poll."""from agent.pet import storefrom agent.pet.manifest import ManifestErrorfrom hermes_cli.pets import _set_active, _set_enabled, print_pet_gallery, set_pet_scale, toggle_pet_display@@ -1770,14 +1703,9 @@ class CLICommandsMixin:print(f"(^_^)b {pet.display_name} is out — it'll pop in shortly.")def _handle_hatch_command(self, cmd: str):- """Generate ("hatch") a brand-new petdex pet from a description.-- ``/hatch <description>`` runs the full pet pipeline in-process: a base- look, then one grounded animation row per state, sliced + normalized into- a spritesheet, then adopted as the active mascot. Progress streams inline- (it's ~a minute of image-model calls). In the desktop app this command- opens the richer generate overlay instead; here we run it directly.- """+ """Generate ("hatch") a new petdex pet from a description: base look, one animation row+ per state, spritesheet, then adopt. Progress streams inline (~a minute of image calls).+ The desktop app opens a richer overlay for this command instead."""from agent.pet import storefrom agent.pet.generate import orchestratefrom agent.pet.generate.imagegen import GenerationError@@ -1787,14 +1715,9 @@ class CLICommandsMixin:concept = parts[1].strip() if len(parts) > 1 else ""if not concept:- # Bare /hatch is dispatched from the process_loop daemon thread- # while prompt_toolkit owns stdin — a raw input() here types into- # a prompt that never renders and swallows the next keystrokes- # (same class as #23185; found in the Aug 2026 full-surface CLI- # QA sweep: bare /hatch left the session eating input until- # Ctrl+C). Route through the thread-aware prompt helper, which- # uses run_in_terminal on the main thread and cancels cleanly- # (None) when prompting isn't safe.+ # Dispatched from the process_loop daemon thread while prompt_toolkit owns+ # stdin — a raw input() here never renders and eats keystrokes. Use the+ # thread-aware prompt helper (run_in_terminal; None when prompting isn't safe).prompt_helper = getattr(self, "_prompt_text_input", None)if callable(prompt_helper):concept = (prompt_helper("(o_o) Describe your pet: ") or "").strip()@@ -1851,263 +1774,181 @@ class CLICommandsMixin:def _handle_cron_command(self, cmd: str):"""Handle the /cron command to manage scheduled tasks."""- from cli import get_jobimport shlex- from tools.cronjob_tools import cronjob as cronjob_tool-- def _cron_api(**kwargs):- return json.loads(cronjob_tool(**kwargs))-- def _normalize_skills(values):- normalized = []- for value in values:- text = str(value or "").strip()- if text and text not in normalized:- normalized.append(text)- return normalized-- def _parse_flags(tokens):- opts = {- "name": None,- "deliver": None,- "repeat": None,- "skills": [],- "add_skills": [],- "remove_skills": [],- "clear_skills": False,- "all": False,- "prompt": None,- "schedule": None,- "positionals": [],- }- i = 0- while i < len(tokens):- token = tokens[i]- if token == "--name" and i + 1 < len(tokens):- opts["name"] = tokens[i + 1]- i += 2- elif token == "--deliver" and i + 1 < len(tokens):- opts["deliver"] = tokens[i + 1]- i += 2- elif token == "--repeat" and i + 1 < len(tokens):- try:- opts["repeat"] = int(tokens[i + 1])- except ValueError:- print("(._.) --repeat must be an integer")- return None- i += 2- elif token == "--skill" and i + 1 < len(tokens):- opts["skills"].append(tokens[i + 1])- i += 2- elif token == "--add-skill" and i + 1 < len(tokens):- opts["add_skills"].append(tokens[i + 1])- i += 2- elif token == "--remove-skill" and i + 1 < len(tokens):- opts["remove_skills"].append(tokens[i + 1])- i += 2- elif token == "--clear-skills":- opts["clear_skills"] = True- i += 1- elif token == "--all":- opts["all"] = True- i += 1- elif token == "--prompt" and i + 1 < len(tokens):- opts["prompt"] = tokens[i + 1]- i += 2- elif token == "--schedule" and i + 1 < len(tokens):- opts["schedule"] = tokens[i + 1]- i += 2- else:- opts["positionals"].append(token)- i += 1- return optstokens = shlex.split(cmd)-if len(tokens) == 1:- print()- print("+" + "-" * 68 + "+")- print("|" + " " * 22 + "(^_^) Scheduled Tasks" + " " * 23 + "|")- print("+" + "-" * 68 + "+")- print()- print(" Commands:")- print(" /cron list")- print(' /cron add "every 2h" "Check server status" [--skill blogwatcher]')- print(' /cron edit <job_id> --schedule "every 4h" --prompt "New task"')- print(" /cron edit <job_id> --skill blogwatcher --skill maps")- print(" /cron edit <job_id> --remove-skill blogwatcher")- print(" /cron edit <job_id> --clear-skills")- print(" /cron pause <job_id>")- print(" /cron resume <job_id>")- print(" /cron run <job_id>")- print(" /cron remove <job_id>")- print()- result = _cron_api(action="list")- jobs = result.get("jobs", []) if result.get("success") else []- if jobs:- print(" Current Jobs:")- print(" " + "-" * 63)- for job in jobs:- repeat_str = job.get("repeat", "?")- print(f" {job['job_id'][:12]:<12} | {job['schedule']:<15} | {repeat_str:<8}")- if job.get("skills"):- print(f" Skills: {', '.join(job['skills'])}")- print(f" {job.get('prompt_preview', '')}")- if job.get("next_run_at"):- print(f" Next: {job['next_run_at']}")- print()- else:- print(" No scheduled jobs. Use '/cron add' to create one.")- print()+ self._cron_overview()return-subcommand = tokens[1].lower()- opts = _parse_flags(tokens[2:])+ opts = _parse_cron_flags(tokens[2:])if opts is None:return+ handler = _CRON_SUBCOMMANDS.get(subcommand)+ if handler is None:+ print(f"(._.) Unknown cron command: {subcommand}")+ print(" Available: list, add, edit, pause, resume, run, remove")+ return+ handler(self, subcommand, opts)- if subcommand == "list":- result = _cron_api(action="list", include_disabled=opts["all"])- jobs = result.get("jobs", []) if result.get("success") else []- if not jobs:- print("(._.) No scheduled jobs.")- return-- print()- print("Scheduled Jobs:")- print("-" * 80)+ def _cron_overview(self) -> None:+ print()+ print("+" + "-" * 68 + "+")+ print("|" + " " * 22 + "(^_^) Scheduled Tasks" + " " * 23 + "|")+ print("+" + "-" * 68 + "+")+ print()+ print(" Commands:")+ print(" /cron list")+ print(' /cron add "every 2h" "Check server status" [--skill blogwatcher]')+ print(' /cron edit <job_id> --schedule "every 4h" --prompt "New task"')+ print(" /cron edit <job_id> --skill blogwatcher --skill maps")+ print(" /cron edit <job_id> --remove-skill blogwatcher")+ print(" /cron edit <job_id> --clear-skills")+ print(" /cron pause <job_id>")+ print(" /cron resume <job_id>")+ print(" /cron run <job_id>")+ print(" /cron remove <job_id>")+ print()+ result = _cron_api(action="list")+ jobs = result.get("jobs", []) if result.get("success") else []+ if jobs:+ print(" Current Jobs:")+ print(" " + "-" * 63)for job in jobs:- print(f" ID: {job['job_id']}")- print(f" Name: {job['name']}")- print(f" State: {job.get('state', '?')}")- print(f" Schedule: {job['schedule']} ({job.get('repeat', '?')})")- print(f" Next run: {job.get('next_run_at', 'N/A')}")+ repeat_str = job.get("repeat", "?")+ print(f" {job['job_id'][:12]:<12} | {job['schedule']:<15} | {repeat_str:<8}")if job.get("skills"):- print(f" Skills: {', '.join(job['skills'])}")- print(f" Prompt: {job.get('prompt_preview', '')}")- if job.get("last_run_at"):- status = job.get("last_status") or "?"- # delivery_failed: the agent ran fine but the output never- # reached the target — name the delivery reason, which- # lives in last_delivery_error (last_error is None).- if status == "delivery_failed" and job.get("last_delivery_error"):- status = f"delivery_failed: {job['last_delivery_error']}"- print(f" Last run: {job['last_run_at']} ({status})")+ print(f" Skills: {', '.join(job['skills'])}")+ print(f" {job.get('prompt_preview', '')}")+ if job.get("next_run_at"):+ print(f" Next: {job['next_run_at']}")print()+ else:+ print(" No scheduled jobs. Use '/cron add' to create one.")+ print()++ def _cron_list(self, subcommand: str, opts: dict) -> None:+ result = _cron_api(action="list", include_disabled=opts["all"])+ jobs = result.get("jobs", []) if result.get("success") else []+ if not jobs:+ print("(._.) No scheduled jobs.")return+ print()+ print("Scheduled Jobs:")+ print("-" * 80)+ for job in jobs:+ print(f" ID: {job['job_id']}")+ print(f" Name: {job['name']}")+ print(f" State: {job.get('state', '?')}")+ print(f" Schedule: {job['schedule']} ({job.get('repeat', '?')})")+ print(f" Next run: {job.get('next_run_at', 'N/A')}")+ if job.get("skills"):+ print(f" Skills: {', '.join(job['skills'])}")+ print(f" Prompt: {job.get('prompt_preview', '')}")+ if job.get("last_run_at"):+ status = job.get("last_status") or "?"+ # delivery_failed: the run succeeded but delivery didn't — the reason lives+ # in last_delivery_error (last_error is None).+ if status == "delivery_failed" and job.get("last_delivery_error"):+ status = f"delivery_failed: {job['last_delivery_error']}"+ print(f" Last run: {job['last_run_at']} ({status})")+ print()- if subcommand in {"add", "create"}:- positionals = opts["positionals"]- if not positionals:- print("(._.) Usage: /cron add <schedule> <prompt>")- return- schedule = opts["schedule"] or positionals[0]- prompt = opts["prompt"] or " ".join(positionals[1:])- skills = _normalize_skills(opts["skills"])- if not prompt and not skills:- print("(._.) Please provide a prompt or at least one skill")- return- result = _cron_api(- action="create",- schedule=schedule,- prompt=prompt or None,- name=opts["name"],- deliver=opts["deliver"],- repeat=opts["repeat"],- skills=skills or None,- )- if result.get("success"):- print(f"(^_^)b Created job: {result['job_id']}")- print(f" Schedule: {result['schedule']}")- if result.get("skills"):- print(f" Skills: {', '.join(result['skills'])}")- print(f" Next run: {result['next_run_at']}")- else:- print(f"(x_x) Failed to create job: {result.get('error')}")+ def _cron_add(self, subcommand: str, opts: dict) -> None:+ positionals = opts["positionals"]+ if not positionals:+ print("(._.) Usage: /cron add <schedule> <prompt>")return+ schedule = opts["schedule"] or positionals[0]+ prompt = opts["prompt"] or " ".join(positionals[1:])+ skills = _normalize_skills(opts["skills"])+ if not prompt and not skills:+ print("(._.) Please provide a prompt or at least one skill")+ return+ result = _cron_api(+ action="create", schedule=schedule, prompt=prompt or None, name=opts["name"],+ deliver=opts["deliver"], repeat=opts["repeat"], skills=skills or None,+ )+ if result.get("success"):+ print(f"(^_^)b Created job: {result['job_id']}")+ print(f" Schedule: {result['schedule']}")+ if result.get("skills"):+ print(f" Skills: {', '.join(result['skills'])}")+ print(f" Next run: {result['next_run_at']}")+ else:+ print(f"(x_x) Failed to create job: {result.get('error')}")- if subcommand == "edit":- positionals = opts["positionals"]- if not positionals:- print("(._.) Usage: /cron edit <job_id> [--schedule ...] [--prompt ...] [--skill ...]")- return- job_id = positionals[0]- existing = get_job(job_id)- if not existing:- print(f"(._.) Job not found: {job_id}")- return+ def _cron_edit(self, subcommand: str, opts: dict) -> None:+ from cli import get_job- final_skills = None- replacement_skills = _normalize_skills(opts["skills"])- add_skills = _normalize_skills(opts["add_skills"])- remove_skills = set(_normalize_skills(opts["remove_skills"]))- existing_skills = list(existing.get("skills") or ([] if not existing.get("skill") else [existing.get("skill")]))- if opts["clear_skills"]:- final_skills = []- elif replacement_skills:- final_skills = replacement_skills- elif add_skills or remove_skills:- final_skills = [skill for skill in existing_skills if skill not in remove_skills]- for skill in add_skills:- if skill not in final_skills:- final_skills.append(skill)-- result = _cron_api(- action="update",- job_id=job_id,- schedule=opts["schedule"],- prompt=opts["prompt"],- name=opts["name"],- deliver=opts["deliver"],- repeat=opts["repeat"],- skills=final_skills,- )- if result.get("success"):- job = result["job"]- print(f"(^_^)b Updated job: {job['job_id']}")- print(f" Schedule: {job['schedule']}")- if job.get("skills"):- print(f" Skills: {', '.join(job['skills'])}")- else:- print(" Skills: none")+ positionals = opts["positionals"]+ if not positionals:+ print("(._.) Usage: /cron edit <job_id> [--schedule ...] [--prompt ...] [--skill ...]")+ return+ job_id = positionals[0]+ existing = get_job(job_id)+ if not existing:+ print(f"(._.) Job not found: {job_id}")+ return++ # Skill edit precedence: --clear-skills > --skill (replace) > --add/--remove (merge) > untouched.+ final_skills = None+ replacement_skills = _normalize_skills(opts["skills"])+ add_skills = _normalize_skills(opts["add_skills"])+ remove_skills = set(_normalize_skills(opts["remove_skills"]))+ existing_skills = list(existing.get("skills") or ([] if not existing.get("skill") else [existing.get("skill")]))+ if opts["clear_skills"]:+ final_skills = []+ elif replacement_skills:+ final_skills = replacement_skills+ elif add_skills or remove_skills:+ final_skills = [skill for skill in existing_skills if skill not in remove_skills]+ for skill in add_skills:+ if skill not in final_skills:+ final_skills.append(skill)++ result = _cron_api(+ action="update", job_id=job_id, schedule=opts["schedule"], prompt=opts["prompt"],+ name=opts["name"], deliver=opts["deliver"], repeat=opts["repeat"], skills=final_skills,+ )+ if result.get("success"):+ job = result["job"]+ print(f"(^_^)b Updated job: {job['job_id']}")+ print(f" Schedule: {job['schedule']}")+ if job.get("skills"):+ print(f" Skills: {', '.join(job['skills'])}")else:- print(f"(x_x) Failed to update job: {result.get('error')}")- return+ print(" Skills: none")+ else:+ print(f"(x_x) Failed to update job: {result.get('error')}")- if subcommand in {"pause", "resume", "run", "remove", "rm", "delete"}:- positionals = opts["positionals"]- if not positionals:- print(f"(._.) Usage: /cron {subcommand} <job_id>")- return- job_id = positionals[0]- action = "remove" if subcommand in {"remove", "rm", "delete"} else subcommand- result = _cron_api(action=action, job_id=job_id, reason="paused from /cron" if action == "pause" else None)- if not result.get("success"):- print(f"(x_x) Failed to {action} job: {result.get('error')}")- return- if action == "pause":- print(f"(^_^)b Paused job: {result['job']['name']} ({job_id})")- elif action == "resume":- print(f"(^_^)b Resumed job: {result['job']['name']} ({job_id})")- print(f" Next run: {result['job'].get('next_run_at')}")- elif action == "run":- print(f"(^_^)b Triggered job: {result['job']['name']} ({job_id})")- print(" It will run on the next scheduler tick.")- else:- removed = result.get("removed_job", {})- print(f"(^_^)b Removed job: {removed.get('name', job_id)} ({job_id})")+ def _cron_job_action(self, subcommand: str, opts: dict) -> None:+ """pause / resume / run / remove (aliases rm, delete) on one job id."""+ positionals = opts["positionals"]+ if not positionals:+ print(f"(._.) Usage: /cron {subcommand} <job_id>")return-- print(f"(._.) Unknown cron command: {subcommand}")- print(" Available: list, add, edit, pause, resume, run, remove")+ job_id = positionals[0]+ action = "remove" if subcommand in {"remove", "rm", "delete"} else subcommand+ result = _cron_api(action=action, job_id=job_id, reason="paused from /cron" if action == "pause" else None)+ if not result.get("success"):+ print(f"(x_x) Failed to {action} job: {result.get('error')}")+ return+ if action == "pause":+ print(f"(^_^)b Paused job: {result['job']['name']} ({job_id})")+ elif action == "resume":+ print(f"(^_^)b Resumed job: {result['job']['name']} ({job_id})")+ print(f" Next run: {result['job'].get('next_run_at')}")+ elif action == "run":+ print(f"(^_^)b Triggered job: {result['job']['name']} ({job_id})")+ print(" It will run on the next scheduler tick.")+ else:+ removed = result.get("removed_job", {})+ print(f"(^_^)b Removed job: {removed.get('name', job_id)} ({job_id})")def _handle_suggestions_command(self, cmd: str):- """Handle /suggestions — review/accept/dismiss suggested automations.-- Delegates to the shared handler so CLI and gateway never drift. CLI- origin is the local platform so an accepted job's "origin" delivery- resolves to a configured home channel.- """+ """Handle /suggestions — review/accept/dismiss suggested automations via the shared handler.+ CLI origin is the local platform so an accepted job's "origin" delivery resolves to a home channel."""import shlextry:@@ -2123,15 +1964,9 @@ class CLICommandsMixin:self._console_print(output)def _handle_blueprint_command(self, cmd: str):- """Handle /blueprint — set up an automation from a blueprint template.-- Delegates to the shared handler. A bare ``/blueprint`` lists the- catalog; ``/blueprint <name>`` name-matches a blueprint and seeds the- agent to ask the user for each value conversationally (the result's- ``agent_seed``); ``/blueprint <name> slot=val …`` creates the job- directly. When a seed is returned it is stashed as a one-shot pending- message the interactive loop runs as the next agent turn.- """+ """Handle /blueprint — set up an automation from a blueprint template (shared handler).+ Bare lists the catalog; ``<name>`` seeds the agent to ask for each value conversationally+ (``agent_seed``, run as the next turn); ``<name> slot=val …`` creates the job directly."""import shlextry:@@ -2175,12 +2010,7 @@ class CLICommandsMixin:print(f"(._.) curator: {exc}")def _handle_kanban_command(self, cmd: str):- """Handle the /kanban command — delegate to the shared kanban CLI.-- The string form passed here is the user's full ``/kanban ...``- including the leading slash; we strip it and hand the remainder- to ``kanban.run_slash`` which returns a single formatted string.- """+ """Handle /kanban — strip the leading ``/kanban`` and hand the rest to ``kanban.run_slash``."""from hermes_cli.kanban import run_slashrest = cmd.strip()@@ -2216,84 +2046,52 @@ class CLICommandsMixin:from hermes_cli.skills_hub import handle_skills_slashhandle_skills_slash(cmd, ChatConsole())+ def _queue_prompt_turn(self, msg: str, command: str) -> None:+ """Inject ``msg`` onto the agent's input queue as the next normal user turn (the+ /learn, /plan, /init pattern: no engine, no model-tool footprint, prompt-cache safe)."""+ if hasattr(self, "_pending_input"):+ self._pending_input.put(msg)+ else: # pragma: no cover - defensive (no live input loop)+ print(f" {command} needs an active chat session to run.")+def _handle_learn_command(self, cmd: str):"""Handle /learn — distill a reusable skill from anything the user describes.- Open-ended: the argument is free text describing the source(s) — a- directory, a URL, "what we just did", pasted notes. We build a- standards-guided prompt and inject it onto the agent's input queue; the- live agent gathers the material with the tools it already has and- authors the skill via ``skill_manage``. No engine, no model-tool- footprint, works on any terminal backend.- """+ Open-ended: the argument is free text describing the source(s) — a directory, a URL,+ "what we just did", pasted notes. The live agent gathers the material with the tools+ it already has and authors the skill via ``skill_manage``."""from agent.learn_prompt import build_learn_prompt- # Everything after the command word is the open-ended request.- parts = cmd.strip().split(None, 1)- user_request = parts[1].strip() if len(parts) > 1 else ""-- msg = build_learn_prompt(user_request)+ user_request = _command_arg(cmd)if user_request:print("\n⚡ Learning a skill from what you described...")else:print("\n⚡ Learning a skill from this conversation...")- if hasattr(self, "_pending_input"):- self._pending_input.put(msg)- else: # pragma: no cover - defensive (no live input loop)- print(" /learn needs an active chat session to run.")+ self._queue_prompt_turn(build_learn_prompt(user_request), "/learn")def _handle_plan_command(self, cmd: str):- """Handle /plan — write a markdown implementation plan, no execution.-- Mirrors /learn: build the plan-mode prompt and inject it onto the- agent's input queue as a normal user turn. The live agent inspects- the workspace with read-only tools and saves the plan under- ``.hermes/plans/`` via ``write_file``. No engine, no model-tool- footprint, works on any terminal backend, and preserves prompt-cache- invariants (no system prompt or history mutation).- """+ """Handle /plan — write a markdown implementation plan, no execution. The live agent+ inspects the workspace read-only and saves the plan under ``.hermes/plans/``."""from agent.plan_prompt import build_plan_prompt- # Everything after the command word is the task to plan (optional —- # empty infers the task from conversation context).- parts = cmd.strip().split(None, 1)- task = parts[1].strip() if len(parts) > 1 else ""-- msg = build_plan_prompt(task)+ task = _command_arg(cmd) # optional — empty infers the task from conversation contextif task:print(f"\n📋 Planning: {task[:80]}{'...' if len(task) > 80 else ''}")else:print("\n📋 Planning from this conversation's context...")- if hasattr(self, "_pending_input"):- self._pending_input.put(msg)- else: # pragma: no cover - defensive (no live input loop)- print(" /plan needs an active chat session to run.")+ self._queue_prompt_turn(build_plan_prompt(task), "/plan")def _handle_init_command(self, cmd: str):- """Handle /init — generate or update AGENTS.md from a project scan.-- Mirrors /learn: build a guidance-laden prompt and inject it onto the- agent's input queue as a normal user turn. The live agent scans the- project with its own read-only tools and writes/updates AGENTS.md via- ``write_file``. No engine, no model-tool footprint, works on any- terminal backend, and preserves prompt-cache invariants (no system- prompt or history mutation).- """+ """Handle /init — generate or update AGENTS.md from a project scan performed by the+ live agent with its own read-only tools."""from hermes_cli.init_command import build_init_prompt_for_cwd- # Everything after the command word is optional user emphasis.- parts = cmd.strip().split(None, 1)- extra = parts[1].strip() if len(parts) > 1 else ""-- msg = build_init_prompt_for_cwd(extra=extra)+ msg = build_init_prompt_for_cwd(extra=_command_arg(cmd)) # optional user emphasisif "UPDATE the existing AGENTS.md" in msg:print("\n⚡ Updating AGENTS.md from a project scan...")else:print("\n⚡ Generating AGENTS.md from a project scan...")- if hasattr(self, "_pending_input"):- self._pending_input.put(msg)- else: # pragma: no cover - defensive (no live input loop)- print(" /init needs an active chat session to run.")+ self._queue_prompt_turn(msg, "/init")def _handle_memory_command(self, cmd: str):"""Handle /memory slash command — pending review + approval-gate toggle."""@@ -2303,14 +2101,9 @@ class CLICommandsMixin:args = parts[1:] if len(parts) > 1 else []store = getattr(self.agent, "_memory_store", None) if getattr(self, "agent", None) else Noneif store is None:- # No live agent store (e.g. /memory approve invoked from the Desktop- # GUI, or any context without an active agent). Apply against a freshly- # loaded on-disk store, mirroring the gateway path- # (gateway/slash_commands.py): it persists to the same MEMORY/USER.md- # and creates MEMORY.md on the first approved write. Without this the- # shared handler returns "memory store unavailable". See #46783.- # load_on_disk_store() honors the user's configured char limits, so- # an approval here enforces the same caps as the live agent would.+ # No live agent store (e.g. /memory approve from the Desktop GUI): apply against+ # a freshly loaded on-disk store, mirroring the gateway path. It persists to the+ # same MEMORY/USER.md and honors the user's configured char limits.from tools.memory_tool import load_on_disk_storestore = load_on_disk_store()out = handle_pending_subcommand(@@ -2329,13 +2122,9 @@ class CLICommandsMixin:save_config_value(f"{subsystem}.write_approval", bool(enabled))def _handle_background_command(self, cmd: str):- """Handle /bg <prompt> — run a prompt in a separate background session.-- Spawns a new AIAgent in a background thread with its own session.- When it completes, prints the result to the CLI without modifying- the active session's conversation history.- """- from cli import AIAgent, ChatConsole, _accent_hex, _cprint, _maybe_remap_for_light_mode, _render_final_assistant_content, set_approval_callback, set_secret_capture_callback, set_sudo_password_callback+ """Handle /bg <prompt> — run a prompt in a separate background session (its own AIAgent+ on a thread); the result prints here without touching the active history."""+ from cli import AIAgent, _cprint, set_approval_callback, set_secret_capture_callback, set_sudo_password_callbackparts = cmd.strip().split(maxsplit=1)if len(parts) < 2 or not parts[1].strip():_cprint(" Usage: /bg <prompt>")@@ -2417,42 +2206,16 @@ class CLICommandsMixin:if not response and result and result.get("error"):response = f"Error: {result['error']}"- # Display result in the CLI (thread-safe via patch_stdout).- # Force a TUI refresh first so spinner/status bar don't overlap- # with the output (fixes #2718).- if self._app:- self._app.invalidate()- time.sleep(0.05) # brief pause for refresh- print()- ChatConsole().print(f"[{_accent_hex()}]{'─' * 40}[/]")- _cprint(f" ✅ Background task #{task_num} complete")- _cprint(f" Prompt: \"{prompt[:60]}{'...' if len(prompt) > 60 else ''}\"")- ChatConsole().print(f"[{_accent_hex()}]{'─' * 40}[/]")- if response:- try:- from hermes_cli.skin_engine import get_active_skin- _skin = get_active_skin()- label = _skin.get_branding("response_label", "⚕ Hermes")- _resp_color = _maybe_remap_for_light_mode(_skin.get_color("response_border", "#CD7F32"))- _resp_text = _maybe_remap_for_light_mode(_skin.get_color("banner_text", "#FFF8DC"))- except Exception:- label = "⚕ Hermes"- _resp_color = "#CD7F32"- _resp_text = "#FFF8DC"-- _chat_console = ChatConsole()- _chat_console.print(Panel(- _render_final_assistant_content(response, mode=self.final_response_markdown),- title=f"[{_resp_color} bold]{label} (background #{task_num})[/]",- title_align="left",- border_style=_resp_color,- style=_resp_text,- box=rich_box.HORIZONTALS,- padding=(1, 4),- width=self._scrollback_box_width(),- ))- else:- _cprint(" (No response generated)")+ _print_side_result_panel(+ self,+ header_lines=[+ f" ✅ Background task #{task_num} complete",+ f" Prompt: \"{prompt[:60]}{'...' if len(prompt) > 60 else ''}\"",+ ],+ body=response,+ title_suffix=f"(background #{task_num})",+ empty_note=" (No response generated)",+ )# Play bell if enabledif self.bell_on_complete:@@ -2460,7 +2223,7 @@ class CLICommandsMixin:sys.stdout.flush()except Exception as e:- # Same TUI refresh pattern as success path (#2718)+ # Same TUI refresh pattern as success pathif self._app:self._app.invalidate()time.sleep(0.05)@@ -2485,15 +2248,10 @@ class CLICommandsMixin:thread.start()def _handle_btw_command(self, cmd: str):- """Handle /btw <question> — answer a side question about this conversation.-- Snapshots the live conversation history and asks a one-shot auxiliary- LLM call (same model as the session by default) to answer the question- against that snapshot. The live session is never touched: no history- mutation, no role-alternation risk, no prompt-cache invalidation. The- current turn keeps running; the answer prints when ready.- """- from cli import ChatConsole, _accent_hex, _cprint+ """Handle /btw <question> — answer a side question about this conversation from a+ history snapshot via a one-shot auxiliary call. The live session is never touched+ (no history mutation, no role-alternation risk, no cache invalidation)."""+ from cli import _cprintparts = cmd.strip().split(maxsplit=1)if len(parts) < 2 or not parts[1].strip():@@ -2536,37 +2294,13 @@ class CLICommandsMixin:parent_agent=parent_agent,main_runtime=main_runtime,)- if self._app:- self._app.invalidate()- time.sleep(0.05)- print()- ChatConsole().print(f"[{_accent_hex()}]{'─' * 40}[/]")- _cprint(f" 💬 /btw: \"{preview}\"")- ChatConsole().print(f"[{_accent_hex()}]{'─' * 40}[/]")- if answer:- from cli import _maybe_remap_for_light_mode, _render_final_assistant_content- try:- from hermes_cli.skin_engine import get_active_skin- _skin = get_active_skin()- label = _skin.get_branding("response_label", "⚕ Hermes")- _resp_color = _maybe_remap_for_light_mode(_skin.get_color("response_border", "#CD7F32"))- _resp_text = _maybe_remap_for_light_mode(_skin.get_color("banner_text", "#FFF8DC"))- except Exception:- label = "⚕ Hermes"- _resp_color = "#CD7F32"- _resp_text = "#FFF8DC"- ChatConsole().print(Panel(- _render_final_assistant_content(answer, mode=self.final_response_markdown),- title=f"[{_resp_color} bold]{label} (btw)[/]",- title_align="left",- border_style=_resp_color,- style=_resp_text,- box=rich_box.HORIZONTALS,- padding=(1, 4),- width=self._scrollback_box_width(),- ))- else:- _cprint(" (No answer generated)")+ _print_side_result_panel(+ self,+ header_lines=[f" 💬 /btw: \"{preview}\""],+ body=answer,+ title_suffix="(btw)",+ empty_note=" (No answer generated)",+ )except Exception as e:if self._app:self._app.invalidate()@@ -2580,12 +2314,8 @@ class CLICommandsMixin:threading.Thread(target=run_side_question, daemon=True, name="btw-side-question").start()def _handle_bundles_command(self, cmd: str) -> None:- """In-session ``/bundles`` — show installed skill bundles.-- Mirrors ``hermes bundles list`` but renders inside the running- CLI so users can discover what's available without dropping out- of their session. Bundles are loaded via ``/<bundle-name>``.- """+ """In-session ``/bundles`` — show installed skill bundles (``hermes bundles list`` rendered+ inside the running CLI). Bundles are loaded via ``/<bundle-name>``."""from cli import ChatConsole, _BOLD, _DIM, _RST, _accent_hex, _cprintfrom hermes_cli.slash_exec import CommandContext, execute_command@@ -2620,297 +2350,248 @@ class CLICommandsMixin:)def _handle_browser_command(self, cmd: str):- """Handle /browser connect|disconnect|status — manage live Chromium-family CDP connection."""- import platform as _plat-+ """Handle /browser connect|disconnect|status|use — manage the live Chromium-family CDP connection."""parts = cmd.strip().split(None, 1)sub = parts[1].lower().strip() if len(parts) > 1 else "status"-- _DEFAULT_CDP = DEFAULT_BROWSER_CDP_URL- current = os.environ.get("BROWSER_CDP_URL", "").strip()-if sub == "use" or sub.startswith("use "):- # /browser use [off] — toggle Browser Use mode (browser.backend),- arg = sub.split(None, 1)[1].strip() if " " in sub else "on"- from hermes_cli.config import load_config, save_config- from tools.registry import invalidate_check_fn_cache+ self._browser_use(sub.split(None, 1)[1].strip() if " " in sub else "on")+ elif sub.startswith("connect"):+ connect_parts = cmd.strip().split(None, 2) # ["/browser", "connect", "ws://..."]+ self._browser_connect(connect_parts[2].strip() if len(connect_parts) > 2 else DEFAULT_BROWSER_CDP_URL)+ elif sub == "disconnect":+ self._browser_disconnect()+ elif sub == "status":+ self._browser_status()+ else:+ _say_block(+ "Usage: /browser connect|disconnect|status|use",+ "",+ " connect Connect browser tools to your live Chromium-family browser session",+ " disconnect Revert to default browser backend",+ " status Show current browser mode",+ " use [off] Switch to Browser Use mode (CLI 3.0) / back to built-in tools",+ )- if arg not in {"on", "off"}:- print()- print("Usage: /browser use [off]")- print(" /browser use — switch to Browser Use mode (browser_exec via CLI 3.0)")- print(" /browser use off — revert to the built-in browser tools")- print()- return+ def _browser_use(self, arg: str) -> None:+ """/browser use [off] — toggle Browser Use mode (browser.backend); resets the session."""+ from hermes_cli.config import load_config, save_config+ from tools.registry import invalidate_check_fn_cache- config = load_config()- browser_cfg = config.setdefault("browser", {})- if arg == "on":- browser_cfg["backend"] = "browser-use"- save_config(config)- invalidate_check_fn_cache()- self.new_session()- print()- print("🌐 Browser Use mode enabled — browser_exec via the Browser Use CLI 3.0")- print(" Session reset. New tool configuration is active.")- print()- else:- from tools.browser_use_cli import BACKEND_DISABLED+ if arg not in {"on", "off"}:+ _say_block(+ "Usage: /browser use [off]",+ " /browser use — switch to Browser Use mode (browser_exec via CLI 3.0)",+ " /browser use off — revert to the built-in browser tools",+ )+ return+ config = load_config()+ if arg == "on":+ config.setdefault("browser", {})["backend"] = "browser-use"+ headline = "🌐 Browser Use mode enabled — browser_exec via the Browser Use CLI 3.0"+ else:+ from tools.browser_use_cli import BACKEND_DISABLED+ config.setdefault("browser", {})["backend"] = BACKEND_DISABLED+ headline = "🌐 Browser Use mode disabled — built-in browser tools restored"+ save_config(config)+ invalidate_check_fn_cache()+ self.new_session()+ _say_block(headline, " Session reset. New tool configuration is active.")- browser_cfg["backend"] = BACKEND_DISABLED- save_config(config)- invalidate_check_fn_cache()- self.new_session()- print()- print("🌐 Browser Use mode disabled — built-in browser tools restored")- print(" Session reset. New tool configuration is active.")- print()+ def _browser_connect(self, cdp_url: str) -> None:+ """/browser connect [url] — validate the CDP URL, find or launch a debug browser, then+ point the browser tools at it (BROWSER_CDP_URL) and tell the model."""+ import platform as _plat++ parsed_cdp = urlparse(cdp_url if "://" in cdp_url else f"http://{cdp_url}")+ if parsed_cdp.scheme not in {"http", "https", "ws", "wss"}:+ _say_block(+ f" ⚠ Unsupported browser url scheme: {parsed_cdp.scheme or '(missing)'} "+ "(expected one of: http, https, ws, wss)"+ )+ return+ try:+ _port = parsed_cdp.port or (443 if parsed_cdp.scheme in {"https", "wss"} else 80)+ except ValueError:+ _say_block(f" ⚠ Invalid port in browser url: {cdp_url}")return+ if not parsed_cdp.hostname:+ _say_block(f" ⚠ Missing host in browser url: {cdp_url}")+ return+ if parsed_cdp.path.startswith("/devtools/browser/"):+ cdp_url = parsed_cdp.geturl()+ else:+ cdp_url = parsed_cdp._replace(path="", params="", query="", fragment="").geturl()- if sub.startswith("connect"):- # Optionally accept a custom CDP URL: /browser connect ws://host:port- connect_parts = cmd.strip().split(None, 2) # ["/browser", "connect", "ws://..."]- cdp_url = connect_parts[2].strip() if len(connect_parts) > 2 else _DEFAULT_CDP- parsed_cdp = urlparse(cdp_url if "://" in cdp_url else f"http://{cdp_url}")- if parsed_cdp.scheme not in {"http", "https", "ws", "wss"}:- print()- print(- f" ⚠ Unsupported browser url scheme: {parsed_cdp.scheme or '(missing)'} "- "(expected one of: http, https, ws, wss)"- )- print()- return- try:- _port = parsed_cdp.port or (443 if parsed_cdp.scheme in {"https", "wss"} else 80)- except ValueError:- print()- print(f" ⚠ Invalid port in browser url: {cdp_url}")- print()- return- if not parsed_cdp.hostname:- print()- print(f" ⚠ Missing host in browser url: {cdp_url}")- print()- return- _host = parsed_cdp.hostname- if parsed_cdp.path.startswith("/devtools/browser/"):- cdp_url = parsed_cdp.geturl()- else:- cdp_url = parsed_cdp._replace(- path="",- params="",- query="",- fragment="",- ).geturl()-- # Clear any existing browser sessions so the next tool call uses the new backend- try:- from tools.browser_tool import cleanup_all_browsers- cleanup_all_browsers()- except Exception:- pass+ # Clear any existing browser sessions so the next tool call uses the new backend+ try:+ from tools.browser_tool import cleanup_all_browsers+ cleanup_all_browsers()+ except Exception:+ pass- print()+ print()- # Check if a Chromium-family browser is already serving CDP on the debug port.- # For the default-local URL, probe both loopbacks (IPv4 + IPv6): a- # squatter on 127.0.0.1:<port> (e.g. an IDE's JS debugger) can push- # the debug browser to bind [::1] only.- _is_default = cdp_url == _DEFAULT_CDP- if _is_default:- _found = discover_local_cdp_url(_port, timeout=1.0)- _already_open = _found is not None- if _found:- cdp_url = _found+ # Already serving CDP? For the default-local URL probe both loopbacks: a squatter+ # on 127.0.0.1:<port> (e.g. an IDE debugger) can push the browser to bind [::1] only.+ _is_default = cdp_url == DEFAULT_BROWSER_CDP_URL+ if _is_default:+ _found = discover_local_cdp_url(_port, timeout=1.0)+ _already_open = _found is not None+ if _found:+ cdp_url = _found+ else:+ _already_open = is_browser_debug_ready(cdp_url, timeout=1.0)++ if _already_open:+ print(f" ✓ Chromium-family browser is already listening at {cdp_url}")+ elif _is_default:+ _launch_port = _port+ if local_port_in_use(_port):+ _launch_port = find_free_debug_port(_port)+ print(f" ⚠ Port {_port} is occupied by another application that isn't a CDP browser")+ print(f" (an IDE debugger or dev server may be using it) — launching on port {_launch_port} instead...")else:- _already_open = is_browser_debug_ready(cdp_url, timeout=1.0)-- if _already_open:- print(f" ✓ Chromium-family browser is already listening at {cdp_url}")- elif _is_default:- _launch_port = _port- if local_port_in_use(_port):- _launch_port = find_free_debug_port(_port)- print(- f" ⚠ Port {_port} is occupied by another application that isn't a CDP browser"- )- print(- f" (an IDE debugger or dev server may be using it) — launching on port {_launch_port} instead..."- )- else:- # Try to auto-launch a Chromium-family browser with remote debugging- print(" Chromium-family browser isn't running with remote debugging — attempting to launch...")- _launch = launch_chrome_debug(_launch_port, _plat.system())- if _launch.launched:- # Wait for the DevTools discovery endpoint to come up- for _wait in range(10):- _found = discover_local_cdp_url(_launch_port, timeout=1.0)- if _found:- cdp_url = _found- _already_open = True- break- time.sleep(0.5)- if _already_open:- print(f" ✓ Chromium-family browser launched and listening on port {_launch_port}")- else:- print(f" ⚠ Browser launched but port {_launch_port} isn't responding yet")- print(" Try again in a few seconds — the debug instance may still be starting")+ print(" Chromium-family browser isn't running with remote debugging — attempting to launch...")+ _launch = launch_chrome_debug(_launch_port, _plat.system())+ if _launch.launched:+ for _wait in range(10): # wait for the DevTools discovery endpoint to come up+ _found = discover_local_cdp_url(_launch_port, timeout=1.0)+ if _found:+ cdp_url = _found+ _already_open = True+ break+ time.sleep(0.5)+ if _already_open:+ print(f" ✓ Chromium-family browser launched and listening on port {_launch_port}")else:- print(" ⚠ Could not auto-launch a Chromium-family browser")- _hint = _launch.hint- if _hint:- print(f" {_hint}")- sys_name = _plat.system()- chrome_cmd = manual_chrome_debug_command(_launch_port, sys_name)- if chrome_cmd:- print(" Launch a Chromium-family browser manually:")- print(f" {chrome_cmd}")- else:- print(" No supported Chromium-family browser executable found in this environment")+ print(f" ⚠ Browser launched but port {_launch_port} isn't responding yet")+ print(" Try again in a few seconds — the debug instance may still be starting")else:- print(f" ⚠ Port {_port} is not reachable at {cdp_url}")-- if not _already_open:- print()- print("Browser not connected — start a Chromium-family browser with remote debugging and retry /browser connect")- print()- return-- os.environ["BROWSER_CDP_URL"] = cdp_url- # Eagerly start the CDP supervisor so pending_dialogs + frame_tree- # show up in the next browser_snapshot. No-op if already started.- try:- from tools.browser_tool import _ensure_cdp_supervisor # type: ignore[import-not-found]- _ensure_cdp_supervisor("default")- except Exception:- pass- print()- print("🌐 Browser connected to live Chromium-family browser via CDP")- print(f" Endpoint: {cdp_url}")- print()+ print(" ⚠ Could not auto-launch a Chromium-family browser")+ if _launch.hint:+ print(f" {_launch.hint}")+ chrome_cmd = manual_chrome_debug_command(_launch_port, _plat.system())+ if chrome_cmd:+ print(" Launch a Chromium-family browser manually:")+ print(f" {chrome_cmd}")+ else:+ print(" No supported Chromium-family browser executable found in this environment")+ else:+ print(f" ⚠ Port {_port} is not reachable at {cdp_url}")- # Inject context message so the model knows this slash command- # intentionally makes the dev/debug CDP browser available for use.- if hasattr(self, '_pending_input'):- self._pending_input.put(- "[System note: The user invoked /browser connect and connected your browser tools to "- "a Chromium-family dev/debug browser via Chrome DevTools Protocol. "- "Your browser_navigate, browser_snapshot, browser_click, and other browser tools now "- "control that CDP browser. The command itself is a signal that using browser tools for "- "their current browser-related request is expected; do not wait for separate permission "- "just because CDP is connected. This is typically a Hermes-managed isolated debug "- "profile, not the user's main everyday browser. It is still user-visible and may contain "- "pages, logged-in sessions, or cookies in that debug profile, so avoid destructive actions, "- "closing tabs, or navigating away unless the user's task calls for it.]"- )+ if not _already_open:+ _say_block("Browser not connected — start a Chromium-family browser with remote debugging and retry /browser connect")+ return- elif sub == "disconnect":- if current:- os.environ.pop("BROWSER_CDP_URL", None)- try:- from tools.browser_tool import cleanup_all_browsers, _stop_cdp_supervisor- _stop_cdp_supervisor("default")- cleanup_all_browsers()- except Exception:- pass- print()- print("🌐 Browser disconnected from live Chromium-family browser")- print(" Browser tools reverted to default mode (local headless or cloud provider)")- print()+ os.environ["BROWSER_CDP_URL"] = cdp_url+ # Eagerly start the CDP supervisor so pending_dialogs + frame_tree show up in the next snapshot.+ try:+ from tools.browser_tool import _ensure_cdp_supervisor # type: ignore[import-not-found]+ _ensure_cdp_supervisor("default")+ except Exception:+ pass+ _say_block("🌐 Browser connected to live Chromium-family browser via CDP", f" Endpoint: {cdp_url}")++ # Tell the model the CDP browser was made available on purpose.+ if hasattr(self, '_pending_input'):+ self._pending_input.put(+ "[System note: The user invoked /browser connect and connected your browser tools to "+ "a Chromium-family dev/debug browser via Chrome DevTools Protocol. "+ "Your browser_navigate, browser_snapshot, browser_click, and other browser tools now "+ "control that CDP browser. The command itself is a signal that using browser tools for "+ "their current browser-related request is expected; do not wait for separate permission "+ "just because CDP is connected. This is typically a Hermes-managed isolated debug "+ "profile, not the user's main everyday browser. It is still user-visible and may contain "+ "pages, logged-in sessions, or cookies in that debug profile, so avoid destructive actions, "+ "closing tabs, or navigating away unless the user's task calls for it.]"+ )- if hasattr(self, '_pending_input'):- self._pending_input.put(- "[System note: The user has disconnected the browser tools from their live Chromium-family browser. "- "Browser tools are back to default mode (headless local browser or cloud provider).]"- )- else:- print()- print("Browser is not connected to a live Chromium-family browser (already using default mode)")- print()+ def _browser_disconnect(self) -> None:+ if not os.environ.get("BROWSER_CDP_URL", "").strip():+ _say_block("Browser is not connected to a live Chromium-family browser (already using default mode)")+ return+ os.environ.pop("BROWSER_CDP_URL", None)+ try:+ from tools.browser_tool import cleanup_all_browsers, _stop_cdp_supervisor+ _stop_cdp_supervisor("default")+ cleanup_all_browsers()+ except Exception:+ pass+ _say_block(+ "🌐 Browser disconnected from live Chromium-family browser",+ " Browser tools reverted to default mode (local headless or cloud provider)",+ )+ if hasattr(self, '_pending_input'):+ self._pending_input.put(+ "[System note: The user has disconnected the browser tools from their live Chromium-family browser. "+ "Browser tools are back to default mode (headless local browser or cloud provider).]"+ )- elif sub == "status":- print()+ def _browser_status(self) -> None:+ current = os.environ.get("BROWSER_CDP_URL", "").strip()+ print()+ try:+ from tools.browser_use_cli import is_browser_use_cli_mode+ _bu_mode = is_browser_use_cli_mode()+ except Exception:+ _bu_mode = False+ if _bu_mode:+ print("🌐 Browser: Browser Use mode (browser_exec via the Browser Use CLI 3.0)")+ print(" Local Chrome via CDP, or Browser Use cloud browsers")+ _print_lightpanda_engine_status()+ _say_block(" /browser use off — revert to the built-in browser tools")+ return+ if current:+ print("🌐 Browser: connected to live Chromium-family browser via CDP")+ print(f" Endpoint: {current}")+ _print_lightpanda_engine_status()+ _port = 9222+ try:+ _port = int(current.rsplit(":", 1)[-1].split("/")[0])+ except (ValueError, IndexError):+ passtry:- from tools.browser_use_cli import is_browser_use_cli_mode- _bu_mode = is_browser_use_cli_mode()+ import socket+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ s.settimeout(1)+ s.connect(("127.0.0.1", _port))+ s.close()+ print(" Status: ✓ reachable")+ except (OSError, Exception):+ print(" Status: ⚠ not reachable (browser may not be running)")+ else:+ try:+ from tools.browser_tool import _get_cloud_provider+ provider = _get_cloud_provider()except Exception:- _bu_mode = False- if _bu_mode:- print("🌐 Browser: Browser Use mode (browser_exec via the Browser Use CLI 3.0)")- print(" Local Chrome via CDP, or Browser Use cloud browsers")+ provider = None+ if provider is not None:+ print(f"🌐 Browser: {provider.provider_name()} (cloud)")_print_lightpanda_engine_status()- print()- print(" /browser use off — revert to the built-in browser tools")- print()- return- if current:- print("🌐 Browser: connected to live Chromium-family browser via CDP")- print(f" Endpoint: {current}")- _print_lightpanda_engine_status()-- _port = 9222- try:- _port = int(current.rsplit(":", 1)[-1].split("/")[0])- except (ValueError, IndexError):- pass- try:- import socket- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- s.settimeout(1)- s.connect(("127.0.0.1", _port))- s.close()- print(" Status: ✓ reachable")- except (OSError, Exception):- print(" Status: ⚠ not reachable (browser may not be running)")else:try:- from tools.browser_tool import _get_cloud_provider- provider = _get_cloud_provider()+ from tools.browser_tool import _get_browser_engine+ engine = _get_browser_engine()except Exception:- provider = None-- if provider is not None:- print(f"🌐 Browser: {provider.provider_name()} (cloud)")+ engine = "auto"+ if engine == "lightpanda":+ print("🌐 Browser: local Lightpanda (agent-browser --engine lightpanda)")+ print(" ⚡ Lightpanda: faster navigation, no screenshot support")+ print(" Automatic Chromium fallback for screenshots and failed commands")_print_lightpanda_engine_status()+ elif engine == "chrome":+ print("🌐 Browser: local headless Chromium (agent-browser --engine chrome)")else:- # Show engine info for local mode- try:- from tools.browser_tool import _get_browser_engine- engine = _get_browser_engine()- except Exception:- engine = "auto"- if engine == "lightpanda":- print("🌐 Browser: local Lightpanda (agent-browser --engine lightpanda)")- print(" ⚡ Lightpanda: faster navigation, no screenshot support")- print(" Automatic Chromium fallback for screenshots and failed commands")- _print_lightpanda_engine_status()- elif engine == "chrome":- print("🌐 Browser: local headless Chromium (agent-browser --engine chrome)")- else:- print("🌐 Browser: local headless Chromium (agent-browser)")- print()- print(" /browser connect — connect to your live Chromium-family browser")- print(" /browser disconnect — revert to default")- print()-- else:- print()- print("Usage: /browser connect|disconnect|status|use")- print()- print(" connect Connect browser tools to your live Chromium-family browser session")- print(" disconnect Revert to default browser backend")- print(" status Show current browser mode")- print(" use [off] Switch to Browser Use mode (CLI 3.0) / back to built-in tools")- print()+ print("🌐 Browser: local headless Chromium (agent-browser)")+ _say_block(+ " /browser connect — connect to your live Chromium-family browser",+ " /browser disconnect — revert to default",+ )def _handle_heartbeat_command(self, cmd: str) -> None:- """Dispatch /heartbeat: set / status / pause / resume / clear.-- ``/heartbeat every 10m Check the deployment`` sets the session's one- recurring instruction; the idle watchdog injects it as a normal user- turn whenever due. Session-scoped and in-process — for durable- cross-process schedules use `hermes cron`.- """+ """Dispatch /heartbeat: set / status / pause / resume / clear. ``/heartbeat every 10m <prompt>``+ sets the session's one recurring instruction, injected as a normal user turn when due.+ Session-scoped and in-process — use `hermes cron` for durable schedules."""from cli import _DIM, _RST, _cprintfrom hermes_cli.heartbeat import parse_interval, format_interval@@ -2989,14 +2670,9 @@ class CLICommandsMixin:)def _handle_refine_command(self, cmd: str) -> None:- """Dispatch /refine — run the memory/skill review fork on demand.-- Same machinery as the automatic post-turn self-improvement loop- (``AIAgent._spawn_background_review``), but user-triggered and with- optional focus instructions. Writes go to the memory + skill stores- in a background fork; the live conversation and prompt cache are- never touched.- """+ """Dispatch /refine — run the memory/skill review fork on demand (same machinery as the+ automatic post-turn ``_spawn_background_review``), with optional focus text. Background+ fork; the live conversation and prompt cache are never touched."""from cli import _DIM, _RST, _cprintparts = (cmd or "").strip().split(None, 1)@@ -3031,14 +2707,9 @@ class CLICommandsMixin:)def _handle_review_command(self, cmd: str) -> None:- """Dispatch /review — spawn an independent reviewer subagent.-- Snapshots the last N chat messages, wraps them (plus any argument- text as extra instructions) in a reviewer briefing, and dispatches a- full-privilege background subagent via the async delegation rail.- The review re-enters this session as a normal async-delegation- completion, addressed to the primary agent.- """+ """Dispatch /review — snapshot the last N messages (+ argument text as instructions) and+ spawn an independent reviewer subagent via async delegation; the review re-enters this+ session as a normal delegation completion."""from cli import _DIM, _RST, _cprintparts = (cmd or "").strip().split(None, 1)@@ -3063,10 +2734,9 @@ class CLICommandsMixin:_cprint(f" {format_dispatch_note(result, prompt)}")def _handle_goal_command(self, cmd: str) -> None:- """Dispatch /goal subcommands: set / draft / show / gate / status / pause / resume / clear."""+ """Dispatch /goal subcommands: set / draft / show / gate / wait / status / pause / resume / clear."""from cli import _DIM, _RST, _cprint- parts = (cmd or "").strip().split(None, 1)- arg = parts[1].strip() if len(parts) > 1 else ""+ arg = _command_arg(cmd)mgr = self._get_goal_manager()if mgr is None:@@ -3074,153 +2744,134 @@ class CLICommandsMixin:returnlower = arg.lower()+ verb, _, rest = arg.partition(" ")+ verb = verb.lower()+ rest = rest.strip()- # Bare /goal or /goal status → show current stateif not arg or lower == "status":_cprint(f" {mgr.status_line()}")- return-- # /goal show → print the active goal's completion contract- if lower == "show":+ elif lower == "show":_cprint(f" {mgr.status_line()}")_cprint(f" {mgr.render_contract()}")- return-- # /goal draft <objective> → expand plain text into a structured- # completion contract (outcome / verification / constraints /- # boundaries / stop_when) and set it as the active goal. Adapted- # from Codex's "let the agent draft the goal" guidance: the contract- # makes "done" evidence-based instead of a loose vibe check.- if lower.startswith("draft"):+ elif lower.startswith("draft"):+ # Expand plain text into a structured completion contract so "done" is+ # evidence-based instead of a vibe check.objective = arg[len("draft"):].strip()if not objective:_cprint(" Usage: /goal draft <objective in plain language>")returnself._handle_goal_draft(objective)- return-- if lower == "pause":+ elif lower == "pause":state = mgr.pause(reason="user-paused")- if state is None:- _cprint(f" {_DIM}No goal set.{_RST}")- else:- _cprint(f" ⏸ Goal paused: {state.goal}")- return-- if lower == "resume":- state = mgr.resume()- if state is None:- _cprint(f" {_DIM}No goal to resume.{_RST}")- else:- _cprint(f" ▶ Goal resumed: {state.goal}")- # Resume must restart work, not just flip persisted state- # (#75362): queue the canonical continuation prompt the same- # way /goal <text> queues its kickoff, so the loop takes the- # next step without the user sending another message.- prompt = mgr.next_continuation_prompt()- queued = False- if prompt:- try:- self._pending_input.put(prompt)- queued = True- except Exception:- pass- if queued:- _cprint(f" {_DIM}Continuing now — taking the next step.{_RST}")- else:- _cprint(- f" {_DIM}Send any message to kick off the next step.{_RST}"- )- return-- if lower in {"clear", "stop", "done"}:+ _cprint(f" ⏸ Goal paused: {state.goal}" if state else f" {_DIM}No goal set.{_RST}")+ elif lower == "resume":+ self._goal_resume(mgr)+ elif lower in {"clear", "stop", "done"}:had = mgr.has_goal()mgr.clear()- if had:- _cprint(" ✓ Goal cleared.")- else:- _cprint(f" {_DIM}No active goal.{_RST}")- return-- # /goal wait <pid> [reason] — park the loop on a background process so- # it stops re-poking the agent every turn while it waits on CI / a- # build / a long job. The barrier auto-clears when the PID exits.- if lower == "wait" or lower.startswith("wait "):- wait_arg = arg[len("wait"):].strip()- if not wait_arg:- _cprint(" Usage: /goal wait <pid> [reason]")- return- wtokens = wait_arg.split(None, 1)- try:- pid = int(wtokens[0])- except ValueError:- _cprint(" /goal wait: <pid> must be an integer process id.")- return- reason = wtokens[1].strip() if len(wtokens) > 1 else ""- try:- mgr.wait_on(pid, reason=reason)- except (RuntimeError, ValueError) as exc:- _cprint(f" /goal wait: {exc}")- return- rtxt = f" ({reason})" if reason else ""- _cprint(f" ⏳ Goal parked on pid {pid}{rtxt}. Loop pauses until it exits.")- return-- # /goal unwait — drop the wait barrier and resume normal looping.- if lower == "unwait":+ _cprint(" ✓ Goal cleared." if had else f" {_DIM}No active goal.{_RST}")+ elif verb == "wait":+ self._goal_wait(mgr, rest)+ elif lower == "unwait":if mgr.stop_waiting():_cprint(" ▶ Wait barrier cleared — goal loop resumes.")else:_cprint(f" {_DIM}No wait barrier set.{_RST}")+ elif verb == "gate":+ self._goal_gate(mgr, rest)+ else:+ self._goal_set(mgr, arg)++ def _goal_resume(self, mgr) -> None:+ from cli import _DIM, _RST, _cprint+ state = mgr.resume()+ if state is None:+ _cprint(f" {_DIM}No goal to resume.{_RST}")+ return+ _cprint(f" ▶ Goal resumed: {state.goal}")+ # Resume must restart work, not just flip state: queue the continuation prompt+ # the same way /goal <text> queues its kickoff.+ prompt = mgr.next_continuation_prompt()+ queued = False+ if prompt:+ try:+ self._pending_input.put(prompt)+ queued = True+ except Exception:+ pass+ if queued:+ _cprint(f" {_DIM}Continuing now — taking the next step.{_RST}")+ else:+ _cprint(f" {_DIM}Send any message to kick off the next step.{_RST}")++ def _goal_wait(self, mgr, wait_arg: str) -> None:+ """/goal wait <pid> [reason] — park the loop on a background process (CI / build);+ the barrier auto-clears when the PID exits."""+ from cli import _cprint+ if not wait_arg:+ _cprint(" Usage: /goal wait <pid> [reason]")+ return+ wtokens = wait_arg.split(None, 1)+ try:+ pid = int(wtokens[0])+ except ValueError:+ _cprint(" /goal wait: <pid> must be an integer process id.")return+ reason = wtokens[1].strip() if len(wtokens) > 1 else ""+ try:+ mgr.wait_on(pid, reason=reason)+ except (RuntimeError, ValueError) as exc:+ _cprint(f" /goal wait: {exc}")+ return+ rtxt = f" ({reason})" if reason else ""+ _cprint(f" ⏳ Goal parked on pid {pid}{rtxt}. Loop pauses until it exits.")- # /goal gate ... — manage deterministic quality gates. A gate is a- # shell command that must pass before the judge may declare the goal- # done; a failing gate's output becomes the continuation prompt.- if lower == "gate" or lower.startswith("gate "):- gate_arg = arg[len("gate"):].strip()- gate_lower = gate_arg.lower()- if not gate_arg or gate_lower == "list":- for line in mgr.render_gates().splitlines():- _cprint(f" {line}")- return- if gate_lower.startswith("add "):- command = gate_arg[len("add"):].strip()- try:- gate = mgr.add_gate(command)- except (RuntimeError, ValueError) as exc:- _cprint(f" /goal gate add: {exc}")- return- _cprint(- f" ⚿ Gate added: $ {gate.command} "- f"({gate.max_retries} retries, {gate.timeout_seconds}s timeout). "- f"It must pass before the goal can complete."- )+ def _goal_gate(self, mgr, gate_arg: str) -> None:+ """/goal gate [list | add <command> | remove <N> | clear] — shell commands that must pass+ before the judge may declare the goal done; a failing gate's output becomes the+ continuation prompt."""+ from cli import _cprint+ gate_lower = gate_arg.lower()+ if not gate_arg or gate_lower == "list":+ for line in mgr.render_gates().splitlines():+ _cprint(f" {line}")+ return+ if gate_lower.startswith("add "):+ command = gate_arg[len("add"):].strip()+ try:+ gate = mgr.add_gate(command)+ except (RuntimeError, ValueError) as exc:+ _cprint(f" /goal gate add: {exc}")return- if gate_lower.startswith("remove ") or gate_lower.startswith("rm "):- idx_text = gate_arg.split(None, 1)[1].strip()- try:- removed = mgr.remove_gate(int(idx_text))- except (RuntimeError, ValueError, IndexError) as exc:- _cprint(f" /goal gate remove: {exc}")- return- _cprint(f" ✓ Gate removed: $ {removed}")+ _cprint(+ f" ⚿ Gate added: $ {gate.command} "+ f"({gate.max_retries} retries, {gate.timeout_seconds}s timeout). "+ f"It must pass before the goal can complete."+ )+ return+ if gate_lower.startswith("remove ") or gate_lower.startswith("rm "):+ idx_text = gate_arg.split(None, 1)[1].strip()+ try:+ removed = mgr.remove_gate(int(idx_text))+ except (RuntimeError, ValueError, IndexError) as exc:+ _cprint(f" /goal gate remove: {exc}")return- if gate_lower == "clear":- try:- prev = mgr.clear_gates()- except RuntimeError as exc:- _cprint(f" /goal gate clear: {exc}")- return- _cprint(f" ✓ Cleared {prev} gate{'s' if prev != 1 else ''}.")+ _cprint(f" ✓ Gate removed: $ {removed}")+ return+ if gate_lower == "clear":+ try:+ prev = mgr.clear_gates()+ except RuntimeError as exc:+ _cprint(f" /goal gate clear: {exc}")return- _cprint(" Usage: /goal gate [list | add <command> | remove <N> | clear]")+ _cprint(f" ✓ Cleared {prev} gate{'s' if prev != 1 else ''}.")return+ _cprint(" Usage: /goal gate [list | add <command> | remove <N> | clear]")- # Otherwise treat the arg as the goal text. Inline `field: value`- # lines (verify:, constraints:, boundaries:, stop when:) are parsed- # into a completion contract; the remaining prose is the headline.- # A plain free-form goal with no such lines behaves exactly as before.+ def _goal_set(self, mgr, arg: str) -> None:+ """Set the goal from free text; inline `verify:`/`constraints:`/`boundaries:`/`stop when:`+ lines become a completion contract, the remaining prose the headline. Kicks the loop off."""+ from cli import _DIM, _RST, _cprintfrom hermes_cli.goals import parse_contractheadline, contract = parse_contract(arg)@@ -3242,8 +2893,7 @@ class CLICommandsMixin:f"Hermes keeps working until it is, you pause/clear it, or the budget is "f"exhausted. Use /goal status, /goal show, /goal pause, /goal resume, /goal clear.{_RST}")- # Kick the loop off immediately so the user doesn't have to send a- # separate message after setting the goal.+ # Kick the loop off immediately so the user doesn't have to send a separate message.try:self._pending_input.put(state.goal)except Exception:@@ -3296,12 +2946,8 @@ class CLICommandsMixin:passdef _handle_loop_command(self, cmd: str) -> None:- """Dispatch /loop — recurring in-session wakeups (Claude Code parity).-- Forms:- /loop [interval] <prompt> [--times N] [--until <cond>] start a loop- /loop status | pause | resume | stop controls- """+ """Dispatch /loop — recurring in-session wakeups: ``/loop [interval] <prompt> [--times N]+ [--until <cond>]`` starts one; ``status | pause | resume | stop`` control it."""from cli import _DIM, _RST, _cprintparts = (cmd or "").strip().split(None, 1)arg = parts[1].strip() if len(parts) > 1 else ""@@ -3329,20 +2975,10 @@ class CLICommandsMixin:passdef _handle_subgoal_command(self, cmd: str) -> None:- """Dispatch /subgoal subcommands.-- Forms:- /subgoal show current subgoals- /subgoal <text> append a criterion- /subgoal remove <n> drop subgoal n (1-based)- /subgoal clear wipe all subgoals-- Subgoals are extra criteria the user adds mid-loop. They get- appended to both the judge prompt (verdict must consider them)- and the continuation prompt (agent sees them) on the next turn- boundary. No special kick — the running turn finishes, the next- judge call includes them.- """+ """Dispatch /subgoal: bare → show, ``<text>`` → append, ``remove <n>`` (1-based), ``clear``.++ Subgoals are extra criteria added mid-loop; they join both the judge prompt and the+ continuation prompt at the next turn boundary (no special kick)."""from cli import _DIM, _RST, _cprintparts = (cmd or "").strip().split(None, 2)arg = " ".join(parts[1:]).strip() if len(parts) > 1 else ""@@ -3448,13 +3084,9 @@ class CLICommandsMixin:print(" Prompt + TUI colors updated.")def _compose_in_editor(self, initial_text: str = "") -> str:- """Open ``$VISUAL``/``$EDITOR`` on a temp markdown file and return the- saved buffer (comment lines starting with ``#!`` stripped).-- Returns the composed prompt text, or an empty string if the editor- could not be launched or the buffer was left empty. Factored out so- the read-back/strip logic is unit-testable without spawning an editor.- """+ """Open ``$VISUAL``/``$EDITOR`` on a temp markdown file and return the saved buffer with+ ``#!`` comment lines stripped; "" if the editor failed or the buffer was left empty.+ Factored out so the read-back/strip logic is unit-testable."""import osimport shleximport subprocess@@ -3492,13 +3124,8 @@ class CLICommandsMixin:return "\n".join(lines).strip()def _handle_prompt_compose_command(self, cmd_original: str) -> None:- """Handle /prompt — compose the next prompt in $EDITOR and send it.-- Opens the user's editor on a temporary markdown file (optionally- seeded with text passed after the command), then queues the saved- buffer as the next agent turn via the one-shot ``_pending_agent_seed``- the interactive loop already consumes (same path as /blueprint).- """+ """Handle /prompt — compose the next prompt in $EDITOR (optionally seeded with the argument)+ and queue it as the next agent turn via the one-shot ``_pending_agent_seed`` (as /blueprint)."""from cli import _DIM, _RST, _cprintinitial = ""@@ -3521,26 +3148,13 @@ class CLICommandsMixin:self._pending_agent_seed = composeddef _handle_focus_command(self, cmd_original: str) -> None:- """Toggle or inspect focus view — the reduced-output display mode.+ """Toggle or inspect focus view (``/focus [on|off|status]``) — a DISPLAY-ONLY reduced-output mode.- Usage:- /focus → toggle- /focus on|off → explicit- /focus status → show current state-- Focus view is a DISPLAY-ONLY mode. It composes with the existing- ``/verbose`` tool-progress machinery rather than adding a second- suppression mechanism: turning it on snaps ``tool_progress_mode`` to- ``"off"`` (the same value ``/verbose off`` uses, honoured by- ``agent/tool_executor.py`` and ``_on_tool_progress``) after stashing- whatever mode the user had, and turning it off restores that mode- verbatim. On top of that it adds the two things ``/verbose off``- lacks: a per-turn hidden-line count with a recovery hint, and a- persistent ``focus`` segment in the status bar.-- Nothing here touches conversation history, the system prompt, or any- request payload — the model sees an identical turn either way.- """+ Composes with the existing ``/verbose`` machinery instead of adding a second suppression+ path: turning it on stashes the user's tool_progress_mode and snaps it to "off" (the value+ ``agent/tool_executor.py`` gates on); turning it off restores the stash verbatim. Adds a+ per-turn hidden-line count with a recovery hint and a ``focus`` status-bar segment. Never+ touches history, system prompt, or request payloads."""from cli import _cprint, save_config_valuefrom hermes_cli.colors import Colors as _Colorsfrom hermes_cli.focus_view import (@@ -3552,14 +3166,7 @@ class CLICommandsMixin:resolve_focus_arg,)- arg = ""- try:- parts = (cmd_original or "").strip().split(None, 1)- if len(parts) > 1:- arg = parts[1].strip()- except Exception:- arg = ""-+ arg = _command_arg(cmd_original)current = bool(getattr(self, "_focus_view_enabled", False))action, target = resolve_focus_arg(arg, current)@@ -3567,8 +3174,7 @@ class CLICommandsMixin:_cprint(" Usage: /focus [on|off|status]")return- # The mode /focus off will restore. While focus is ON the live- # tool_progress_mode is "off", so the pre-focus mode is the stash.+ # The mode /focus off restores: while focus is ON the live mode is "off", so use the stash.restore_mode = normalize_tool_progress_mode(getattr(self, "_focus_saved_tool_progress", None)if current@@ -3618,12 +3224,8 @@ class CLICommandsMixin:_cprint(f" {message}")def _set_tool_progress_mode(self, mode: str) -> None:- """Set the live tool-progress mode on both the CLI and the agent.-- Extracted so ``/focus`` and ``/verbose`` share one write path — the- agent copy is what ``agent/tool_executor.py`` gates on, and forgetting- it means the new mode only takes effect after an agent rebuild.- """+ """Set the live tool-progress mode on both the CLI and the agent (one write path for+ /focus and /verbose — the agent copy is what ``agent/tool_executor.py`` gates on)."""from hermes_cli.focus_view import normalize_tool_progress_modenormalized = normalize_tool_progress_mode(mode)@@ -3636,12 +3238,8 @@ class CLICommandsMixin:passdef _note_focus_hidden_line(self, function_name: str) -> None:- """Count one tool line that focus view is suppressing this turn.-- Counted against the mode the user had BEFORE focus snapped things to- "off", so a user who already ran ``/verbose off`` is never told that- focus hid lines it did not hide.- """+ """Count one tool line focus view is suppressing this turn — against the mode the user had+ BEFORE focus snapped to "off", so a prior ``/verbose off`` user is never told focus hid lines."""if not getattr(self, "_focus_view_enabled", False):returnfrom hermes_cli.focus_view import would_display_tool_line@@ -3683,46 +3281,26 @@ class CLICommandsMixin:_cprint(f" {result.message}")def _handle_footer_command(self, cmd_original: str) -> None:- """Toggle or inspect ``display.runtime_footer.enabled`` from the CLI.-- Usage:- /footer → toggle- /footer on|off → explicit- /footer status → show current state- """+ """Toggle or inspect ``display.runtime_footer.enabled`` (``/footer [on|off|status]``)."""from cli import _cprint, save_config_valuefrom hermes_cli.config import load_configfrom hermes_cli.colors import Colors as _Colors- # Parse arg- arg = ""- try:- parts = (cmd_original or "").strip().split(None, 1)- if len(parts) > 1:- arg = parts[1].strip().lower()- except Exception:- arg = ""-+ arg = _command_arg(cmd_original, lower=True)cfg = load_config() or {}footer_cfg = ((cfg.get("display") or {}).get("runtime_footer") or {})current = bool(footer_cfg.get("enabled", False))fields = footer_cfg.get("fields") or ["model", "context_pct", "cwd"]- if arg in {"status", "?"}:+ new_state = _toggle_target(arg, current)+ if new_state == "status":state = "ON" if current else "OFF"_cprint(f" {_Colors.BOLD}Runtime footer:{_Colors.RESET} {state}\n"f" Fields: {', '.join(fields)}")return-- if arg in {"on", "enable", "true", "1"}:- new_state = True- elif arg in {"off", "disable", "false", "0"}:- new_state = False- elif arg == "":- new_state = not current- else:+ if new_state is None:_cprint(" Usage: /footer [on|off|status]")return@@ -3736,42 +3314,20 @@ class CLICommandsMixin:_cprint(" Failed to save runtime_footer setting to config.yaml")def _handle_timestamps_command(self, cmd_original: str) -> None:- """Toggle or inspect ``display.timestamps`` from the CLI.-- When on, submitted and streamed message labels carry an ``[HH:MM]``- suffix and ``/history`` prefixes each turn with its time (for turns- that carry a stored timestamp).-- Usage:- /timestamps → toggle- /timestamps on|off → explicit- /timestamps status → show current state- """+ """Toggle or inspect ``display.timestamps`` (``/timestamps [on|off|status]``). When on,+ message labels carry an ``[HH:MM]`` suffix and ``/history`` prefixes stored-timestamp turns."""from cli import _cprint, save_config_valuefrom hermes_cli.colors import Colors as _Colors- arg = ""- try:- parts = (cmd_original or "").strip().split(None, 1)- if len(parts) > 1:- arg = parts[1].strip().lower()- except Exception:- arg = ""-+ arg = _command_arg(cmd_original, lower=True)current = bool(getattr(self, "show_timestamps", False))- if arg in {"status", "?"}:+ new_state = _toggle_target(arg, current)+ if new_state == "status":state = "ON" if current else "OFF"_cprint(f" {_Colors.BOLD}Message timestamps:{_Colors.RESET} {state}")return-- if arg in {"on", "enable", "true", "1"}:- new_state = True- elif arg in {"off", "disable", "false", "0"}:- new_state = False- elif arg == "":- new_state = not current- else:+ if new_state is None:_cprint(" Usage: /timestamps [on|off|status]")return@@ -3789,14 +3345,11 @@ class CLICommandsMixin:"""Handle /reasoning — manage effort level and display toggle.Usage:- /reasoning Show current effort level and display state- /reasoning <level> Set effort for this session only (none, minimal, low, medium, high, xhigh, max, ultra)- /reasoning <level> --global Persist reasoning effort to config.yaml- /reasoning show|on Show model thinking/reasoning in output- /reasoning hide|off Hide model thinking/reasoning from output- /reasoning full Show complete thinking (no 10-line clamp)- /reasoning clamp Collapse long thinking to the first 10 lines- """+ /reasoning Show effort level and display state+ /reasoning <level> [--global] Set effort for this session (none, minimal, low, medium,+ high, xhigh, max, ultra); --global persists to config.yaml+ /reasoning show|hide Show / hide model thinking in output+ /reasoning full|clamp Complete thinking vs. first-10-lines clamp"""from cli import CLI_CONFIG, _ACCENT, _DIM, _RST, _cprint, _parse_reasoning_config, save_config_valueparts = cmd.strip().split(maxsplit=1)@@ -3816,17 +3369,7 @@ class CLICommandsMixin:_cprint(f" {_DIM}Usage: /reasoning <none|minimal|low|medium|high|xhigh|max|ultra|show|hide|full|clamp> [--global]{_RST}")return- arg = parts[1].strip().lower()- arg_tokens = arg.split()- # Session scope is the default; --global opts into persisting to- # config.yaml. --session is accepted as an explicit no-op for parity- # with /model and the gateway /reasoning handler.- explicit_global = "--global" in arg_tokens- if explicit_global or "--session" in arg_tokens:- arg = " ".join(- token for token in arg_tokens- if token not in ("--global", "--session")- )+ arg, explicit_global = _split_scope_flags(parts[1])# Display toggleif arg in {"show", "on"}:@@ -3872,75 +3415,42 @@ class CLICommandsMixin:self.reasoning_config = parsedself.agent = None # Force agent re-init with new reasoning config- if explicit_global and save_config_value("agent.reasoning_effort", arg):+ saved = explicit_global and save_config_value("agent.reasoning_effort", arg)+ if saved:agent_cfg = CLI_CONFIG.get("agent")if not isinstance(agent_cfg, dict):agent_cfg = {}CLI_CONFIG["agent"] = agent_cfgagent_cfg["reasoning_effort"] = arg- _cprint(f" {_ACCENT}✓ Reasoning effort set to '{arg}' (saved to config){_RST}")- elif explicit_global:- _cprint(f" {_ACCENT}✓ Reasoning effort set to '{arg}' (session only; config save failed){_RST}")- else:- _cprint(f" {_ACCENT}✓ Reasoning effort set to '{arg}' (this session — use --global to persist){_RST}")+ _cprint(f" {_ACCENT}✓ Reasoning effort set to '{arg}' {_scope_outcome(explicit_global, saved)}{_RST}")def _handle_busy_command(self, cmd: str):- """Handle /busy — control what Enter does while Hermes is working.-- Usage:- /busy Show current busy input mode- /busy status Show current busy input mode- /busy queue Queue input for the next turn instead of interrupting- /busy steer Inject Enter mid-run via /steer (after next tool call)- /busy interrupt Redirect the current run on Enter (default)- """+ """Handle /busy [status|queue|steer|interrupt] — what Enter does while Hermes is working."""from cli import _ACCENT, _DIM, _RST, _cprint, save_config_valueparts = cmd.strip().split(maxsplit=1)if len(parts) < 2 or parts[1].strip().lower() == "status":_cprint(f" {_ACCENT}Busy input mode: {self.busy_input_mode}{_RST}")- if self.busy_input_mode == "queue":- _behavior = "queues for next turn"- elif self.busy_input_mode == "steer":- _behavior = "steers into current run (after next tool call)"- else:- _behavior = "redirects current run immediately"+ _behavior = _BUSY_MODE_SHORT.get(self.busy_input_mode, _BUSY_MODE_SHORT["interrupt"])_cprint(f" {_DIM}Enter while busy: {_behavior}{_RST}")_cprint(f" {_DIM}Usage: /busy [queue|steer|interrupt|status]{_RST}")returnarg = parts[1].strip().lower()- if arg not in {"queue", "interrupt", "steer"}:+ if arg not in _BUSY_MODE_LONG:_cprint(f" {_DIM}(._.) Unknown argument: {arg}{_RST}")_cprint(f" {_DIM}Usage: /busy [queue|steer|interrupt|status]{_RST}")returnself.busy_input_mode = argif save_config_value("display.busy_input_mode", arg):- if arg == "queue":- behavior = "Enter will queue follow-up input while Hermes is busy."- elif arg == "steer":- behavior = "Enter will steer your message into the current run (after the next tool call)."- else:- behavior = "Enter will redirect the current run while Hermes is busy; /stop still cancels it."_cprint(f" {_ACCENT}✓ Busy input mode set to '{arg}' (saved to config){_RST}")- _cprint(f" {_DIM}{behavior}{_RST}")+ _cprint(f" {_DIM}{_BUSY_MODE_LONG[arg]}{_RST}")else:_cprint(f" {_ACCENT}✓ Busy input mode set to '{arg}' (session only){_RST}")def _handle_indicator_command(self, cmd: str):- """Handle /indicator — pick the TUI busy-indicator style.-- Usage:- /indicator Show the current busy-indicator style- /indicator status Show the current busy-indicator style- /indicator kaomoji Animated kaomoji faces (default)- /indicator emoji Emoji spinner- /indicator unicode Braille spinner- /indicator ascii Plain ASCII spinner-- Persists to ``display.tui_status_indicator`` — the same config key the- TUI reads — so the change is picked up the next time the TUI renders.- """+ """Handle /indicator [status|kaomoji|emoji|unicode|ascii] — pick the TUI busy-indicator style.+ Persists to ``display.tui_status_indicator`` (the key the TUI reads) for its next render."""from cli import _ACCENT, _DIM, _RST, _cprint, save_config_valuefrom hermes_constants import DEFAULT_INDICATOR_STYLE, INDICATOR_STYLESstyles = INDICATOR_STYLES@@ -3994,86 +3504,46 @@ class CLICommandsMixin:_cprint(f" {_DIM}Usage: /fast [normal|fast|auto|cold|status] [--global]{_RST}")return- arg_tokens = parts[1].strip().lower().split()- explicit_global = "--global" in arg_tokens- arg = " ".join(- token for token in arg_tokens- if token not in ("--global", "--session")- )-- if arg in {"fast", "on"}:- self.service_tier = "priority"- saved_value = "fast"- label = "FAST"- elif arg in {"normal", "off"}:- self.service_tier = None- saved_value = "normal"- label = "NORMAL"- elif arg in {"auto", "cold"}:- self.service_tier = arg- saved_value = arg- label = arg.upper()- else:+ arg, explicit_global = _split_scope_flags(parts[1])+ if arg not in _FAST_TIERS:_cprint(f" {_DIM}(._.) Unknown argument: {arg}{_RST}")_cprint(f" {_DIM}Usage: /fast [normal|fast|auto|cold|status] [--global]{_RST}")return+ self.service_tier, saved_value = _FAST_TIERS[arg]+ label = saved_value.upper()self.agent = None # Force agent re-init with new service-tier config- if explicit_global and save_config_value("agent.service_tier", saved_value):- _cprint(f" {_ACCENT}✓ {feature_name} set to {label} (saved to config){_RST}")- elif explicit_global:- _cprint(f" {_ACCENT}✓ {feature_name} set to {label} (session only; config save failed){_RST}")- else:- _cprint(f" {_ACCENT}✓ {feature_name} set to {label} (this session — use --global to persist){_RST}")+ saved = explicit_global and save_config_value("agent.service_tier", saved_value)+ _cprint(f" {_ACCENT}✓ {feature_name} set to {label} {_scope_outcome(explicit_global, saved)}{_RST}")def _handle_debug_command(self, cmd_original: str = ""):- """Handle /debug — upload debug report + logs and print share URLs.-- Accepts optional destination words after the command:-- - ``/debug`` → upload to the public paste service (default)- - ``/debug nous`` → upload to Nous-internal storage (private, staff-only)- - ``/debug local`` → render the report to stdout, no upload-- ``nous`` and ``local`` are mutually exclusive; if both are given,- ``local`` wins (it never touches the network).- """+ """Handle /debug [nous|local] — upload debug report + logs and print share URLs.+ Default: public paste service; ``nous``: Nous-internal (staff-only); ``local``: render to+ stdout, no upload. ``local`` wins if both are given (never touches the network)."""from hermes_cli.debug import run_debug_sharefrom types import SimpleNamespacewords = {w.lower() for w in cmd_original.split()[1:]}local = "local" in wordsnous = "nous" in words and not local- # Typing the /debug slash command is itself the explicit consent to- # upload, so we pass yes=True to skip run_debug_share's [y/N] prompt.- # input() would hang inside prompt_toolkit's event loop anyway.+ # Typing /debug is the upload consent (yes=True); input() would hang in prompt_toolkit anyway.args = SimpleNamespace(lines=200, expire=7, local=local, nous=nous, yes=True)run_debug_share(args)def _handle_update_command(self) -> bool:- """Handle /update — update Hermes Agent to the latest version.-- In the classic CLI this exits the session and relaunches as- ``hermes update`` so the user sees update output directly and gets- the new version on next launch.+ """Handle /update — exit the session and relaunch as ``hermes update``.- Returns ``True`` when the update was confirmed (caller should trigger- app exit so the relaunch is deferred to the main thread after- prompt_toolkit cleans up terminal modes). Returns ``False`` / falsy- when cancelled.- """+ Returns True when confirmed: the caller triggers app exit so the relaunch happens on the+ main thread after prompt_toolkit restores terminal modes. False when cancelled."""from hermes_cli.config import is_managed, format_managed_messageif is_managed():print(f" ✗ {format_managed_message('update Hermes Agent')}")return False- # Use the prompt_toolkit-native modal so the confirmation panel- # renders properly above the composer and avoids raw input() races- # with the prompt_toolkit event loop (same pattern as- # _confirm_destructive_slash).+ # prompt_toolkit-native modal: renders above the composer, no raw input() races.choices = [("once", "Update Now", "exit the current session and update Hermes Agent"),("cancel", "Cancel", "keep the current session"),@@ -4095,66 +3565,46 @@ class CLICommandsMixin:print(" ⚕ Launching update...")print()- # Store the relaunch args so run() can exec them from the main thread- # after prompt_toolkit exits and restores terminal modes. Calling- # relaunch() directly here (from the process_loop daemon thread) would- # skip terminal cleanup on POSIX (execvp replaces the process mid-TUI)- # and only exit the worker thread on Windows (subprocess.run +- # sys.exit inside a non-main thread does not exit the process).+ # run() execs this from the main thread after prompt_toolkit restores terminal+ # modes. Relaunching here (daemon thread) would skip terminal cleanup on POSIX+ # and, on Windows, sys.exit would only end the worker thread.self._pending_relaunch = ["update"]return Truedef _handle_voice_command(self, command: str):"""Handle /voice [on|off|tts|status] command."""from cli import _cprint- parts = command.strip().split(maxsplit=1)- subcommand = parts[1].lower().strip() if len(parts) > 1 else ""-- if subcommand == "on":- self._enable_voice_mode()- elif subcommand == "off":- self._disable_voice_mode()- elif subcommand == "tts":- self._toggle_voice_tts()- elif subcommand == "status":- self._show_voice_status()- elif subcommand == "":- # Toggle- if self._voice_mode:- self._disable_voice_mode()- else:- self._enable_voice_mode()+ subcommand = _command_arg(command, lower=True)+ if subcommand == "": # bare /voice toggles+ subcommand = "off" if self._voice_mode else "on"+ actions = {+ "on": self._enable_voice_mode,+ "off": self._disable_voice_mode,+ "tts": self._toggle_voice_tts,+ "status": self._show_voice_status,+ }+ if subcommand in actions:+ actions[subcommand]()else:_cprint(f"Unknown voice subcommand: {subcommand}")_cprint("Usage: /voice [on|off|tts|status]")def _handle_wake_command(self, command: str):- """Handle /wake [on|off|status] — the 'Hey Hermes' hotword listener.-- The toggle IS the config: an explicit on/off (or bare toggle) also- writes ``wake_word.enabled`` to config.yaml so the choice persists- across sessions. Startup auto-arm (_maybe_start_wake_word) only reads.- """+ """Handle /wake [on|off|status] — the 'Hey Hermes' hotword listener. The toggle IS the+ config: on/off also writes ``wake_word.enabled`` so the choice persists; startup+ auto-arm only reads it."""from cli import _cprint- parts = command.strip().split(maxsplit=1)- subcommand = parts[1].lower().strip() if len(parts) > 1 else ""-+ subcommand = _command_arg(command, lower=True)+ if subcommand == "": # bare /wake toggles+ subcommand = "off" if getattr(self, "_wake_word_active", False) else "on"if subcommand == "on":if self._start_wake_word_listener(announce=True):self._persist_wake_word_enabled(True)elif subcommand == "off":self._stop_wake_word_listener(announce=True)self._persist_wake_word_enabled(False)- elif subcommand in ("", "status"):- if subcommand == "":- # Bare /wake toggles.- if getattr(self, "_wake_word_active", False):- self._stop_wake_word_listener(announce=True)- self._persist_wake_word_enabled(False)- elif self._start_wake_word_listener(announce=True):- self._persist_wake_word_enabled(True)- else:- self._show_wake_word_status()+ elif subcommand == "status":+ self._show_wake_word_status()else:_cprint(f"Unknown wake subcommand: {subcommand}")_cprint("Usage: /wake [on|off|status]")@@ -4173,3 +3623,12 @@ class CLICommandsMixin:if save_config_value("wake_word.enabled", enabled):_cprint(f"{_DIM}Wake word {'enabled' if enabled else 'disabled'} in config "f"(wake_word.enabled: {str(enabled).lower()}).{_RST}")+++_CRON_SUBCOMMANDS.update({+ "list": CLICommandsMixin._cron_list,+ "add": CLICommandsMixin._cron_add,+ "create": CLICommandsMixin._cron_add,+ "edit": CLICommandsMixin._cron_edit,+ **{k: CLICommandsMixin._cron_job_action for k in ("pause", "resume", "run", "remove", "rm", "delete")},+})