The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(pricing): verify custom upstream identity
KoNit-Kddc8c2dcb639
diff --git a/hermes_cli/inventory.py b/hermes_cli/inventory.pyindex 6c6740beaad..e59d29ca71d 100644--- a/hermes_cli/inventory.py+++ b/hermes_cli/inventory.py@@ -637,6 +637,8 @@ def _apply_pricing(rows: list[dict], *, force_fresh_nous_tier: bool = False, caccontinuetry:pricing_kwargs = {"cached_only": True} if cached_only else {}+ if slug.startswith("custom:"):+ pricing_kwargs["base_url"] = str(row.get("api_url") or "")raw_pricing = get_pricing_for_provider(slug, **pricing_kwargs) or {}except Exception:raw_pricing = {}@@ -741,10 +743,18 @@ def _prewarm_pricing_async(from hermes_constants import hermes_home_keyfrom hermes_cli.models_pricing import pricing_cache_scope- slugs = {str(row.get("slug") or "").lower() for row in rows if row.get("slug")}+ slugs = {+ (+ str(row.get("slug") or "").lower(),+ str(row.get("api_url") or "") if str(row.get("slug") or "").lower().startswith("custom:") else "",+ )+ for row in rows if row.get("slug")+ }endpoint_scope = tuple(sorted(- (slug, pricing_cache_scope(slug, current_provider=current_provider, current_base_url=current_base_url))- for slug in slugs))+ (slug, pricing_cache_scope(+ slug, base_url=base_url, current_provider=current_provider, current_base_url=current_base_url,+ ))+ for slug, base_url in slugs))prewarm_key = (hermes_home_key(), endpoint_scope)with _pricing_prewarm_lock:diff --git a/hermes_cli/models_pricing.py b/hermes_cli/models_pricing.pyindex 3fc8432ee1d..98c1c5a5f42 100644--- a/hermes_cli/models_pricing.py+++ b/hermes_cli/models_pricing.py@@ -456,12 +456,46 @@ _STATIC_PRICING_SCOPES = {}-def pricing_cache_scope(provider: str, *, current_provider: str = "", current_base_url: str = "") -> str:+def resolve_pricing_provider(provider: str, *, base_url: str = "") -> str:+ """Return the canonical pricing source for a provider, or ``""`` when unproven.++ A ``custom:<name>`` inventory slug identifies a user configuration entry, not its upstream.+ It can deliberately shadow a canonical name while pointing at a proxy, so custom entries may+ use pricing only when their concrete endpoint is recognized as that canonical upstream.+ """+ from hermes_cli.models import normalize_provider++ normalized = normalize_provider(provider)+ if not normalized.startswith("custom:"):+ return normalized+ if not base_url:+ return ""+ try:+ from agent.model_metadata import _URL_TO_PROVIDER, _infer_provider_from_url+ from utils import base_url_host_matches++ inferred = _infer_provider_from_url(base_url)+ except Exception:+ return ""+ # ``_infer_provider_from_url`` is deliberately broad for user-facing hints. Pricing is a+ # trust boundary: require an exact official hostname (or one of its explicit subdomains),+ # never a mere substring such as ``openrouter.ai.attacker.invalid``.+ if not inferred or not any(+ provider == inferred and not host.startswith(".") and base_url_host_matches(base_url, host)+ for host, provider in _URL_TO_PROVIDER.items()+ ):+ return ""+ return normalize_provider(inferred)+++def pricing_cache_scope(+ provider: str, *, base_url: str = "", current_provider: str = "", current_base_url: str = ""+) -> str:"""The current endpoint identity a provider's pricing cache is keyed on. Resolves local configurationonly, never fetches: picker prewarm single-flight uses it so an endpoint rotation can start a newworker while the previous endpoint is still slow or unreachable."""from hermes_cli.models import _deepinfra_catalog_url, _pricing_profile_key, normalize_provider- normalized = normalize_provider(provider).removeprefix("custom:")+ normalized = resolve_pricing_provider(provider, base_url=base_url)static = _STATIC_PRICING_SCOPES.get(normalized)if static:return static()@@ -498,17 +532,13 @@ def _cached_only_pricing(normalized: str) -> dict[str, dict[str, str]]:def get_pricing_for_provider(- provider: str, *, force_refresh: bool = False, cached_only: bool = False+ provider: str, *, base_url: str = "", force_refresh: bool = False, cached_only: bool = False) -> dict[str, dict[str, str]]:"""Return live pricing for providers that support it (openrouter, nous, ai-gateway, novita,deepinfra, fireworks); ``{}`` for everything else. ``cached_only`` never starts provider I/O:normal picker opens use it so cold endpoints cannot hold the response path, while a backgroundprewarm fills the same caches for later opens."""- from hermes_cli.models import normalize_provider- # Config-defined providers use ``custom:<key>`` inventory slugs. When a- # key names a provider with a canonical pricing source, share that source- # (and its cache) rather than treating the configured row as unsupported.- normalized = normalize_provider(provider).removeprefix("custom:")+ normalized = resolve_pricing_provider(provider, base_url=base_url)if cached_only:return _cached_only_pricing(normalized)fetcher = _PRICING_FETCHERS.get(normalized)diff --git a/tests/hermes_cli/test_inventory_pricing.py b/tests/hermes_cli/test_inventory_pricing.pyindex e6dd06962f3..e2a4414f194 100644--- a/tests/hermes_cli/test_inventory_pricing.py+++ b/tests/hermes_cli/test_inventory_pricing.py@@ -8,6 +8,8 @@ same way the `hermes model` CLI picker does.from threading import Eventfrom time import monotonic+import pytest+import hermes_cli.inventory as invimport hermes_cli.models as models_modfrom hermes_cli import models_pricing@@ -436,8 +438,8 @@ def test_cached_only_pricing_returns_a_warm_value_without_fetching(monkeypatch):) == expected-def test_custom_provider_slug_reuses_canonical_pricing_source(monkeypatch):- """A configured OpenRouter row keeps both its live and warmed prices."""+def test_custom_provider_with_proven_upstream_reuses_canonical_pricing_source(monkeypatch):+ """A custom row borrows a priced source only when its endpoint proves that source."""expected = {"vendor/model": {"prompt": "0.000001", "completion": "0.000002"}}fetch_calls = []@@ -453,16 +455,119 @@ def test_custom_provider_slug_reuses_canonical_pricing_source(monkeypatch):lambda provider: cached_calls.append(provider) or expected,)- assert models_pricing.get_pricing_for_provider("custom:openrouter") == expected+ assert models_pricing.get_pricing_for_provider(+ "custom:openrouter", base_url="https://openrouter.ai/api/v1"+ ) == expectedassert fetch_calls == [False]- assert models_pricing.get_pricing_for_provider("custom:openrouter", cached_only=True) == expected+ assert models_pricing.get_pricing_for_provider(+ "custom:unrelated-name", base_url="https://openrouter.ai/api/v1", cached_only=True+ ) == expectedassert cached_calls == ["openrouter"]assert (- models_pricing.pricing_cache_scope("custom:openrouter")+ models_pricing.pricing_cache_scope("custom:unrelated-name", base_url="https://openrouter.ai/api/v1")== models_pricing.pricing_cache_scope("openrouter"))+def test_custom_provider_pricing_fails_closed_without_a_proven_upstream(monkeypatch):+ """A shadowed canonical slug or empty suffix never leaks canonical prices to a proxy."""+ monkeypatch.setitem(+ models_pricing._PRICING_FETCHERS,+ "openrouter",+ lambda **_kwargs: (_ for _ in ()).throw(AssertionError("custom proxy fetched OpenRouter pricing")),+ )+ monkeypatch.setattr(models_pricing, "_cached_only_pricing",+ lambda _provider: (_ for _ in ()).throw(AssertionError("custom proxy read canonical cache")),+ )++ assert models_pricing.get_pricing_for_provider(+ "custom:openrouter", base_url="https://proxy.example/v1"+ ) == {}+ assert models_pricing.get_pricing_for_provider("custom:") == {}+ assert models_pricing.pricing_cache_scope("custom:openrouter", base_url="https://proxy.example/v1") == ""++[email protected]("base_url", [+ "https://openrouter.ai.attacker.invalid/v1",+ "https://not-openrouter.ai/v1",+ "https://ai-gateway.vercel.sh.attacker.invalid/v1",+])+def test_custom_provider_pricing_rejects_lookalike_upstream_hosts(monkeypatch, base_url):+ """A hostname merely containing a priced provider's hostname is still an untrusted proxy."""+ monkeypatch.setitem(+ models_pricing._PRICING_FETCHERS,+ "openrouter",+ lambda **_kwargs: (_ for _ in ()).throw(AssertionError("lookalike host fetched OpenRouter pricing")),+ )++ assert models_pricing.get_pricing_for_provider(+ "custom:any-name", base_url=base_url+ ) == {}+++def test_custom_provider_alias_uses_proven_canonical_upstream(monkeypatch):+ """A Vercel-named row on the real AI Gateway uses its canonical pricing cache."""+ expected = {"vendor/model": {"prompt": "0.000001", "completion": "0.000002"}}+ monkeypatch.setattr(models_pricing, "_cached_only_pricing", lambda provider: expected if provider == "ai-gateway" else {})++ assert models_pricing.get_pricing_for_provider(+ "custom:vercel", base_url="https://ai-gateway.vercel.sh/v1", cached_only=True+ ) == expected+ assert (+ models_pricing.pricing_cache_scope("custom:vercel", base_url="https://ai-gateway.vercel.sh/v1")+ == models_pricing.pricing_cache_scope("ai-gateway")+ )+++def test_apply_pricing_uses_custom_row_endpoint_identity(monkeypatch):+ """The picker prices an actual OpenRouter row but leaves a canonical-named proxy unpriced."""+ expected = {"vendor/model": {"prompt": "0.000003", "completion": "0.000015"}}+ calls = []++ def pricing(provider, **kwargs):+ calls.append((provider, kwargs))+ return expected if kwargs.get("base_url") == "https://openrouter.ai/api/v1" else {}++ monkeypatch.setattr(models_pricing, "get_pricing_for_provider", pricing)+ rows = [+ {"slug": "custom:openrouter", "api_url": "https://openrouter.ai/api/v1", "models": ["vendor/model"]},+ {"slug": "custom:openrouter", "api_url": "https://proxy.example/v1", "models": ["vendor/model"]},+ ]++ inv._apply_pricing(rows, cached_only=True)++ assert rows[0]["pricing"]["vendor/model"] == {+ "input": "$3.00", "output": "$15.00", "cache": None, "free": False,+ }+ assert "pricing" not in rows[1]+ assert calls == [+ ("custom:openrouter", {"base_url": "https://openrouter.ai/api/v1", "cached_only": True}),+ ("custom:openrouter", {"base_url": "https://proxy.example/v1", "cached_only": True}),+ ]+++def test_prewarm_cache_scope_uses_custom_row_endpoint_identity(monkeypatch):+ """Prewarm resolves a custom row with the same endpoint evidence as pricing lookup."""+ observed = []+ monkeypatch.setattr(inv, "_pricing_prewarm_threads", {})+ monkeypatch.setattr(+ models_pricing,+ "pricing_cache_scope",+ lambda provider, **kwargs: observed.append((provider, kwargs)) or "openrouter-scope",+ )+ monkeypatch.setattr(inv, "_apply_pricing", lambda _rows: None)++ thread = inv._prewarm_pricing_async([+ {"slug": "custom:unrelated-name", "api_url": "https://openrouter.ai/api/v1", "models": ["vendor/model"]},+ ])+ thread.join(timeout=2)++ assert observed == [(+ "custom:unrelated-name",+ {"base_url": "https://openrouter.ai/api/v1", "current_provider": "", "current_base_url": ""},+ )]++def test_cached_only_dynamic_pricing_is_profile_scoped(tmp_path, monkeypatch):"""Alternating profiles read the endpoint each profile warmed."""from hermes_constants import (