Skip to content

The agent that grows with you

refactor(hermes_cli): try/except-pass -> contextlib.suppress in setup flows

Tekniuma6e3fe5f5b67
diff --git a/hermes_cli/main_platform_setup.py b/hermes_cli/main_platform_setup.py
index c4b214623b2..66312227f0b 100644
--- a/hermes_cli/main_platform_setup.py
+++ b/hermes_cli/main_platform_setup.py
@@ -7,6 +7,7 @@ imported lazily inside the functions that use them (call-time resolution keeps
``hermes_cli.main.<name>`` patches effective and avoids an import cycle).
"""
+import contextlib
import shutil
import subprocess
import sys
@@ -179,12 +180,10 @@ def cmd_whatsapp(args):
else:
print("πŸ“± Open WhatsApp on your phone, then scan:")
_say("", " Settings β†’ Linked Devices β†’ Link a Device", "─" * 50, "")
- try:
+ with contextlib.suppress(KeyboardInterrupt):
subprocess.run(
[find_node_executable("node") or "node", str(bridge_script), "--pair-only", "--session", str(session_dir)],
cwd=str(bridge_dir), env=with_hermes_node_path())
- except KeyboardInterrupt:
- pass
print()
if not (session_dir / "creds.json").exists():
diff --git a/hermes_cli/main_provider_setup.py b/hermes_cli/main_provider_setup.py
index c03f6f69112..a528d992e66 100644
--- a/hermes_cli/main_provider_setup.py
+++ b/hermes_cli/main_provider_setup.py
@@ -7,6 +7,7 @@ imported lazily inside the functions that use them (call-time resolution keeps
``hermes_cli.main.<name>`` patches effective and avoids an import cycle).
"""
+import contextlib
import subprocess
from typing import Optional
@@ -86,12 +87,11 @@ def _all_aux_tasks() -> list[tuple[str, str, str]]:
(:meth:`hermes_cli.plugins.PluginContext.register_auxiliary_task`)."""
from hermes_cli.main import _AUX_TASKS
tasks = list(_AUX_TASKS)
- try:
+ # Plugin discovery failure must not break the aux config UI.
+ with contextlib.suppress(Exception):
from hermes_cli.plugins import get_plugin_auxiliary_tasks
for entry in get_plugin_auxiliary_tasks():
tasks.append((entry["key"], entry["display_name"], entry["description"]))
- except Exception:
- pass # Plugin discovery failure must not break the aux config UI.
return tasks
@@ -359,14 +359,12 @@ def _ask_index(prompt: str, count: int, *, echo_cancel: bool):
def _prompt_provider_choice(choices, *, default=0, title="Select provider:"):
"""Provider menu with curses arrow keys; numbered-list fallback when curses is unavailable
(piped stdin, non-TTY). Returns the selected index, or None if the user cancels."""
- try:
+ with contextlib.suppress(Exception):
from hermes_cli.setup import _curses_prompt_choice
idx = _curses_prompt_choice(title, choices, default)
if idx >= 0:
print()
return idx
- except Exception:
- pass
_print_numbered(title, choices, default)
print()
diff --git a/hermes_cli/model_setup_flows.py b/hermes_cli/model_setup_flows.py
index 8acdfa6e068..fa95714a026 100644
--- a/hermes_cli/model_setup_flows.py
+++ b/hermes_cli/model_setup_flows.py
@@ -10,6 +10,7 @@ patch ``hermes_cli.config.load_config`` etc. at call time. The shared skeleton l
from __future__ import annotations
+import contextlib
import argparse
import os
@@ -296,10 +297,8 @@ def _model_flow_nous(config, current_model="", args=None):
def _login_then_offer_gateway(login_args, pconfig):
_login_nous(login_args, pconfig)
# Offer Tool Gateway enablement for paid subscribers
- try:
+ with contextlib.suppress(Exception):
prompt_enable_tool_gateway(load_config() or {})
- except Exception:
- pass
# login_nous already handles model selection + config update
_run_login(_login_then_offer_gateway, _nous_login_args(args), PROVIDER_REGISTRY["nous"])
@@ -331,12 +330,10 @@ def _model_flow_nous(config, current_model="", args=None):
# Portal URL is needed for upgrade links and the recommendations endpoints.
_nous_portal_url = ""
- try:
+ with contextlib.suppress(Exception):
_nous_state = get_provider_auth_state("nous")
if _nous_state:
_nous_portal_url = _nous_state.get("portal_base_url", "")
- except Exception:
- pass
catalog = _nous_model_catalog(free_tier, _nous_portal_url, model_ids, pricing)
if catalog is None:
@@ -376,18 +373,14 @@ def _model_flow_openai_codex(config, current_model=""):
# Prefer the credential pool (where `hermes auth` stores device_code tokens),
# fall back to legacy provider state.
_codex_token = None
- try:
+ with contextlib.suppress(Exception):
_codex_status = get_codex_auth_status()
if _codex_status.get("logged_in"):
_codex_token = _codex_status.get("api_key")
- except Exception:
- pass
if not _codex_token:
- try:
+ with contextlib.suppress(Exception):
from hermes_cli.auth import resolve_codex_runtime_credentials
_codex_token = resolve_codex_runtime_credentials().get("api_key")
- except Exception:
- pass
codex_models = get_codex_model_ids(access_token=_codex_token)
selected = _prompt_model_selection(
@@ -413,11 +406,9 @@ def _model_flow_xai_oauth(_config, current_model="", *, args=None):
# credentials may live only in the pool (``hermes auth add xai-oauth``) β€” fall back to
# the default base URL so the picker still completes.
base_url = DEFAULT_XAI_OAUTH_BASE_URL
- try:
+ with contextlib.suppress(Exception):
creds = resolve_xai_oauth_runtime_credentials()
base_url = (creds.get("base_url") or "").strip().rstrip("/") or base_url
- except Exception:
- pass
models = provider_model_ids("xai-oauth")
selected = _prompt_model_selection(models, current_model=current_model or (models[0] if models else "grok-4.6"))
@@ -443,11 +434,9 @@ def _model_flow_qwen_oauth(_config, current_model=""):
# Try live model discovery, fall back to curated list.
models = None
- try:
+ with contextlib.suppress(Exception):
creds = resolve_qwen_runtime_credentials(refresh_if_expiring=True)
models = fetch_api_models(creds["api_key"], creds["base_url"])
- except Exception:
- pass
if not models:
models = list(_DEFAULT_QWEN_PORTAL_MODELS)
@@ -543,14 +532,12 @@ def _copilot_obtain_token() -> bool:
print(" Cancelled.")
return False
# Validate token type
- try:
+ with contextlib.suppress(ImportError):
from hermes_cli.copilot_auth import validate_copilot_token
valid, msg = validate_copilot_token(new_key)
if not valid:
print(f" βœ— {msg}")
return False
- except ImportError:
- pass
save_env_value("COPILOT_GITHUB_TOKEN", new_key)
_say(" Token saved.", "")
return True
@@ -643,10 +630,8 @@ def _model_flow_copilot_acp(config, current_model=""):
effective_base = creds.get("base_url") or effective_base
catalog_api_key = ""
- try:
+ with contextlib.suppress(Exception):
catalog_api_key = resolve_api_key_provider_credentials("copilot").get("api_key", "")
- except Exception:
- pass
_catalog, catalog_ids, _normalize = _copilot_catalog(catalog_api_key)
selected = _pick_model_or_prompt(
_copilot_model_list(catalog_ids), "Model name: ", current_model=_normalize(current_model),
@@ -974,12 +959,10 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""):
# localhost when the user just presses Enter.
current_base = _env_base_url(base_url_env)
if not current_base:
- try:
+ with contextlib.suppress(Exception):
_m = load_config().get("model") or {}
if str(_m.get("provider") or "").strip().lower() == provider_id:
current_base = str(_m.get("base_url") or "").strip()
- except Exception:
- pass
effective_base = current_base or pconfig.inference_base_url
if provider_id == "zai":
@@ -1053,13 +1036,11 @@ def _model_flow_anthropic(config, current_model=""):
# Check ALL credential sources
existing_key = get_anthropic_key()
cc_available = False
- try:
+ with contextlib.suppress(Exception):
from agent.anthropic_adapter import read_claude_code_credentials, is_claude_code_token_valid, _is_oauth_token
cc_creds = read_claude_code_credentials()
if cc_creds and is_claude_code_token_valid(cc_creds):
cc_available = True
- except Exception:
- pass
# Stale-OAuth guard: an expired OAuth token with no valid cc_creds fallback is treated
# as missing so the re-auth path is offered.
diff --git a/hermes_cli/model_setup_flows_common.py b/hermes_cli/model_setup_flows_common.py
index 1152f33f3bf..93233ab7a4c 100644
--- a/hermes_cli/model_setup_flows_common.py
+++ b/hermes_cli/model_setup_flows_common.py
@@ -11,6 +11,8 @@ flows (import cycle) and tests patch ``hermes_cli.config.load_config`` etc. at c
from __future__ import annotations
+import contextlib
+
from hermes_cli.cli_output import line_input
from hermes_cli.config import clear_model_endpoint_credentials
@@ -195,11 +197,9 @@ def _models_dev_merged(provider_id: str, curated) -> list:
"""models.dev agentic models for *provider_id* plus curated ids not yet listed
(case-insensitive). Empty list when models.dev has nothing / is unavailable."""
mdev_models: list = []
- try:
+ with contextlib.suppress(Exception):
from agent.models_dev import list_agentic_models
mdev_models = list_agentic_models(provider_id)
- except Exception:
- pass
if not mdev_models:
return []
seen = {m.lower() for m in mdev_models}
diff --git a/hermes_cli/model_setup_flows_custom.py b/hermes_cli/model_setup_flows_custom.py
index 98fc979082c..bb68fa2e646 100644
--- a/hermes_cli/model_setup_flows_custom.py
+++ b/hermes_cli/model_setup_flows_custom.py
@@ -7,6 +7,7 @@ tests patch them at call time). Prompt strings and config write order are behavi
from __future__ import annotations
+import contextlib
import os
import subprocess
import urllib.parse
@@ -252,11 +253,9 @@ def _discover_named_custom_models(provider_info: dict, api_key: str, configured_
# (dashboard, desktop, ACP) show the full list; mirrors model_switch.py's
# _save_discovered_models_to_config. A failed save is non-fatal.
if live_models:
- try:
+ with contextlib.suppress(Exception):
from hermes_cli.model_switch import _save_discovered_models_to_config
_save_discovered_models_to_config(base_url, live_models, api_mode=api_mode, headers=extra_headers or None)
- except Exception:
- pass
return models, native_catalog_empty