Skip to content

The agent that grows with you

refactor(hermes_cli): model_switch_providers _entry_credentials; docstring compaction

Teknium3154403db377
diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.py
index 189994c2532..feecdeccb73 100644
--- a/hermes_cli/model_switch.py
+++ b/hermes_cli/model_switch.py
@@ -1,11 +1,8 @@
"""Shared model-switching logic for the CLI and gateway /model commands.
Pipeline: parse flags -> alias resolution -> provider resolution -> credential resolution ->
-normalize model name -> metadata lookup -> build result. Built on ``agent.models_dev``
-(catalog), ``hermes_cli.providers`` (identity + overlays) and ``hermes_cli.model_normalize``.
-
-Provider switching uses ``--provider`` exclusively; colons are reserved for OpenRouter variant
-suffixes (``:free``, ``:extended``, ``:fast``).
+normalize model name -> metadata lookup -> build result. Provider switching uses ``--provider``
+exclusively; colons are reserved for OpenRouter variant suffixes (``:free``, ``:extended``).
"""
from __future__ import annotations
@@ -212,12 +209,9 @@ def _load_direct_aliases() -> dict[str, DirectAlias]:
``model_aliases:`` entries are dicts (``model``, ``provider``, ``base_url``, optional
``api_key`` — literal or ``"${VAR}"`` — / ``key_env``); with neither credential field the key
- is resolved from the alias HOST, never from the previously active provider.
-
- ``model.aliases`` (``hermes config set model.aliases.xxx`` or hand-written) never overrides
- ``model_aliases``. String entries (``ds-flash: deepseek/deepseek-v4-flash``) take the provider
- from the ``provider/`` prefix, else the current provider; dict entries use the
- ``model_aliases`` shape.
+ is resolved from the alias HOST, never from the previously active provider. ``model.aliases``
+ never overrides ``model_aliases``; its string entries (``ds-flash: deepseek/deepseek-v4-flash``)
+ take the provider from the ``provider/`` prefix, else the current provider.
"""
merged = dict(_BUILTIN_DIRECT_ALIASES)
try:
@@ -372,11 +366,10 @@ def resolve_startup_model_route(
``HermesCLI`` is constructed before the interactive ``/model`` pipeline runs; resolving here
keeps startup from attaching the configured default provider to an explicitly requested
- model. ``provider/model`` strings are consumed only for providers present in user config;
- aggregator namespaces stay untouched. When ``current_provider`` is a routing aggregator and
- the raw string is an aggregator-native slug (``anthropic/claude-opus-4.6`` on OpenRouter),
- the input stays on the aggregator — a ``providers:`` block for the same vendor must not
- steal the route.
+ model. ``provider/model`` strings are consumed only for providers present in user config. When
+ ``current_provider`` is a routing aggregator and the raw string is an aggregator-native slug
+ (``anthropic/claude-opus-4.6`` on OpenRouter) the input stays on the aggregator — a
+ ``providers:`` block for the same vendor must not steal the route.
"""
raw = _clean(raw_model)
if not raw:
@@ -597,9 +590,8 @@ def parse_model_switch_args(raw: str) -> ModelSwitchRequest:
scope = next((name for name, on in (("once", parsed.is_once), ("session", parsed.is_session),
("global", parsed.is_global)) if on), "default")
return ModelSwitchRequest(
- raw=raw, target=parsed.model_input, explicit_provider=parsed.explicit_provider,
- is_global=parsed.is_global, is_session=parsed.is_session, is_once=parsed.is_once,
- force_refresh=parsed.force_refresh, scope=scope, errors=tuple(errors))
+ raw=raw, target=parsed.model_input, scope=scope, errors=tuple(errors),
+ **{f: getattr(parsed, f) for f in ("explicit_provider", "is_global", "is_session", "is_once", "force_refresh")})
def _effective_model_candidate(value: Any) -> str:
@@ -1014,15 +1006,13 @@ def _apply_direct_alias_endpoint(
) -> tuple[str, str, dict | None, bool]:
"""Route a direct alias to its own base_url and decide its credential.
- Returns ``(api_key, base_url, validation_headers_override, suppress_ollama_headers)`` where a
- ``None`` headers override means "leave as is".
-
- Credentials were resolved against the DEFAULT provider; carrying that key onto the alias's
- endpoint both 401s and ships the default provider's secret to an unrelated host. The alias's
- own endpoint decides: its declared key when it has one; the session key only when the alias
- points at the SAME ORIGIN; otherwise a fresh resolution against the alias base_url (whose
- env-key fallbacks are gated on authoritative hosts, so OLLAMA_API_KEY still resolves for
- ollama.com while OPENROUTER_API_KEY never reaches an unrelated host).
+ Returns ``(api_key, base_url, validation_headers_override, suppress_ollama_headers)``; a
+ ``None`` headers override means "leave as is". Credentials were resolved against the DEFAULT
+ provider; carrying that key onto the alias endpoint both 401s and ships the default provider's
+ secret to an unrelated host. The alias's own endpoint decides: its declared key; else the
+ session key only for the SAME ORIGIN; else a fresh resolution against the alias base_url
+ (env-key fallbacks are host-gated: OLLAMA_API_KEY resolves for ollama.com, OPENROUTER_API_KEY
+ never reaches an unrelated host).
"""
from hermes_cli.models import _same_ollama_native_root
from hermes_cli.runtime_provider import resolve_runtime_provider
@@ -1507,11 +1497,10 @@ def switch_model(
user_providers: dict = None, custom_providers: list | None = None) -> ModelSwitchResult:
"""Core model-switching pipeline shared between CLI and gateway.
- Route (:func:`_route_explicit_provider` when ``--provider`` was given, else
- :func:`_route_from_model_input`) -> :func:`_resolve_switch_credentials` ->
- :func:`_validate_switch` -> :func:`_build_switch_result`; each step returns a failure
- :class:`ModelSwitchResult` to stop the chain, or ``None`` to continue. ``user_providers`` /
- ``custom_providers`` are the ``providers:`` dict and ``custom_providers:`` list from config.yaml.
+ Route (PATH A with ``--provider``, else PATH B) -> credentials -> validation -> result; each
+ step returns a failure :class:`ModelSwitchResult` to stop the chain, or ``None`` to continue.
+ ``user_providers`` / ``custom_providers`` are the config.yaml ``providers:`` dict and
+ ``custom_providers:`` list.
"""
st = _Switch(
raw_input=raw_input, current_provider=current_provider, current_model=current_model,
diff --git a/hermes_cli/model_switch_providers.py b/hermes_cli/model_switch_providers.py
index fd84faef1e5..5a40877effc 100644
--- a/hermes_cli/model_switch_providers.py
+++ b/hermes_cli/model_switch_providers.py
@@ -195,11 +195,9 @@ _PARALLEL_PREFETCH_WORKERS = 8
def _prefetch_provider_models_parallel(provider_slugs: list[str]) -> None:
"""Fetch stale/missing provider catalogs in parallel before the serial picker loop.
- On a cold cache the serial loop would block 1-8s per provider; after the prefetch it hits
- warm entries and the wait is the slowest single provider. Fresh entries are skipped. Each
- worker re-persists through the thread-safe ``update_provider_cache_entry`` so concurrent
- writes to ``provider_models_cache.json`` cannot clobber each other. Unknown slugs are
- silently skipped.
+ On a cold cache the serial loop would block 1-8s per provider; after the prefetch the wait is
+ the slowest single provider. Each worker re-persists through the thread-safe
+ ``update_provider_cache_entry`` so concurrent writes cannot clobber each other.
"""
from hermes_cli.models import (
_PROVIDER_MODELS_CACHE_TTL, _credential_fingerprint, _load_provider_models_cache,
@@ -287,13 +285,9 @@ def _iter_builtin_candidates(models_dev_data: dict, excluded: set, seen: set):
pconfig = PROVIDER_REGISTRY.get(hermes_id)
if (pconfig and pconfig.auth_type != "api_key") or not is_runtime_provider_routable(hermes_id):
continue
- if pconfig and pconfig.api_key_env_vars:
- env_vars = list(pconfig.api_key_env_vars)
- else:
- env_vars = pdata.get("env", [])
- if not isinstance(env_vars, list):
- continue
- yield hermes_id, mdev_id, pconfig, env_vars
+ env_vars = list(pconfig.api_key_env_vars) if pconfig and pconfig.api_key_env_vars else pdata.get("env", [])
+ if isinstance(env_vars, list):
+ yield hermes_id, mdev_id, pconfig, env_vars
def _auth_store_has_provider(*keys: str) -> bool:
@@ -475,12 +469,11 @@ def _entry_api_mode(entry: dict) -> str | None:
return str(entry.get("api_mode") or entry.get("transport") or "").strip().lower() or None
-def _entry_key_env(entry: dict, *keys: str) -> str:
- return str(next((entry.get(k) for k in keys if entry.get(k)), "")).strip()
-
-
-def _credential_identity(inline_api_key: str, key_env: str) -> str:
- return inline_api_key if inline_api_key else (f"env:{key_env}" if key_env else "")
+def _entry_credentials(entry: dict, *key_env_keys: str) -> tuple[str, str, str]:
+ """``(inline_api_key, key_env, identity)`` — identity is the inline key, else ``env:<VAR>``, else ""."""
+ inline_api_key = str(entry.get("api_key", "") or "").strip()
+ key_env = str(next((entry.get(k) for k in key_env_keys if entry.get(k)), "")).strip()
+ return inline_api_key, key_env, inline_api_key or (f"env:{key_env}" if key_env else "")
def _discover_flag(entry: dict):
@@ -588,12 +581,10 @@ def _collect_authed_provider_slugs(
@dataclass
class _PickerBuild:
- """Mutable state threaded through the ``list_authenticated_providers`` sections:
- 1 built-ins mapped to models.dev, 2 Hermes-only overlays (nous, openai-codex, copilot,
- opencode-*), 2b canonical providers missed by 1/2 (keeps /model in sync with `hermes model`),
- 3 ``providers:`` entries + 3b the bare active custom endpoint, 4 ``custom_providers:`` entries.
- Every ``hermes_cli.auth/models`` import in the row builders stays lazy so tests can patch
- those modules."""
+ """State threaded through the ``list_authenticated_providers`` sections: 1 built-ins mapped to
+ models.dev, 2 Hermes-only overlays, 2b canonical providers missed by 1/2, 3 ``providers:``
+ entries + 3b the bare active custom endpoint, 4 ``custom_providers:`` entries. Row-builder
+ imports of ``hermes_cli.auth/models`` stay lazy so tests can patch those modules."""
current_provider: str
current_base_url: str
current_model: str
@@ -837,12 +828,9 @@ def _lap_user_provider_rows(b: _PickerBuild, user_providers: dict) -> None:
continue
display_name = coerce_provider_id(ep_cfg.get("name")) or ep_name
api_url = _entry_base_url(ep_cfg, ("base_url", "api", "url"))
- key_env = _entry_key_env(ep_cfg, "key_env", "api_key_env")
- inline_api_key = str(ep_cfg.get("api_key", "") or "").strip()
+ inline_api_key, key_env, cred_identity = _entry_credentials(ep_cfg, "key_env", "api_key_env")
headers = _extra_headers_from_config(ep_cfg)
- group_key = (
- _norm_url(api_url), _credential_identity(inline_api_key, key_env), _entry_api_mode(ep_cfg),
- tuple(sorted(headers.items())))
+ group_key = (_norm_url(api_url), cred_identity, _entry_api_mode(ep_cfg), tuple(sorted(headers.items())))
# ``default_model`` is the legacy key; ``model`` matches custom_providers.
entry_models: list = []
@@ -946,17 +934,14 @@ def _lap_custom_provider_rows(b: _PickerBuild, custom_providers: list) -> None:
api_url = str(_entry_base_url(entry) or "").strip().rstrip("/")
if not raw_name or not api_url:
continue
- inline_api_key = str(entry.get("api_key") or "").strip()
- key_env = _entry_key_env(entry, "key_env")
+ inline_api_key, key_env, cred_identity = _entry_credentials(entry, "key_env")
api_key = inline_api_key or _scoped_key_env(key_env)
api_mode = _entry_api_mode(entry)
discover = _discover_flag(entry)
entry_extra_headers = _extra_headers_from_config(entry)
prefix = _display_prefix(raw_name)
provider_key = str(entry.get("provider_key") or "").strip()
- group_key = (
- api_url, _credential_identity(inline_api_key, key_env), api_mode,
- tuple(sorted(entry_extra_headers.items())), prefix.lower())
+ group_key = (api_url, cred_identity, api_mode, tuple(sorted(entry_extra_headers.items())), prefix.lower())
if group_key not in groups:
display_name = prefix or raw_name
groups[group_key] = {
@@ -1067,21 +1052,15 @@ def list_authenticated_providers(
max_models: int | None = None, current_model: str = "", refresh: bool = False,
probe_custom_providers: bool = True, probe_current_custom_provider: bool = False,
for_picker: bool = False, excluded_providers: list | None = None) -> List[dict]:
- """Detect which providers have credentials and list their curated models.
-
- Uses the hand-picked agentic lists from hermes_cli/models.py, NOT the full models.dev
- catalog. Only providers with API keys set or user-defined endpoints appear.
+ """Detect which providers have credentials and list their curated (not full models.dev) models.
Returns dicts with ``slug`` (the --provider value), ``name``, ``is_current``,
``is_user_defined``, ``models`` (up to max_models), ``total_models``, ``source``
("built-in", "hermes", "canonical", "user-config", "model-config").
-
- ``force_fresh_nous_tier`` bypasses the short Nous tier cache (account-sensitive flows only).
- ``refresh`` busts the per-provider model-id disk cache up front (explicit "refresh models"
- action only). ``probe_custom_providers`` controls live ``/models`` discovery for saved custom
- endpoints (default true for CLI parity; GUI opens pass false).
- ``probe_current_custom_provider`` probes only the currently-selected custom endpoint so its
- list matches without blocking on offline ones.
+ ``force_fresh_nous_tier`` bypasses the short Nous tier cache (account-sensitive flows only);
+ ``refresh`` busts the model-id disk cache up front (explicit user action only);
+ ``probe_custom_providers`` enables live ``/models`` discovery for saved custom endpoints (CLI
+ true, GUI false); ``probe_current_custom_provider`` probes only the selected custom endpoint.
"""
from hermes_cli.model_switch import _collect_authed_provider_slugs, _prefetch_provider_models_parallel
from agent.models_dev import fetch_models_dev
@@ -1193,11 +1172,9 @@ def list_picker_providers(
include_moa: bool = False, excluded_providers: list | None = None) -> List[dict]:
"""Interactive-picker variant of :func:`list_authenticated_providers`.
- Narrows the payload to models actually callable in this install: OpenRouter's list is
- replaced with :func:`hermes_cli.models.fetch_openrouter_models` (curated snapshot filtered
- against the live catalog), and rows whose model list ends up empty are dropped — except
- custom endpoints (``is_user_defined`` with an ``api_url``) where the user may supply their
- own model set through config. The typed ``/model <name>`` path is unaffected.
+ OpenRouter's list is replaced with :func:`hermes_cli.models.fetch_openrouter_models` (curated
+ snapshot filtered against the live catalog) and rows left with no models are dropped — except
+ custom endpoints, where the user may supply their own model set through config.
"""
from hermes_cli.model_switch import list_authenticated_providers
from hermes_cli.models import fetch_openrouter_models