Skip to content

The agent that grows with you

fix: /model collapses compat views of one configured provider by identity, keeps custom:<slug> sessions

teknium101d2e6c3d103
diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.py
index fa1f31d78c1..5bf0e9eb8ed 100644
--- a/hermes_cli/model_switch.py
+++ b/hermes_cli/model_switch.py
@@ -857,14 +857,13 @@ def _configured_provider_matches(
if isinstance(user_providers, dict):
candidates += [(slug, cfg) for slug, cfg in user_providers.items()
if isinstance(slug, str) and isinstance(cfg, dict)]
- # get_compatible_custom_providers() re-lists every ``providers.<slug>`` row as a ``custom:<name>``
- # entry stamped with ``provider_key: <slug>``; callers (gateway, TUI, CLI) pass both views, so
- # that projection is the same endpoint as the row above, not a second declaration (#112788).
- # Hand-written ``custom_providers:`` rows carry no provider_key and stay separate candidates.
- projected = {slug for slug, _ in candidates}
+ # Callers (gateway, TUI, CLI) pass both ``providers:`` and the compat ``custom_providers`` view,
+ # which re-lists every ``providers.<slug>`` row as ``custom:<name>``; a hand-migrated config may
+ # also keep the same endpoint in both sections. Either is one provider, not two (#112788).
+ rows = {slug: _configured_provider_identity(slug, cfg) for slug, cfg in candidates}
candidates += [(f"custom:{e['name']}", e) for e in _custom_entries(custom_providers)
if isinstance(e.get("name"), str) and e["name"].strip()
- and str(e.get("provider_key") or "").strip() not in projected]
+ and not _duplicates_configured_row(f"custom:{e['name']}", e, rows)]
matches: dict[str, str] = {}
for slug, cfg in candidates:
@@ -875,6 +874,50 @@ def _configured_provider_matches(
return matches
+def _configured_provider_identity(slug: str, cfg: dict) -> tuple[str, str, str, str]:
+ """``(name, endpoint, credential, api_mode)`` of one configured provider, read through the same
+ normalizer that builds the compat view, so a ``providers.<slug>`` row, its ``custom:<name>``
+ projection and a legacy duplicate of the same endpoint reduce to one tuple. Any difference in
+ endpoint, credential identity or wire protocol keeps two rows distinct."""
+ from hermes_cli.config_providers import _canonical_api_mode, _normalize_custom_provider_entry
+ # ``provider_key`` is the compat view's stamp, not a config key: drop it so the normalizer does
+ # not warn about it as unknown.
+ entry = _normalize_custom_provider_entry({k: v for k, v in cfg.items() if k != "provider_key"},
+ provider_key="" if slug.startswith("custom:") else slug) or cfg
+ name = (_clean(entry.get("name")).lower() or slug.removeprefix("custom:").lower()).replace(" ", "-")
+ base_url = _clean(entry.get("base_url") or entry.get("url") or entry.get("api")).rstrip("/").lower()
+ api_key, key_env = _clean(entry.get("api_key")), _clean(entry.get("key_env") or entry.get("api_key_env"))
+ if api_key.startswith("${") and api_key.endswith("}"):
+ api_key, key_env = "", api_key[2:-1].strip()
+ credential = (f"key:{api_key}" if api_key else f"env:{key_env}" if key_env
+ else f"cmd:{_clean(entry.get('key_cmd'))}" if _clean(entry.get("key_cmd")) else "")
+ api_mode = _clean(entry.get("api_mode") or entry.get("transport"))
+ return name, base_url, credential, _canonical_api_mode(api_mode).lower() if api_mode else ""
+
+
+def _duplicates_configured_row(slug: str, entry: dict, rows: dict[str, tuple[str, str, str, str]]) -> bool:
+ """A ``custom_providers`` entry is a second view of a ``providers.<slug>`` row when it is that
+ row's compat projection (``provider_key`` names the slug AND it points at the same endpoint —
+ on the raw-list fallback a hand-written provider_key aimed elsewhere stays a candidate) or a
+ legacy duplicate with the same provider identity."""
+ identity = _configured_provider_identity(slug, entry)
+ provider_key = _clean(entry.get("provider_key")).lower()
+ return any(identity == row or (provider_key == row_slug.lower() and identity[1] == row[1])
+ for row_slug, row in rows.items())
+
+
+def _current_provider_match(st: "_Switch", cfg_matches: dict[str, str]) -> Optional[str]:
+ """The slug in *cfg_matches* the session already runs on: an exact hit, or — for a session on
+ the compat projection slug (``custom:relay``) of ``providers.relay`` — that row's slug, so a
+ same-provider switch keeps the caller's slug instead of flipping it (#112788)."""
+ if st.current_provider in cfg_matches:
+ return st.current_provider
+ current = _clean(st.current_provider).lower()
+ providers = st.user_providers if isinstance(st.user_providers, dict) else {}
+ return next((slug for slug in cfg_matches if isinstance(providers.get(slug), dict)
+ and current in custom_provider_aliases(str(providers[slug].get("name") or ""), slug)), None)
+
+
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 = _clean(target_provider).lower()
@@ -1194,8 +1237,9 @@ def _route_configured_provider(st: _Switch) -> Optional[ModelSwitchResult] | boo
cfg_matches = _configured_provider_matches(st.new_model, st.user_providers, st.custom_providers)
if not cfg_matches:
return False
- if st.current_provider in cfg_matches:
- st.new_model = cfg_matches[st.current_provider]
+ current_slug = _current_provider_match(st, cfg_matches)
+ if current_slug is not None:
+ st.new_model = cfg_matches[current_slug]
return True
match_slugs = sorted(cfg_matches)
if len(match_slugs) > 1:
diff --git a/tests/hermes_cli/test_model_switch_configured_provider_routing.py b/tests/hermes_cli/test_model_switch_configured_provider_routing.py
index 323dc7c85ee..0c8657f7901 100644
--- a/tests/hermes_cli/test_model_switch_configured_provider_routing.py
+++ b/tests/hermes_cli/test_model_switch_configured_provider_routing.py
@@ -21,6 +21,8 @@ Hermetic: the model-resolution chain is fully mocked (no network), mirroring
from unittest.mock import patch
+import pytest
+
from hermes_cli.model_switch import switch_model
_ACCEPTED = {"accepted": True, "persist": True, "recognized": True, "message": None}
@@ -156,3 +158,68 @@ def test_distinct_legacy_endpoint_with_same_model_stays_ambiguous():
assert result.success is False
assert "multiple configured providers" in (result.error_message or "")
assert "custom:backup-relay" in result.error_message and "relay" in result.error_message
+
+
+_RELAY = {"name": "relay", "api": "https://relay.example/v1", "key_env": "RELAY_KEY",
+ "default_model": "claude-opus-4-7"}
+_LEGACY_RELAY = {"name": "relay", "base_url": "https://relay.example/v1", "key_env": "RELAY_KEY",
+ "model": "claude-opus-4-7"}
+
+
+def test_legacy_duplicate_of_same_endpoint_collapses_by_identity():
+ """A hand-migrated config that kept the same endpoint under ``providers.relay`` AND as a legacy
+ ``custom_providers`` row (same name, endpoint, credential, protocol) is one provider: ``/model``
+ routes to ``relay`` instead of calling it ambiguous (#112788)."""
+ from hermes_cli.config import get_compatible_custom_providers
+
+ user_providers = {"relay": _RELAY}
+ cfg = {"providers": user_providers, "custom_providers": [_LEGACY_RELAY]}
+ result = _run_switch(
+ raw_input="claude-opus-4-7", current_provider="openrouter", user_providers=user_providers,
+ custom_providers=get_compatible_custom_providers(cfg))
+ assert result.success is True, result.error_message
+ assert result.target_provider == "relay"
+
+
+ {"key_env": "OTHER_KEY"}, {"api_mode": "anthropic_messages"}, {"base_url": "https://backup.example/v1"},
+], ids=["credential", "protocol", "endpoint"])
+def test_same_named_legacy_row_with_different_identity_stays_ambiguous(delta):
+ """Identity collapse is exact: a legacy row sharing the display name but differing in credential,
+ wire protocol or endpoint is still a second candidate (#112788 acceptance criterion)."""
+ from hermes_cli.config import get_compatible_custom_providers
+
+ user_providers = {"relay": _RELAY}
+ cfg = {"providers": user_providers, "custom_providers": [{**_LEGACY_RELAY, **delta}]}
+ result = _run_switch(
+ raw_input="claude-opus-4-7", current_provider="openrouter", user_providers=user_providers,
+ custom_providers=get_compatible_custom_providers(cfg))
+ assert result.success is False
+ assert "multiple configured providers" in (result.error_message or "")
+
+
+def test_session_on_projection_slug_keeps_its_slug():
+ """A session whose current provider is the compat projection slug ``custom:relay`` switching to
+ a model ``providers.relay`` declares stays on ``custom:relay`` — same provider, no flip (#112788)."""
+ from hermes_cli.config import get_compatible_custom_providers
+
+ user_providers = {"relay": _RELAY}
+ result = _run_switch(
+ raw_input="claude-opus-4-7", current_provider="custom:relay", user_providers=user_providers,
+ custom_providers=get_compatible_custom_providers({"providers": user_providers}))
+ assert result.success is True, result.error_message
+ assert result.target_provider == "custom:relay"
+
+
+def test_raw_list_provider_key_pointing_elsewhere_stays_ambiguous():
+ """Raw-list fallback (callers pass ``cfg['custom_providers']`` verbatim when the compat view
+ fails): a hand-written entry whose ``provider_key`` names a ``providers`` slug but points at a
+ different endpoint is a distinct candidate, not silently hidden (#112788)."""
+ user_providers = {"relay": _RELAY}
+ raw = [{"name": "relay", "provider_key": "relay", "base_url": "https://backup.example/v1",
+ "key_env": "BACKUP_KEY", "model": "claude-opus-4-7"}]
+ result = _run_switch(
+ raw_input="claude-opus-4-7", current_provider="openrouter", user_providers=user_providers,
+ custom_providers=raw)
+ assert result.success is False
+ assert "multiple configured providers" in (result.error_message or "")