Skip to content

The agent that grows with you

fix(nous): keep anonymous errors exclusive to anonymous users

Robin Fernandes165271fcebdd
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index 7ef6f88ba95..0ad9dc2f90e 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -2243,14 +2243,6 @@ def _describe_openrouter_unavailable(model: str = None) -> str:
def _try_nous(vision: bool = False) -> Tuple[Optional[OpenAI], Optional[str]]:
- # Cross-session rate guard: another session's 429 means skip Nous rather than pile onto the tapped RPH bucket.
- with contextlib.suppress(Exception):
- from agent.nous_rate_guard import nous_rate_limit_remaining
- _remaining = nous_rate_limit_remaining()
- if _remaining is not None and _remaining > 0:
- logger.debug("Auxiliary: skipping Nous Portal (rate-limited, resets in %.0fs)", _remaining)
- _mark_provider_unhealthy("nous", ttl=_remaining)
- return None, None
nous = _read_nous_auth()
runtime = _resolve_nous_runtime_api(force_refresh=False)
if runtime is None and not nous:
@@ -2273,6 +2265,18 @@ def _try_nous(vision: bool = False) -> Tuple[Optional[OpenAI], Optional[str]]:
base_url = str(
(nous or {}).get("inference_base_url") or _scoped_key_env("NOUS_INFERENCE_BASE_URL") or _NOUS_DEFAULT_BASE_URL
).rstrip("/")
+ # Resolve the request identity before consulting its cross-session cooldown.
+ with contextlib.suppress(Exception):
+ from agent.nous_rate_guard import nous_rate_limit_remaining
+ from hermes_cli.anon_auth import is_anonymous_request
+ anonymous = is_anonymous_request("nous", api_key)
+ remaining = nous_rate_limit_remaining(anonymous=anonymous)
+ if remaining is not None and remaining > 0:
+ logger.debug("Auxiliary: skipping Nous Portal (rate-limited, resets in %.0fs)", remaining)
+ # A provider-wide cache would outlive signing in with a named account.
+ if not anonymous:
+ _mark_provider_unhealthy("nous", ttl=remaining)
+ return None, None
lane = "vision" if vision else "text"
# The free tier's host serves exactly one model, for every lane: asking it for the Portal's
# recommended aux model is a guaranteed 429 ``model_not_free``. Pin the route's model instead.
diff --git a/agent/error_classifier.py b/agent/error_classifier.py
index b0b8b1935d8..fc097f640e2 100644
--- a/agent/error_classifier.py
+++ b/agent/error_classifier.py
@@ -526,6 +526,7 @@ class _Ctx:
context_length: int
num_messages: int
base_url: str = "" # the route the call went to; "" when the caller did not say
+ anonymous: bool = False
def __post_init__(self) -> None:
self.error_type = type(self.error).__name__
@@ -579,6 +580,8 @@ def _nous_welcome_tier(c: _Ctx) -> Optional[Verdict]:
400/403 whose message names the wrong host or a dark tier is deterministic for the request.
The parsed refusal rides ``error_context`` so the terminal copy can say what happened.
"""
+ if not c.anonymous:
+ return None
from hermes_cli.anon_auth import (
WELCOME_TIER_GATE_REASONS, parse_welcome_refusal, welcome_route_refusal)
status = c.status_code
@@ -732,11 +735,15 @@ def classify_api_error(
error: Exception, *, provider: str = "", model: str = "",
approx_tokens: int = 0, context_length: int = 200000, num_messages: int = 0,
base_url: str = "",
+ api_key: Any = None,
) -> ClassifiedError:
"""Classify an API error into a structured recovery recommendation (see ``_STAGES``).
``base_url`` (optional) is the route the call went to; the Nous welcome tier keys its
- dark-tier 403 on it because that refusal carries no distinguishing message."""
+ dark-tier 403 on it because that refusal carries no distinguishing message.
+ ``api_key`` identifies an anonymous request; a host or fairshare reason alone does not.
+ The credential is never included in the returned context."""
+ from hermes_cli.anon_auth import is_anonymous_request
status_code = _extract_status_code(error)
# Copilot/GitHub Models RateLimitError may not set .status_code; force 429.
if status_code is None and type(error).__name__ == "RateLimitError":
@@ -745,6 +752,7 @@ def classify_api_error(
c = _Ctx(
error, status_code, body, _build_error_msg(error, body), provider, model,
approx_tokens, context_length, num_messages, str(base_url or ""),
+ is_anonymous_request(provider, api_key),
)
verdict = next((v for v in (stage(c) for stage in _STAGES) if v is not None), _V_UNKNOWN)
base = {"status_code": status_code, "provider": provider, "model": model, "message": _extract_message(error, body)}
diff --git a/agent/nous_rate_guard.py b/agent/nous_rate_guard.py
index 834027cec92..2b44fca308b 100644
--- a/agent/nous_rate_guard.py
+++ b/agent/nous_rate_guard.py
@@ -34,14 +34,16 @@ WELCOME_LONG_WAIT_SECONDS = 20.0
format_remaining = _fmt_seconds
-def _state_path() -> str:
+def _state_path(*, anonymous: bool = False) -> str:
"""Path to the Nous rate limit state file."""
try:
from hermes_constants import get_hermes_home
base = get_hermes_home()
except ImportError:
base = os.path.join(os.path.expanduser("~"), ".hermes")
- return os.path.join(base, "rate_limits", "nous.json")
+ # Signing in must not inherit the anonymous allowance's cooldown (or clear it for
+ # another anonymous session). Keep the existing named-account file unchanged.
+ return os.path.join(base, "rate_limits", "nous-anonymous.json" if anonymous else "nous.json")
def _parse_reset_seconds(headers: Optional[Mapping[str, str]]) -> Optional[float]:
@@ -58,6 +60,7 @@ def _parse_reset_seconds(headers: Optional[Mapping[str, str]]) -> Optional[float
def record_nous_rate_limit(
*, headers: Optional[Mapping[str, str]] = None, error_context: Optional[dict[str, Any]] = None,
default_cooldown: float = 300.0,
+ anonymous: bool = False,
) -> None:
"""Record that Nous Portal is rate-limited in the shared state file.
@@ -78,15 +81,15 @@ def record_nous_rate_limit(
state = {"reset_at": reset_at, "recorded_at": now, "reset_seconds": reset_at - now}
try:
- atomic_write_text(_state_path(), json.dumps(state))
+ atomic_write_text(_state_path(anonymous=anonymous), json.dumps(state))
logger.info("Nous rate limit recorded: resets in %.0fs (at %.0f)", reset_at - now, reset_at)
except Exception as exc:
logger.debug("Failed to write Nous rate limit state: %s", exc)
-def nous_rate_limit_remaining() -> Optional[float]:
+def nous_rate_limit_remaining(*, anonymous: bool = False) -> Optional[float]:
"""Seconds remaining until reset, or None if not rate-limited (expired state is removed)."""
- path = _state_path()
+ path = _state_path(anonymous=anonymous)
try:
with open(path, encoding="utf-8") as f:
state = json.load(f)
@@ -100,10 +103,10 @@ def nous_rate_limit_remaining() -> Optional[float]:
return None
-def clear_nous_rate_limit() -> None:
+def clear_nous_rate_limit(*, anonymous: bool = False) -> None:
"""Clear the rate limit state (e.g., after a successful Nous request)."""
try:
- os.unlink(_state_path())
+ os.unlink(_state_path(anonymous=anonymous))
except FileNotFoundError:
pass
except OSError as exc:
diff --git a/agent/turn_api_call.py b/agent/turn_api_call.py
index 127fee02bef..a54d1d7b188 100644
--- a/agent/turn_api_call.py
+++ b/agent/turn_api_call.py
@@ -243,11 +243,11 @@ def nous_rate_limit_guard(
from agent.nous_rate_guard import (
nous_rate_limit_remaining, format_remaining as _fmt_nous_remaining
)
- _nous_remaining = nous_rate_limit_remaining()
+ from hermes_cli import anon_auth
+ _welcome = anon_auth.is_anonymous_request(agent.provider, getattr(agent, "api_key", None))
+ _nous_remaining = nous_rate_limit_remaining(anonymous=_welcome)
if _nous_remaining is not None and _nous_remaining > 0:
- from hermes_cli import anon_auth
reset = _fmt_nous_remaining(_nous_remaining)
- _welcome = anon_auth.route_is_welcome_host(getattr(agent, "base_url", ""))
if _welcome:
_nous_msg = anon_auth.FREE_TIER_RATE_LIMIT_CHAT.format(
reset=anon_auth.friendly_wait(_nous_remaining))
diff --git a/agent/turn_api_error.py b/agent/turn_api_error.py
index 4a0d218423f..8057b468790 100644
--- a/agent/turn_api_error.py
+++ b/agent/turn_api_error.py
@@ -111,6 +111,7 @@ def handle_api_error(
model=getattr(agent, "model", "") or "", approx_tokens=approx_tokens,
context_length=_ctx_len, num_messages=len(api_messages) if api_messages else 0,
base_url=str(getattr(agent, "base_url", "") or ""),
+ api_key=getattr(agent, "api_key", None),
)
logger.debug(
"Error classified: reason=%s status=%s retryable=%s compress=%s rotate=%s fallback=%s",
diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py
index 791ebf57336..ccceea924a1 100644
--- a/agent/turn_recovery.py
+++ b/agent/turn_recovery.py
@@ -268,8 +268,8 @@ def _print_nous_401_diagnostics(agent: Any, api_error: Exception) -> None:
if _body_text:
_plines(agent, f" Response: {_body_text}")
try:
- from hermes_cli.anon_auth import route_is_welcome_host
- if route_is_welcome_host(getattr(agent, "base_url", "")):
+ from hermes_cli.anon_auth import is_anonymous_request
+ if is_anonymous_request(getattr(agent, "provider", ""), getattr(agent, "api_key", None)):
# The free tier has no credits, no agent key and no auth.json to inspect: its session
# ended and could not be replaced. The two doors are a sign-in or another provider.
_plines(agent, " Your session ended and Hermes couldn't start a new one.",
@@ -747,13 +747,13 @@ def _stamp_free_tier(result: Dict[str, Any], kind: str, message: str) -> Dict[st
return result
-def _welcome_outage_copy(base_url: Any, classified: Any) -> str:
+def _welcome_outage_copy(base_url: Any, classified: Any, *, anonymous: bool = False) -> str:
"""On the Nous free tier, a transport / server failure that outlived every retry reads as one
plain sentence (the free model is having trouble) rather than the technical summary. Empty
for every other route and for rate limits / billing, which have their own copy."""
try:
from hermes_cli.anon_auth import FREE_TIER_OUTAGE_COPY, route_is_welcome_host
- if not route_is_welcome_host(base_url):
+ if not anonymous or not route_is_welcome_host(base_url):
return ""
# Not ``unknown``: that is the classifier's catch-all for status-less local failures, which
# are not the free model's trouble.
@@ -914,6 +914,7 @@ def max_retries_exhausted_result(
guidance (the latter wins), persist, build the result with ``failure_reason`` /
``failure_retryable`` / ``billing_block``."""
# Result/guidance helpers stay in the loop module (tests import + patch them there).
+ from hermes_cli.anon_auth import is_anonymous_request
from agent.conversation_loop import (
_billing_block_dict, _billing_or_entitlement_message, _billing_terminal_label,
_print_billing_or_entitlement_guidance,
@@ -998,7 +999,10 @@ def max_retries_exhausted_result(
if _welcome_hint:
_final_response = _welcome_tier_guidance(classified, model=model, in_chat=True)
_free_tier_kind = _welcome_surface_kind(classified)
- elif _outage := _welcome_outage_copy(base_url, classified):
+ elif _outage := _welcome_outage_copy(
+ base_url, classified,
+ anonymous=is_anonymous_request(provider, getattr(agent, "api_key", None)),
+ ):
_final_response, _free_tier_kind = _outage, "outage"
if _is_thinking_timeout:
# Thinking-timeout guidance overrides stream-drop guidance, which would wrongly
@@ -1420,16 +1424,17 @@ def _is_genuine_nous_rate_limit(agent: Any, api_error: Exception, error_context:
is_genuine_nous_rate_limit, is_long_welcome_rate_limit, record_nous_rate_limit)
_err_resp = getattr(api_error, "response", None)
_err_hdrs = getattr(_err_resp, "headers", None) if _err_resp else None
- from hermes_cli.anon_auth import route_is_welcome_host
+ from hermes_cli.anon_auth import is_anonymous_request
+ anonymous = is_anonymous_request(getattr(agent, "provider", ""), getattr(agent, "api_key", None))
_classified_ctx = getattr(classified, "error_context", None) or {}
- # Route-gated: only the welcome host's fairshare body is an allowance verdict; a paid-host
- # 429 keeps main's rule (an exhausted x-ratelimit bucket), whatever its body says.
+ # Only an anonymous request's fairshare body is an allowance verdict; named
+ # requests keep the exhausted-bucket rule, whatever their host or body says.
_genuine = (
- (route_is_welcome_host(getattr(agent, "base_url", "")) and is_long_welcome_rate_limit(_classified_ctx))
+ (anonymous and is_long_welcome_rate_limit(_classified_ctx))
or is_genuine_nous_rate_limit(headers=_err_hdrs, last_known_state=agent._rate_limit_state))
if _genuine:
_merged = {**(error_context if isinstance(error_context, dict) else {}), **_classified_ctx}
- record_nous_rate_limit(headers=_err_hdrs, error_context=_merged)
+ record_nous_rate_limit(headers=_err_hdrs, error_context=_merged, anonymous=anonymous)
else:
logger.info(
"Nous 429 looks like upstream capacity "
diff --git a/agent/turn_response_check.py b/agent/turn_response_check.py
index cd63090a410..3413024549e 100644
--- a/agent/turn_response_check.py
+++ b/agent/turn_response_check.py
@@ -198,7 +198,8 @@ def check_api_response(
if agent.provider == "nous":
try:
from agent.nous_rate_guard import clear_nous_rate_limit
- clear_nous_rate_limit()
+ from hermes_cli.anon_auth import is_anonymous_request
+ clear_nous_rate_limit(anonymous=is_anonymous_request(agent.provider, getattr(agent, "api_key", None)))
except Exception:
pass
from agent import relay_llm
diff --git a/hermes_cli/anon_auth.py b/hermes_cli/anon_auth.py
index 0fb1db1b811..ae10fb0c320 100644
--- a/hermes_cli/anon_auth.py
+++ b/hermes_cli/anon_auth.py
@@ -162,6 +162,16 @@ def is_guest_state(state: Any) -> bool:
return isinstance(state, dict) and state.get("auth_method") == ANON_AUTH_METHOD
+def is_anonymous_request(provider: Any, api_key: Any) -> bool:
+ """Select anonymous error UX from the credential actually sent, never the saved profile or URL.
+
+ This is display/recovery metadata, not token verification; the gateway authenticates the JWT.
+ Named free accounts and opaque API keys must retain normal provider errors.
+ """
+ from hermes_cli.auth_constants import _decode_jwt_claims
+ return provider == "nous" and _decode_jwt_claims(api_key).get("account_tier") == ANON_ACCOUNT_TIER
+
+
def current_nous_state() -> Optional[Dict[str, Any]]:
"""The profile's ``providers.nous`` state without locking or network (status/picker reads)."""
from hermes_cli.auth import _load_auth_store, _load_provider_state
diff --git a/tests/agent/test_error_classifier.py b/tests/agent/test_error_classifier.py
index 69b45e27321..138c6419795 100644
--- a/tests/agent/test_error_classifier.py
+++ b/tests/agent/test_error_classifier.py
@@ -3,6 +3,7 @@
from types import SimpleNamespace
import pytest
+
from agent.error_classifier import (
ClassifiedError,
FailoverReason,
@@ -13,6 +14,7 @@ from agent.error_classifier import (
_extract_error_code,
_classify_402,
)
+from tests.hermes_cli.anon_portal import make_jwt
# ── Helper: mock API errors ────────────────────────────────────────────
@@ -1796,7 +1798,7 @@ class TestNousWelcomeTier:
def test_model_not_free_is_a_non_retryable_gate_with_fallback(self):
err = self._refusal("model_not_free", alternates=["nous/welcome"], upgrade_url="https://portal.example/upgrade")
- result = classify_api_error(err, provider="nous", model="gpt-5")
+ result = classify_api_error(err, provider="nous", api_key=make_jwt(), model="gpt-5")
assert result.reason == FailoverReason.model_not_found
assert result.retryable is False
assert result.should_fallback is True
@@ -1807,13 +1809,13 @@ class TestNousWelcomeTier:
assert refusal["upgrade_url"] == "https://portal.example/upgrade"
def test_feature_not_free_is_the_same_gate(self):
- result = classify_api_error(self._refusal("feature_not_free"), provider="nous")
+ result = classify_api_error(self._refusal("feature_not_free"), provider="nous", api_key=make_jwt())
assert result.reason == FailoverReason.model_not_found
assert result.retryable is False
@pytest.mark.parametrize("reason", ["at_capacity", "admission_closed", "rate_limited"])
def test_capacity_refusals_are_rate_limits_that_honour_retry_after(self, reason):
- result = classify_api_error(self._refusal(reason, retry_after=30), provider="nous", model="nous/welcome")
+ result = classify_api_error(self._refusal(reason, retry_after=30), provider="nous", api_key=make_jwt(), model="nous/welcome")
assert result.reason == FailoverReason.rate_limit
assert result.retryable is True
assert result.should_fallback is True
@@ -1822,40 +1824,40 @@ class TestNousWelcomeTier:
assert ctx["reset_at"] > 0
def test_retry_after_zero_carries_no_reset(self):
- result = classify_api_error(self._refusal("at_capacity", retry_after=0), provider="nous")
+ result = classify_api_error(self._refusal("at_capacity", retry_after=0), provider="nous", api_key=make_jwt())
assert "reset_at" not in result.error_context
def test_unknown_reason_is_not_the_welcome_shape(self):
err = MockAPIError("Error code: 429", status_code=429,
body={"status": 429, "message": "x", "reason": "something_else", "retry_after": 5})
- result = classify_api_error(err, provider="nous")
+ result = classify_api_error(err, provider="nous", api_key=make_jwt())
assert "welcome_refusal" not in result.error_context
def test_anonymous_jwt_on_the_paid_host_is_deterministic(self):
body = {"status": 400, "message": "Anonymous accounts must use https://welcome-api.nousresearch.com for inference."}
err = MockAPIError(f"Error code: 400 - {body}", status_code=400, body=body)
- result = classify_api_error(err, provider="nous", model="nous/welcome")
+ result = classify_api_error(err, provider="nous", api_key=make_jwt(), model="nous/welcome")
assert result.reason == FailoverReason.format_error
assert result.retryable is False and result.should_fallback is True
assert result.error_context["welcome_route"] == "anon_on_paid_host"
- def test_named_caller_on_the_welcome_host_is_deterministic(self):
+ def test_named_caller_on_the_welcome_host_keeps_standard_errors(self):
body = {"status": 400, "message": "This endpoint serves anonymous Hermes Agent accounts only. Use https://inference-api.nousresearch.com with your API key or signed-in account."}
err = MockAPIError(f"Error code: 400 - {body}", status_code=400, body=body)
- result = classify_api_error(err, provider="nous")
- assert result.error_context["welcome_route"] == "named_on_welcome_host"
+ result = classify_api_error(err, provider="nous", api_key=make_jwt(account_tier="free"))
+ assert "welcome_route" not in result.error_context
assert result.retryable is False
def test_dark_tier_403_never_triggers_a_credential_refresh(self):
body = {"status": 403, "message": "Anonymous accounts are not accepted by this API right now."}
err = MockAPIError(f"Error code: 403 - {body}", status_code=403, body=body)
- result = classify_api_error(err, provider="nous", model="nous/welcome")
+ result = classify_api_error(err, provider="nous", api_key=make_jwt(), model="nous/welcome")
assert result.reason == FailoverReason.auth_permanent
assert result.retryable is False and result.should_fallback is True
assert result.should_rotate_credential is False
assert result.error_context["welcome_route"] == "tier_disabled"
def test_ordinary_403_is_untouched(self):
- result = classify_api_error(MockAPIError("forbidden", status_code=403, body={"message": "forbidden"}), provider="nous")
+ result = classify_api_error(MockAPIError("forbidden", status_code=403, body={"message": "forbidden"}), provider="nous", api_key=make_jwt())
assert result.reason == FailoverReason.auth
assert "welcome_route" not in result.error_context
diff --git a/tests/agent/test_nous_rate_guard.py b/tests/agent/test_nous_rate_guard.py
index 949ee3f9ccf..dfd78194698 100644
--- a/tests/agent/test_nous_rate_guard.py
+++ b/tests/agent/test_nous_rate_guard.py
@@ -6,6 +6,8 @@ import time
import pytest
+from tests.hermes_cli.anon_portal import make_jwt
+
@pytest.fixture
def rate_guard_env(tmp_path, monkeypatch):
@@ -164,6 +166,7 @@ class TestAuxiliaryClientIntegration:
"inference_base_url": "https://api.nous.test/v1",
})
+ monkeypatch.setattr(aux, "_resolve_nous_runtime_api", lambda **kw: None)
result = aux._try_nous()
assert result == (None, None)
@@ -174,6 +177,7 @@ class TestAuxiliaryClientIntegration:
# (will return None because no real creds, but won't be blocked
# by the rate guard)
monkeypatch.setattr(aux, "_read_nous_auth", lambda: None)
+ monkeypatch.setattr(aux, "_resolve_nous_runtime_api", lambda **kw: None)
result = aux._try_nous()
assert result == (None, None)
@@ -268,11 +272,12 @@ class TestWelcomeRouteCopy:
from agent import nous_rate_guard
from agent.turn_api_call import nous_rate_limit_guard
- monkeypatch.setattr(nous_rate_guard, "nous_rate_limit_remaining", lambda: 600)
+ monkeypatch.setattr(nous_rate_guard, "nous_rate_limit_remaining", lambda **kw: 600)
buffered = []
statuses = []
agent = SimpleNamespace(
provider="nous",
+ api_key=make_jwt(account_tier="anonymous" if "welcome-api" in base_url else "paid"),
base_url=base_url,
log_prefix="",
_buffer_vprint=buffered.append,
diff --git a/tests/agent/test_welcome_error_identity.py b/tests/agent/test_welcome_error_identity.py
new file mode 100644
index 00000000000..aa6af6f30fd
--- /dev/null
+++ b/tests/agent/test_welcome_error_identity.py
@@ -0,0 +1,139 @@
+"""The anonymous UI is a property of the request credential, not a free model or host (#111970)."""
+
+from types import SimpleNamespace
+
+import pytest
+
+from agent.error_classifier import classify_api_error
+from tests.hermes_cli.anon_portal import make_jwt
+from agent.error_surface import build_error_surface_from_result
+from agent.turn_recovery import max_retries_exhausted_result, nonretryable_client_error_result
+
+WELCOME = "https://welcome-api.nousresearch.com/v1"
+NAMED = "https://inference-api.nousresearch.com/v1"
+
+
+def agent_for(api_key, base_url):
+ return SimpleNamespace(
+ provider="nous", api_key=api_key, base_url=base_url, model="stepfun/step-3.7-flash:free",
+ log_prefix="", _rate_limit_state=None, _has_pending_fallback=lambda: False,
+ _dump_api_request_debug=lambda *a, **kw: None, _flush_status_buffer=lambda: None,
+ _summarize_api_error=lambda e: str(e), _emit_status=lambda *a, **kw: None,
+ _persist_session=lambda *a, **kw: None, _plines=lambda *a, **kw: None, _vprint=lambda *a, **kw: None,
+ _buffer_status=lambda *a, **kw: None, _buffer_vprint=lambda *a, **kw: None,
+ _try_activate_fallback=lambda: False,
+ )
+
+
[email protected]("api_key", [
+ make_jwt(account_tier="free", client_id="hermes-cli"),
+ make_jwt(account_tier="paid", client_id="hermes-cli"), "sk-named", None,
+], ids=["named-free", "named-paid", "api-key", "unknown"])
[email protected]("base_url", [NAMED, WELCOME])
[email protected]("case", ["rate_limited", "at_capacity", "admission_closed", "model_not_free", "feature_not_free", "403", "named_route", "503"])
+def test_named_errors_do_not_offer_anonymous_recovery(api_key, base_url, case):
+ """A shared fairshare body or wrong welcome URL cannot establish anonymous identity."""
+ status = 403 if case in {"403", "named_route"} else 503 if case == "503" else 429
+ message = ("This host serves anonymous Hermes Agent accounts only." if case == "named_route"
+ else "You tried to access something that you don't have permissions for." if case == "403"
+ else "The service refused this request.")
+ body = {"status": status, "message": message, "reason": case, "retry_after": 158}
+ error = Exception(message)
+ error.status_code, error.body = status, body
+ agent = agent_for(api_key, base_url)
+ classified = classify_api_error(error, provider="nous", model=agent.model, base_url=base_url, api_key=api_key)
+ common = dict(api_kwargs=None, api_messages=[], messages=[], conversation_history=[],
+ api_call_count=1, approx_tokens=10, provider="nous", base_url=base_url, model=agent.model)
+ if status == 403:
+ result = nonretryable_client_error_result(agent, error, classified, status_code=status, **common)
+ else:
+ result = max_retries_exhausted_result(agent, error, classified, max_retries=3,
+ is_rate_limited=status == 429, error_msg=message, **common)
+ assert "welcome_refusal" not in classified.error_context
+ assert "welcome_route" not in classified.error_context
+ assert "free_tier" not in result
+ surface = build_error_surface_from_result(result, provider="nous", model=agent.model)
+ assert surface["code"] == {403: "auth", 429: "rate_limit", 503: "overloaded"}[status]
+ assert "without signing in" not in result["final_response"]
+
+
+def guard_for(agent):
+ from agent.turn_api_call import nous_rate_limit_guard
+ return nous_rate_limit_guard(
+ agent, _retry=None, api_messages=[], messages=[], conversation_history=[],
+ active_system_prompt="system", retry_count=0, compression_attempts=0, api_call_count=0,
+ )
+
+
[email protected]("tier", ["free", "paid"])
+def test_signing_in_does_not_inherit_anonymous_cooldown(tmp_path, monkeypatch, tier):
+ from agent.agent_runtime_helpers import extract_api_error_context
+ from agent.nous_rate_guard import clear_nous_rate_limit, nous_rate_limit_remaining, record_nous_rate_limit
+ from agent.turn_recovery import _is_genuine_nous_rate_limit
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ guest = agent_for(make_jwt(), WELCOME)
+ error = Exception("refused")
+ error.status_code = 429
+ error.body = {"status": 429, "message": "refused", "reason": "rate_limited", "retry_after": 600}
+ classified = classify_api_error(error, provider="nous", base_url=WELCOME, api_key=guest.api_key)
+ assert _is_genuine_nous_rate_limit(guest, error, extract_api_error_context(error), classified)
+ blocked = guard_for(guest)
+ assert blocked.action == "return"
+ assert build_error_surface_from_result(blocked.result)["code"] == "free_tier_rate_limited"
+
+ # Keep the old welcome URL deliberately: the changed credential owns the boundary.
+ guest.api_key = make_jwt(account_tier=tier, client_id="hermes-cli")
+ assert guard_for(guest).action == "fallthrough"
+ record_nous_rate_limit(headers={"retry-after": "300"})
+ named_blocked = guard_for(guest)
+ assert named_blocked.action == "return"
+ assert "free_tier" not in named_blocked.result
+ assert "Your Nous account has hit its rate limit" in named_blocked.result["final_response"]
+ clear_nous_rate_limit()
+ assert nous_rate_limit_remaining() is None
+ assert nous_rate_limit_remaining(anonymous=True) > 0
+ record_nous_rate_limit(headers={"retry-after": "300"})
+ clear_nous_rate_limit(anonymous=True)
+ assert nous_rate_limit_remaining(anonymous=True) is None
+ assert nous_rate_limit_remaining() > 0
+
+
+def test_auxiliary_anonymous_cooldown_does_not_cache_named_provider_as_unhealthy(tmp_path, monkeypatch):
+ import agent.auxiliary_client as aux
+ from agent.nous_rate_guard import record_nous_rate_limit
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ record_nous_rate_limit(headers={"retry-after": "600"}, anonymous=True)
+ runtime = [make_jwt(), WELCOME]
+ monkeypatch.setattr(aux, "_read_nous_auth", lambda: {})
+ monkeypatch.setattr(aux, "_resolve_nous_runtime_api", lambda **kw: tuple(runtime))
+ unhealthy = []
+ monkeypatch.setattr(aux, "_mark_provider_unhealthy", lambda *a, **kw: unhealthy.append(a))
+ client = object()
+ monkeypatch.setattr(aux, "_create_openai_client", lambda **kw: client)
+ monkeypatch.setattr(aux, "_aux_probe_active", lambda: True)
+ assert aux._try_nous() == (None, None)
+ assert unhealthy == []
+ runtime[:] = [make_jwt(account_tier="free", client_id="hermes-cli"), NAMED]
+ assert aux._try_nous()[0] is client
+
+
[email protected]("tier", ["anonymous", "free", "paid"])
+def test_401_diagnostics_follow_request_identity_on_welcome_host(tier, capsys, monkeypatch):
+ import agent.conversation_loop as loop
+ from agent.turn_recovery import _print_nous_401_diagnostics
+
+ monkeypatch.setattr(loop, "_print_nous_entitlement_guidance", lambda *a: False)
+ _print_nous_401_diagnostics(agent_for(make_jwt(account_tier=tier), WELCOME), Exception("unauthorized"))
+ output = capsys.readouterr().out
+ assert ("Hermes couldn't start a new one" in output) == (tier == "anonymous")
+ assert ("hermes auth add nous" in output) == (tier != "anonymous")
+
+
+def test_anonymous_claim_does_not_classify_other_providers_as_nous():
+ error = Exception("refused")
+ error.status_code = 429
+ error.body = {"reason": "rate_limited", "retry_after": 600}
+ classified = classify_api_error(error, provider="custom", api_key=make_jwt(), base_url=WELCOME)
+ assert "welcome_refusal" not in classified.error_context
diff --git a/tests/agent/test_welcome_tier_recovery.py b/tests/agent/test_welcome_tier_recovery.py
index b1aa300ed74..76e17ecc112 100644
--- a/tests/agent/test_welcome_tier_recovery.py
+++ b/tests/agent/test_welcome_tier_recovery.py
@@ -15,6 +15,7 @@ import pytest
from agent.agent_runtime_helpers import extract_api_error_context
from agent.error_classifier import FailoverReason, classify_api_error
from agent.turn_retry_state import TurnRetryState
+from tests.hermes_cli.anon_portal import make_jwt
WELCOME = "https://welcome-api.nousresearch.com/v1"
PAID = "https://inference-api.nousresearch.com/v1"
@@ -42,7 +43,7 @@ def _refusal(reason: str, *, retry_after: int = 0, alternates=None) -> MockAPIEr
def _classify(err: MockAPIError, *, model: str = "nous/welcome", base_url: str = WELCOME):
- return classify_api_error(err, provider="nous", model=model, base_url=base_url)
+ return classify_api_error(err, provider="nous", model=model, base_url=base_url, api_key=make_jwt())
class TestDarkTier403:
@@ -76,7 +77,7 @@ class TestDarkTier403:
def _agent(**overrides):
lines = []
agent = SimpleNamespace(
- provider="nous", model="gpt-5", base_url=WELCOME, log_prefix="", _rate_limit_state=None,
+ provider="nous", api_key=make_jwt(), model="gpt-5", base_url=WELCOME, log_prefix="", _rate_limit_state=None,
_vprint=lambda text, force=False: lines.append(text),
_try_refresh_nous_client_credentials=lambda **kw: True,
)
@@ -153,9 +154,9 @@ class TestLongWaitRule:
classified = _classify(err)
assert _is_genuine_nous_rate_limit(_agent(), err, turn_ctx, classified) is True
assert recorded and recorded[0]["error_context"]["reset_at"] == classified.error_context["reset_at"]
- # The same body from the PAID host is not an allowance verdict: main's header rule stands.
+ # The same body for a named account is not an anonymous allowance verdict.
recorded.clear()
- assert _is_genuine_nous_rate_limit(_agent(base_url=PAID), err, turn_ctx, classified) is False
+ assert _is_genuine_nous_rate_limit(_agent(base_url=PAID, api_key=make_jwt(account_tier="paid")), err, turn_ctx, classified) is False
assert recorded == []
# A short one is not an exhausted allowance: nothing recorded, the turn waits it out.
recorded.clear()
@@ -170,7 +171,7 @@ class TestOutageCopy:
def test_a_spent_transport_failure_on_the_welcome_host_reads_as_one_sentence(self, reason):
from agent.turn_recovery import _welcome_outage_copy
from hermes_cli.anon_auth import FREE_TIER_OUTAGE_COPY
- assert _welcome_outage_copy(WELCOME, SimpleNamespace(reason=reason)) == FREE_TIER_OUTAGE_COPY
+ assert _welcome_outage_copy(WELCOME, SimpleNamespace(reason=reason), anonymous=True) == FREE_TIER_OUTAGE_COPY
def test_other_routes_and_other_reasons_keep_the_technical_summary(self):
from agent.turn_recovery import _welcome_outage_copy