The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): setup cluster — compact docstrings/comments, fold help-line loops into _info
Teknium2e555504bf98
diff --git a/hermes_cli/secrets_cli.py b/hermes_cli/secrets_cli.pyindex 7c1d58969b2..662593ae477 100644--- a/hermes_cli/secrets_cli.py+++ b/hermes_cli/secrets_cli.py@@ -15,14 +15,11 @@ from rich.console import Consolefrom rich.panel import Panelfrom rich.table import Table-# The Bitwarden backend (``agent.secret_sources.bitwarden``) pulls in ``cryptography`` at import-# time; on Windows the mapped ``cryptography._rust.pyd`` makes the ``hermes update`` self-lock-# preflight defer. This module is registered parse-time from ``hermes_cli.main``, so the backend-# import stays lazy and nothing touches ``bw`` until a handler runs.-#-# ``_BWS_VERSION`` is duplicated here (plain string) so ``register_cli`` can render the-# ``install --help`` text without importing the backend. ``agent.secret_sources.bitwarden._BWS_VERSION``-# is the source of truth; bump both together.+# The Bitwarden backend pulls in ``cryptography`` at import time; on Windows that mapped native+# module makes the ``hermes update`` self-lock preflight defer. This module is registered+# parse-time from ``hermes_cli.main``, so the backend import stays lazy (nothing touches ``bw``+# until a handler runs) and ``_BWS_VERSION`` is duplicated here for the ``install --help`` text.+# ``agent.secret_sources.bitwarden._BWS_VERSION`` is the source of truth; bump both together._BWS_VERSION = "2.0.0"from hermes_cli._secrets_common import (@@ -56,8 +53,8 @@ def _load_bw():def __getattr__(name: str):- """PEP 562 lazy ``bw`` attribute: callers and tests monkeypatch ``hermes_cli.secrets_cli.bw``- directly, and resolving it at import time would re-import ``cryptography`` eagerly."""+ """PEP 562 lazy ``bw`` attribute (tests monkeypatch ``secrets_cli.bw``); an eager binding+ would re-import ``cryptography`` at import time."""if name == "bw":return _load_bw()raise AttributeError(f"module {__name__!r} has no attribute {name!r}")@@ -526,12 +523,9 @@ _REGION_PRESETS = [def _resolve_server_url(args: argparse.Namespace, secrets_cfg: dict, console: Console,) -> Optional[str]:- """Pick a Bitwarden server URL for setup.-- Resolution order: ``--server-url`` flag, ``BWS_SERVER_URL`` env var (already set in the shell),- existing ``secrets.bitwarden.server_url`` (re-runs), then the interactive US / EU / self-hosted- menu. None (after printing) when a custom URL is left empty.- """+ """Pick a Bitwarden server URL: ``--server-url``, then ``BWS_SERVER_URL``, then the existing+ ``secrets.bitwarden.server_url``, then the interactive US / EU / self-hosted menu. None (after+ printing) when a custom URL is left empty."""if args.server_url and args.server_url.strip():return args.server_url.strip()diff --git a/hermes_cli/send_cmd.py b/hermes_cli/send_cmd.pyindex d7c202becd2..867f11e4d6a 100644--- a/hermes_cli/send_cmd.py+++ b/hermes_cli/send_cmd.py@@ -93,10 +93,8 @@ def _list_targets(platform_filter: Optional[str], *, json_mode: bool) -> int:platforms = dict(raw.get("platforms") or {})- # Merge in configured-but-undiscovered platforms so `--list` never hides a working send- # target: the directory only holds platforms the gateway has discovered channels for, so a- # platform configured via env/config.yaml that never ran discovery (e.g. a fresh SimpleX- # setup used only for outbound `hermes send`) would otherwise be invisible.+ # Merge in configured-but-undiscovered platforms (e.g. a fresh SimpleX setup used only for+ # outbound sends) so `--list` never hides a working send target.try:from gateway.config import load_gateway_config@@ -165,9 +163,8 @@ def _load_hermes_env() -> None:env_path = home / ".env"if load_dotenv and env_path.exists():try:- # utf-8-sig strips a leading UTF-8 BOM (PowerShell 5.1 Set-Content -Encoding UTF8 /- # Notepad) and is a no-op otherwise; plain "utf-8" would keep U+FEFF on the first key- # name and silently drop it from os.environ under its canonical name.+ # utf-8-sig strips a leading BOM (PowerShell 5.1 / Notepad); plain "utf-8" would keep+ # U+FEFF on the first key name and silently drop it from os.environ.load_dotenv(str(env_path), override=True, encoding="utf-8-sig")except UnicodeDecodeError:try:@@ -184,16 +181,14 @@ def _load_hermes_env() -> None:except Exception:pass- # Bridge top-level config.yaml scalars into the environment (never overriding values already- # in the env) so gateway.config.load_gateway_config() sees them.+ # Bridge top-level config.yaml scalars into the environment (never overriding existing values).import osconfig_path = home / "config.yaml"if not config_path.exists():returntry:- # Presence-sensitive env bridge: raw read is deliberate — only keys the user actually- # wrote get bridged. Overlay + expansion below.+ # Raw read is deliberate — only keys the user actually wrote get bridged.from hermes_cli.config import read_user_config_rawraw = read_user_config_raw(config_path)except Exception:@@ -205,8 +200,7 @@ def _load_hermes_env() -> None:except Exception:pass- # Managed scope: overlay administrator-pinned values before bridging to env, so a managed- # top-level scalar wins here too. Fail-open via the helper.+ # Managed scope: administrator-pinned values win here too (fail-open via the helper).try:from hermes_cli import managed_scoperaw = managed_scope.apply_managed_overlay(raw if isinstance(raw, dict) else {})@@ -223,9 +217,7 @@ def _load_hermes_env() -> None:def cmd_send(args: argparse.Namespace) -> None:"""Entry point wired into the top-level argparse dispatcher."""- # The gateway config loader (used downstream by send_message_tool and the channel directory)- # needs platform credentials and home channels in os.environ.- _load_hermes_env()+ _load_hermes_env() # the downstream gateway config loader reads credentials from os.environif getattr(args, "list_targets", False): # --list short-circuits everything else# `hermes send --list telegram` lands "telegram" in the `message` positional.@@ -259,9 +251,8 @@ def cmd_send(args: argparse.Namespace) -> None:# Lazy import keeps `hermes send --help` fast (no tool registry / gateway config stack).from tools.send_message_tool import send_message_tool- # send_message_tool auto-loads gateway config + env and routes to the platform adapter- # (bot-token path for Telegram/Discord/Slack/Signal/SMS/WhatsApp; live-adapter path for- # plugin platforms). It takes the standard tool-call dict and returns a JSON string.+ # Routes to the platform adapter (bot-token path for built-ins, live-adapter path for plugin+ # platforms); takes the standard tool-call dict and returns a JSON string.result = send_message_tool({"action": "send", "target": target, "message": message})sys.exit(_emit_result(result, json_mode=getattr(args, "json", False), quiet=getattr(args, "quiet", False)))diff --git a/hermes_cli/setup.py b/hermes_cli/setup.pyindex 61a022320fe..bc9b135f930 100644--- a/hermes_cli/setup.py+++ b/hermes_cli/setup.py@@ -138,29 +138,22 @@ class _SetupNavigationState:"""Per-invocation navigation state for the synchronous setup wizard."""def __init__(self, *, section_index: int = -1, prompt_index: int = 0):- self.section_index = section_index+ self.reset(section_index)self.prompt_index = prompt_index- self.active_prompt_index = -1- self.resolved_choices: list[object] = []- self.replay_choices: list[object] = []def reset(self, section_index: int = -1, replay: list | None = None) -> None:"""Rewind per-section counters (entering a section, or leaving the wizard)."""self.section_index = section_indexself.prompt_index = 0self.active_prompt_index = -1- self.resolved_choices = []- self.replay_choices = copy.deepcopy(replay or [])+ self.resolved_choices: list[object] = []+ self.replay_choices: list[object] = copy.deepcopy(replay or [])-_SETUP_NAVIGATION: ContextVar[_SetupNavigationState | None] = ContextVar(- "hermes_setup_navigation", default=None-)+_SETUP_NAVIGATION: ContextVar[_SetupNavigationState | None] = ContextVar("hermes_setup_navigation", default=None)-def _handle_setup_menu_navigation(- event: MenuNavigationEvent, value: object = None-) -> MenuNavigationStart | None:+def _handle_setup_menu_navigation(event: MenuNavigationEvent, value: object = None) -> MenuNavigationStart | None:"""Translate shared curses menu events into setup control flow."""state = _SETUP_NAVIGATION.get()if state is None:@@ -177,14 +170,8 @@ def _handle_setup_menu_navigation(return MenuNavigationStart(allow_back=allow_back)if event is MenuNavigationEvent.RESOLVE:prompt_index = state.active_prompt_index- if prompt_index < 0:- return None- resolved = copy.deepcopy(value)- if prompt_index < len(state.resolved_choices):- state.resolved_choices[prompt_index] = resolved- del state.resolved_choices[prompt_index + 1 :]- else:- state.resolved_choices.append(resolved)+ if prompt_index >= 0: # replace this answer and drop every later one+ state.resolved_choices[prompt_index:] = [copy.deepcopy(value)]return Noneif event is MenuNavigationEvent.CANCEL:raise _SetupCancelled()@@ -207,11 +194,9 @@ def _setup_navigation_scope():def _run_setup_steps(steps: list[tuple[str, Callable[[], None]]]) -> None:- """Run setup sections with left-arrow navigation between choices.-- Left arrow at a section's first choice returns to the previous section; from a later, nested- choice it replays earlier selections invisibly and reopens only the preceding prompt.- """+ """Run setup sections with left-arrow navigation: at a section's first choice it returns to+ the previous section; from a later choice it replays earlier selections invisibly and reopens+ only the preceding prompt."""state = _SETUP_NAVIGATION.get()section_index = 0answers_by_section: dict[int, list[object]] = {}@@ -256,11 +241,8 @@ def _run_setup_steps(steps: list[tuple[str, Callable[[], None]]]) -> None:def run_setup_action_with_navigation(label: str, action: Callable[[], None], *, cancelled_message: str = "Setup cancelled.") -> None:- """Run a setup-style menu flow with Escape and nested Left navigation.-- Shared commands such as ``hermes model`` use the wizard's pickers outside ``run_setup_wizard``;- this installs the navigation context for them and reuses the prompt replay state machine.- """+ """Run a setup-style menu flow with Escape and nested Left navigation — for commands such as+ ``hermes model`` that use the wizard's pickers outside ``run_setup_wizard``."""with _setup_navigation_scope():try:_run_setup_steps([(label, action)])@@ -278,12 +260,9 @@ def _curses_prompt_choice(question: str, choices: list, default: int = 0, descridef prompt_choice(question: str, choices: list, default: int = 0, description: str | None = None) -> int:- """Prompt for a choice from a list with arrow key navigation.-- Escape cancels an active setup wizard; outside setup it keeps the default. The curses- component owns its own numbered fallback, so a cancel result must never be mistaken for a- request to open another prompt. Ctrl+C exits the wizard.- """+ """Prompt for a choice from a list with arrow key navigation. Escape cancels an active setup+ wizard; outside setup it keeps the default (the curses component owns its own numbered+ fallback, so a cancel result must never open another prompt). Ctrl+C exits the wizard."""idx = _curses_prompt_choice(question, choices, default, description=description)if idx < 0:return default@@ -295,22 +274,15 @@ def prompt_choice(question: str, choices: list, default: int = 0, description: sdef is_noninteractive() -> bool:- """True when no human is available to answer a prompt.-- The dashboard/desktop spawn CLI actions with ``stdin=DEVNULL`` and ``HERMES_NONINTERACTIVE=1``- (see ``hermes_cli/web_server.py``); there ``input()`` raises ``EOFError`` immediately, and a- prompt that aborts on EOF would kill the spawned action. Honour the flag so callers fall back- to their default.- """+ """True when no human is available to answer a prompt: the dashboard/desktop spawn CLI actions+ with ``stdin=DEVNULL`` and ``HERMES_NONINTERACTIVE=1`` (``hermes_cli/web_server.py``), where a+ prompt that aborts on EOF would kill the spawned action — callers fall back to their default."""return os.environ.get("HERMES_NONINTERACTIVE", "").strip().lower() in {"1", "true", "yes", "on"}def prompt_yes_no(question: str, default: bool = True) -> bool:- """Prompt for yes/no. Ctrl+C exits, empty input returns default.-- Non-interactive callers (``HERMES_NONINTERACTIVE=1`` or a closed/redirected stdin) have no- one to answer, so fall back to ``default`` instead of aborting the whole process.- """+ """Prompt for yes/no. Ctrl+C exits; empty input, ``HERMES_NONINTERACTIVE=1`` or a+ closed/redirected stdin return ``default`` instead of aborting the whole process."""if is_noninteractive():return default# Inside setup, route binary selections through the curses menu so ESC and left-arrow work@@ -340,11 +312,8 @@ def prompt_yes_no(question: str, default: bool = True) -> bool:def prompt_checklist(title: str, items: list, pre_selected: list = None) -> list:- """Multi-select checklist; returns the sorted indices of selected items.-- ``pre_selected`` indices start checked; Space toggles, Enter on the appended "Continue →"- confirms, cancel keeps the pre-selection. Numbered fallback when curses is unavailable.- """+ """Multi-select checklist; returns the sorted indices of selected items. ``pre_selected``+ start checked; Space toggles, Enter confirms, cancel keeps the pre-selection."""from hermes_cli.curses_ui import curses_checklistpre = set(pre_selected or [])return sorted(curses_checklist(title, items, pre, cancel_returns=pre))@@ -398,12 +367,9 @@ def _print_banner(*lines: str) -> None:def setup_model_provider(config: dict, *, quick: bool = False):- """Configure the inference provider and default model.-- Delegates to the ``hermes model`` flow (provider picker, credential prompting, model pick,- persistence) so there is one code path — any provider added there is available here.- *quick* skips credential rotation, vision and TTS (first-time quick setup).- """+ """Configure the inference provider and default model via the ``hermes model`` flow (one code+ path — any provider added there is available here). *quick* is accepted for the first-time+ quick setup caller; rotation, vision and TTS keep safe defaults either way."""from hermes_cli.config import load_config, save_configprint_header("Inference Provider")_info("Choose how to connect to your main chat model.",@@ -465,8 +431,7 @@ def _prompt_int_setting(section: dict, key: str, label: str, current, accept) ->_TOOL_PROGRESS_HELP = (- "Tool Progress Display",- "Controls how much tool activity is shown (CLI and messaging).",+ "Tool Progress Display", "Controls how much tool activity is shown (CLI and messaging)."," off — Silent, just the final response"," new — Show tool name only when it changes (less noise)"," all — Show every tool call with a short preview",@@ -475,14 +440,11 @@ _TOOL_PROGRESS_HELP = ()_SESSION_RESET_HELP = ("Messaging sessions (Telegram, Discord, etc.) accumulate context over time.",- "Each message adds to the conversation history, which means growing API costs.",- "",+ "Each message adds to the conversation history, which means growing API costs.", "","To manage this, sessions can automatically reset after a period of inactivity","or at a fixed time each day. When a reset happens, the agent saves important",- "things to its persistent memory first — but the conversation context is cleared.",- "",- "You can also manually reset anytime by typing /reset in chat.",- "",+ "things to its persistent memory first — but the conversation context is cleared.", "",+ "You can also manually reset anytime by typing /reset in chat.", "",)_SESSION_RESET_CHOICES = ["Inactivity + daily reset (reset whichever comes first)",@@ -517,9 +479,7 @@ def setup_agent_settings(config: dict):print_success(f"Max iterations set to {max_iter}")# ── Tool Progress Display ──- print_info("")- for line in _TOOL_PROGRESS_HELP:- print_info(line)+ _info("", *_TOOL_PROGRESS_HELP)current_mode = cfg_get(config, "display", "tool_progress", default="all")mode = prompt("Tool progress mode", current_mode)@@ -544,8 +504,7 @@ def setup_agent_settings(config: dict):# ── Session Reset Policy ──print_header("Session Reset Policy")- for line in _SESSION_RESET_HELP:- print_info(line)+ _info(*_SESSION_RESET_HELP)current_policy = config.get("session_reset", {})current_mode = current_policy.get("mode", "none")@@ -591,16 +550,14 @@ def setup_tools(config: dict, first_install: bool = False):_SEND_CONSENT_EXPLAINER = (- "",- "Sending uploads each daily package to the Nous telemetry",+ "", "Sending uploads each daily package to the Nous telemetry","service. Packages carry your profile-scoped install ID, a","stable random UUID that identifies this profile across days","(it contains no personal information and is reset by deleting","the shared-metrics directory). Only packages whose entire","collection period falls inside a recorded consent window are","ever sent — data from before you opt in, or from any gap",- "while sending was off, stays on this machine. Sending can be",- "turned off again at any time.",+ "while sending was off, stays on this machine. Sending can be", "turned off again at any time.",)@@ -625,8 +582,7 @@ def setup_telemetry(config: dict):returnprint_success("Local shared metrics enabled.")- for line in _SEND_CONSENT_EXPLAINER:- print_info(line)+ _info(*_SEND_CONSENT_EXPLAINER)shared_metrics["send"] = prompt_yes_no("Send shared metrics to Nous?", default=shared_metrics.get("send") is True)_record_send_consent_change(enabled=shared_metrics["send"])if shared_metrics["send"]:@@ -811,15 +767,12 @@ def _run_setup_wizard_impl(args):# Existing installation == a provider is configuredfrom hermes_cli.auth import get_active_provider- is_existing = bool(- get_env_value("OPENROUTER_API_KEY") or get_env_value("OPENAI_BASE_URL") or get_active_provider() is not None- )- _print_banner(- "│ ⚕ Hermes Agent Setup Wizard │",- "├─────────────────────────────────────────────────────────┤",- "│ Let's configure your Hermes Agent installation. │",- "│ Press Ctrl+C at any time to exit. │",- )+ is_existing = bool(get_env_value("OPENROUTER_API_KEY") or get_env_value("OPENAI_BASE_URL")+ or get_active_provider() is not None)+ _print_banner("│ ⚕ Hermes Agent Setup Wizard │",+ "├─────────────────────────────────────────────────────────┤",+ "│ Let's configure your Hermes Agent installation. │",+ "│ Press Ctrl+C at any time to exit. │")migration_ran = Falseif is_existing:diff --git a/hermes_cli/setup_quick.py b/hermes_cli/setup_quick.pyindex 946a0ecd3a8..b9ddc0002ee 100644--- a/hermes_cli/setup_quick.py+++ b/hermes_cli/setup_quick.py@@ -47,9 +47,7 @@ def _run_nous_flow(config: dict, *, context: str, cancel_exc: tuple, cancel_linedef _run_portal_one_shot(config: dict) -> None:- """One-shot Nous Portal setup (``hermes setup --portal`` / ``hermes portal``); the login,- model pick and Tool Gateway opt-in are delegated to ``_model_flow_nous`` so ``hermes portal``- always offers a picker."""+ """One-shot Nous Portal setup (``hermes setup --portal`` / ``hermes portal``)."""from hermes_cli.setup import _info, _print_banner, print_error, print_info, print_success_print_banner("│ ⚕ Hermes Setup — Nous Portal (one-shot) │")_info(None, " One subscription, 300+ models, plus the Tool Gateway:",@@ -79,8 +77,8 @@ def _run_portal_one_shot(config: dict) -> None:def _run_first_time_quick_setup(config: dict, hermes_home, is_existing: bool):- """Streamlined first-time setup via Nous Portal: OAuth, model, terminal & messaging.- Everything else gets sensible defaults (``hermes setup <section>`` / ``hermes model`` later)."""+ """Streamlined first-time setup via Nous Portal: OAuth, model, terminal & messaging;+ everything else gets defaults."""from hermes_cli.setup import (_apply_default_agent_settings, _info, print_header, print_info, _print_macos_fda_tip,_print_setup_summary, print_success, print_warning, prompt_choice, save_config, setup_gateway,@@ -134,10 +132,9 @@ def _run_first_time_quick_setup(config: dict, hermes_home, is_existing: bool):def _print_macos_fda_tip() -> None:- """One-time macOS onboarding tip: a single Full Disk Access grant kills every per-folder- permission prompt. Same prompt-free probe as doctor's check_macos_full_disk_access (the TCC- db dir is FDA-gated but probing it never triggers a dialog). Silent on non-macOS and when FDA- is already granted or indeterminate."""+ """One-time macOS tip: one Full Disk Access grant kills every per-folder prompt. Same+ prompt-free probe as doctor's check_macos_full_disk_access (the FDA-gated TCC dir never+ triggers a dialog); silent on non-macOS and when FDA is granted or indeterminate."""from hermes_cli.setup import _infoif sys.platform != "darwin":return@@ -156,16 +153,11 @@ def _print_macos_fda_tip() -> None:def _blank_slate_minimal_toolsets(config: dict):- """Write the minimal toolset state for a Blank Slate install.-- Only ``file``, ``terminal``, ``vision`` and ``skills`` stay on: ``read_file`` can't read images- (it points at ``vision_analyze``), and the always-seeded ``hermes-agent`` skill needs- ``skill_view``. Two layers enforce the selection: ``platform_toolsets["cli"]`` (an explicit- list the resolver treats as authoritative, so defaults aren't re-expanded) and- ``agent.disabled_toolsets`` (global hard-suppression applied last in ``_get_platform_tools``,- overriding even the platform-toolset recovery that would re-add e.g. ``kanban``). Users- re-enable via ``hermes tools`` or by editing ``agent.disabled_toolsets``.- """+ """Write the minimal toolset state for a Blank Slate install: only ``file``, ``terminal``,+ ``vision`` (``read_file`` can't read images) and ``skills`` (the seeded ``hermes-agent`` skill+ needs ``skill_view``) stay on. Two layers enforce it: ``platform_toolsets["cli"]`` (explicit,+ so defaults aren't re-expanded) and ``agent.disabled_toolsets`` (hard-suppression applied last+ in ``_get_platform_tools``, overriding the recovery that would re-add e.g. ``kanban``)."""keep = {"file", "terminal", "vision", "skills"}config.setdefault("platform_toolsets", {})["cli"] = sorted(keep)@@ -191,9 +183,7 @@ def _blank_slate_minimal_toolsets(config: dict):def _blank_slate_minimize_config(config: dict):- """Turn OFF the optional config features (compression, memory/profile capture, checkpoints,- smart routing, auto session reset; quiet display). All opt-in afterwards via- ``hermes setup agent`` / ``hermes config set``."""+ """Turn OFF every optional config feature; all opt back in via ``hermes setup agent``."""config.setdefault("agent", {})["max_turns"] = 90config.setdefault("compression", {})["enabled"] = Falsemem = config.setdefault("memory", {})@@ -221,9 +211,8 @@ def _set_bundled_skills_opt_out(opt_out: bool, log_label: str, on_success=None,def _run_blank_slate_setup(config: dict, hermes_home, is_existing: bool):- """Blank Slate setup — essentials only (provider/model, file + terminal), everything else OFF;- then either finish now or walk through opting capabilities back in. Nothing is enabled that- the user did not explicitly choose."""+ """Blank Slate setup — essentials only, everything else OFF; then finish now or walk through+ opting capabilities back in. Nothing is enabled that the user did not explicitly choose."""from hermes_cli.setup import (_blank_slate_minimal_toolsets, _blank_slate_minimize_config, _blank_slate_walkthrough, _info,print_header, print_info, _print_setup_summary, print_success, prompt_choice, save_config,