The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(config): provider switch via config set drops the previous provider's route (#113719)
teknium1250e12e760e7
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]new file mode 100644index 00000000000..b35f2866e2f--- /dev/null+++ b/contributors/emails/[email protected]@@ -0,0 +1,2 @@+timrichardson+# PR #47533 co-authordiff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]index 15ead58f930..b335e442ad3 100644--- a/contributors/emails/[email protected]+++ b/contributors/emails/[email protected]@@ -1 +1,2 @@whyyagswhy+# PR #113725 co-authordiff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex b58ad75870e..ed8808dbccc 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -3701,23 +3701,31 @@ def set_config_value(key: str, value: str, force: bool = False):user_config["model"] = {"default": _model_val}key = _guard_section_overwrite(key, value, user_config, force)value = _refuse_container_type_mismatch(key, value, user_config, force)+ _old_provider = _model_val.get("provider") if isinstance(_model_val, dict) else Nonetry:_set_nested(user_config, key, value)except ValueError as e:_exit_invalid(f"✗ {e}")-- # When switching model.provider, clear stale model.base_url so the- # runtime auto-detection resolves the correct endpoint for the new- # provider. Without this, ``hermes config set model.provider deepseek``- # after a wizard run that set base_url to xAI's endpoint leaves config- # in an inconsistent state (provider=deepseek, base_url=https://api.x.ai/v1).- # See: https://github.com/NousResearch/hermes-agent/issues/40862- if key == "model.provider":- model_section = user_config.get("model")- if isinstance(model_section, dict) and "base_url" in model_section:- removed_url = model_section.pop("base_url")- print(f" Cleared stale model.base_url ({removed_url}) — "- "the new provider's endpoint will be resolved automatically.")+ # A provider switch re-points ``model:`` at a new route; ``base_url``/``api_mode`` are route+ # state of the OLD provider, and the runtime honours them for whatever provider the block now+ # names — the new provider's key would be posted to the old endpoint (#113719, #40862). Sync+ # them the way a persisted ``/model`` switch does: the previous route goes unless it is the+ # new provider's own endpoint.+ _route_notice = ""+ _old_provider = str(_old_provider or "").strip() or "the previous provider"+ if key == "model.provider" and _old_provider.lower() != str(value).strip().lower():+ from hermes_cli.route_identity import drop_stale_model_route+ _popped, _unverified = drop_stale_model_route(user_config.get("model"), value, user_config)+ if _popped:+ _route_notice = (+ " Cleared " + ", ".join(f"model.{k} ({v})" for k, v in _popped.items())+ + f" — that route belonged to {_old_provider}, not {value}. {value}'s endpoint resolves "+ "automatically; set model.base_url again if you meant a custom endpoint.")+ elif _unverified:+ _route_notice = color(+ f"⚠ model.base_url ({user_config['model'].get('base_url')}) was set under {_old_provider} and "+ f"still applies to {value} — requests go there. If it is not {value}'s endpoint: "+ "`hermes config unset model.base_url` (and model.api_mode).", Colors.YELLOW)# api_base -> base_url alias at set-time too (mirrors _normalize_root_model_keys).if key.strip().lower() in ("model.api_base", "api_base"):# Normalize the api_base → base_url alias at set-time too (issue #8919), so a fresh `hermes config@@ -3742,6 +3750,8 @@ def set_config_value(key: str, value: str, force: bool = False):from agent.redact import mask_secret_display_value = mask_secret(value)print(f"✓ Set {key} = {_display_value} in {config_path}")+ if _route_notice:+ print(_route_notice)warn_unpinned_cron_jobs_after_model_config_change(key, value, user_config)# Post-write unknown-key notice (#34067): value IS saved, but tell the user the runtime may never readdiff --git a/hermes_cli/route_identity.py b/hermes_cli/route_identity.pyindex 6ada71c1d03..56d3a2e7b33 100644--- a/hermes_cli/route_identity.py+++ b/hermes_cli/route_identity.py@@ -2,7 +2,7 @@from __future__ import annotations-from typing import Any+from typing import Any, Optionalfrom urllib.parse import urlsplit, urlunsplit@@ -44,6 +44,65 @@ def normalize_route_base_url(base_url: Any) -> str:return normalized+def provider_owns_route(provider: Any, base_url: Any, config: Any = None) -> Optional[bool]:+ """Whether ``model.base_url`` is *provider*'s own endpoint.++ ``True``: the host is the provider's registry/plugin endpoint or the endpoint of a+ ``providers:``/``custom_providers:`` entry that resolves to *provider*, or *provider* is bare+ ``custom``/``local`` (the URL *is* the route). ``False``: the host is another known provider's+ stock endpoint, or *provider* names a user entry with a different endpoint. ``None``: unknown+ host (a proxy, a LAN server) — nothing here can say whose it is. Offline: the registry lookup+ never fetches the models.dev catalog.+ """+ from hermes_cli.providers import get_provider, normalize_provider, resolve_custom_provider, resolve_user_provider+ from utils import base_url_hostname++ host = base_url_hostname(str(base_url or ""))+ if not host:+ return None+ raw = str(provider or "").strip().lower()+ canonical = normalize_provider(raw)+ if canonical in ("custom", "local"):+ # Bare custom / local-server aliases are configured BY model.base_url (#14676, #27132);+ # resolve_custom_provider would also self-heal bare "custom" to the first entry (#17478).+ return True+ cfg = config if isinstance(config, dict) else {}+ user_pdef = resolve_user_provider(raw, cfg.get("providers") or {}) or resolve_custom_provider(+ raw, cfg.get("custom_providers"))+ if user_pdef is not None and user_pdef.base_url:+ return base_url_hostname(user_pdef.base_url) == host+ pdef = get_provider(canonical, allow_network=False)+ if pdef is not None and pdef.base_url and base_url_hostname(pdef.base_url) == host:+ return True+ if pdef is None and user_pdef is None:+ return True+ from agent.model_metadata import _infer_provider_from_url+ inferred = _infer_provider_from_url(str(base_url))+ if inferred is None:+ return None+ return normalize_provider(inferred) == canonical+++def drop_stale_model_route(model_cfg: Any, provider: Any, config: Any = None) -> "tuple[dict[str, Any], bool]":+ """Pop the route keys (``base_url``, ``api_mode``) a previous provider left in ``model:``+ when the block is re-pointed at *provider* without a fresh route (``hermes config set+ model.provider``). Mirrors what a persisted ``/model`` switch writes: the route is synced to+ the target, never carried over. Returns ``(popped {key: old value}, unverified)`` where+ ``unverified`` is True when a base_url of unknown ownership was kept — the caller should say so.+ A base_url that belongs to *provider* is kept together with its api_mode; with no base_url the+ api_mode alone is wire state of the old route and goes."""+ if not isinstance(model_cfg, dict):+ return {}, False+ base_url = str(model_cfg.get("base_url") or "").strip()+ owned = provider_owns_route(provider, base_url, config) if base_url else False+ if owned:+ return {}, False+ if owned is None:+ return {}, True+ popped = {k: model_cfg.pop(k) for k in ("base_url", "api_mode") if model_cfg.get(k) not in (None, "")}+ return popped, False++def should_clear_context_pin(configured_model: Any, active_model: Any, configured_base_url: Any, active_base_url: Any,configured_provider: Any, active_provider: Any) -> bool:"""True when a configured ``model.context_length`` pin no longer matches its runtime route.diff --git a/tests/hermes_cli/test_set_config_value.py b/tests/hermes_cli/test_set_config_value.pyindex eaa6862d23e..84a7e8f244c 100644--- a/tests/hermes_cli/test_set_config_value.py+++ b/tests/hermes_cli/test_set_config_value.py@@ -1103,65 +1103,47 @@ class TestContainerTypeRefusal:class TestProviderSwitchClearsBaseUrl:- """When model.provider changes via config set, stale model.base_url- must be cleared so runtime auto-detection resolves the correct endpoint.- See: https://github.com/NousResearch/hermes-agent/issues/40862- """-- def _write_config(self, tmp_path, body):- (tmp_path / "config.yaml").write_text(body)-- def test_switching_provider_clears_base_url(self, _isolated_hermes_home, capsys):- """Switching from xai-oauth to deepseek should remove base_url."""- self._write_config(_isolated_hermes_home, (- "model:\n"- " default: grok-4.3\n"- " provider: xai-oauth\n"- " base_url: https://api.x.ai/v1\n"- ))-- set_config_value("model.provider", "deepseek")-- import yaml- reloaded = yaml.safe_load(_read_config(_isolated_hermes_home))- assert reloaded["model"]["provider"] == "deepseek"- assert "base_url" not in reloaded["model"]- # User gets a message about the cleared URL- captured = capsys.readouterr()- assert "Cleared stale model.base_url" in captured.out- assert "api.x.ai" in captured.out-- def test_switching_provider_no_base_url_is_noop(self, _isolated_hermes_home, capsys):- """If there's no base_url to clear, the switch still works silently."""- self._write_config(_isolated_hermes_home, (- "model:\n"- " default: gpt-4o\n"- " provider: openai\n"- ))-- set_config_value("model.provider", "anthropic")+ """``config set model.provider X`` must not carry the previous provider's route (#113719,+ #40862): a ``base_url``/``api_mode`` that is not X's own endpoint goes, with a notice, so X's+ key is never posted to the old endpoint. A route that IS X's stays."""- import yaml- reloaded = yaml.safe_load(_read_config(_isolated_hermes_home))- assert reloaded["model"]["provider"] == "anthropic"- assert "base_url" not in reloaded["model"]- captured = capsys.readouterr()- assert "Cleared stale" not in captured.out-- def test_non_provider_key_preserves_base_url(self, _isolated_hermes_home):- """Changing model.default should NOT touch base_url."""- self._write_config(_isolated_hermes_home, (- "model:\n"- " default: grok-4.3\n"- " provider: xai-oauth\n"- " base_url: https://api.x.ai/v1\n"- ))+ ROUTE = {"base_url": "https://chatgpt.com/backend-api/codex", "api_mode": "codex_responses"}- set_config_value("model.default", "deepseek-v4-pro")+ def _seed(self, tmp_path, model):+ (tmp_path / "config.yaml").write_text(yaml.safe_dump({+ "model": model,+ "custom_providers": [{"name": "mylab", "base_url": "http://10.0.0.5:8000/v1", "api_key": "k"}]}))- import yaml- reloaded = yaml.safe_load(_read_config(_isolated_hermes_home))- assert reloaded["model"]["default"] == "deepseek-v4-pro"- # base_url must be preserved — only model.default changed- assert reloaded["model"]["base_url"] == "https://api.x.ai/v1"- assert reloaded["model"]["provider"] == "xai-oauth"+ @pytest.mark.parametrize("target, seed_route", [+ ("anthropic", ROUTE), # the reporter's switch: both route keys are stale+ ("mylab", ROUTE), # named custom entry has its own endpoint+ ("anthropic", {"api_mode": "codex_responses"}), # wire mode alone is old-route state+ ])+ def test_switching_provider_clears_foreign_route(self, _isolated_hermes_home, capsys, target, seed_route):+ self._seed(_isolated_hermes_home, {"provider": "opencode-go", "default": "gpt-5.3-codex", **seed_route})+ set_config_value("model.provider", target)+ model = yaml.safe_load(_read_config(_isolated_hermes_home))["model"]+ assert model == {"provider": target, "default": "gpt-5.3-codex"}+ out = capsys.readouterr().out+ assert "Cleared" in out and "opencode-go" in out+ for key, value in seed_route.items():+ assert f"model.{key} ({value})" in out++ @pytest.mark.parametrize("key, target, seed", [+ ("model.default", "gpt-5", {"provider": "opencode-go", **ROUTE}), # not a provider switch+ ("model.provider", "opencode-go", {"provider": "opencode-go", **ROUTE}), # same provider: no-op+ ("model.provider", "openai-codex", {"provider": "opencode-go", **ROUTE}), # route IS the target's+ ("model.provider", "mylab", {"provider": "openai", "base_url": "http://10.0.0.5:8000/v1"}),+ ("model.provider", "custom", {"provider": "openai", "base_url": "https://api.openai.com/v1"}),+ ("model.provider", "anthropic", {"provider": "opencode-go", "base_url": "http://proxy.internal:8080/v1"}),+ ])+ def test_route_that_belongs_to_target_is_kept(self, _isolated_hermes_home, capsys, key, target, seed):+ self._seed(_isolated_hermes_home, {**seed, "default": "m"})+ set_config_value(key, target)+ model = yaml.safe_load(_read_config(_isolated_hermes_home))["model"]+ expected = {**seed, "default": "m", key.split(".", 1)[1]: target}+ assert model == expected+ out = capsys.readouterr().out+ assert "Cleared" not in out+ # Unknown host: kept, but the user is told the old route still applies (from #113725).+ assert ("still applies" in out) == ("proxy.internal" in seed["base_url"])diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex 45f19283fd2..5cd02467341 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -1266,6 +1266,13 @@ Subcommands:| `check` | Check for missing or stale config. || `migrate` | Add newly introduced options interactively. |+`config set model.provider <provider>` keeps the `model:` block on one route: a `model.base_url` /+`model.api_mode` left over from the previous provider is removed (and listed) when it is another+provider's endpoint — otherwise the new provider's key would be posted to the old endpoint and fail+with a credential error naming the wrong provider. A URL that is the new provider's own endpoint, a+named `custom_providers` entry's endpoint, or any URL under `custom`/local aliases stays; an+unrecognised host (a proxy, a LAN server) stays with a warning that it still applies.+### Dots inside key names`hermes config set/get/unset` use `.` as the nesting separator, but many real