The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(nous): read the org model policy and expose it as a list filter
Mariano Nicolinic248d5356c38
diff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex cc2ba908b87..c1f7d580f1a 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -2604,6 +2604,74 @@ def _resolve_nous_pricing_credentials() -> tuple[str, str]:return (api_key, base_url)+def nous_policy_allowed_ids(*, force_refresh: bool = False) -> Optional[set[str]]:+ """The Nous model ids the caller's org may reach, or ``None`` to not filter.++ The gateway filters ``GET /v1/models`` by the org's model policy for an+ authenticated read, omitting blocked rows with no marker field, so the keys+ of the authenticated pricing response are the reachable set. This reuses+ that response rather than issuing a second round trip.++ Returns ``None`` — meaning "leave the caller's list alone" — in three cases,+ each of which would otherwise narrow a list on evidence that cannot support+ it:++ * the org carries no policy, or the token is too old to say (see+ :func:`~hermes_cli.nous_account.nous_policy_present`). Filtering an+ unrestricted org's list buys nothing and risks dropping a model the+ Portal recommends before the gateway catalog lists it.+ * credential resolution failed, so the read is anonymous and therefore+ unfiltered. A full catalog must not be mistaken for a policy-filtered one.+ * the read came back empty, which is a fetch failure rather than an org+ that may reach nothing.+ """+ try:+ from hermes_cli.nous_account import nous_policy_present++ if nous_policy_present() is not True:+ return None+ except Exception:+ return None++ api_key, base_url = _resolve_nous_pricing_credentials()+ if not api_key or not base_url:+ return None++ # Same arguments as get_pricing_for_provider's nous branch, so a caller+ # that also asks for pricing shares this cache entry instead of paying for+ # a second request.+ pricing = fetch_models_with_pricing(+ api_key=api_key,+ base_url=base_url,+ force_refresh=force_refresh,+ include_sale_original=True,+ )+ return set(pricing) or None+++def restrict_to_nous_policy(+ model_ids: list[str], allowed: Optional[set[str]]+) -> list[str]:+ """*model_ids* narrowed to *allowed*, preserving the caller's order.++ A ``None`` or empty *allowed* leaves the list untouched — see+ :func:`nous_policy_allowed_ids` for when that happens.++ A ``:free`` sibling is kept when its base model is reachable. The gateway+ admits a row when any of its requestable ids passes, and treats anything+ unknown as a keep on the grounds that over-listing costs a 403 from the+ authoritative gate while hiding a row the gate would serve is unrecoverable+ from the client. This mirrors that.+ """+ if not allowed:+ return list(model_ids)+ return [+ mid+ for mid in model_ids+ if mid in allowed or mid.split(":", 1)[0] in allowed+ ]++def get_pricing_for_provider(provider: str, *, force_refresh: bool = False) -> dict[str, dict[str, str]]:"""Return live pricing for providers that support it (openrouter, nous, ai-gateway, novita)."""normalized = normalize_provider(provider)diff --git a/hermes_cli/nous_account.py b/hermes_cli/nous_account.pyindex 654487e684d..4c3bf0a51f7 100644--- a/hermes_cli/nous_account.py+++ b/hermes_cli/nous_account.py@@ -99,6 +99,7 @@ class NousPortalAccountInfo:subscription: Optional[NousPortalSubscriptionInfo] = Nonepaid_service_access: Optional[bool] = Nonepaid_service_access_info: Optional[NousPaidServiceAccessInfo] = None+ policy_present: Optional[bool] = Nonetool_access: Optional[NousToolAccessInfo] = Noneraw_claims: Optional[dict[str, Any]] = Noneraw_account: Optional[dict[str, Any]] = None@@ -396,6 +397,36 @@ def get_nous_portal_account_info()+def nous_policy_present() -> Optional[bool]:+ """Whether the caller's org carries a restrictive model/provider policy.++ Read from the ``policy_present`` claim on the Nous OAuth access token, so+ this costs no request. ``/api/oauth/account`` does not carry the claim,+ which is why this reads the token directly rather than going through+ :func:`get_nous_portal_account_info`.++ ``None`` means unknown — an older mint, an unreadable token, or a+ non-boolean claim. Unknown is NOT "no policy": callers must not report the+ absence of the claim as the absence of a restriction.++ The claim is stamped at mint time, so it goes stale until the next token+ refresh.+ """+ try:+ from hermes_cli.auth import get_provider_auth_state, _decode_jwt_claims++ state = get_provider_auth_state("nous") or {}+ access_token = state.get("access_token")+ if not isinstance(access_token, str) or not access_token.strip():+ return None+ claims = _decode_jwt_claims(access_token)+ if not claims:+ return None+ return _coerce_bool(claims.get("policy_present"))+ except Exception:+ return None++def _fresh_account_info(*,state: dict[str, Any],@@ -642,6 +673,7 @@ def _info_from_valid_jwt(expires_at=datetime.fromtimestamp(exp, tz=timezone.utc),paid_service_access=paid_access,paid_service_access_info=access_info,+ policy_present=_coerce_bool(claims.get("policy_present")),tool_access=_tool_access_from_value(claims.get("tool_access")),raw_claims=dict(claims),)diff --git a/tests/hermes_cli/test_nous_policy_filter.py b/tests/hermes_cli/test_nous_policy_filter.pynew file mode 100644index 00000000000..a225d560dc5--- /dev/null+++ b/tests/hermes_cli/test_nous_policy_filter.py@@ -0,0 +1,159 @@+"""Narrowing the Nous model lists to an org's policy.++The inference gateway omits policy-blocked rows from an authenticated+``GET /v1/models`` with no marker field, so the keys of the authenticated+catalog read are the reachable set. These helpers turn that into a filter the+pickers can apply without a second round trip, and — just as importantly —+decline to filter when the evidence cannot support it.+"""++from __future__ import annotations++import base64+import json++import pytest++import hermes_cli.models as models_mod+import hermes_cli.nous_account as account_mod+from hermes_cli.models import nous_policy_allowed_ids, restrict_to_nous_policy+from hermes_cli.nous_account import nous_policy_present+++def _jwt(claims: dict) -> str:+ def seg(obj):+ raw = json.dumps(obj).encode()+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()++ return f"{seg({'alg': 'RS256'})}.{seg(claims)}.sig"+++class TestRestrictToNousPolicy:+ def test_none_leaves_the_list_untouched(self):+ ids = ["a/one", "b/two"]+ assert restrict_to_nous_policy(ids, None) == ids++ def test_empty_set_leaves_the_list_untouched(self):+ """Empty is a failed read, not an org that may reach nothing."""+ ids = ["a/one", "b/two"]+ assert restrict_to_nous_policy(ids, set()) == ids++ def test_drops_ids_outside_the_policy(self):+ assert restrict_to_nous_policy(+ ["a/one", "b/two", "c/three"], {"a/one", "c/three"}+ ) == ["a/one", "c/three"]++ def test_preserves_curated_order(self):+ """The pickers show a curated order deliberately; filtering must not+ reorder it into the catalog's alphabetical order."""+ curated = ["z/last", "a/first", "m/middle"]+ allowed = {"a/first", "m/middle", "z/last"}+ assert restrict_to_nous_policy(curated, allowed) == curated++ def test_keeps_a_free_sibling_when_its_base_is_reachable(self):+ """Portal free recommendations are ``:free`` ids; the gateway admits a+ row when any of its requestable ids passes."""+ assert restrict_to_nous_policy(["vendor/model:free"], {"vendor/model"}) == [+ "vendor/model:free"+ ]++ def test_keeps_a_free_id_listed_in_its_own_right(self):+ assert restrict_to_nous_policy(+ ["vendor/model:free"], {"vendor/model:free"}+ ) == ["vendor/model:free"]++ def test_drops_a_free_sibling_whose_base_is_blocked(self):+ assert restrict_to_nous_policy(["vendor/model:free"], {"other/model"}) == []+++class TestNousPolicyAllowedIds:+ @pytest.fixture(autouse=True)+ def _clear_cache(self):+ models_mod._pricing_cache.clear()+ models_mod._pricing_cache_retry_after.clear()+ yield+ models_mod._pricing_cache.clear()+ models_mod._pricing_cache_retry_after.clear()++ def _patch(self, monkeypatch, *, policy_present, api_key="sk-test", pricing=None):+ calls = []+ monkeypatch.setattr(+ account_mod, "nous_policy_present", lambda: policy_present+ )+ monkeypatch.setattr(+ models_mod,+ "_resolve_nous_pricing_credentials",+ lambda: (api_key, "https://inference.example.com"),+ )++ def _fake_fetch(**kwargs):+ calls.append(kwargs)+ return pricing if pricing is not None else {}++ monkeypatch.setattr(models_mod, "fetch_models_with_pricing", _fake_fetch)+ return calls++ def test_returns_the_authenticated_catalog_keys(self, monkeypatch):+ calls = self._patch(+ monkeypatch,+ policy_present=True,+ pricing={"a/one": {}, "b/two": {}},+ )+ assert nous_policy_allowed_ids() == {"a/one", "b/two"}+ assert len(calls) == 1+ assert calls[0]["api_key"] == "sk-test"++ def test_declines_to_filter_an_unrestricted_org(self, monkeypatch):+ calls = self._patch(monkeypatch, policy_present=False, pricing={"a/one": {}})+ assert nous_policy_allowed_ids() is None+ assert calls == [], "an unrestricted org should not pay for the read"++ def test_declines_to_filter_when_the_claim_is_unknown(self, monkeypatch):+ """Absent is an older mint, not an unrestricted org."""+ calls = self._patch(monkeypatch, policy_present=None, pricing={"a/one": {}})+ assert nous_policy_allowed_ids() is None+ assert calls == []++ def test_declines_to_filter_on_an_anonymous_read(self, monkeypatch):+ """An anonymous read returns the full catalog; treating it as the+ policy-filtered set would silently widen the list to everything."""+ self._patch(monkeypatch, policy_present=True, api_key="", pricing={"a/one": {}})+ assert nous_policy_allowed_ids() is None++ def test_declines_to_filter_on_an_empty_read(self, monkeypatch):+ """A failed fetch must not read as an org that may reach nothing."""+ self._patch(monkeypatch, policy_present=True, pricing={})+ assert nous_policy_allowed_ids() is None+++class TestNousPolicyPresent:+ def _patch_token(self, monkeypatch, token):+ import hermes_cli.auth as auth_mod++ monkeypatch.setattr(+ auth_mod,+ "get_provider_auth_state",+ lambda _p: {"access_token": token} if token is not None else {},+ )++ @pytest.mark.parametrize("claim,expected", [(True, True), (False, False)])+ def test_reads_the_claim(self, monkeypatch, claim, expected):+ self._patch_token(monkeypatch, _jwt({"policy_present": claim}))+ assert nous_policy_present() is expected++ def test_absent_claim_is_unknown_not_false(self, monkeypatch):+ self._patch_token(monkeypatch, _jwt({"org_id": "org_1"}))+ assert nous_policy_present() is None++ def test_non_boolean_claim_is_unknown(self, monkeypatch):+ """The gateway refuses to read a corrupt claim as "no policy"."""+ self._patch_token(monkeypatch, _jwt({"policy_present": "yes"}))+ assert nous_policy_present() is None++ def test_no_token_is_unknown(self, monkeypatch):+ self._patch_token(monkeypatch, None)+ assert nous_policy_present() is None++ def test_undecodable_token_is_unknown(self, monkeypatch):+ self._patch_token(monkeypatch, "not-a-jwt")+ assert nous_policy_present() is None