Skip to content

The agent that grows with you

refactor(hermes_cli): model_switch/moa pass 3 (_clean/_extend_unique helpers, stale-catalog predicate)

Teknium6d55980f39c0
diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.py
index cd3f3a112d6..23604f6b5f3 100644
--- a/hermes_cli/model_switch.py
+++ b/hermes_cli/model_switch.py
@@ -96,7 +96,7 @@ def _models_config_is_allowlist(value: Any, discovered: bool = False) -> bool:
def _bare_custom_provider_def(current_base_url: str) -> Optional[ProviderDef]:
"""ProviderDef for a direct ``model.provider: custom`` endpoint."""
- base_url = str(current_base_url or "").strip()
+ base_url = _clean(current_base_url)
if not base_url:
return None
return ProviderDef(
@@ -198,6 +198,11 @@ class DirectAlias(NamedTuple):
# Built-in direct aliases (extended via config.yaml model_aliases:)
_BUILTIN_DIRECT_ALIASES: dict[str, DirectAlias] = {}
+
+def _clean(value: Any) -> str:
+ """``str(value or "").strip()`` — the config-field normaliser used throughout this module."""
+ return str(value or "").strip()
+
# Merged dict (builtins + user config); populated by _load_direct_aliases()
DIRECT_ALIASES: dict[str, DirectAlias] = {}
@@ -225,9 +230,8 @@ def _load_direct_aliases() -> dict[str, DirectAlias]:
if isinstance(entry, dict) and entry.get("model", ""):
merged[name.strip().lower()] = DirectAlias(
model=entry.get("model", ""), provider=entry.get("provider", "custom"),
- base_url=entry.get("base_url", ""),
- api_key=str(entry.get("api_key", "") or "").strip(),
- key_env=str(entry.get("key_env", "") or "").strip())
+ base_url=entry.get("base_url", ""), api_key=_clean(entry.get("api_key", "")),
+ key_env=_clean(entry.get("key_env", "")))
model_section = cfg.get("model", {})
simple_aliases = model_section.get("aliases") if isinstance(model_section, dict) else None
@@ -238,12 +242,11 @@ def _load_direct_aliases() -> dict[str, DirectAlias]:
if not key or key in merged:
continue
if isinstance(value, dict):
- model = str(value.get("model") or "").strip()
+ model = _clean(value.get("model"))
if model:
- provider = str(value.get("provider") or "").strip()
merged[key] = DirectAlias(
- model=model, provider=provider or current_provider or "custom",
- base_url=str(value.get("base_url") or "").strip())
+ model=model, provider=_clean(value.get("provider")) or current_provider or "custom",
+ base_url=_clean(value.get("base_url")))
elif isinstance(value, str) and value.strip():
val = value.strip()
provider, model = val.split("/", 1) if "/" in val else (current_provider, val)
@@ -376,7 +379,7 @@ def resolve_startup_model_route(
the input stays on the aggregator — a ``providers:`` block for the same vendor must not
steal the route.
"""
- raw = str(raw_model or "").strip()
+ raw = _clean(raw_model)
if not raw:
return None
@@ -412,7 +415,7 @@ def resolve_startup_model_route(
configured.update(
f"custom:{entry.get('name', '').strip().lower()}"
for entry in (custom_providers or [])
- if isinstance(entry, dict) and str(entry.get("name") or "").strip())
+ if isinstance(entry, dict) and _clean(entry.get("name")))
try:
from hermes_cli.models import normalize_provider
canonical = normalize_provider(prefix)
@@ -610,9 +613,9 @@ def _effective_model_candidate(value: Any) -> str:
if isinstance(value, str):
return value.strip()
if isinstance(value, dict):
- return str(value.get("model") or "").strip()
+ return _clean(value.get("model"))
model_attr = getattr(value, "model", None)
- return str(model_attr or "").strip() if model_attr is not None else ""
+ return _clean(model_attr) if model_attr is not None else ""
def resolve_effective_model(
@@ -890,7 +893,7 @@ def _configured_provider_matches(
def _resolve_named_custom_model_id(model_name: str, target_provider: str, custom_providers: Optional[list]) -> str:
"""Map a picker-prefixed custom model selection (``prefix/model``) to its configured ID."""
- provider = str(target_provider or "").strip().lower()
+ provider = _clean(target_provider).lower()
if not provider.startswith("custom:") or "/" not in model_name:
return model_name
@@ -924,11 +927,11 @@ def _runtime_creds(fallback_headers: dict, **kwargs) -> tuple[str, str, str, dic
def _entry_configured_key(cfg: dict, read_env) -> str:
"""Inline ``api_key`` (a ``${VAR}`` template resolves via *read_env*), else
``key_env``/``api_key_env`` via *read_env*."""
- key = str(cfg.get("api_key", "") or "").strip()
+ key = _clean(cfg.get("api_key", ""))
if key.startswith("${") and key.endswith("}"):
key = read_env(key[2:-1])
if not key:
- key_env = str(cfg.get("key_env") or cfg.get("api_key_env") or "").strip()
+ key_env = _clean(cfg.get("key_env") or cfg.get("api_key_env"))
key = read_env(key_env) if key_env else ""
return key
@@ -936,7 +939,7 @@ def _entry_configured_key(cfg: dict, read_env) -> str:
def _ollama_configured_base() -> tuple[dict, str]:
from hermes_cli.models import _get_provider_config_dict
cfg = _get_provider_config_dict("ollama")
- return cfg, str(cfg.get("base_url") or cfg.get("api") or cfg.get("url") or "").strip()
+ return cfg, _clean(cfg.get("base_url") or cfg.get("api") or cfg.get("url"))
def _unknown_provider_message(explicit_provider: str) -> str:
@@ -964,9 +967,7 @@ def _aggregator_alias_error(
explicit_norm = explicit_provider.strip().lower()
alias_target = ALIASES.get(explicit_norm)
if not (
- alias_target
- and alias_target == target_provider
- and target_provider != explicit_norm
+ alias_target and alias_target == target_provider and target_provider != explicit_norm
and target_provider in _AGGREGATOR_PROVIDERS):
return ""
authed = get_authenticated_provider_slugs(
@@ -1189,11 +1190,8 @@ def _convert_vendor_colon_slug(st: _Switch) -> None:
colon_pos = raw_input.find(":")
cur_norm = str(st.current_provider).strip().lower()
if (
- colon_pos > 0
- and "/" not in raw_input
- and is_aggregator(st.current_provider)
- and not cur_norm.startswith("custom")
- and cur_norm != "ollama"):
+ colon_pos > 0 and "/" not in raw_input and is_aggregator(st.current_provider)
+ and not cur_norm.startswith("custom") and cur_norm != "ollama"):
left = raw_input[:colon_pos].strip().lower()
right = raw_input[colon_pos + 1:].strip()
if left and right:
@@ -1277,15 +1275,11 @@ def _route_from_model_input(st: _Switch) -> Optional[ModelSwitchResult]:
# Step e
is_custom = (
- current_provider in {"custom", "local"}
- or current_provider.startswith("custom:")
+ current_provider in {"custom", "local"} or current_provider.startswith("custom:")
or base_url_hostname(st.current_base_url or "") in ("localhost", "127.0.0.1"))
if (
- st.target_provider == current_provider
- and not is_custom
- and not st.resolved_alias
- and not resolved_in_current_catalog
- and not config_routed):
+ st.target_provider == current_provider and not is_custom and not st.resolved_alias
+ and not resolved_in_current_catalog and not config_routed):
detected = detect_provider_for_model(st.new_model, current_provider)
if detected:
st.target_provider, st.new_model = detected
@@ -1425,8 +1419,7 @@ def _validate_switch(st: _Switch) -> Optional[ModelSwitchResult]:
else:
headers = st.validation_headers or (
_extra_headers_from_config(st.user_providers.get(st.target_provider))
- if st.user_providers and st.target_provider in st.user_providers
- else None)
+ if st.user_providers and st.target_provider in st.user_providers else None)
try:
validation = validate_requested_model(
st.new_model, st.target_provider, api_key=st.api_key, base_url=st.base_url,
diff --git a/hermes_cli/model_switch_providers.py b/hermes_cli/model_switch_providers.py
index 2e24969ed9b..e9bc88ee472 100644
--- a/hermes_cli/model_switch_providers.py
+++ b/hermes_cli/model_switch_providers.py
@@ -52,22 +52,7 @@ def _save_discovered_models_to_config(
continue
if headers is not None and _extra_headers_from_config(entry) != headers:
continue
- existing = entry.get("models")
- legacy_discovered = isinstance(existing, dict) and existing.get("__discovered_model_catalog__") is True
- entry_discovered = entry.get("models_discovered") is True or legacy_discovered
- # A ``models`` mapping or list of dicts is user-curated per-model metadata — never
- # replace it. A mapping Hermes itself discovered (entry flag or legacy in-mapping
- # sentinel) is ours to refresh.
- if isinstance(existing, dict) and not entry_discovered:
- continue
- if isinstance(existing, list) and any(isinstance(m, dict) for m in existing):
- continue
- # Only write when stale. A legacy-shape entry is always rewritten so the save
- # migrates it to the clean entry-level flag.
- if isinstance(existing, list) and existing == model_ids:
- continue
- if (isinstance(existing, dict) and entry_discovered and not legacy_discovered
- and list(existing) == model_ids):
+ if not _discovered_catalog_stale(entry, model_ids):
continue
entry["models"] = {model_id: {} for model_id in model_ids}
entry["models_discovered"] = True
@@ -80,6 +65,24 @@ def _save_discovered_models_to_config(
pass
+def _discovered_catalog_stale(entry: dict, model_ids: list[str]) -> bool:
+ """Whether a live probe may overwrite ``entry["models"]``.
+
+ A ``models`` mapping or list of dicts is user-curated per-model metadata — never replaced.
+ A mapping Hermes itself discovered (entry flag or legacy in-mapping sentinel) is ours to
+ refresh, but only when stale; a legacy-shape entry is always rewritten so the save migrates
+ it to the clean entry-level flag.
+ """
+ existing = entry.get("models")
+ legacy_discovered = isinstance(existing, dict) and existing.get("__discovered_model_catalog__") is True
+ entry_discovered = entry.get("models_discovered") is True or legacy_discovered
+ if isinstance(existing, dict):
+ return entry_discovered and (legacy_discovered or list(existing) != model_ids)
+ if isinstance(existing, list):
+ return not any(isinstance(m, dict) for m in existing) and existing != model_ids
+ return True
+
+
_MODEL_DISCOVERY_ERRORS = (
ImportError, OSError, RuntimeError, TimeoutError, TypeError, ValueError, http.client.HTTPException,
)
@@ -213,10 +216,8 @@ def _prefetch_provider_models_parallel(provider_slugs: list[str]) -> None:
continue
entry = cache.get(normalized)
if (
- isinstance(entry, dict)
- and entry.get("fp") == _credential_fingerprint(normalized)
- and isinstance(entry.get("models"), list)
- and entry["models"]
+ isinstance(entry, dict) and entry.get("fp") == _credential_fingerprint(normalized)
+ and isinstance(entry.get("models"), list) and entry["models"]
and now - float(entry.get("at", 0)) < _PROVIDER_MODELS_CACHE_TTL):
continue
stale_slugs.append(normalized)
@@ -269,15 +270,14 @@ def _iter_builtin_candidates(models_dev_data: dict, excluded: set, seen: set):
alias_target = ALIASES.get(hermes_id)
if alias_target and alias_target != hermes_id and alias_target in _AGGREGATOR_PROVIDERS:
continue
- canonical = hermes_id
try:
from providers import get_provider_profile
prof = get_provider_profile(hermes_id)
- if prof is not None:
- canonical = prof.name
+ if prof is not None and prof.name != hermes_id:
+ continue
except Exception:
pass
- if canonical != hermes_id or hermes_id.lower() in seen:
+ if hermes_id.lower() in seen:
continue
if hermes_id.lower() in excluded or mdev_id.lower() in excluded:
continue
@@ -414,14 +414,10 @@ def _first_curated(curated: dict, keys) -> list:
def _aws_live_or_curated_ids(slug: str, curated: dict, *fallback_keys: str) -> list:
"""Bedrock: live discovery reflects the active region (eu.*, ap.*) rather than the static
us.* list; any failure falls back to the curated list."""
- from hermes_cli.models import cached_provider_model_ids
try:
- ids = cached_provider_model_ids(slug)
- if ids:
- return ids
+ return _live_or_curated_ids(slug, curated, *fallback_keys, merge_models_dev=False) or []
except Exception:
- pass
- return _first_curated(curated, fallback_keys or (slug,)) or []
+ return _first_curated(curated, fallback_keys or (slug,)) or []
def _nous_picker_model_ids(curated: dict, force_fresh_nous_tier: bool) -> list:
@@ -461,6 +457,13 @@ def _cap_models(model_ids: list, max_models: int | None, slug: str = "") -> list
return model_ids[:max_models]
+def _extend_unique(target: list, items) -> None:
+ """Append each truthy item of *items* not already in *target* (order preserved)."""
+ for item in items:
+ if item and item not in target:
+ target.append(item)
+
+
def _norm_url(url: Any) -> str:
return str(url or "").strip().rstrip("/").lower()
@@ -567,8 +570,7 @@ def _collect_authed_provider_slugs(
continue
if (
_overlay_has_env_creds(pid, hermes_slug, overlay, _scoped_key_env)
- or _auth_store_has_provider(pid, hermes_slug)
- or _pool_usable(hermes_slug)):
+ or _auth_store_has_provider(pid, hermes_slug) or _pool_usable(hermes_slug)):
_emit(hermes_slug, pid, hermes_slug)
for cp in CANONICAL_PROVIDERS:
@@ -656,16 +658,22 @@ class _PickerBuild:
"api_url": api_url, "native_catalog_empty": native_catalog_empty})
self.seen_slugs.add(slug.lower())
+ def record_section3_pair(self, name: str, url_norm: str) -> bool:
+ """Remember a (display_name, base_url) pair for section-4 dedup; False when either is blank."""
+ pair = (str(name).strip().lower(), url_norm)
+ if not (pair[0] and pair[1]):
+ return False
+ self.section3_pairs.add(pair)
+ return True
+
def endpoint_is_current(self, slug: str, aliases: set, url_norm: str, *, url_match_ok: bool = True) -> bool:
"""Row is current by slug/alias, or (bare ``custom`` provider) by matching base_url."""
return (
str(slug).strip().lower() == self.current_provider_norm
or self.current_provider_norm in aliases
or (
- self.current_provider_norm == "custom"
- and bool(self.current_base_url_norm)
- and url_norm == self.current_base_url_norm
- and url_match_ok))
+ self.current_provider_norm == "custom" and bool(self.current_base_url_norm)
+ and url_norm == self.current_base_url_norm and url_match_ok))
def discover_endpoint(
self, api_key: str, api_url: str, native_provider: str, has_explicit_models: bool, *,
@@ -677,8 +685,7 @@ class _PickerBuild:
the probe. A dict-shaped ``models:`` is metadata, so still probe; pin with
``discover_models: false``."""
probe_live = (
- discovery_allowed
- and (bool(api_key) or not has_explicit_models)
+ discovery_allowed and (bool(api_key) or not has_explicit_models)
and self.can_probe_custom(row_is_current=is_current))
discovered, native_catalog_empty = _discover_endpoint_models(
api_key, api_url, native_provider, has_explicit_models,
@@ -847,11 +854,9 @@ def _lap_user_provider_rows(b: _PickerBuild, user_providers: dict) -> None:
tuple(sorted(headers.items())))
# ``default_model`` is the legacy key; ``model`` matches custom_providers.
- default_model = ep_cfg.get("default_model", "") or ep_cfg.get("model", "")
- entry_models = [default_model] if default_model else []
- for model_id in _declared_model_ids(ep_cfg.get("models", [])):
- if model_id not in entry_models:
- entry_models.append(model_id)
+ entry_models: list = []
+ _extend_unique(entry_models, [ep_cfg.get("default_model", "") or ep_cfg.get("model", "")])
+ _extend_unique(entry_models, _declared_model_ids(ep_cfg.get("models", [])))
if group_key not in ep_groups:
# Strip the per-model suffix and trailing version tokens ("Palantir Claude 4.7 Opus"
@@ -870,9 +875,7 @@ def _lap_user_provider_rows(b: _PickerBuild, user_providers: dict) -> None:
"headers": headers, "api_mode": ep_cfg.get("api_mode"),
"discovery_allowed": bool(api_url) and _discover_flag(ep_cfg), "raw_names": [], "aliases": set()}
grp = ep_groups[group_key]
- for m in entry_models:
- if m and m not in grp["models"]:
- grp["models"].append(m)
+ _extend_unique(grp["models"], entry_models)
# A singular default_model/model is only the active selection and must not suppress
# discovery; dict-shaped ``models:`` is context_length metadata, not an allowlist — see
# ``_models_config_is_allowlist``.
@@ -904,13 +907,9 @@ def _lap_user_provider_rows(b: _PickerBuild, user_providers: dict) -> None:
# Record every raw member name so section 4 can match per-model custom_providers rows
# even though the group label was collapsed.
for raw_name in grp["raw_names"] or [display_name]:
- pair = (str(raw_name).strip().lower(), ep_url_norm)
- if pair[0] and pair[1]:
- b.section3_pairs.add(pair)
+ if b.record_section3_pair(raw_name, ep_url_norm):
b.seen_slugs.add(custom_provider_slug(raw_name).lower())
- pair = (str(display_name).strip().lower(), ep_url_norm)
- if pair[0] and pair[1]:
- b.section3_pairs.add(pair)
+ b.record_section3_pair(display_name, ep_url_norm)
def _lap_bare_custom_row(b: _PickerBuild, custom_providers: list | None) -> None:
@@ -983,15 +982,11 @@ def _lap_custom_provider_rows(b: _PickerBuild, custom_providers: list) -> None:
grp["aliases"].update(custom_provider_aliases(raw_name, provider_key))
# ``model:`` is only the active selection; every configured model lives under
# ``models:`` (dict written by _save_custom_provider).
- default_model = (entry.get("model") or "").strip()
- if default_model and default_model not in grp["models"]:
- grp["models"].append(default_model)
+ _extend_unique(grp["models"], [(entry.get("model") or "").strip()])
models_field = entry.get("models", {})
if _models_config_is_allowlist(models_field, _entry_models_discovered(entry)):
grp["has_explicit_models"] = True
- for model_id in _declared_model_ids(models_field):
- if model_id not in grp["models"]:
- grp["models"].append(model_id)
+ _extend_unique(grp["models"], _declared_model_ids(models_field))
section4_slugs: set = set()
current_url_group_count = sum(
@@ -1156,8 +1151,7 @@ def _finalize_picker_rows(results: list, user_providers, current_model: str) ->
from hermes_cli.config import is_provider_enabled
if isinstance(user_providers, dict):
disabled = {
- str(name).strip().lower()
- for name, cfg in user_providers.items()
+ str(name).strip().lower() for name, cfg in user_providers.items()
if isinstance(cfg, dict) and not is_provider_enabled(cfg)}
if disabled:
results = [