The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(cli): health clean for the classic CLI gateway seams; behaviour unchanged
Teknium602cad14246a
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.pyindex c4203a86095..17e5e66cc3e 100644--- a/hermes_cli/cli_agent_setup_mixin.py+++ b/hermes_cli/cli_agent_setup_mixin.py@@ -649,7 +649,7 @@ class CLIAgentSetupMixin:logger.warning("SQLite session store not available — session will NOT be indexed: %s", e)try:self._ensure_gateway_session()- except Exception as e:+ except Exception as e: # health: allow BLE001 -- any session.create/resume failure is main's agent-init failure copy, never a tracebackChatConsole().print(f"[bold red]{_escape(agent_init_failure_message(e))}[/]")return Falseif (diff --git a/hermes_cli/cli_info_mixin.py b/hermes_cli/cli_info_mixin.pyindex 064a315ed49..fe59157450d 100644--- a/hermes_cli/cli_info_mixin.py+++ b/hermes_cli/cli_info_mixin.py@@ -96,6 +96,25 @@ class CLIInfoMixin:"""Informational views and reload flows for the interactive CLI: banner, help, tools, usage,insights, MCP/skills reload, bang shell."""+ def _show_gateway_banner(self, build_welcome_banner, inventory, banner_kw, cwd, ctx_len):+ """Main's banner from the gateway session's snapshot (the TUI banner's data): the CLI+ enumerates nothing. The canonical id shows as main's 8-character label (display only)."""+ from hermes_cli.gateway_session_store import session_label+ self._defer_tool_warnings = True+ build_welcome_banner(+ tools=inventory["tools"], get_toolset_for_tool=inventory["get_toolset_for_tool"],+ availability=inventory["availability"], skills_by_category=inventory["skills_by_category"],+ **{**banner_kw, "cwd": inventory["cwd"] or cwd, "context_length": inventory["context_length"] or ctx_len,+ "session_id": session_label(self.session_id)})++ def _print_gateway_tool_warnings(self, lines):+ """Main's ``_show_tool_availability_warnings`` lines, computed by the gateway that resolved+ this session's tools."""+ if lines:+ self._console_print()+ for line in lines:+ self._console_print(line)+def show_banner(self):"""Display the welcome banner in Claude Code style."""from cli import _build_compact_banner, get_tool_definitions, logger@@ -130,16 +149,7 @@ class CLIInfoMixin:context_length=ctx_len, provider=self.provider, context_pinned=ctx_pinned)if gateway_inventory is not None:- from hermes_cli.gateway_session_store import session_label- # The gateway session's snapshot (the TUI banner's data): the CLI enumerates nothing.- self._defer_tool_warnings = True- build_welcome_banner(- tools=gateway_inventory["tools"], get_toolset_for_tool=gateway_inventory["get_toolset_for_tool"],- availability=gateway_inventory["availability"],- skills_by_category=gateway_inventory["skills_by_category"],- **{**banner_kw, "cwd": gateway_inventory["cwd"] or cwd,- "context_length": gateway_inventory["context_length"] or ctx_len,- "session_id": session_label(self.session_id)})+ self._show_gateway_banner(build_welcome_banner, gateway_inventory, banner_kw, cwd, ctx_len)elif snapshot is not None:self._defer_tool_warnings = Truetoolset_map = snapshot["toolset_map"]@@ -181,13 +191,8 @@ class CLIInfoMixin:# Tool discovery is deferred on the Termux bare prompt path (warnings show once tools# init). On the snapshot fast path the check walks every check_fn (~180ms) — run it in# the background and let its output land above the prompt (patch_stdout-safe).- gateway_lines = (gateway_inventory or {}).get("tool_availability_warnings")- if isinstance(gateway_lines, list):- # The gateway resolved this session's tools: print main's warning lines from its snapshot.- if gateway_lines:- self._console_print()- for line in gateway_lines:- self._console_print(line)+ if isinstance((gateway_inventory or {}).get("tool_availability_warnings"), list):+ self._print_gateway_tool_warnings(gateway_inventory["tool_availability_warnings"])elif os.environ.get("HERMES_DEFER_AGENT_STARTUP") != "1":if getattr(self, "_defer_tool_warnings", False):threading.Thread(diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.pyindex dc43a516e96..fb15a88d666 100644--- a/hermes_cli/gateway_agent.py+++ b/hermes_cli/gateway_agent.py@@ -263,7 +263,7 @@ class GatewayAgent:try:self.connection.call("session.interrupt", session_id=self.session_id,execution_generation=generation, timeout=5)- except Exception as exc: # the settle wait below bounds a lost interrupt+ except Exception as exc: # health: allow BLE001 -- the settle wait below bounds a lost interruptlogger.debug("session.interrupt failed: %s", exc)def hard_interrupt(self, message=None, tool_reason=None):diff --git a/hermes_cli/gateway_connection.py b/hermes_cli/gateway_connection.pyindex 94abe248c95..7ccc2450ac8 100644--- a/hermes_cli/gateway_connection.py+++ b/hermes_cli/gateway_connection.py@@ -116,7 +116,7 @@ class GatewayConnection:def _run(self):try:asyncio.run(self._main())- except BaseException as exc: # reported to the waiting caller+ except BaseException as exc: # health: allow BLE001 -- the loop thread reports every failure to the waiting callerif self._error is None:self._error = exc if isinstance(exc, GatewayClientError) else GatewayClientError("Gateway connection failed; no local fallback")@@ -140,7 +140,7 @@ class GatewayConnection:await asyncio.wait({pump, stop}, return_when=asyncio.FIRST_COMPLETED)pump.cancel()stop.cancel()- except Exception as exc:+ except Exception as exc: # health: allow BLE001 -- a transport failure becomes the connect error or the disconnect frameif not self._ready.is_set():self._error = exc if isinstance(exc, GatewayClientError) else GatewayClientError(f"Gateway connection failed; no local fallback ({type(exc).__name__})")diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.pyindex ba32a0a81c1..f99bcbf0ac2 100644--- a/hermes_cli/gateway_session_store.py+++ b/hermes_cli/gateway_session_store.py@@ -78,7 +78,7 @@ class GatewaySessionStore:try:from hermes_state import SessionDBself._reader = SessionDB(db_path=path, read_only=True)- except Exception as exc: # reads find nothing; retried on the next read+ except Exception as exc: # health: allow BLE001 -- reads find nothing; retried on the next readlogger.debug("read-only state.db unavailable: %s", exc)return self._reader@@ -178,7 +178,7 @@ class GatewaySessionStore:" AND NOT EXISTS (SELECT 1 FROM messages WHERE messages.session_id = sessions.id)"" AND NOT EXISTS (SELECT 1 FROM sessions child WHERE child.parent_session_id = sessions.id)",(session_id,)).fetchone()- except Exception as exc:+ except Exception as exc: # health: allow BLE001 -- a failed probe keeps the row (never deletes on doubt)logger.debug("empty-session probe failed: %s", exc)return Falseif not empty:diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 9f782cb0dc2..cba9bf702d1 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -904,6 +904,7 @@ from hermes_cli.main_web_build import ( # frozen updater surface: update_cmd*.p_run_npm_install_deterministic,)from hermes_cli.main_tui_launch import (+ _bypass_chat_launch,_launch_tui,_pin_kanban_board_env,_refuse_unforwarded_tui_flags,@@ -1707,9 +1708,8 @@ _CHAT_PASSTHROUGH = (def cmd_chat(args):"""Run interactive chat CLI."""from hermes_cli.stream_json import stream_json_requested- # Structured stdout (stream-json) and the --safe-mode / --ignore-user-config bypass keep the- # gateway transport client; the classic CLI (interactive and -q/-Q) is main's HermesCLI, whose- # agent is a gateway-backed proxy (hermes_cli/gateway_agent.py).+ # stream-json and the --safe-mode / --ignore-user-config bypass keep the transport client; the+ # classic CLI (interactive, -q/-Q) is main's HermesCLI with a gateway-backed agent (gateway_agent.py).if stream_json_requested(args) or _bypass_chat_launch(args):from hermes_cli.gateway_chat_startup import launch_gateway_chatsys.exit(launch_gateway_chat(args))@@ -2891,14 +2891,6 @@ def _is_tui_chat_launch(args) -> bool:return _resolve_use_tui(args)-def _bypass_chat_launch(args) -> bool:- """--safe-mode / --ignore-user-config chat: the gateway owner freezes code defaults and runs- the turn out of process, so the profile's display.interface must not pick a surface and the- client performs no discovery. Explicit --tui forwards the flags in its session.create policy."""- return bool(getattr(args, "safe_mode", False) or getattr(args, "ignore_user_config", False)) \- and not getattr(args, "tui", False)--def _agent_subcommand_selected(args) -> bool:"""True for ``cron run/tick``, ``gateway run``, ``mcp serve`` (see _AGENT_SUBCOMMANDS)."""_sub_attr, _sub_set = _AGENT_SUBCOMMANDS.get(args.command, (None, None))diff --git a/hermes_cli/main_tui_launch.py b/hermes_cli/main_tui_launch.pyindex 657b1a70b6e..a1e2a1e8108 100644--- a/hermes_cli/main_tui_launch.py+++ b/hermes_cli/main_tui_launch.py@@ -20,6 +20,14 @@ from agent.i18n import tlogger = logging.getLogger("hermes_cli.main")+def _bypass_chat_launch(args) -> bool:+ """--safe-mode / --ignore-user-config chat: the gateway owner freezes code defaults and runs+ the turn out of process, so the profile's display.interface must not pick a surface and the+ client performs no discovery. Explicit --tui forwards the flags in its session.create policy."""+ return bool(getattr(args, "safe_mode", False) or getattr(args, "ignore_user_config", False)) \+ and not getattr(args, "tui", False)++def _read_tui_active_session_file(path: Optional[str]) -> Optional[str]:if not path:return Nonediff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.pyindex 8c2047d86dc..18b0f289233 100644--- a/tests/hermes_cli/test_gateway_agent.py+++ b/tests/hermes_cli/test_gateway_agent.py@@ -49,7 +49,7 @@ class FakeClient:await self.events.put(GatewayClientError("Gateway disconnected"))returnif item == "wait":- await asyncio.sleep(0.3)+ await asyncio.sleep(0.3) # health: allow HX013 -- a slow stream frame gap IS the scripted behaviourcontinueawait self.events.put(item)@@ -147,8 +147,8 @@ def test_interrupt_sends_session_interrupt_and_settles_interrupted(make_agent):out = {}worker = threading.Thread(target=lambda: out.update(agent.run_conversation("story")))worker.start()- import time- time.sleep(0.4)+ from tests.waiting import wait_until+ wait_until(lambda: agent._generation is not None and agent._admission, timeout=5)agent.interrupt("stop")worker.join(5)assert not worker.is_alive()diff --git a/tests/hermes_cli/test_gateway_session_store.py b/tests/hermes_cli/test_gateway_session_store.pyindex 8ed657d72cb..65b604f30fa 100644--- a/tests/hermes_cli/test_gateway_session_store.py+++ b/tests/hermes_cli/test_gateway_session_store.py@@ -156,6 +156,7 @@ def test_cli_startup_notices_render_from_the_snapshot(store, monkeypatch):banner = SimpleNamespace(**vars(host), console=SimpleNamespace(clear=lambda: None), compact=True,session_id="local-old", _show_status=lambda: None, agent=None,_show_tool_availability_warnings=lambda: printed.append("LOCAL-WARN"))+ banner._print_gateway_tool_warnings = lambda lines: CLIInfoMixin._print_gateway_tool_warnings(banner, lines)printed.clear()CLIInfoMixin.show_banner(banner)assert "[yellow]⚠ terminal off[/]" in printed and "LOCAL-WARN" not in printed