The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(auth): purge silent OpenRouter paid-default adoption (#81952 class fix)
Teknium51609a35f63b
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex e82fa4c71e5..cbaf0a74c9d 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -1334,8 +1334,15 @@ NOUS_EXTRA_BODY = _nous_extra_body()# Set at resolve time — True if the auxiliary client points to Nous Portalauxiliary_is_nous: bool = False-# Default auxiliary models per provider-_OPENROUTER_MODEL = "google/gemini-3.6-flash"+# Default auxiliary models per provider.+# _OPENROUTER_MODEL is the BUILT-IN fallback used only when the user never set+# auxiliary.openrouter_model — it MUST be a :free SKU: this lane engages+# silently (auxiliary tasks, no user prompt), and a paid built-in default here+# meant silent real OpenRouter spend the user never opted into (#81952). The+# SKU matches the one the free_only warning below recommends. User-configured+# auxiliary.openrouter_model values are honored untouched (paid allowed when+# the user chose it; _warn_paid_lane_once still fires for that case).+_OPENROUTER_MODEL = "nvidia/nemotron-3-ultra-550b-a55b:free"_NOUS_MODEL = "google/gemini-3.6-flash"_NOUS_DEFAULT_BASE_URL = "https://inference-api.nousresearch.com/v1"_ANTHROPIC_DEFAULT_BASE_URL = "https://api.anthropic.com"diff --git a/agent/credential_pool.py b/agent/credential_pool.pyindex 8eca1740a55..93ed82f8925 100644--- a/agent/credential_pool.py+++ b/agent/credential_pool.py@@ -3265,6 +3265,35 @@ def get_env_prefer_dotenv(key: str) -> str:return raw or scoped_value+# Providers we've already warned about env-key → pool ingestion for, once per+# process. See _warn_env_ingestion_once (#81952 expected-behavior #3).+_ENV_INGESTION_WARNED: Set[str] = set()+++def _warn_env_ingestion_once(provider: str, env_var: str) -> None:+ """WARN (once per process per provider) when an env credential is newly+ ingested into a paid provider's pool.++ Auto-ingesting OPENROUTER_API_KEY is what ARMS silent OpenRouter spend —+ every downstream auto-detect (resolve_provider pool probe, aux fallback)+ keys off the pool having credentials. Ingestion itself stays allowed (the+ user exported the key = arguable intent, per #81952), but it must never be+ silent.+ """+ if provider in _ENV_INGESTION_WARNED:+ return+ _ENV_INGESTION_WARNED.add(provider)+ logger.warning(+ "Ingested %s from environment into the %s credential pool — this "+ "enables %s spend. Remove the key or run "+ "hermes auth remove %s <n> to suppress.",+ env_var,+ provider,+ "OpenRouter" if provider == "openrouter" else provider,+ provider,+ )++def _seed_from_env(provider: str, entries: List[PooledCredential]) -> Tuple[bool, Set[str]]:changed = Falseactive_sources: Set[str] = set()@@ -3335,7 +3364,7 @@ def _seed_from_env(provider: str, entries: List[PooledCredential]) -> Tuple[boolif _is_source_suppressed(provider, source):return changed, active_sourcesactive_sources.add(source)- changed |= _upsert_entry(+ ingested = _upsert_entry(entries,provider,source,@@ -3346,6 +3375,9 @@ def _seed_from_env(provider: str, entries: List[PooledCredential]) -> Tuple[boolbase_url=OPENROUTER_BASE_URL,),)+ changed |= ingested+ if ingested:+ _warn_env_ingestion_once(provider, "OPENROUTER_API_KEY")return changed, active_sourcespconfig = PROVIDER_REGISTRY.get(provider)diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex 963fe0632c2..d04b28341bd 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -2206,6 +2206,38 @@ def _get_config_hint_for_unknown_provider(provider_name: str) -> str:return ""+def _refuse_env_adoption_if_config_corrupt() -> None:+ """Refuse env-key/pool auto-adoption of openrouter while config.yaml is corrupt.++ When ``~/.hermes/config.yaml`` EXISTS but fails to parse, ``load_config()``+ falls back to ``DEFAULT_CONFIG`` — so the tier-2 config check above finds+ no ``model.provider`` and the env-var sniff / pool probe silently adopts+ the PAID openrouter provider, even though the user's real (broken) config+ may name a completely different provider (e.g. ``openai-codex``). That is+ silent real-money spend against the user's actual intent (#81952).++ This probe fires ONLY on the auto path — explicitly requested providers+ never reach it — and clears itself as soon as the file changes (a fixed+ config resolves normally on the next call).+ """+ try:+ from hermes_cli.config import get_active_config_parse_failure, get_config_path++ err = get_active_config_parse_failure()+ if not err:+ return+ path = get_config_path()+ except Exception as e:+ logger.debug("Could not probe config parse-failure state: %s", e)+ return+ raise AuthError(+ f"config.yaml at {path} is corrupt ({err}) — refusing to auto-select "+ f"an inference provider from environment keys. Fix the YAML (a backup "+ f"was saved next to it) or run hermes setup.",+ code="corrupt_config",+ )++def resolve_provider(requested: Optional[str] = None,*,@@ -2344,6 +2376,7 @@ def resolve_provider(if has_usable_secret(_scoped_key_env("OPENAI_API_KEY")) or has_usable_secret(_scoped_key_env("OPENROUTER_API_KEY")):+ _refuse_env_adoption_if_config_corrupt()return "openrouter"# Auto-detect an OpenRouter credential added via `hermes auth add openrouter`@@ -2356,10 +2389,13 @@ def resolve_provider(try:from agent.credential_pool import load_pool as _load_pool- if _load_pool("openrouter").has_credentials():- return "openrouter"+ _pool_has_creds = _load_pool("openrouter").has_credentials()except Exception as e:+ _pool_has_creds = Falselogger.debug("Could not check OpenRouter credential pool: %s", e)+ if _pool_has_creds:+ _refuse_env_adoption_if_config_corrupt()+ return "openrouter"# Determine the logged-in OAuth provider up front so the env-key loop below# can WARN when an exported API key preempts it (#29285 transparency). Thediff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 3f55f782317..a3c934d0506 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -44,6 +44,14 @@ logger = logging.getLogger(__name__)# every time. Cleared automatically when the file changes (different mtime)._CONFIG_PARSE_WARNED: set = set()+# Parallel record of active parse failures keyed by path -> (mtime_ns, size,+# error message). Written by _warn_config_parse_failure() (the single funnel+# every load-path parse failure goes through) and probed by+# get_active_config_parse_failure() so provider auto-resolution can refuse to+# adopt a paid provider from environment keys while the user's REAL config —+# which may name a completely different provider — is unreadable (#81952).+_CONFIG_PARSE_FAILURES: dict = {}+class InvalidUserConfigError(RuntimeError):"""Raised when a run that cannot repair config finds invalid user YAML."""@@ -131,6 +139,11 @@ def _warn_config_parse_failure(try:st = config_path.stat()key = (str(config_path), st.st_mtime_ns, st.st_size)+ _CONFIG_PARSE_FAILURES[str(config_path)] = (+ st.st_mtime_ns,+ st.st_size,+ str(exc),+ )except OSError:key = (str(config_path), 0, 0)if key in _CONFIG_PARSE_WARNED:@@ -167,6 +180,37 @@ def _warn_config_parse_failure(except Exception:pass++def get_active_config_parse_failure() -> Optional[str]:+ """Return the parse-error message if the ACTIVE config.yaml is corrupt.++ Probes the failure record written by :func:`_warn_config_parse_failure`+ for the current :func:`get_config_path` and re-stats the file NOW: the+ recorded error is returned only while the file is byte-identical+ (mtime_ns + size) to the one that failed to parse. The moment the user+ fixes (or deletes) the file, this returns ``None`` without any cache+ invalidation dance.++ Consumers: ``hermes_cli.auth.resolve_provider`` uses this to refuse+ env-key/pool auto-adoption of a paid provider while the user's real+ config — which may name a different provider entirely — is unreadable+ (#81952). Returns ``None`` when no failure was ever recorded, when the+ file changed since the failure, or on any stat error.+ """+ try:+ path = get_config_path()+ recorded = _CONFIG_PARSE_FAILURES.get(str(path))+ if not recorded:+ return None+ mtime_ns, size, err = recorded+ st = path.stat()+ if st.st_mtime_ns == mtime_ns and st.st_size == size:+ return err+ except Exception:+ return None+ return None++_IS_WINDOWS = platform.system() == "Windows"_ENV_VAR_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")diff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.pyindex fecd60a5f7b..bd970dd972d 100644--- a/tests/agent/test_auxiliary_client.py+++ b/tests/agent/test_auxiliary_client.py@@ -993,12 +993,32 @@ class TestOpenRouterPaidLaneGuard:"""Issue #75803: auxiliary auto-chain OpenRouter fallback must beconfigurable and never silently engage a PAID model."""- def test_free_only_skips_paid_default_model(self, monkeypatch):- """free_only=true + default (paid) model → OpenRouter skipped."""+ def test_free_only_allows_builtin_default_model(self, monkeypatch):+ """free_only=true + built-in default → allowed (default is :free now, #81952).++ Before the #81952 purge the built-in default was a PAID SKU and this+ test asserted the free_only gate skipped it. The default itself is now+ a :free model, so the gate passes it; the paid-model gating behavior is+ covered by test_free_only_skips_paid_configured_model below.+ """monkeypatch.setenv("OPENROUTER_API_KEY", "or-key")with patch("agent.auxiliary_client._select_pool_entry", return_value=(False, None)), \patch("hermes_cli.config.load_config_readonly", return_value={"auxiliary": {"free_only": True}}), \patch("agent.auxiliary_client.OpenAI") as mock_openai:+ mock_client = MagicMock(name="openrouter_client")+ mock_openai.return_value = mock_client+ client, model = _try_openrouter()+ assert client is mock_client+ assert model == _OPENROUTER_MODEL++ def test_free_only_skips_paid_configured_model(self, monkeypatch):+ """free_only=true + user-configured PAID model → OpenRouter skipped."""+ monkeypatch.setenv("OPENROUTER_API_KEY", "or-key")+ with patch("agent.auxiliary_client._select_pool_entry", return_value=(False, None)), \+ patch("hermes_cli.config.load_config_readonly",+ return_value={"auxiliary": {"free_only": True,+ "openrouter_model": "google/gemini-3.6-flash"}}), \+ patch("agent.auxiliary_client.OpenAI") as mock_openai:client, model = _try_openrouter()assert client is Noneassert model is None@@ -1088,30 +1108,36 @@ class TestOpenRouterPaidLaneGuard:assert not any("credentials" in message for message in messages)def test_paid_lane_warns_once(self, monkeypatch, caplog):- """Engaging the default paid model logs a WARNING (once per model)."""+ """Engaging a user-configured PAID model logs a WARNING (once per model).++ (#81952: the BUILT-IN default is a :free SKU now, so the paid lane can+ only engage via an explicit auxiliary.openrouter_model choice.)+ """import loggingfrom agent.auxiliary_client import _paid_lane_warned- _paid_lane_warned.discard(_OPENROUTER_MODEL)+ _paid_model = "google/gemini-3.6-flash"+ _paid_cfg = {"auxiliary": {"openrouter_model": _paid_model}}+ _paid_lane_warned.discard(_paid_model)monkeypatch.setenv("OPENROUTER_API_KEY", "or-key")with patch("agent.auxiliary_client._select_pool_entry", return_value=(False, None)), \- patch("hermes_cli.config.load_config_readonly", return_value={"auxiliary": {}}), \+ patch("hermes_cli.config.load_config_readonly", return_value=_paid_cfg), \patch("agent.auxiliary_client.OpenAI") as mock_openai:mock_client = MagicMock(name="openrouter_client")mock_openai.return_value = mock_clientwith caplog.at_level(logging.WARNING, logger="agent.auxiliary_client"):client, model = _try_openrouter()assert client is mock_client- assert model == _OPENROUTER_MODEL+ assert model == _paid_modelassert any("PAID lane engaged" in r.getMessage() for r in caplog.records)# Second call logs nothing new.with patch("agent.auxiliary_client._select_pool_entry", return_value=(False, None)), \- patch("hermes_cli.config.load_config_readonly", return_value={"auxiliary": {}}), \+ patch("hermes_cli.config.load_config_readonly", return_value=_paid_cfg), \patch("agent.auxiliary_client.OpenAI") as mock_openai:caplog.clear()with caplog.at_level(logging.WARNING, logger="agent.auxiliary_client"):_try_openrouter()assert not any("PAID lane engaged" in r.getMessage() for r in caplog.records)- _paid_lane_warned.discard(_OPENROUTER_MODEL)+ _paid_lane_warned.discard(_paid_model)def test_is_free_model(self):from agent.auxiliary_client import _is_free_modeldiff --git a/tests/agent/test_openrouter_silent_default_purge.py b/tests/agent/test_openrouter_silent_default_purge.pynew file mode 100644index 00000000000..a365473cffb--- /dev/null+++ b/tests/agent/test_openrouter_silent_default_purge.py@@ -0,0 +1,105 @@+"""Regression tests for issue #81952 — aux free default + env-ingestion WARNING.++KILL 2: the auxiliary lane's BUILT-IN OpenRouter fallback model (used only+when the user never set ``auxiliary.openrouter_model``) must be a ``:free``+SKU — the paid ``google/gemini-3.6-flash`` default meant silent real spend on+a lane the user never opted into.++KILL 3: auto-ingesting OPENROUTER_API_KEY from the environment into the+credential pool arms silent spend; it must log a WARNING naming the provider+and env var when a credential is newly ingested.+"""++import logging+import uuid++import pytest+++class TestAuxiliaryOpenrouterDefaultIsFree:+ def test_builtin_openrouter_default_is_free_sku(self):+ from agent import auxiliary_client as ac++ assert ac._is_free_model(ac._OPENROUTER_MODEL), (+ "the built-in auxiliary OpenRouter fallback model must be a :free "+ "SKU — a paid built-in default is silent real spend (#81952)"+ )++ def test_builtin_default_matches_free_only_warning_recommendation(self):+ """The default is the same SKU the free_only warning tells users to set."""+ from agent import auxiliary_client as ac++ assert ac._OPENROUTER_MODEL == "nvidia/nemotron-3-ultra-550b-a55b:free"++ def test_user_configured_model_still_honored(self, monkeypatch):+ """auxiliary.openrouter_model from config wins over the built-in default."""+ from agent import auxiliary_client as ac++ monkeypatch.setattr(+ "hermes_cli.config.load_config_readonly",+ lambda: {"auxiliary": {"openrouter_model": "google/gemini-3.6-flash"}},+ )+ free_only, model = ac._aux_openrouter_settings()+ assert model == "google/gemini-3.6-flash"+++class TestEnvIngestionWarning:+ def _fresh_home(self, tmp_path, monkeypatch, token="sk-or-FAKEINGEST123"):+ home = tmp_path / "hermes"+ home.mkdir(parents=True, exist_ok=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv("OPENROUTER_API_KEY", token)+ return home++ def test_warns_on_new_openrouter_env_ingestion(self, tmp_path, monkeypatch, caplog):+ self._fresh_home(tmp_path, monkeypatch)+ from agent import credential_pool as cp++ monkeypatch.setattr(cp, "_ENV_INGESTION_WARNED", set())+ entries = []+ with caplog.at_level(logging.WARNING, logger=cp.logger.name):+ changed, sources = cp._seed_from_env("openrouter", entries)++ assert changed is True+ assert "env:OPENROUTER_API_KEY" in sources+ warnings = [+ r.getMessage()+ for r in caplog.records+ if r.levelno == logging.WARNING and "Ingested OPENROUTER_API_KEY" in r.getMessage()+ ]+ assert warnings, "expected a WARNING for env->pool openrouter ingestion"+ assert "OpenRouter spend" in warnings[0]+ assert "hermes auth remove openrouter" in warnings[0]++ def test_warning_once_per_process(self, tmp_path, monkeypatch, caplog):+ self._fresh_home(tmp_path, monkeypatch)+ from agent import credential_pool as cp++ monkeypatch.setattr(cp, "_ENV_INGESTION_WARNED", set())+ with caplog.at_level(logging.WARNING, logger=cp.logger.name):+ cp._warn_env_ingestion_once("openrouter", "OPENROUTER_API_KEY")+ cp._warn_env_ingestion_once("openrouter", "OPENROUTER_API_KEY")+ warnings = [+ r+ for r in caplog.records+ if r.levelno == logging.WARNING and "Ingested OPENROUTER_API_KEY" in r.getMessage()+ ]+ assert len(warnings) == 1++ def test_no_warning_when_entry_unchanged(self, tmp_path, monkeypatch, caplog):+ """Re-seeding an already-present, identical credential stays silent."""+ self._fresh_home(tmp_path, monkeypatch)+ from agent import credential_pool as cp++ entries = []+ changed, _ = cp._seed_from_env("openrouter", entries)+ assert changed is True++ monkeypatch.setattr(cp, "_ENV_INGESTION_WARNED", set())+ caplog.clear()+ with caplog.at_level(logging.WARNING, logger=cp.logger.name):+ changed_again, _ = cp._seed_from_env("openrouter", entries)+ assert changed_again is False+ assert not [+ r for r in caplog.records if "Ingested OPENROUTER_API_KEY" in r.getMessage()+ ]diff --git a/tests/hermes_cli/test_resolve_provider_corrupt_config.py b/tests/hermes_cli/test_resolve_provider_corrupt_config.pynew file mode 100644index 00000000000..c0a6841f6bf--- /dev/null+++ b/tests/hermes_cli/test_resolve_provider_corrupt_config.py@@ -0,0 +1,164 @@+"""Regression tests for issue #81952 (silent OpenRouter paid-default class fix).++When ``~/.hermes/config.yaml`` EXISTS but fails to parse, ``load_config()``+falls back to ``DEFAULT_CONFIG`` — so ``resolve_provider('auto')``'s tier-2+config check finds no ``model.provider`` and the tier-3 env sniff+(OPENROUTER_API_KEY / OPENAI_API_KEY) or tier-4 pool probe silently adopts the+PAID openrouter provider, even though the user's real (broken) config may name+a completely different provider (e.g. ``openai-codex``). Real money, zero+consent.++The fix: ``hermes_cli.config`` records active parse failures+(``get_active_config_parse_failure``), and ``resolve_provider`` refuses+env/pool auto-adoption with ``AuthError(code='corrupt_config')`` while the+active config is corrupt. Explicit provider requests and valid-config+env-sniff flows are untouched, and fixing the file in place clears the block.+"""++import uuid++import pytest++[email protected](autouse=True)+def _clean_inference_env(monkeypatch):+ for key in (+ "OPENROUTER_API_KEY",+ "OPENAI_API_KEY",+ "ANTHROPIC_API_KEY",+ "ANTHROPIC_TOKEN",+ "CLAUDE_CODE_OAUTH_TOKEN",+ "NOUS_API_KEY",+ "HERMES_INFERENCE_PROVIDER",+ ):+ monkeypatch.delenv(key, raising=False)+++CORRUPT_YAML = "model:\n provider: openai-codex\n default: gpt-5.5\n broken: [unterminated\n"+VALID_YAML = "gateway:\n enabled: false\n"+++def _setup_home(tmp_path, monkeypatch, config_text):+ home = tmp_path / "hermes"+ home.mkdir(parents=True, exist_ok=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ cfg = home / "config.yaml"+ cfg.write_text(config_text)+ return home, cfg+++def _load_config_fresh():+ """Call load_config so a corrupt file goes through the warn/record funnel."""+ from hermes_cli.config import load_config++ return load_config()+++class TestParseFailureProbe:+ def test_probe_reports_active_corrupt_config(self, tmp_path, monkeypatch):+ _home, _cfg = _setup_home(tmp_path, monkeypatch, CORRUPT_YAML)+ _load_config_fresh()++ from hermes_cli.config import get_active_config_parse_failure++ err = get_active_config_parse_failure()+ assert err, "expected an active parse failure to be reported"++ def test_probe_clears_when_file_fixed_in_place(self, tmp_path, monkeypatch):+ _home, cfg = _setup_home(tmp_path, monkeypatch, CORRUPT_YAML)+ _load_config_fresh()++ from hermes_cli.config import get_active_config_parse_failure++ assert get_active_config_parse_failure()+ cfg.write_text(VALID_YAML) # user fixes the YAML — different size/mtime+ assert get_active_config_parse_failure() is None++ def test_probe_none_for_valid_config(self, tmp_path, monkeypatch):+ _setup_home(tmp_path, monkeypatch, VALID_YAML)+ _load_config_fresh()++ from hermes_cli.config import get_active_config_parse_failure++ assert get_active_config_parse_failure() is None+++class TestResolveProviderCorruptConfig:+ def test_corrupt_config_blocks_env_sniff_adoption(self, tmp_path, monkeypatch):+ """Corrupt config + OPENROUTER_API_KEY must NOT resolve to openrouter."""+ _setup_home(tmp_path, monkeypatch, CORRUPT_YAML)+ monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-FAKE1234567890")+ _load_config_fresh()++ from hermes_cli.auth import AuthError, resolve_provider++ with pytest.raises(AuthError) as excinfo:+ resolve_provider("auto")+ assert excinfo.value.code == "corrupt_config"+ assert "config.yaml" in str(excinfo.value)++ def test_corrupt_config_blocks_pool_probe_adoption(self, tmp_path, monkeypatch):+ """Corrupt config + pool-only credential must NOT resolve to openrouter."""+ _setup_home(tmp_path, monkeypatch, CORRUPT_YAML)+ _load_config_fresh()++ from agent.credential_pool import (+ AUTH_TYPE_API_KEY,+ SOURCE_MANUAL,+ PooledCredential,+ load_pool,+ )++ pool = load_pool("openrouter")+ pool.add_entry(+ PooledCredential(+ provider="openrouter",+ id=uuid.uuid4().hex[:6],+ label="api-key-1",+ auth_type=AUTH_TYPE_API_KEY,+ priority=0,+ source=SOURCE_MANUAL,+ access_token="sk-or-FAKEKEY123",+ base_url="https://openrouter.ai/api/v1",+ )+ )++ from hermes_cli.auth import AuthError, resolve_provider++ with pytest.raises(AuthError) as excinfo:+ resolve_provider("auto")+ assert excinfo.value.code == "corrupt_config"++ def test_valid_config_env_sniff_keep_path_unbroken(self, tmp_path, monkeypatch):+ """KEEP: valid config that names no provider + env key still resolves."""+ _setup_home(tmp_path, monkeypatch, VALID_YAML)+ monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-FAKE1234567890")+ _load_config_fresh()++ from hermes_cli.auth import resolve_provider++ assert resolve_provider("auto") == "openrouter"++ def test_fixed_config_clears_block(self, tmp_path, monkeypatch):+ """Rewriting the corrupt file valid clears the refusal immediately."""+ _home, cfg = _setup_home(tmp_path, monkeypatch, CORRUPT_YAML)+ monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-FAKE1234567890")+ _load_config_fresh()++ from hermes_cli.auth import AuthError, resolve_provider++ with pytest.raises(AuthError):+ resolve_provider("auto")++ cfg.write_text(VALID_YAML)+ assert resolve_provider("auto") == "openrouter"++ def test_explicit_provider_request_untouched(self, tmp_path, monkeypatch):+ """Explicit user intent (requested != auto) resolves even with corrupt config."""+ _setup_home(tmp_path, monkeypatch, CORRUPT_YAML)+ monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-FAKE1234567890")+ _load_config_fresh()++ from hermes_cli.auth import resolve_provider++ assert resolve_provider("openrouter") == "openrouter"