The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): compact mixin docstrings/comments by hand (keep every WHY), drop intra-body blank padding
Teknium670b974bed21
diff --git a/hermes_cli/cli_model_switch_mixin.py b/hermes_cli/cli_model_switch_mixin.pyindex 2300415dce1..20906f0ed21 100644--- a/hermes_cli/cli_model_switch_mixin.py+++ b/hermes_cli/cli_model_switch_mixin.py@@ -4,9 +4,8 @@ Mixin split out of ``cli.py``; bound onto ``HermesCLI`` via the MRO. cli.py-intesymbols are imported LAZILY inside each method (``from cli import ...``) — the mixinnever imports ``cli`` at module load time (import cycle).-Test stubs drive the switch paths with ``object.__new__`` / SimpleNamespace objects that-lack most mixin methods, so shared steps are module-level functions taking ``cli`` and-sibling methods are invoked through ``HermesCLI.<name>(self, ...)``.+Tests drive the switch paths with bare stubs lacking most mixin methods, so shared steps are+module-level functions taking ``cli`` and siblings are called as ``HermesCLI.<name>(self, ...)``."""from __future__ import annotations@@ -18,8 +17,8 @@ import threadingfrom rich.markup import escape as _escapefrom utils import base_url_host_matches-# CLI-level fields that together describe the active model route; snapshotted before a-# switch / one-turn override and restored wholesale on rollback.+# CLI-level fields describing the active model route; snapshotted before a switch / one-turn+# override and restored wholesale on rollback._RUNTIME_FIELDS = ("model", "provider", "requested_provider", "_explicit_api_key", "_explicit_base_url","api_key", "base_url", "api_mode",@@ -31,13 +30,9 @@ def _runtime_fields(cli) -> dict:def _heal_bare_custom_provider(provider, *, base_url, model):- """Bare ``custom`` is the resolved billing class, not a routable identity.-- Persisting/restoring it verbatim makes a later resume hard-fail once the config default- has moved off the custom endpoint (resolve_runtime_provider only trusts config base_url- for bare custom while the config provider is still custom-ish). Recover the durable- ``custom:<name>`` menu key from the endpoint, else drop the provider (None).- """+ """Bare ``custom`` is a billing class, not a routable identity: persisting/restoring it makes a+ later resume hard-fail once the config default leaves the custom endpoint. Recover the durable+ ``custom:<name>`` menu key from the endpoint, else drop the provider (None)."""if str(provider or "").strip().lower() != "custom":return providertry:@@ -71,9 +66,9 @@ def _merge_preflight_warning(cli, result, custom_providers) -> None:def _print_switch_summary(cli, result, old_model, *, one_turn: bool, strict_context: bool) -> None:"""Record the next-turn switch note and print the "Model switched" block.- The note is prepended to the next user message (not injected as a system message- mid-history, which breaks providers and prompt caching). ``strict_context``: the- typed /model path lets context-resolution errors propagate; the picker path swallows them.+ The note is prepended to the next user message (a mid-history system message would break+ providers and prompt caching). ``strict_context``: the typed /model path lets+ context-resolution errors propagate; the picker path swallows them."""from cli import _cprintfrom hermes_cli.model_switch import format_model_for_display, resolve_display_context_length@@ -88,9 +83,8 @@ def _print_switch_summary(cli, result, old_model, *, one_turn: bool, strict_cont_cprint(f" ✓ Model switched: {_display_new}")_cprint(f" Provider: {result.provider_label or result.target_provider}")- # Context: always resolve via the provider-aware chain so Codex OAuth, Copilot, and- # Nous-enforced caps win over the raw models.dev entry (gpt-5.5 is 1.05M on openai- # but 272K on Codex OAuth).+ # Provider-aware context chain: Codex OAuth / Copilot / Nous caps win over the raw+ # models.dev entry (gpt-5.5 is 1.05M on openai but 272K on Codex OAuth).mi = result.model_infoagent = cli.agenttry:@@ -151,10 +145,8 @@ def _commit_model_switch(cli, result, *, persist_global: bool, one_turn: bool = False, picker: bool = False) -> None:"""Stage + swap, print the summary, persist (session row unless --once; config on --global).-- ``picker``: the picker path tolerates context-resolution errors and labels the config write- "(--global)"; the typed /model path additionally records the one-turn restore snapshot.- """+ ``picker``: tolerate context-resolution errors and label the config write "(--global)"; the+ typed path additionally records the one-turn restore snapshot."""from cli import HermesCLI, _cprintold_model = cli.modelsnapshot = cli._snapshot_model_runtime() if one_turn else None@@ -170,20 +162,16 @@ def _commit_model_switch(_cprint(" (next turn only — restores after one response)")else:_cprint(" (session only — add --global to persist)")- # --global also updates config.yaml (future sessions), but the row still records what THIS- # session runs — otherwise a later resume would restore the stale creation-time model over- # the new global choice. --once is ephemeral and restored after one turn: never touch the row.+ # The row records what THIS session runs even on --global (else a later resume restores the+ # stale creation-time model); --once is restored after one turn and never touches the row.if not one_turn:HermesCLI._persist_model_switch_to_session(cli, result)def _persist_global_switch(cli, result) -> None:- """Write the switched route to config.yaml (--global).-- base_url/api_mode are always freshly resolved for the target provider (model_switch.py),- so sync them every time; None clears a value the new provider doesn't need — otherwise a- global switch leaves the OLD provider's endpoint/wire-protocol in config.yaml (#25106).- """+ """Write the switched route to config.yaml (--global). base_url/api_mode are freshly resolved+ for the target provider, so sync them every time (None clears a value the new provider doesn't+ need) — otherwise the OLD provider's endpoint/wire-protocol lingers in config.yaml."""from cli import HermesCLI, save_config_valueHermesCLI._clear_persisted_context_for_model_switch(cli, result)save_config_value("model.default", result.new_model)@@ -324,13 +312,10 @@ class CLIModelSwitchMixin:def _persist_model_switch_to_session(self, result) -> None:"""Persist a session-scoped /model switch to the session DB row.- Writes the model column plus the runtime route so ``--resume`` (CLI, reads- ``gateway_runtime``) and ``session.resume`` (TUI/desktop, reads top-level- ``model_config`` keys) both restore the switched provider instead of recombining- the model with the ambient default. Mirrors the gateway's ``update_session_model()``.- Both shapes derive from one ``route`` dict with or-None values so stale keys from a- previous switch are DELETED (``_merge_model_config_json`` only deletes on explicit- None) and the two shapes can never diverge.+ Writes the model column plus the route in both shapes readers use — nested+ ``gateway_runtime`` (CLI --resume) and top-level keys (TUI session.resume) — from one+ or-None dict so stale keys are DELETED (``_merge_model_config_json`` only deletes on+ explicit None) and the shapes never diverge."""from cli import loggerdb = getattr(self, "_session_db", None)@@ -351,22 +336,18 @@ class CLIModelSwitchMixin:logger.debug("Failed to persist model switch to session DB", exc_info=True)def _restore_session_model(self, session_meta: dict, *, quiet: bool = False) -> None:- """Restore model/provider from the session DB row on resume.-- Called from every resume path (startup ``--resume``/``-c`` and mid-chat ``/resume``);- without it a resumed session silently falls back to the config default model. Skips- when no model is recorded or the CLI was launched with an explicit ``-m`` (user intent- wins). When the stored provider differs from the ambient one, credentials are- re-resolved for it — the ambient ``api_key`` belongs to the config-default provider- and must not be sent to the session's endpoint; on failure the ambient credentials are- kept so the session still opens (the first turn surfaces the auth error).+ """Restore model/provider from the session DB row on every resume path.++ Skips when no model is recorded or the CLI got an explicit ``-m`` (user intent wins).+ A different stored provider gets its credentials re-resolved — the ambient ``api_key``+ must not be sent to the session's endpoint; on failure the ambient credentials are kept+ so the session still opens (the first turn surfaces the auth error)."""from cli import loggerstored_model = (session_meta or {}).get("model")if not stored_model or getattr(self, "_explicit_model_override", False):return- # Canonical row-level reader: prefers model_config.gateway_runtime, falls back to- # the TUI gateway's top-level keys.+ # Canonical row reader: model_config.gateway_runtime, else the TUI's top-level keys.from hermes_state import SessionDB as _SessionDB_stored_runtime = _SessionDB.session_gateway_runtime(session_meta)stored_base_url = _stored_runtime.get("base_url") or None@@ -389,13 +370,11 @@ class CLIModelSwitchMixin:if stored_api_mode:self.api_mode = stored_api_modeif provider_changed:- # Stale launch-time explicit overrides belong to the AMBIENT provider; carrying- # them into the restored provider's resolution poisons- # _ensure_runtime_credentials on startup resume.+ # Launch-time explicit overrides belong to the AMBIENT provider and would poison+ # _ensure_runtime_credentials for the restored one. api_key is never persisted to+ # the session DB — runtime provider resolution owns credentials.self._explicit_api_key = Noneself._explicit_base_url = stored_base_url- # api_key is never persisted to the session DB (by design) — runtime provider- # resolution owns credentials.try:from hermes_cli.runtime_provider import resolve_runtime_providerresolved = resolve_runtime_provider(requested=stored_provider)@@ -412,8 +391,8 @@ class CLIModelSwitchMixin:"%s failed; keeping ambient credentials",stored_provider, exc_info=True,)- # Mid-chat /resume: swap the live agent in place. On startup --resume the agent- # isn't built yet — _init_agent picks up self.model / self.provider.+ # Mid-chat /resume swaps the live agent; on startup --resume _init_agent picks up+ # self.model / self.provider.if self.agent is not None:try:self.agent.switch_model(@@ -533,12 +512,9 @@ class CLIModelSwitchMixin:@staticmethoddef _filter_model_picker_entries(entries: list, query: str) -> list:- """Return (original_index, label) pairs for entries matching ``query``.-- Case-insensitive subsequence match; an empty query matches everything. Pairs carry- the ORIGINAL index into ``entries`` so a selection in the filtered view resolves to- exactly one concrete model — filtering never introduces fuzzy *resolution*.- """+ """Return (original_index, label) pairs matching ``query`` (case-insensitive subsequence;+ empty matches all). The ORIGINAL index keeps a filtered selection resolving to exactly one+ concrete model — filtering never introduces fuzzy *resolution*."""pairs = list(enumerate(entries))q = (query or "").strip().lower()if not q:@@ -555,12 +531,9 @@ class CLIModelSwitchMixin:selected: int, scroll_offset: int, n: int, term_rows: int, reserved_below: int = 6,panel_chrome: int = 6, min_visible: int = 3,) -> tuple[int, int]:- """Resolve (scroll_offset, visible) for the /model picker viewport.-- ``reserved_below`` matches the approval / clarify panels (input area, status bar,- separators); ``panel_chrome`` is this panel's borders + blanks + hint row. The- offset slides to keep ``selected`` on screen.- """+ """Resolve (scroll_offset, visible) for the /model picker viewport. ``reserved_below``+ matches the approval/clarify panels (input, status bar, separators); ``panel_chrome`` is+ borders + blanks + hint row. The offset slides to keep ``selected`` on screen."""max_visible = max(min_visible, term_rows - reserved_below - panel_chrome)if n <= max_visible:return 0, n@@ -593,19 +566,17 @@ class CLIModelSwitchMixin:def _stage_and_swap_model(self, result, old_model) -> bool:"""Stage ``result`` onto the CLI fields, then swap the live agent in place.- CLI-level fields are snapshotted first (mirrors the gateway) so a failed in-place- agent swap rolls the whole CLI back to the old working model — otherwise the broken- credentials staged here leak into the next turn's resolution even though the agent- itself rolled back. Returns False after printing the failure so the caller aborts- the rest of the commit (a failed switch is a no-op, not a dead session).+ CLI fields are snapshotted first so a failed agent swap rolls the whole CLI back —+ otherwise the staged broken credentials leak into the next turn even though the agent+ rolled back. Returns False after printing the failure (a failed switch is a no-op)."""from cli import _cprint_cli_snapshot = _runtime_fields(self)self.model = result.new_modelself.provider = result.target_providerself.requested_provider = result.target_provider- # Always overwrite explicit overrides so stale credentials from the previous- # provider (e.g. Ollama api_key/base_url) don't leak into the next resolution.+ # Always overwrite explicit overrides so stale credentials from the previous provider+ # (e.g. Ollama api_key/base_url) don't leak into the next resolution.self._explicit_api_key = result.api_keyself._explicit_base_url = result.base_urlif result.api_key:@@ -655,9 +626,8 @@ class CLIModelSwitchMixin:self._close_model_picker()returnprovider_data = providers[selected]- # Curated list from list_authenticated_providers() (same as `hermes model` and- # gateway pickers); live catalog only when the curated list is empty- # (user-defined endpoints).+ # Curated list (same as `hermes model` / gateway pickers); live catalog only when+ # it is empty (user-defined endpoints).model_list = provider_data.get("models", [])if not model_list:try:@@ -674,8 +644,7 @@ class CLIModelSwitchMixin:if stage == "model":provider_data = state.get("provider_data") or {}model_list = state.get("model_list") or []- # Map the selected row through the active fuzzy filter; the filtered pair- # carries the ORIGINAL index, so the resolved model is one concrete entry.+ # Map the row through the active fuzzy filter; pairs carry the ORIGINAL index.filtered_pairs = state.get("_filtered_pairs")if filtered_pairs is None:filtered_pairs = list(enumerate(model_list))@@ -721,15 +690,12 @@ class CLIModelSwitchMixin:/model <name> --provider <provider> — switch provider + model/model --provider <provider> — switch to provider, auto-detect model- Persistence defaults to off (``model.persist_switch_by_default``, default False —- switches are session-scoped). ``--global`` persists, ``--once`` is next-turn only.+ Switches are session-scoped unless ``model.persist_switch_by_default`` or ``--global``."""from cli import _cprintfrom hermes_cli.model_switch import parse_model_switch_args, resolve_persist_behaviorparts = cmd_original.split(None, 1) # split off '/model'- # Single-owner flag parser (hermes_cli.model_switch): --provider/--global/--session/- # --once/--refresh.request = parse_model_switch_args(parts[1].strip() if len(parts) > 1 else "")if request.errors:# CLI decoration: " ✗ " prefix over the canonical error copy.@@ -741,8 +707,7 @@ class CLIModelSwitchMixin:explicit_provider=request.explicit_provider,)- # --refresh: wipe the on-disk picker cache so every authed provider's /v1/models- # is re-fetched live on this open.+ # --refresh: wipe the picker cache so every authed provider's /v1/models is re-fetched.if request.force_refresh:try:from hermes_cli.models import clear_provider_models_cache@@ -751,8 +716,7 @@ class CLIModelSwitchMixin:except Exception:pass- # Single inventory context; live session state overlaid via with_overrides- # (truthy-only) so empty self.* attrs don't clobber disk config.+ # Live session state is overlaid truthy-only so empty self.* attrs don't clobber config.from hermes_cli.inventory import load_picker_contexttry:ctx = load_picker_context().with_overrides(@@ -785,12 +749,8 @@ class CLIModelSwitchMixin:def _confirm_and_apply_cli_model_switch(self, result, persist_global: bool, one_turn: bool, custom_provs=None) -> None:- """Confirm an expensive model switch and apply it to CLI state.-- Runs on a worker thread when the TUI is active (see _run_confirm_and_apply) so the- confirmation modal can render. Updates requested_provider (via the swap) so- _ensure_runtime_credentials() doesn't overwrite the switch on the next turn.- """+ """Confirm an expensive model switch and apply it (typed /model path). Runs on a worker+ thread when the TUI is active (see _run_confirm_and_apply) so the modal can render."""from cli import _cprintif not self._confirm_expensive_model_switch(result):_cprint(" Model switch cancelled.")@@ -843,9 +803,8 @@ class CLIModelSwitchMixin:return Falsedef _cmd_moa(self, cmd_original: str):- """/moa is one-shot sugar: run one prompt through the default MoA preset, then restore- the prior model. Switching to MoA for the session is done via the model picker (MoA- presets surface as a virtual "Mixture of Agents" provider)."""+ """/moa one-shot: run one prompt through the default MoA preset, then restore the prior+ model (a session-long MoA switch goes through the picker's virtual MoA provider)."""from cli import _cprint, _slash_argsfrom hermes_cli.moa_config import moa_usage, normalize_moa_configdiff --git a/hermes_cli/cli_stream_mixin.py b/hermes_cli/cli_stream_mixin.pyindex b881020a2bc..13071b2681b 100644--- a/hermes_cli/cli_stream_mixin.py+++ b/hermes_cli/cli_stream_mixin.py@@ -19,7 +19,9 @@ from rich.markup import escape as _escape# Model-generated reasoning tags: suppressed during streaming (they'd display as raw XML;# the agent strips them from final_response too) unless show_reasoning routes them to the box.-_OPEN_TAGS = ("<REASONING_SCRATCHPAD>", "<think>", "<reasoning>", "<THINKING>", "<thinking>", "<thought>")+_OPEN_TAGS = (+ "<REASONING_SCRATCHPAD>", "<think>", "<reasoning>", "<THINKING>", "<thinking>", "<thought>",+)_CLOSE_TAGS = tuple("</" + t[1:] for t in _OPEN_TAGS)_MAX_CLOSE_TAG_LEN = max(len(t) for t in _CLOSE_TAGS)@@ -57,10 +59,9 @@ class CLIStreamMixin:def _on_notice(self, notice) -> None:"""Queue an out-of-band AgentNotice for rendering at the next clean boundary.- Notices fire from inside the agent turn (cold-start seed during _init_agent, per-turn- _capture_credits after the API call) — printing immediately races the streaming- response and the line gets buried behind the prompt. Flushed by- _flush_credit_notices() right after run_conversation returns. Fail-soft.+ Notices fire mid-turn (cold-start seed, per-turn _capture_credits); printing immediately+ races the stream and buries the line behind the prompt. Flushed by _flush_credit_notices()+ after run_conversation returns. Fail-soft."""try:text = getattr(notice, "text", "") or ""@@ -107,9 +108,7 @@ class CLIStreamMixin:preview_text = reasoning_text.strip()if not preview_text:return- prefix = " [thinking] "- wrap_width = max(30, _terminal_columns() - len(prefix) - 2)-+ wrap_width = max(30, _terminal_columns() - len(" [thinking] ") - 2)paragraphs = []for paragraph in re.split(r"\n\s*\n+", preview_text.replace("\r\n", "\n")):compact = " ".join(line.strip() for line in paragraph.splitlines() if line.strip())@@ -151,9 +150,12 @@ class CLIStreamMixin:flush_text, buf = buf[: line_break + 1], buf[line_break + 1 :]elif len(buf) >= target_width:search_start = max(20, target_width // 2)- search_end = min(len(buf), max(target_width + (target_width // 3), target_width + 8))+ search_end = min(+ len(buf), max(target_width + (target_width // 3), target_width + 8)+ )cut = max(- buf.rfind(b, search_start, search_end) for b in (" ", "\t", ".", "!", "?", ",", ";", ":")+ buf.rfind(b, search_start, search_end)+ for b in (" ", "\t", ".", "!", "?", ",", ";", ":"))if cut != -1:flush_text, buf = buf[: cut + 1], buf[cut + 1 :]@@ -221,12 +223,11 @@ class CLIStreamMixin:ChatConsole().print(f"[bold {_accent_hex()}]●[/] [bold]{_escape(text)}[/]")def _stream_reasoning_delta(self, text: str) -> None:- """Stream reasoning/thinking tokens into a dim box above the response.+ """Stream reasoning tokens into a dim box above the response.- Opens the box on the first token; closed automatically when content tokens arrive- (_stream_delta → _emit_stream_text). Once the response box is open, further- reasoning is suppressed — a late thinking block (e.g. after an interrupt) would- otherwise draw a reasoning box inside the response box.+ Opened on the first token, closed when content arrives (_emit_stream_text). Once the+ response box is open further reasoning is suppressed — a late thinking block (e.g. after+ an interrupt) would otherwise draw a reasoning box inside the response box."""from cli import _DIM, _RST, _cprintif not text:@@ -271,11 +272,9 @@ class CLIStreamMixin:def _stream_delta(self, text) -> None:"""Line-buffered streaming callback for real-time token rendering.- Buffers partial lines and emits complete lines via _cprint (reliable under- prompt_toolkit's patch_stdout). Reasoning tags are suppressed — or routed to the- reasoning box when show_reasoning is on. ``None`` signals an intermediate turn- boundary (tools about to execute): flush open boxes and reset state so tool feed- lines render cleanly between turns.+ Emits complete lines via _cprint (reliable under prompt_toolkit's patch_stdout);+ reasoning tags are suppressed, or routed to the reasoning box when show_reasoning is on.+ ``None`` = intermediate turn boundary (tools about to run): flush boxes and reset state."""if text is None:self._flush_stream()@@ -286,16 +285,14 @@ class CLIStreamMixin:self._stream_started = Trueself._stream_prefilt = getattr(self, "_stream_prefilt", "") + text- # Open tags only count at a "block boundary": stream start, after a newline (plus- # optional whitespace), or when only whitespace has been emitted on the current- # line. Prevents false positives when models *mention* tags in prose like- # "(/think not producing <think> tags)". _stream_last_was_newline is True at- # stream start and whenever emitted text ends with '\n'.+ # Open tags only count at a "block boundary" (stream start / after a newline plus+ # optional whitespace) so prose that *mentions* a tag — "(/think not producing+ # <think> tags)" — is not swallowed. _stream_last_was_newline tracks the boundary.if not hasattr(self, "_stream_last_was_newline"):self._stream_last_was_newline = Trueif not getattr(self, "_in_reasoning_block", False):- # Lowercased view so mixed-case variants (<Think>, <THINKING>, …) are caught.+ # Lowercased view catches mixed-case variants (<Think>, <THINKING>, …).prefilt_lower = self._stream_prefilt.lower()for tag in _OPEN_TAGS:tag_lower = tag.lower()@@ -336,8 +333,8 @@ class CLIStreamMixin:self._stream_prefilt = self._stream_prefilt[len(safe):]return- # Inside a reasoning block — look for a close tag. Keep accumulating because close- # tags can arrive split across tokens ("</REASONING_SCRATCH" + "PAD>...").+ # Inside a reasoning block — look for a close tag; keep accumulating because close tags+ # can arrive split across tokens ("</REASONING_SCRATCH" + "PAD>...").if getattr(self, "_in_reasoning_block", False):prefilt_lower = self._stream_prefilt.lower()for tag in _CLOSE_TAGS:@@ -350,13 +347,11 @@ class CLIStreamMixin:self._stream_reasoning_delta(inner)after = self._stream_prefilt[idx + len(tag):]self._stream_prefilt = ""- # Text after the close tag goes through full filtering (it could- # contain another open tag).- if after:+ if after: # re-filter: the remainder could contain another open tagself._stream_delta(after)return- # Stream reasoning live when show_reasoning is on; keep only the tail that- # could be a partial close-tag prefix.+ # Stream reasoning live when show_reasoning is on; keep only a possible partial+ # close-tag tail.if len(self._stream_prefilt) > _MAX_CLOSE_TAG_LEN:if self.show_reasoning:self._stream_reasoning_delta(self._stream_prefilt[:-_MAX_CLOSE_TAG_LEN])@@ -372,11 +367,8 @@ class CLIStreamMixin:)def _flush_stream_table_buf(self) -> None:- """Emit the held table block re-aligned as a whole.-- Cell-level markdown (`code`, **bold**, ~~strike~~) is stripped FIRST so the- realigner pads to the final visible cell width, not the marker-decorated width.- """+ """Emit the held table block re-aligned as a whole. Cell-level markdown is stripped FIRST+ so the realigner pads to the final visible width, not the marker-decorated width."""from cli import (_strip_markdown_syntax, _terminal_width_for_streaming, realign_markdown_tables)@@ -400,8 +392,7 @@ class CLIStreamMixin:)if not text:return- # While the reasoning box is still rendering, defer content so the reasoning block- # always appears BEFORE the response.+ # Defer content while the reasoning box renders so reasoning always lands BEFORE it.if self.show_reasoning and getattr(self, "_reasoning_box_opened", False):self._deferred_content = getattr(self, "_deferred_content", "") + textreturn@@ -421,8 +412,7 @@ class CLIStreamMixin:except Exception:label = "⚕ Hermes"_text_hex = "#FFF8DC"- # True-color ANSI escape so streamed content matches the Rich Panel appearance.- try:+ try: # true-color escape so streamed text matches the Rich Panel appearance_r, _g, _b = (int(_text_hex[i:i + 2], 16) for i in (1, 3, 5))self._stream_text_ansi = f"\033[38;2;{_r};{_g};{_b}m"except (ValueError, IndexError):@@ -436,9 +426,8 @@ class CLIStreamMixin:self._stream_buf += textwhile "\n" in self._stream_buf:line, self._stream_buf = self._stream_buf.split("\n", 1)- # Table-shaped lines are held in a side-buffer and re-padded as a block once it- # ends (streaming line-by-line we cannot re-align already-printed rows); the- # table appears in one batch when the block closes.+ # Table rows are held and re-padded as a block once it ends (already-printed rows+ # can't be re-aligned), so a table appears in one batch when the block closes.if self._in_stream_table:if looks_like_table_row(line) or is_table_divider(line):self._stream_table_buf.append(line)@@ -452,11 +441,9 @@ class CLIStreamMixin:line = _strip_markdown_syntax(line)self._emit_stream_line(line)- # Long partial lines are emitted ONLY at real newlines — no hard-wrapping at- # terminal width: each logical line lands in scrollback as one line the terminal- # soft-wraps, so highlight-copy yields the original unwrapped text. For TTFT- # perception, mirror the tail of a long unfinished paragraph into the status-bar- # spinner so the user sees tokens arriving instead of a blank box.+ # Partial lines are emitted ONLY at real newlines (no hard-wrapping — the terminal+ # soft-wraps, so highlight-copy yields the original text). For TTFT perception, mirror+ # the tail of a long unfinished paragraph into the status-bar spinner.if (self._stream_bufand not self._in_stream_table@@ -478,18 +465,15 @@ class CLIStreamMixin:from cli import (_ACCENT, _RST, _cprint, _strip_markdown_syntax, is_table_divider, looks_like_table_row)- # Still inside a "reasoning block" at end-of-stream means a false positive — the- # model mentioned a tag like <think> in prose and never closed it. Recover the- # buffered content as regular text.+ # Still inside a "reasoning block" at end-of-stream = false positive (the model+ # mentioned a tag in prose and never closed it): recover the buffer as regular text.if getattr(self, "_in_reasoning_block", False) and getattr(self, "_stream_prefilt", ""):self._in_reasoning_block = Falseself._emit_stream_text(self._stream_prefilt)self._stream_prefilt = ""- # Close reasoning box if still open (in case no content tokens arrived)- self._close_reasoning_box()-- # A trailing partial line that looks like a table row joins the table buffer so- # the whole block is re-aligned together (else the final row prints under-padded).+ self._close_reasoning_box() # in case no content tokens arrived+ # A trailing partial table row joins the table buffer so the whole block is re-aligned+ # together (else the final row prints under-padded).if (self._stream_bufand getattr(self, "_in_stream_table", False)@@ -543,9 +527,8 @@ class CLIStreamMixin:def _busy_command(self, status: str, *, blocks_input: bool = True):"""Expose a temporary busy state in the TUI while a slash command runs.- Most synchronous slash commands must reserve the composer because their completion- changes the active session state. Manual compression is safe to draft through: the- queued input is processed against the compacted history afterwards.+ Most sync slash commands reserve the composer (their completion changes session state);+ manual compression is safe to draft through (queued input runs against compacted history)."""previous_blocks_input = getattr(self, "_command_blocks_input", False)self._command_running = True@@ -562,17 +545,12 @@ class CLIStreamMixin:self._invalidate(min_interval=0.0)def _preprocess_images_with_vision(self, text: str, images: list, *, announce: bool = True) -> str:- """Analyze attached images via the vision tool and return enriched text.-- Instead of embedding raw base64 ``image_url`` parts (vision-capable models only),- each image is described by the auxiliary vision model and the descriptions are- prepended to the user's message — the same approach the messaging gateway uses.- The local path is included so the agent can re-examine via ``vision_analyze``.- """+ """Describe attached images via the auxiliary vision model and prepend the descriptions+ to the user's text (works with non-vision models; same approach as the gateway). The+ local path is included so the agent can re-examine via ``vision_analyze``."""from cli import _DIM, _RST, _cprintimport asyncio as _asynciofrom tools.vision_tools import vision_analyze_tool-analysis_prompt = ("Describe everything visible in this image in thorough detail. ""Include any text, code, data, objects, people, layout, colors, "@@ -631,11 +609,8 @@ class CLIStreamMixin:console.print(*args, **kwargs)def _on_tool_gen_start(self, tool_name: str) -> None:- """Called when the model begins generating tool-call arguments.-- Closes any open streaming boxes exactly once, then prints a short status line so- the user sees activity while a large payload (e.g. 45 KB write_file) streams.- """+ """Model began generating tool-call arguments: close open boxes once, then print a status+ line so a large payload (e.g. 45 KB write_file) doesn't look like a frozen screen."""from cli import _cprintif getattr(self, "_stream_box_opened", False):self._flush_stream()@@ -645,16 +620,14 @@ class CLIStreamMixin:_cprint(f" ┊ {get_tool_emoji(tool_name, default='⚡')} preparing {tool_name}…")def _on_tool_progress(self, event_type: str, function_name: str = None, preview: str = None, function_args: dict = None, **kwargs):- """Called on tool lifecycle events (tool.started, tool.completed, reasoning.available, …).+ """Tool lifecycle events (tool.started / tool.completed / reasoning.* / moa.*).- Updates the TUI spinner so the user can see what the agent is doing during tool- execution. tool.started records a monotonic timestamp for the live elapsed timer.- When tool_progress_mode is "all"/"new"/"verbose", tool.completed also prints a- persistent stacked scrollback line (full tool-call history, not just the spinner).+ Drives the TUI spinner (tool.started stamps the elapsed timer); in "all"/"new"/"verbose"+ progress modes tool.completed also commits a stacked scrollback line (tool history)."""from cli import CLI_CONFIG, _DIM, _RST, _cprint, _hermes_home- # MoA reference-model outputs: display-only events from the MoA facade; render each- # reference's answer as a labelled thinking-style block BEFORE the aggregator acts.+ # MoA reference outputs (display-only events from the MoA facade): render each answer+ # as a labelled thinking-style block BEFORE the aggregator acts.if event_type == "moa.reference":label = function_name or "reference"text = preview or ""@@ -679,8 +652,7 @@ class CLIStreamMixin:self._invalidate()return- # Feed the pet: tools mean "running" (not reasoning); a failed tool latches the- # turn so it ends on a sulk.+ # Feed the pet: tools mean "running"; a failed tool latches the turn to end on a sulk.if event_type == "tool.started":self._pet_reasoning = Falseelif event_type == "tool.completed" and kwargs.get("is_error"):@@ -690,20 +662,17 @@ class CLIStreamMixin:if event_type == "tool.completed":self._tool_start_time = 0.0- # Per-turn accounting: this feed sees every tool call with its result.self._turn_summary_record(function_name, kwargs.get("result"), kwargs.get("is_error", False))- # Focus view: count the scrollback line we are NOT printing so the post-turn- # recovery line can report how much was hidden.+ # Focus view: count the hidden scrollback line for the post-turn recovery report.if getattr(self, "_focus_view_enabled", False):try:self._note_focus_hidden_line(function_name or "")except Exception:pass- # "verbose" must commit at least the same line as "all": non-streaming model- # calls (MoA aggregator, copilot-acp) never emit _on_tool_gen_start's- # "preparing" line, so without this no scrollable tool history accumulates.+ # "verbose" must commit the same line as "all": non-streaming calls (MoA aggregator,+ # copilot-acp) never emit the "preparing" line, so nothing else builds history.if function_name and self.tool_progress_mode in {"new", "all", "verbose"}:duration = kwargs.get("duration", 0.0)# Pop stored args from tool.started for this function@@ -722,9 +691,8 @@ class CLIStreamMixin:_cprint(f" {line}")except Exception:pass- # First-touch onboarding: one-time /verbose hint on the first long tool in- # the noisiest mode. Latched on self (once per process) and persisted to- # config.yaml (never again across processes).+ # One-time /verbose hint on the first long tool in the noisiest mode; latched+ # on self and persisted to config.yaml.try:if (not getattr(self, "_long_tool_hint_fired", False)@@ -773,9 +741,8 @@ class CLIStreamMixin:def _on_tool_complete(self, tool_call_id: str, function_name: str, function_args: dict, function_result: str):"""Render file edits with inline diff after write-capable tools complete."""from cli import _cprint, logger- # A top-level delegate_task dispatches in the background and re-enters as a fresh- # turn when done. Say so once — no spinner, nothing to poll — so the idle prompt- # doesn't read as "nothing happened" (⛓ tracks the work).+ # A background delegate_task re-enters as a fresh turn when done; say so once so the+ # idle prompt doesn't read as "nothing happened".if function_name == "delegate_task":try:parsed = json.loads(function_result) if isinstance(function_result, str) else (function_result or {})diff --git a/hermes_cli/cli_voice_mixin.py b/hermes_cli/cli_voice_mixin.pyindex c80ce39e110..16e28bf1442 100644--- a/hermes_cli/cli_voice_mixin.py+++ b/hermes_cli/cli_voice_mixin.py@@ -101,8 +101,8 @@ class CLIVoiceMixin:voice_cfg = _config_section("voice")- # Recorder creation can fail (no input device, PortAudio init error). Reset the- # flag on failure or every future voice start is silently skipped by the guard.+ # Recorder creation can fail (no input device, PortAudio init). Reset the flag on+ # failure or every future voice start is silently skipped by the guard above.if self._voice_recorder is None:try:self._voice_recorder = create_audio_recorder()@@ -198,9 +198,8 @@ class CLIVoiceMixin:def _voice_stop_and_transcribe(self):"""Stop recording, transcribe via STT, and queue the transcript as input."""from cli import _DIM, _RST, _VoiceInputMessage, _cprint- # Atomic guard: only one thread enters stop-and-transcribe. Set _voice_processing- # immediately so concurrent Ctrl+B presses don't race into the START path while- # recorder.stop() holds its lock.+ # Atomic guard; _voice_processing is set immediately so concurrent Ctrl+B presses+ # don't race into the START path while recorder.stop() holds its lock.with self._voice_lock:if not self._voice_recording:return@@ -220,7 +219,6 @@ class CLIVoiceMixin:_cprint(f"{_DIM}No speech detected.{_RST}")returnself._voice_invalidate()-stt_model = self._voice_stt_model()if self._voice_stt_provider() == "local":_cprint(@@ -229,16 +227,12 @@ class CLIVoiceMixin:)else:_cprint(f"{_DIM}Transcribing...{_RST}")-- from tools.voice_mode import transcribe_recording+ from tools.voice_mode import is_voice_stop_phrase, transcribe_recordingresult = transcribe_recording(wav_path, model=stt_model)-if result.get("success") and result.get("transcript", "").strip():transcript = result["transcript"].strip()- from tools.voice_mode import is_voice_stop_phraseif is_voice_stop_phrase(transcript):- # Bare "stop" (or configured phrase) ends the voice chat instead of- # being sent to the agent.+ # Bare "stop" (or configured phrase) ends the voice chat, not a turn._cprint(f"{_DIM}Stop phrase detected — ending voice chat.{_RST}")self._disable_voice_mode()return@@ -268,10 +262,10 @@ class CLIVoiceMixin:except Exception:pass- # Consecutive no-speech cycles end continuous mode (no infinite restart loop).- # While the agent is mid-turn or TTS is speaking the user is CORRECTLY silent —- # those cycles must not count, or a multi-minute tool run ends the voice chat- # under the user. Stop phrase and barge-in still work during the hold.+ # Three consecutive no-speech cycles end continuous mode (no infinite restart+ # loop). While the agent is mid-turn or TTS is speaking the user is CORRECTLY+ # silent — those cycles must not count, or a multi-minute tool run ends the voice+ # chat under the user (stop phrase and barge-in still work during the hold).stop_continuous_restart = False_tts_done = getattr(self, "_voice_tts_done", None)_activity_hold = bool(@@ -287,9 +281,8 @@ class CLIVoiceMixin:self._no_speech_count = 0_cprint(f"{_DIM}No speech detected 3 times, continuous mode stopped.{_RST}")stop_continuous_restart = True-- # No transcript but continuous mode active: restart so the user can keep- # talking. (When a transcript IS submitted, process_loop restarts after chat().)+ # No transcript but continuous mode active: restart so the user can keep talking+ # (when a transcript IS submitted, process_loop restarts after chat()).if (self._voice_continuousand not submitted@@ -304,10 +297,8 @@ class CLIVoiceMixin:returnself._voice_tts_done.clear()threading.Thread(target=self._voice_speak_response, args=(text,), daemon=True).start()- # Spoken barge-in must work on the whole-file fallback path too. The full-duplex- # agent-turn listener normally already covers playback (armed at turn start in- # chat()); this arm is an idempotent safety net for speak calls outside a chat- # turn — the listener refuses to double-arm via _voice_fd_active.+ # Barge-in safety net for speak calls outside a chat turn (the agent-turn listener+ # armed in chat() normally covers playback); idempotent via _voice_fd_active.if self._voice_continuous:threading.Thread(target=self._voice_full_duplex_listener, daemon=True).start()@@ -320,10 +311,8 @@ class CLIVoiceMixin:try:from tools.tts_tool import text_to_speech_toolfrom tools.voice_mode import play_audio_file-- # Shared cleaner (tools/tts_text_normalize): markdown, emoji, ⋗ blocks, verifier- # footer, units, newline flattening. The TTS tool owns provider request limits- # and long-form chunking.+ # Shared cleaner strips markdown/emoji/⋗ blocks/verifier footer; the TTS tool owns+ # provider request limits and long-form chunking.try:from tools.tts_text_normalize import prepare_spoken_texttts_text = prepare_spoken_text(text, max_chars=None)@@ -343,9 +332,8 @@ class CLIVoiceMixin:if not tts_text:returnself._voice_last_tts_text = tts_text-- # MP3 output for CLI playback (afplay doesn't handle OGG well). The TTS tool- # may auto-convert MP3->OGG, but the original MP3 remains.+ # MP3 for CLI playback (afplay doesn't handle OGG well); the TTS tool may+ # auto-convert MP3->OGG but the original MP3 remains.out_dir = os.path.join(tempfile.gettempdir(), "hermes_voice")os.makedirs(out_dir, exist_ok=True)mp3_path = os.path.join(out_dir, f"tts_{time.strftime('%Y%m%d_%H%M%S')}.mp3")@@ -355,9 +343,7 @@ class CLIVoiceMixin:tts_result = json.loads(raw_result) if isinstance(raw_result, str) else {}except Exception:tts_result = {}-- # The tool result is authoritative — long-form chunked output returns multiple- # files. Play each in order.+ # The tool result is authoritative — chunked long-form output returns several files.play_paths = tts_result.get("file_paths") or [tts_result.get("file_path") or mp3_path]for play_path in play_paths if tts_result.get("success") else []:if os.path.isfile(play_path) and os.path.getsize(play_path) > 0:@@ -374,19 +360,11 @@ class CLIVoiceMixin:def _voice_full_duplex_listener(self) -> None:"""Full-duplex agent-turn listener: mic live for the WHOLE turn.- Armed at utterance-submit (chat() start in continuous voice mode) and disarmed when- the turn is fully done (agent finished + TTS played), so the user can interject by- voice during LLM generation, not only during playback (see- tools.voice_mode.full_duplex_listen).-- * generation (no TTS audio yet): speech interrupts the in-flight agent turn via- ``self.agent.interrupt()`` — the same seam the typed/Ctrl+C interrupt uses — and- the captured utterance is submitted as the next message.- * playback: speech cuts TTS (pipeline stop event + stop_playback) and the- interruption is captured with pre-roll and submitted.-- The stop phrase ends the voice chat in BOTH phases (the turn is already interrupted- at trip time, then ``_voice_submit_barge_utterance`` disables voice mode).+ Armed at utterance-submit (chat() start in continuous voice mode), disarmed when agent+ finished + TTS played, so the user can interject during generation too. Generation+ phase: speech interrupts the turn via ``self.agent.interrupt()`` (same seam as+ Ctrl+C); playback phase: speech cuts TTS. Either way the captured utterance is+ submitted as the next message; the stop phrase ends the voice chat in BOTH phases."""from cli import _DIM, _RST, _cprint, loggerfd_active = getattr(self, "_voice_fd_active", None)@@ -425,8 +403,8 @@ class CLIVoiceMixin:return not is_audio_output_active()def _on_trigger(phase: str) -> None:- # Latch BEFORE cutting anything: suppresses process_loop's auto-restart- # until the capture is submitted.+ # Latch BEFORE cutting anything: suppresses process_loop's auto-restart until+ # the capture is submitted.self._voice_barge_capture.set()self._voice_barge_phase = phase_pipe_stop = getattr(self, "_voice_tts_stop", None)@@ -438,8 +416,7 @@ class CLIVoiceMixin:_pipe_stop.set()stop_playback()else:- # Generation phase: no audio to cut — interrupt the in-flight agent- # turn (same seam as typed interrupt).+ # Generation phase: no audio to cut — interrupt the in-flight agent turn.logger.debug("full-duplex listener tripped during generation — ""interrupting agent turn"@@ -481,9 +458,8 @@ class CLIVoiceMixin:_cprint(f"\n{_DIM}Stop phrase detected — ending voice chat.{_RST}")self._disable_voice_mode()return- # Fail-closed echo guard: a playback-phase capture has no acoustic echo- # cancellation, so speaker bleed alone can trip the barge trigger. A close- # match for what Hermes just spoke is self-capture, not a user turn.+ # Fail-closed echo guard: playback-phase capture has no echo cancellation, so+ # a close match for what Hermes just spoke is speaker bleed, not a user turn.if getattr(self, "_voice_barge_phase", None) == "playback":from tools.voice_mode import is_tts_echoif is_tts_echo(transcript, getattr(self, "_voice_last_tts_text", "")):@@ -509,9 +485,7 @@ class CLIVoiceMixin:def _voice_beeps_enabled(self) -> bool:"""Return whether CLI voice mode should play record start/stop beeps."""try:- from utils import is_truthy_value- # is_truthy_value handles quoted YAML strings like "false" which bool() would- # misread as True.+ from utils import is_truthy_value # handles quoted YAML "false" (bool() would not)return is_truthy_value(_config_section("voice").get("beep_enabled", True), default=True)except Exception:return True@@ -524,8 +498,6 @@ class CLIVoiceMixin:returnfrom tools.voice_mode import check_voice_requirements, detect_audio_environment-- # Environment detection -- warn and block in incompatible environmentsenv_check = detect_audio_environment()if not env_check["available"]:_cprint(f"\n{_ACCENT}Voice mode unavailable in this environment:{_RST}")@@ -557,9 +529,7 @@ class CLIVoiceMixin:# prompt change) to avoid invalidating the prompt cache — see _voice_message_prefix.tts_status = " (TTS enabled)" if self._voice_tts else ""if self._voice_tts:- # Speech output is on from the start — warm the engine now so the first- # spoken reply doesn't pay the model load as dead air.- self._tts_lease_async(True)+ self._tts_lease_async(True) # warm the engine so the first reply isn't dead air# Startup-pinned label so the advertised shortcut always matches the live# prompt_toolkit binding (live config would drift after a mid-session edit)._cprint(f"\n{_ACCENT}Voice mode enabled{tts_status}{_RST}")@@ -576,13 +546,9 @@ class CLIVoiceMixin:_cprint(f" {_DIM}/voice off to disable voice mode{_RST}")def _typed_voice_stop(self, user_input) -> bool:- """Typed bare stop phrase during an active voice chat ends the chat.-- Mirrors the spoken stop phrase; guarded on voice mode being ON so typed "stop"- outside voice chat passes through to the agent. Reuses ``is_voice_stop_phrase``- (same ``voice.stop_phrases`` config, exact-match semantics), so longer typed- messages containing "stop" are never swallowed.- """+ """Typed bare stop phrase during an active voice chat ends the chat (mirrors the spoken+ one; outside voice mode "stop" passes through to the agent). Exact-match via+ ``is_voice_stop_phrase``, so longer messages containing "stop" are never swallowed."""from cli import _DIM, _RST, _cprintif not isinstance(user_input, str):return False@@ -612,10 +578,8 @@ class CLIVoiceMixin:self._voice_tts = Falseself._voice_continuous = False- # Release the TTS engine lease so a resident local model (piper/kittentts) is- # freed once nothing else in this process still needs it.+ # Release the TTS lease so a resident local model (piper/kittentts) can be freed.self._tts_lease_async(False)-# Shut down the persistent audio stream in backgroundif recorder is not None:def _bg_shutdown(rec=recorder):@@ -625,7 +589,6 @@ class CLIVoiceMixin:passthreading.Thread(target=_bg_shutdown, daemon=True).start()self._voice_recorder = None-# Stop any active TTS playback (file player + streaming pipeline)try:if self._voice_tts_stop is not None:@@ -636,7 +599,6 @@ class CLIVoiceMixin:except Exception:passself._voice_tts_done.set()-_cprint(f"\n{_DIM}Voice mode disabled.{_RST}")def _maybe_start_wake_word(self):@@ -731,9 +693,8 @@ class CLIVoiceMixin:returnself._wake_suspended = True- # Multi-profile routing: the CLI is a single-profile process, so a phrase enrolled- # by ANOTHER profile can't be routed here — print the switch command and re-arm- # rather than answering as the wrong profile.+ # The CLI is single-profile: a phrase enrolled by ANOTHER profile can't be routed+ # here — print the switch command and re-arm rather than answer as the wrong profile.try:from tools.wake_word import get_last_match_match = get_last_match()@@ -760,8 +721,7 @@ class CLIVoiceMixin:except Exception as e:logger.debug("wake word new_session failed: %s", e)- # Single-utterance capture (not continuous) via the voice pipeline; VAD auto-stop- # transcribes and queues the transcript for process_loop.+ # Single-utterance capture; VAD auto-stop transcribes and queues for process_loop.with self._voice_lock:self._voice_mode = Trueself._voice_continuous = False@@ -824,7 +784,6 @@ class CLIVoiceMixin:reqs = check_wake_word_requirements(cfg)owned = owns_listener(self)state = "LISTENING" if owned and is_listening() else "PAUSED" if owned else "OFF"-_cprint(f"\n{_BOLD}Wake Word Status{_RST}")_cprint(f" State: {state}")_cprint(f" Phrase: \"{reqs['phrase']}\"")@@ -843,10 +802,8 @@ class CLIVoiceMixin:def _tts_lease_async(self, active: bool) -> None:"""Acquire/release this CLI's TTS engine lease in the background.- The /voice tts toggle (and voice-mode on/off with speech output set) is the "TTS is- about to be needed / no longer needed" signal: acquiring pre-loads the configured- provider so the first reply starts hot; releasing lets the last-holder path unload- resident local models. Never blocks the toggle and never fails it.+ Acquiring pre-loads the configured provider so the first reply starts hot; releasing+ lets the last-holder path unload resident local models. Never blocks or fails the toggle."""from cli import logger@@ -872,15 +829,11 @@ class CLIVoiceMixin:with self._voice_lock:self._voice_tts = not self._voice_ttsstatus = "enabled" if self._voice_tts else "disabled"-if self._voice_tts:from tools.tts_tool import check_tts_requirementsif not check_tts_requirements():_cprint(f"{_DIM}Warning: No TTS provider available. Install edge-tts or set API keys.{_RST}")-- # Toggle = warm-up / release signal for the TTS engine (tools.tts_tool.acquire_tts_lease).- self._tts_lease_async(self._voice_tts)-+ self._tts_lease_async(self._voice_tts) # warm-up / release signal for the TTS engine_cprint(f"{_ACCENT}Voice TTS {status}.{_RST}")def _show_voice_status(self):@@ -889,7 +842,6 @@ class CLIVoiceMixin:from tools.voice_mode import check_voice_requirementsreqs = check_voice_requirements()-_cprint(f"\n{_BOLD}Voice Mode Status{_RST}")_cprint(f" Mode: {'ON' if self._voice_mode else 'OFF'}")_cprint(f" TTS: {'ON' if self._voice_tts else 'OFF'}")