The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(free-tier): connectors and managed tools use a connectors-only guest token
Robin Fernandesea45ec393672
diff --git a/hermes_cli/anon_auth.py b/hermes_cli/anon_auth.pyindex d9fe32427ba..186c120868d 100644--- a/hermes_cli/anon_auth.py+++ b/hermes_cli/anon_auth.py@@ -33,7 +33,8 @@ from typing import Any, Callable, Dict, Optionalfrom agent.retry_utils import parse_retry_after_secondsfrom hermes_cli.auth_constants import (- AuthError, DEFAULT_NOUS_PORTAL_URL, DEFAULT_NOUS_WELCOME_URL, _decode_jwt_claims, httpx)+ AuthError, DEFAULT_NOUS_PORTAL_URL, DEFAULT_NOUS_WELCOME_URL, NOUS_INFERENCE_INVOKE_SCOPE, _decode_jwt_claims,+ httpx)logger = logging.getLogger("hermes_cli.auth")@@ -351,8 +352,36 @@ def mint_guest(client: httpx.Client, portal_base_url: str) -> dict[str, Any]:return payload+# ``purpose: "connectors"`` (NAS hermes-portal#1516) mints a JWT whose only scope is+# ``connectors:invoke``: connector routes and the tool gateway accept it, the welcome host refuses it,+# and NAS never puts the free-inference challenge in front of it. A NAS from before #1516 ignores the+# field and answers with an inference token (a superset), so which slot a token fills is read off its+# ``scope`` claim, never off the purpose that asked for it.+def is_connectors_only(token: Any) -> bool:+ """*token* carries a scope claim and it lacks ``inference:invoke`` (a scopeless JWT reads as today's)."""+ from hermes_cli.auth_nous import _scope_values+ claims = _decode_jwt_claims(token)+ scopes = _scope_values(claims.get("scope")) | _scope_values(claims.get("scp"))+ return bool(scopes) and NOUS_INFERENCE_INVOKE_SCOPE not in scopes+++def held_connectors_token(state: Any, *, skew_seconds: Optional[int] = None) -> Optional[str]:+ """The bearer a connectors / managed-tools call sends: the profile's token (for a guest the+ inference one, a superset), else a guest's connectors-only token, preferring one that outlives+ *skew_seconds*. ``None`` also accepts an expiring token (availability probes)."""+ from hermes_cli.auth import _is_expiring+ if not isinstance(state, dict):+ return None+ slots = (state, state.get("connectors_token") if is_guest_state(state) else None)+ held = [(s["access_token"], s.get("expires_at")) for s in slots+ if isinstance(s, dict) and isinstance(s.get("access_token"), str) and s["access_token"]]+ live = next((token for token, exp in held if not _is_expiring(exp, skew_seconds or 0)), None)+ return live or (held[0][0] if held and skew_seconds is None else None)++def exchange_anon_jwt(client: httpx.Client, portal_base_url: str, anon_token: str, *, auth_state: dict[str, Any],+ purpose: str = "inference",) -> dict[str, Any]:"""``POST /api/anonymous/token {token}`` -> ``{access_token, expires_in, inference_base_url, ...}``.@@ -363,7 +392,7 @@ def exchange_anon_jwt(from hermes_cli import anon_challengeresponse = client.post(f"{portal_base_url.rstrip('/')}/api/anonymous/token", headers=_anon_headers(),- json={"token": anon_token, "client": anon_challenge.client_info()})+ json={"token": anon_token, "client": anon_challenge.client_info(), "purpose": purpose})def challenge(body: dict[str, Any]) -> AuthError:return anon_challenge.challenge_error(@@ -385,12 +414,15 @@ def exchange_anon_jwt(if not isinstance(payload.get("access_token"), str) or not payload["access_token"]:logger.info("Nous free tier token exchange returned no token")raise _anon_err(ANON_FAILURE_COPY[ANON_SERVER_ERROR], ANON_SERVER_ERROR)- anon_challenge.note_optional_challenges(payload, portal_base_url)+ # A connectors-only grant must neither clear nor announce an inference challenge.+ if not is_connectors_only(payload["access_token"]):+ anon_challenge.note_optional_challenges(payload, portal_base_url)return payloaddef apply_exchange_to_state(state: dict[str, Any], exchanged: dict[str, Any]) -> None:- """Write a fresh exchange result into a guest state in place (token, expiry, routing)."""+ """Write a fresh exchange result into a guest state in place: an inference token (token, expiry,+ routing) into the state itself, a connectors-only one into ``connectors_token`` beside it."""from hermes_cli.auth_nous import _validate_nous_inference_url_from_networkaccess_token = exchanged["access_token"]claims = _decode_jwt_claims(access_token)@@ -400,6 +432,9 @@ def apply_exchange_to_state(state: dict[str, Any], exchanged: dict[str, Any]) ->expires_at = datetime.fromtimestamp(float(exp), tz=UTC)else:expires_at = now + timedelta(seconds=int(exchanged.get("expires_in") or 900))+ if is_connectors_only(access_token):+ state["connectors_token"] = {"access_token": access_token, "expires_at": expires_at.isoformat()}+ return# NAS names the welcome host on every exchange; absent (older NAS) or outside the allowlist# (a staging host without NOUS_INFERENCE_BASE_URL set), the literal stands in. Never the paid# host: the gateway cross-refuses an anonymous JWT there.@@ -630,8 +665,9 @@ def ensure_portal_identity(return state-def refresh_guest_state(state: dict[str, Any], client: httpx.Client) -> None:- """Token-acquisition seam for a guest: re-exchange the ``anon_`` credential in place.+def refresh_guest_state(state: dict[str, Any], client: httpx.Client, *, purpose: str = "inference") -> str:+ """Token-acquisition seam for a guest: re-exchange the ``anon_`` credential in place and return+ the minted token (``purpose="connectors"`` asks for a connectors-only one).The portal URL is the resolver's canonical one (env override, else the validated stored URL,else the default), never a raw stored value on its own.@@ -642,8 +678,10 @@ def refresh_guest_state(state: dict[str, Any], client: httpx.Client) -> None:if not isinstance(anon_token, str) or not anon_token:raise AnonCredentialDead(ANON_FAILURE_COPY[ANON_CREDENTIAL_DEAD], code=ANON_CREDENTIAL_DEAD)from hermes_cli.auth import _nous_portal_base_url- apply_exchange_to_state(state, exchange_anon_jwt(- client, _nous_portal_base_url(state), anon_token, auth_state=state))+ exchanged = exchange_anon_jwt(+ client, _nous_portal_base_url(state), anon_token, auth_state=state, purpose=purpose)+ apply_exchange_to_state(state, exchanged)+ return exchanged["access_token"]def clear_dead_guest(reason: str, *, dead_token: Optional[str] = None) -> None:diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex e296bbb6235..e7a41d1390e 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -1808,10 +1808,9 @@ def resolve_nous_access_token(insecure: Optional[bool] = None,ca_bundle: Optional[str] = None,refresh_skew_seconds: int = ACCESS_TOKEN_REFRESH_SKEW_SECONDS) -> str:- """Resolve a refresh-aware Nous Portal access token for managed tool gateways.-- A free-tier exchange may be answered with a browser challenge (``anon_challenge``); it is worked- here, after the exchange's locks have unwound, and the exchange is then run once more."""+ """Refresh-aware Nous Portal token for managed tool gateways, connectors and account reads, never+ the free model: a guest gets a live held token, else a connectors-only mint NAS never challenges.+ Only a NAS from before hermes-portal#1516 challenges that mint; it is worked here as before."""from hermes_cli.anon_challenge import run_with_challengereturn run_with_challenge(lambda: _resolve_nous_access_token(timeout_seconds=timeout_seconds, insecure=insecure, ca_bundle=ca_bundle,@@ -1850,20 +1849,17 @@ def _resolve_nous_access_token(lock_timeout = max(timeout_seconds + 5.0, AUTH_LOCK_TIMEOUT_SECONDS)with _nous_shared_store_lock(timeout_seconds=lock_timeout):- from hermes_cli.anon_auth import is_guest_state, refresh_guest_state+ from hermes_cli.anon_auth import held_connectors_token, is_guest_state, refresh_guest_stateif is_guest_state(state):- # Guest seam: the anon_ credential is the identity; a first use has no access token- # yet and an expired one is re-exchanged. No refresh token, no quarantine.- access_token = state.get("access_token")- if isinstance(access_token, str) and access_token and not _is_expiring(- state.get("expires_at"), refresh_skew_seconds):+ # A live held token serves (an inference one is a superset); else mint connectors-only.+ if access_token := held_connectors_token(state, skew_seconds=refresh_skew_seconds):return _memo(access_token)with httpx.Client(timeout=httpx.Timeout(timeout_seconds or 15.0),headers={"Accept": "application/json"}, verify=verify) as client:- refresh_guest_state(state, client)+ minted = refresh_guest_state(state, client, purpose="connectors")persist()_write_shared_nous_state(state)- return _memo(state["access_token"])+ return _memo(minted)merged_shared = _merge_shared_nous_oauth_state(state)access_token = state.get("access_token")diff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex 241c6f3ccd9..5b900144ae3 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -1465,17 +1465,17 @@ def _copilot_catalog(normalized: str, force_refresh: bool) -> Optional[list[str]def _nous_catalog(normalized: str, force_refresh: bool) -> Optional[list[str]]:try:+ from hermes_cli.anon_challenge import background_callerfrom hermes_cli.auth import fetch_nous_models, resolve_nous_runtime_credentials-- creds = resolve_nous_runtime_credentials()+ with background_caller(): # never waits on or opens a challenge+ creds = resolve_nous_runtime_credentials()if creds:live = fetch_nous_models(api_key=creds.get("api_key", ""), inference_base_url=creds.get("base_url", ""))if live:return liveexcept Exception:pass- # Live failed / no creds: the docs-hosted manifest — NOT the in-repo snapshot — so newly added- # Portal models still surface without a Hermes release.+ # Live failed / no creds: the docs-hosted manifest, so new Portal models surface without a release.return get_curated_nous_model_ids() or Nonediff --git a/hermes_cli/models_pricing.py b/hermes_cli/models_pricing.pyindex 57807cbeb98..6a278d8f14e 100644--- a/hermes_cli/models_pricing.py+++ b/hermes_cli/models_pricing.py@@ -315,9 +315,11 @@ def _resolve_nous_pricing_credentials() -> tuple[str, str]:env_base = Noneapi_key = creds_base = ""try:+ from hermes_cli.anon_challenge import background_callerfrom hermes_cli.auth import resolve_nous_runtime_credentials- creds = resolve_nous_runtime_credentials()+ with background_caller(): # a pricing read never opens a free-tier challenge+ creds = resolve_nous_runtime_credentials()if creds:api_key = creds.get("api_key", "") or ""creds_base = (creds.get("base_url", "") or "").strip()diff --git a/hermes_cli/nous_account.py b/hermes_cli/nous_account.pyindex 068867fece0..0e38c06d77c 100644--- a/hermes_cli/nous_account.py+++ b/hermes_cli/nous_account.py@@ -310,7 +310,10 @@ def get_nous_portal_account_info(*, force_fresh: bool = False, min_jwt_ttl_seconexcept Exception as exc:return _error_info(error=exc, logged_in=False)- access_token = state.get("access_token")+ # A guest that has only used connectors holds just a connectors-only token (same claims).+ from hermes_cli.anon_auth import held_connectors_token++ access_token = held_connectors_token(state) or ""portal_base_url = _portal_base_url(state)if not _nonblank(access_token):return (diff --git a/hermes_cli/nous_auth_keepalive.py b/hermes_cli/nous_auth_keepalive.pyindex 24eaa00eefb..990eeaf302e 100644--- a/hermes_cli/nous_auth_keepalive.py+++ b/hermes_cli/nous_auth_keepalive.py@@ -162,7 +162,14 @@ def refresh_nous_auth_keepalive_once()if pool_result is not None:return pool_result- if not get_provider_auth_state("nous"):+ state = get_provider_auth_state("nous")+ if not state:+ return False+ # Mid-life twin of start_nous_auth_keepalive's guard (a guest minted after the thread+ # started): its tokens are minted on demand, and an inference mint here would put a guest+ # who only uses connectors through the free-inference challenge every tick.+ from hermes_cli.anon_auth import is_guest_state+ if is_guest_state(state):return Falsetry:# Nobody is waiting on a keepalive tick: a free-tier browser challenge is announced to thediff --git a/tests/hermes_cli/anon_portal.py b/tests/hermes_cli/anon_portal.pyindex 93b550c7e68..9fdc9e6e72a 100644--- a/tests/hermes_cli/anon_portal.py+++ b/tests/hermes_cli/anon_portal.py@@ -51,6 +51,9 @@ class FakePortal:self.challenge_status_errors: list[int] = []self.challenge_url = f"{PORTAL}/challenge?code=ticket"self.optional_challenge = False+ # NAS since hermes-portal#1516: ``purpose: "connectors"`` mints a ``connectors:invoke``-only+ # JWT with any CHALLENGE rule waived. False = an older NAS that drops the unknown key.+ self.honours_purpose = Trueself.token_requests: list[dict] = []self.create_requests: list[dict] = []@@ -87,20 +90,22 @@ class FakePortal:{"body": json.loads(request.content), "user_agent": request.headers.get("user-agent")})if self.token_response is not None:return self.token_response- if self.challenge_required:+ connectors = self.honours_purpose and json.loads(request.content).get("purpose") == "connectors"+ token = json.loads(request.content)["token"]+ if token in self.dead_tokens: # NAS validates the credential before any gate+ return httpx.Response(404, json={"error": "unknown_token"})+ if self.challenge_required and not connectors:return httpx.Response(428, json={"error": "challenge_required", "message": "A quick check first.","challenges": [{"type": "browser", "url": self.challenge_url, "state": "pending","required": True, "expires_in": 600, "interval": 2}],"fallback_url": f"{PORTAL}/login"})- token = json.loads(request.content)["token"]- if token in self.dead_tokens:- return httpx.Response(404, json={"error": "unknown_token"})- body = {"access_token": make_jwt(), "token_type": "Bearer", "expires_in": 900,+ body = {"access_token": make_jwt(**({"scope": "connectors:invoke"} if connectors else {})),+ "token_type": "Bearer", "expires_in": 900,"user_id": "nas_user:1", "org_id": "nas_org:1"}if self.inference_base_url:body["inference_base_url"] = self.inference_base_url- if self.optional_challenge:+ if self.optional_challenge and not connectors:body["challenges"] = [{"type": "browser", "url": self.challenge_url, "state": "pending","required": False, "expires_in": 600, "interval": 2}]return httpx.Response(200, json=body)diff --git a/tests/hermes_cli/test_anon_challenge.py b/tests/hermes_cli/test_anon_challenge.pyindex e240f870ad0..6cf2d050f67 100644--- a/tests/hermes_cli/test_anon_challenge.py+++ b/tests/hermes_cli/test_anon_challenge.py@@ -177,8 +177,10 @@ class TestRequiredChallenge:assert [p for _, p in nas.calls].count("/api/anonymous/token") == 2def test_the_managed_tool_token_path_works_a_challenge_too(self, nas, presented):+ """Against a NAS from before the connectors purpose, which still challenges that mint."""from hermes_cli.auth import resolve_nous_access_tokenassert anon_auth.is_guest_state(anon_auth.ensure_portal_identity(explicit=True))+ nas.honours_purpose = Falsenas.challenge_required = Truenas.challenge_statuses = ["pending"]assert resolve_nous_access_token()diff --git a/tests/hermes_cli/test_anon_connectors_token.py b/tests/hermes_cli/test_anon_connectors_token.pynew file mode 100644index 00000000000..b0411d63c44--- /dev/null+++ b/tests/hermes_cli/test_anon_connectors_token.py@@ -0,0 +1,228 @@+"""Nous free tier: the connectors-only guest token (NAS hermes-portal#1516).++A guest who only uses connectors or managed tools never meets the free-inference browser challenge:+those callers (``resolve_nous_access_token``) hold or mint a ``purpose: "connectors"`` token, and an+inference token is minted (inside ``run_with_challenge``) only when the free model is called+(``resolve_nous_runtime_credentials``). Driven through the fake NAS with Hermes' real client code;+no request leaves the process.+"""++from __future__ import annotations++import threading+import time+from datetime import datetime, timedelta, timezone, UTC++import httpx+import pytest++from hermes_cli import anon_auth, anon_challenge+from hermes_cli import auth as auth_mod+from hermes_cli.auth_nous import resolve_nous_runtime_credentials++from tests.hermes_cli.anon_portal import WELCOME, install_portal, make_jwt+++def nas(monkeypatch, tmp_path):+ fake = install_portal(monkeypatch, tmp_path)+ assert anon_auth.is_guest_state(anon_auth.ensure_portal_identity(explicit=True))+ return fake+++def presented(monkeypatch):+ seen: list[anon_challenge.BrowserChallenge] = []+ monkeypatch.setattr(anon_challenge, "present", seen.append)+ return seen+++def _purposes(nas) -> list:+ return [r["body"].get("purpose") for r in nas.token_requests]+++def _scope(token: str) -> str:+ return anon_auth._decode_jwt_claims(token)["scope"]+++def _forget_memo(monkeypatch):+ monkeypatch.setattr(auth_mod, "_RESOLVE_TOKEN_CACHE", {})+++def _persist_guest_tokens(*, inference: int | None = None, connectors: int | None = None) -> dict:+ """Write held tokens expiring in the given seconds. An inference-only write is exactly what+ current releases persist; ``connectors`` adds the new slot beside it."""+ from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store+ at = lambda s: (datetime.now(UTC) + timedelta(seconds=s)).isoformat()+ tokens = {}+ with _auth_store_lock():+ store = _load_auth_store()+ nous = store["providers"]["nous"]+ if inference is not None:+ tokens["inference"] = make_jwt(exp=int(time.time()) + inference)+ nous.update(access_token=tokens["inference"], scope="inference:invoke", token_type="Bearer",+ inference_base_url=WELCOME, expires_at=at(inference))+ if connectors is not None:+ tokens["connectors"] = make_jwt(scope="connectors:invoke", exp=int(time.time()) + connectors)+ nous["connectors_token"] = {"access_token": tokens["connectors"], "expires_at": at(connectors)}+ _save_auth_store(store)+ return tokens+++class TestConnectorsCallers:+ def test_never_challenged_even_while_the_inference_mint_would_be(self, nas, presented):+ from tools.managed_tool_gateway import read_nous_access_token+ nas.challenge_required = True+ nas.challenge_never_clears = True+ token = auth_mod.resolve_nous_access_token()+ assert _scope(token) == "connectors:invoke"+ assert read_nous_access_token() == token+ assert _purposes(nas) == ["connectors"]+ assert presented == [] and "/api/anonymous/challenge/status" not in [p for _, p in nas.calls]++ @pytest.mark.parametrize("inference, connectors, serves", [+ (-60, 900, "connectors"), # expired inference, live connectors: no mint+ (900, -60, "inference"), # live inference, expired connectors: no mint+ (-60, -60, None), # both expired: one connectors mint, never an inference one+ (-60, None, None), # only an expired inference token (a current release's state)+ ])+ def test_picks_the_live_slot_or_mints_connectors_only(self, nas, presented, monkeypatch,+ inference, connectors, serves):+ from tools.managed_tool_gateway import read_nous_access_token+ held = _persist_guest_tokens(inference=inference, connectors=connectors)+ nas.challenge_required = True+ token = auth_mod.resolve_nous_access_token()+ _forget_memo(monkeypatch)+ assert read_nous_access_token() == token+ if serves:+ assert token == held[serves] and nas.token_requests == []+ else:+ assert _scope(token) == "connectors:invoke" and _purposes(nas) == ["connectors"]+ assert anon_auth.current_nous_state()["connectors_token"]["access_token"] == token+ assert presented == []++ def test_the_connectors_token_is_persisted_beside_the_inference_slot(self, nas, monkeypatch):+ token = auth_mod.resolve_nous_access_token()+ state = anon_auth.current_nous_state()+ assert state["connectors_token"]["access_token"] == token+ assert not state.get("access_token") # filled only when the free model is used+ _forget_memo(monkeypatch)+ assert auth_mod.resolve_nous_access_token() == token+ assert len(nas.token_requests) == 1++ def test_account_reads_use_the_connectors_token(self, nas, presented):+ from hermes_cli.nous_account import get_nous_portal_account_info, reset_nous_portal_account_info_cache+ nas.challenge_required = True+ auth_mod.resolve_nous_access_token()+ reset_nous_portal_account_info_cache()+ info = get_nous_portal_account_info()+ assert info.logged_in and info.source == "jwt" and info.account_tier == "anonymous"+ assert len(nas.token_requests) == 1 and presented == []++ @pytest.mark.parametrize("error", ["signin_required", "access_denied"])+ def test_a_refusal_surfaces_as_it_does_today(self, nas, error):+ nas.token_response = httpx.Response(403, json={"error": error})+ with pytest.raises(anon_auth.AuthError) as exc:+ auth_mod.resolve_nous_access_token()+ assert exc.value.code == anon_auth.ANON_SIGNIN_REQUIRED and exc.value.retryable is False+ assert str(exc.value) == anon_auth.ANON_FAILURE_COPY[anon_auth.ANON_SIGNIN_REQUIRED]+++class TestInferenceCallers:+ def test_still_work_the_challenge_and_never_take_the_connectors_token(self, nas, presented):+ connectors = auth_mod.resolve_nous_access_token()+ nas.challenge_required = True+ nas.challenge_statuses = ["pending"]+ creds = resolve_nous_runtime_credentials()+ assert creds["api_key"] != connectors and _scope(creds["api_key"]) == "inference:invoke"+ assert [c.url for c in presented] == [nas.challenge_url]+ assert _purposes(nas) == ["connectors", "inference", "inference"]++ def test_a_held_inference_token_satisfies_connectors_callers(self, nas, monkeypatch):+ creds = resolve_nous_runtime_credentials()+ _forget_memo(monkeypatch)+ assert auth_mod.resolve_nous_access_token() == creds["api_key"]+ assert len(nas.token_requests) == 1++ def test_a_connectors_mint_leaves_a_pending_inference_challenge_alone(self, nas, presented):+ """The connectors grant says nothing about the inference check: the desktop's hidden window+ must keep the ticket it was handed."""+ nas.challenge_required = True+ nas.challenge_never_clears = True+ with anon_challenge.background_caller(), pytest.raises(anon_auth.AuthError):+ resolve_nous_runtime_credentials()+ assert anon_challenge.pending_challenge()["url"] == nas.challenge_url+ auth_mod.resolve_nous_access_token()+ assert anon_challenge.pending_challenge()["url"] == nas.challenge_url++ def test_a_connectors_caller_never_queues_behind_an_inference_challenge(self, nas, monkeypatch):+ """The wait runs outside the auth locks and its work lock is the inference mint's alone."""+ nas.challenge_required = True+ nas.challenge_statuses = ["pending"]+ during_wait: list[str] = []++ def present(_challenge):+ reader = threading.Thread(+ target=lambda: during_wait.append(auth_mod.resolve_nous_access_token()), daemon=True)+ reader.start()+ reader.join(timeout=5)+ monkeypatch.setattr(anon_challenge, "present", present)+ assert resolve_nous_runtime_credentials()["api_key"]+ assert [_scope(t) for t in during_wait] == ["connectors:invoke"]++ def test_an_inference_give_up_cooldown_does_not_fail_connectors_callers_fast(+ self, nas, presented, monkeypatch):+ nas.challenge_required = True+ nas.challenge_never_clears = True+ monkeypatch.setattr(anon_challenge, "CHALLENGE_WAIT_SECONDS", 0)+ with pytest.raises(anon_auth.AuthError):+ resolve_nous_runtime_credentials()+ assert anon_challenge._gave_up_recently()+ assert _scope(auth_mod.resolve_nous_access_token()) == "connectors:invoke"+++class TestNoInferenceIntent:+ """Paths that are not a free-model call never mint inference in the foreground or on a timer."""++ def test_the_keepalive_never_mints_for_a_guest(self, nas):+ from hermes_cli.nous_auth_keepalive import refresh_nous_auth_keepalive_once+ auth_mod.resolve_nous_access_token()+ assert refresh_nous_auth_keepalive_once() is False+ assert _purposes(nas) == ["connectors"]++ def test_a_model_catalog_read_never_waits_on_a_challenge(self, nas, presented):+ from hermes_cli.models import _nous_catalog, get_curated_nous_model_ids+ nas.challenge_required = True+ nas.challenge_never_clears = True+ assert _nous_catalog("nous", False) == (get_curated_nous_model_ids() or None)+ assert "/api/anonymous/challenge/status" not in [p for _, p in nas.calls]+++class TestOlderNas:+ """A NAS from before #1516 drops the unknown ``purpose`` key and mints today's token."""++ def test_an_inference_token_for_a_connectors_mint_fills_the_inference_slot(self, nas, monkeypatch):+ nas.honours_purpose = False+ token = auth_mod.resolve_nous_access_token()+ assert _scope(token) == "inference:invoke"+ state = anon_auth.current_nous_state()+ assert state["access_token"] == token and "connectors_token" not in state+ assert resolve_nous_runtime_credentials()["api_key"] == token+ assert len(nas.token_requests) == 1++ def test_a_challenged_connectors_mint_falls_back_to_the_challenge_flow(self, nas, presented):+ nas.honours_purpose = False+ nas.challenge_required = True+ nas.challenge_statuses = ["pending"]+ assert _scope(auth_mod.resolve_nous_access_token()) == "inference:invoke"+ assert len(presented) == 1+++class TestPersistedState:+ def test_state_written_by_current_releases_loads_unchanged(self, nas):+ from tools.managed_tool_gateway import peek_nous_access_token+ token = _persist_guest_tokens(inference=900)["inference"]+ assert peek_nous_access_token() == token+ assert auth_mod.resolve_nous_access_token() == token+ assert resolve_nous_runtime_credentials()["api_key"] == token+ assert nas.token_requests == []diff --git a/tools/managed_tool_gateway.py b/tools/managed_tool_gateway.pyindex f767f44c958..4b69b063ac1 100644--- a/tools/managed_tool_gateway.py+++ b/tools/managed_tool_gateway.py@@ -5,7 +5,6 @@ from __future__ import annotationsimport jsonimport loggingimport os-from datetime import datetime, timezone, UTCfrom dataclasses import dataclassfrom typing import Callable, Optional@@ -61,22 +60,6 @@ def _read_nous_provider_state() -> Optional[dict]:return None-def _parse_timestamp(value: object) -> Optional[datetime]:- normalized = _clean(value)- if normalized is None:- return None- try:- parsed = datetime.fromisoformat(normalized[:-1] + "+00:00" if normalized.endswith("Z") else normalized)- except ValueError:- return None- return (parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)).astimezone(UTC)---def _access_token_is_expiring(expires_at: object, skew_seconds: int) -> bool:- expires = _parse_timestamp(expires_at)- return expires is None or (expires - datetime.now(UTC)).total_seconds() <= max(0, int(skew_seconds))--def _read_user_token_override() -> Optional[str]:"""Read the TOOL_GATEWAY_USER_TOKEN override through the secret scope. Scope verdict is authoritativewhen installed (a scoped miss must NOT borrow the process env under multiplex); ``os.environ`` only@@ -94,7 +77,9 @@ def _read_user_token_override() -> Optional[str]:def peek_nous_access_token() -> Optional[str]:"""Cheap token probe: env override or cached auth-store token, no expiry check and no network —availability scans must stay off the synchronous OAuth refresh path (:func:`read_nous_access_token`)."""- return _read_user_token_override() or _clean((_read_nous_provider_state() or {}).get("access_token"))+ from hermes_cli.anon_auth import held_connectors_token++ return _read_user_token_override() or _clean(held_connectors_token(_read_nous_provider_state()))def read_nous_access_token() -> Optional[str]:@@ -110,9 +95,11 @@ def read_nous_access_token() -> Optional[str]:nous_provider = _read_nous_provider_state() or {}if not nous_provider:return None+ from hermes_cli.anon_auth import held_connectors_token++ if fresh_token := _clean(held_connectors_token(nous_provider, skew_seconds=_NOUS_ACCESS_TOKEN_REFRESH_SKEW_SECONDS)):+ return fresh_tokencached_token = peek_nous_access_token()- if cached_token and not _access_token_is_expiring(nous_provider.get("expires_at"), _NOUS_ACCESS_TOKEN_REFRESH_SKEW_SECONDS):- return cached_tokentry:from hermes_cli.auth import resolve_nous_access_token