The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(models): keep discovery sentinels out of the user-facing models mapping
Teknium72b7c6c8d17c
diff --git a/acp_adapter/server.py b/acp_adapter/server.pyindex 3c9cbf36166..792e44b70d4 100644--- a/acp_adapter/server.py+++ b/acp_adapter/server.py@@ -117,6 +117,7 @@ def _named_custom_provider_catalogs() -> list[tuple[str, str, list[tuple[str, stfrom hermes_cli.model_switch import (_NativePickerModelList,_declared_model_ids,+ _entry_models_discovered,_fetch_picker_live_models,_models_config_is_allowlist,)@@ -180,7 +181,9 @@ def _named_custom_provider_catalogs() -> list[tuple[str, str, list[tuple[str, stis_native_ollama = should_use_ollama_native_catalog(native_catalog_provider, base_url, headers=native_headers)- explicit_catalog = _models_config_is_allowlist(models_cfg)+ explicit_catalog = _models_config_is_allowlist(+ models_cfg, _entry_models_discovered(entry)+ )if not api_key and not declared and not is_native_ollama:# No credential to discover with and nothing declared:# not addressable from the selector.@@ -755,7 +758,7 @@ class HermesACPAgent(acp.Agent):capabilities=False,refresh=False,probe_custom_providers=False,- probe_current_custom_provider=True,+ probe_current_custom_provider=False,max_models=ACP_MAX_MODELS_PER_PROVIDER,)diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex ccfdb406eba..5e6fd1942ed 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -1370,6 +1370,7 @@ def _normalize_custom_provider_entry("name", "api", "url", "base_url", "api_key", "key_env", "api_key_env","key_cmd","api_mode", "transport", "model", "default_model", "models",+ "models_discovered","context_length", "rate_limit_delay","request_timeout_seconds", "stale_timeout_seconds","discover_models", "extra_body", "extra_headers",@@ -1456,12 +1457,24 @@ def _normalize_custom_provider_entry(if isinstance(model_name, str) and model_name.strip():normalized["model"] = model_name.strip()+ # Entry-level marker: the ``models`` mapping was auto-discovered by+ # Hermes (``_save_discovered_models_to_config``), not hand-curated.+ # Older Hermes versions wrote an in-mapping ``__discovered_model_catalog__``+ # sentinel instead; accept it on read and strip it from the models+ # mapping so sentinel keys never surface as model IDs.+ models_discovered = entry.get("models_discovered") is True+models = entry.get("models")if isinstance(models, dict) and models:# Shallow-copy: `entry` may alias a cached config sub-dict, and the# normalized entry escapes into long-lived runtime state# (agent._custom_providers) — don't share the cached models mapping.- normalized["models"] = dict(models)+ models_copy = dict(models)+ if models_copy.pop("__discovered_model_catalog__", None) is True:+ models_discovered = True+ models_copy.pop("__explicit_model_allowlist__", None)+ if models_copy:+ normalized["models"] = models_copyelif isinstance(models, list) and models:# Hand-edited configs (and older Hermes versions) may write# ``models`` as a plain list of ids or as ``[{id: ...}]`` rows.@@ -1485,12 +1498,11 @@ def _normalize_custom_provider_entry(}normalized_models[model_id.strip()] = model_metaif normalized_models:- if normalized_models.get("__discovered_model_catalog__"):- normalized_models.pop("__explicit_model_allowlist__", None)- else:- normalized_models["__explicit_model_allowlist__"] = Truenormalized["models"] = normalized_models+ if models_discovered:+ normalized["models_discovered"] = True+context_length = entry.get("context_length")if isinstance(context_length, int) and context_length > 0:normalized["context_length"] = context_length@@ -1547,6 +1559,7 @@ def _custom_provider_entry_to_provider_config("api_key","key_env","models",+ "models_discovered","context_length","rate_limit_delay","discover_models",diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 65e628b69fd..044501e2b6d 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -3667,6 +3667,7 @@ def select_provider_and_model(args=None):"key_env": entry.get("key_env") or entry.get("api_key_env", ""),"model": entry.get("model", ""),"models": entry.get("models", {}),+ "models_discovered": entry.get("models_discovered", False),"extra_headers": entry.get("extra_headers", {}),"discover_models": entry.get("discover_models", True),"api_mode": entry.get("api_mode", ""),diff --git a/hermes_cli/model_setup_flows.py b/hermes_cli/model_setup_flows.pyindex 0c8d870e747..6e54ac7472f 100644--- a/hermes_cli/model_setup_flows.py+++ b/hermes_cli/model_setup_flows.py@@ -1513,7 +1513,10 @@ def _model_flow_named_custom(config, provider_info):from hermes_cli.main import _custom_provider_api_key_config_value, _custom_provider_base_url_config_value, _save_custom_providerfrom hermes_cli.auth import _save_model_choice, deactivate_providerfrom hermes_cli.config import load_config, normalize_extra_headers, save_config- from hermes_cli.model_switch import _models_config_is_allowlist+ from hermes_cli.model_switch import (+ _entry_models_discovered,+ _models_config_is_allowlist,+ )from hermes_cli.models import (fetch_api_models,fetch_ollama_local_models,@@ -1548,7 +1551,9 @@ def _model_flow_named_custom(config, provider_info):configured_models: list[str] = []native_catalog_empty = Falsecfg_models = provider_info.get("models", {})- explicit_catalog = _models_config_is_allowlist(cfg_models)+ explicit_catalog = _models_config_is_allowlist(+ cfg_models, _entry_models_discovered(provider_info)+ )if isinstance(cfg_models, dict):configured_models = [str(m)diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.pyindex 6e8d11ad4e5..aae5f4cadee 100644--- a/hermes_cli/model_switch.py+++ b/hermes_cli/model_switch.py@@ -88,6 +88,8 @@ def _declared_model_ids(value: Any) -> list[str]:if isinstance(value, dict):for model_id in value:+ # Backward compat: pre-fix Hermes wrote sentinel keys inside the+ # user-facing ``models`` mapping. Never list them as model IDs.if model_id in {"__explicit_model_allowlist__","__discovered_model_catalog__",@@ -111,7 +113,27 @@ def _declared_model_ids(value: Any) -> list[str]:return ids-def _models_config_is_allowlist(value: Any) -> bool:+def _entry_models_discovered(entry: Any) -> bool:+ """True when the entry's ``models`` mapping was auto-discovered by Hermes.++ The current shape is an entry-level ``models_discovered: true`` sibling of+ ``models``. Older Hermes versions wrote an in-mapping+ ``__discovered_model_catalog__: true`` sentinel instead — accept that on+ read for backward compatibility (the next discovery save migrates the+ entry to the clean shape).+ """+ if not isinstance(entry, dict):+ return False+ if entry.get("models_discovered") is True:+ return True+ models = entry.get("models")+ return (+ isinstance(models, dict)+ and models.get("__discovered_model_catalog__") is True+ )+++def _models_config_is_allowlist(value: Any, discovered: bool = False) -> bool:"""Return True when ``models:`` is an intentional ID allowlist.A mapping like ``{model_id: {context_length: N}}`` is per-model *metadata*@@ -123,16 +145,19 @@ def _models_config_is_allowlist(value: Any) -> bool:List/string shapes remain allowlists for no-key endpoints. To pin adict-shaped catalog, set ``discover_models: false``.++ ``discovered`` is the entry-level ``models_discovered`` flag (see+ ``_entry_models_discovered``): a catalog Hermes itself persisted after a+ successful probe is never a user pin, whatever its shape."""+ if discovered:+ return Falseif value is None:return Falseif isinstance(value, str):return bool(value.strip())if isinstance(value, dict):- return bool(- value.get("__explicit_model_allowlist__")- and not value.get("__discovered_model_catalog__")- )+ return Falseif isinstance(value, (list, tuple)):return bool(_declared_model_ids(value))return False@@ -183,35 +208,40 @@ def _save_discovered_models_to_config(if entry_headers != headers:continueexisting = 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+ )# Preserve per-model metadata: when ``models`` is a mapping# (e.g. ``{"model-a": {"context_length": 8192}}``) or a list of# dicts (e.g. ``[{"id": "model-a", "context_length": 8192}]``),# the user has curated metadata per model — do not replace it.- if isinstance(existing, dict):+ # A mapping Hermes itself discovered (``models_discovered: true``+ # or the legacy in-mapping sentinel) is ours to refresh.+ if isinstance(existing, dict) and not entry_discovered:continueif isinstance(existing, list) and any(isinstance(m, dict) for m in existing):continue# Only update when models are stale — avoids unnecessary- # config writes on every picker open.+ # config writes on every picker open. A legacy-shape entry+ # (sentinel inside ``models``) is always rewritten so the next+ # save migrates it to the clean entry-level flag.if isinstance(existing, list) and existing == model_ids:continue- if isinstance(existing, dict):- existing_ids = [- model_id- for model_id in existing- if model_id != "__discovered_model_catalog__"- ]- if (- existing.get("__discovered_model_catalog__") is True- and existing_ids == model_ids- ):- continue- entry["models"] = {- "__discovered_model_catalog__": True,- **{model_id: {} for model_id in model_ids},- }+ if (+ isinstance(existing, dict)+ and entry_discovered+ and not legacy_discovered+ and list(existing) == model_ids+ ):+ continue+ entry["models"] = {model_id: {} for model_id in model_ids}+ entry["models_discovered"] = Truechanged = Trueif changed:@@ -1940,7 +1970,7 @@ def switch_model(base_url = runtime.get("base_url", "")api_mode = runtime.get("api_mode", "")validation_headers = runtime.get("extra_headers") or validation_headers- except (OSError, RuntimeError, TypeError, ValueError):+ except Exception:pass# --- Direct alias override: use exact base_url from the alias if set ---@@ -3288,7 +3318,9 @@ def list_authenticated_providers(# #61928). Dict-shaped ``models:`` is context_length metadata from# ``hermes model``, not an allowlist — see# ``_models_config_is_allowlist``.- if _models_config_is_allowlist(ep_cfg.get("models")):+ if _models_config_is_allowlist(+ ep_cfg.get("models"), _entry_models_discovered(ep_cfg)+ ):ep_groups[group_key]["has_explicit_models"] = Trueep_groups[group_key]["raw_names"].append(display_name)ep_groups[group_key]["aliases"].update(@@ -3391,7 +3423,7 @@ def list_authenticated_providers(or isinstance(live_models, _NativePickerModelList)):models_list = live_models- except _MODEL_DISCOVERY_ERRORS:+ except Exception:passelif _discovery_allowed:try:@@ -3494,7 +3526,7 @@ def list_authenticated_providers(_live_models, _NativePickerModelList) and not _live_models_models = _live_models- except _MODEL_DISCOVERY_ERRORS:+ except Exception:passresults.append({"slug": "custom",@@ -3638,7 +3670,9 @@ def list_authenticated_providers(# Dict-shaped models: is context_length metadata from# ``_save_custom_provider``, not an allowlist — see# ``_models_config_is_allowlist``.- if _models_config_is_allowlist(models_field):+ if _models_config_is_allowlist(+ models_field, _entry_models_discovered(entry)+ ):groups[group_key]["has_explicit_models"] = Truefor model_id in declared_models:if model_id not in groups[group_key]["models"]:@@ -3785,7 +3819,7 @@ def list_authenticated_providers(api_mode=grp.get("api_mode"),headers=grp.get("extra_headers") or None,)- except _MODEL_DISCOVERY_ERRORS:+ except Exception:passelif _discovery_allowed:try:diff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex 3372507ae81..e44b278f964 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -2972,7 +2972,7 @@ def _get_model_config_dict() -> dict[str, Any]:model_cfg = config.get("model", {})if isinstance(model_cfg, dict):return model_cfg- except (ImportError, OSError, RuntimeError, TypeError, ValueError, AttributeError):+ except Exception:passreturn {}@@ -3994,7 +3994,7 @@ def _credential_fingerprint(provider: str) -> str:bev = getattr(pcfg, "base_url_env_var", "") or ""if bev:parts.append(f"{bev}={_os.environ.get(bev, '')}")- except (ImportError, AttributeError):+ except Exception:pass# Effective configured endpoint: config.yaml's model.base_url changes thediff --git a/tests/hermes_cli/test_model_switch_custom_providers.py b/tests/hermes_cli/test_model_switch_custom_providers.pyindex deb80cacaa5..8e3822316e5 100644--- a/tests/hermes_cli/test_model_switch_custom_providers.py+++ b/tests/hermes_cli/test_model_switch_custom_providers.py@@ -2082,8 +2082,11 @@ def test_auto_saved_catalog_round_trips_without_pinning(tmp_path, monkeypatch):_save_discovered_models_to_config(_LOCAL_ENDPOINT, list(_LOCAL_CATALOG))saved = yaml.safe_load(cfg_path.read_text())["custom_providers"][0]- assert saved["models"]["__discovered_model_catalog__"] is True- assert [m for m in saved["models"] if not m.startswith("__")] == _LOCAL_CATALOG+ assert saved["models_discovered"] is True+ assert list(saved["models"]) == _LOCAL_CATALOG+ assert not any(m.startswith("__") for m in saved["models"]), (+ "sentinel keys must never appear inside the user-facing models mapping"+ )# The persisted shape is what the picker will read on the next open. It# must not, on a keyless entry, suppress discovery of a wider catalog.@@ -2098,3 +2101,70 @@ def test_auto_saved_catalog_round_trips_without_pinning(tmp_path, monkeypatch):"cached lineup")assert fetched == []+++def test_legacy_sentinel_catalog_still_resolves_and_migrates(tmp_path, monkeypatch):+ """Old-shape configs (sentinels inside ``models``) keep working.++ Pre-fix Hermes wrote ``__discovered_model_catalog__: true`` (and+ ``__explicit_model_allowlist__``) inside the user-facing ``models``+ mapping. Reading such a config must (a) recognize the catalog as+ discovered — not a user pin, (b) never list the sentinels as model IDs,+ and (c) migrate to the clean entry-level ``models_discovered`` shape on+ the next discovery save.+ """+ import hermes_cli.config as config_mod+ from hermes_cli.model_switch import (+ _declared_model_ids,+ _entry_models_discovered,+ _models_config_is_allowlist,+ )++ legacy_entry = {+ "name": "Local MLX",+ "base_url": _LOCAL_ENDPOINT,+ "model": "omlx-model-1",+ "models": {+ "__discovered_model_catalog__": True,+ **{m: {} for m in _LOCAL_CATALOG},+ },+ }++ # (a) recognized as a discovered catalog, not an allowlist.+ assert _entry_models_discovered(legacy_entry) is True+ assert not _models_config_is_allowlist(+ legacy_entry["models"], _entry_models_discovered(legacy_entry)+ )++ # (b) sentinels never surface as model IDs.+ assert _declared_model_ids(legacy_entry["models"]) == _LOCAL_CATALOG+ normalized = config_mod._normalize_custom_provider_entry(dict(legacy_entry))+ assert normalized is not None+ assert normalized["models_discovered"] is True+ assert list(normalized["models"]) == _LOCAL_CATALOG+ assert not any(m.startswith("__") for m in normalized["models"])++ # ...and the picker row built from the legacy entry lists no phantoms.+ _seed_custom_model_cache(monkeypatch, [])+ row, fetched = _no_probe_local_row(+ monkeypatch, custom_providers=[legacy_entry]+ )+ assert row is not None+ assert not any(str(m).startswith("__") for m in row["models"])+ assert fetched == []++ # (c) the next discovery save rewrites to the clean shape.+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ cfg_path = tmp_path / "config.yaml"+ cfg_path.write_text(+ yaml.safe_dump({"custom_providers": [legacy_entry]})+ )+ monkeypatch.setattr(config_mod, "CONFIG_PATH", str(cfg_path), raising=False)++ _save_discovered_models_to_config(_LOCAL_ENDPOINT, list(_LOCAL_CATALOG))++ saved = yaml.safe_load(cfg_path.read_text())["custom_providers"][0]+ assert saved["models_discovered"] is True+ assert list(saved["models"]) == _LOCAL_CATALOG+ assert "__discovered_model_catalog__" not in saved["models"]+ assert "__explicit_model_allowlist__" not in saved["models"]