The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(free-tier): every free-tier rate limit offers sign-in
alt-glitchd86d8aa177e1
diff --git a/agent/error_classifier.py b/agent/error_classifier.pyindex a191920c23a..529b23ec5c9 100644--- a/agent/error_classifier.py+++ b/agent/error_classifier.py@@ -801,10 +801,17 @@ def _nous_welcome_tier(c: _Ctx) -> Optional[Verdict]:return _v(_R.format_error, retryable=False, should_fallback=True,error_context={"welcome_route": "named_on_welcome_host"})return None+ if status == 402:+ # The free tier has no credits to top up: a payment wall on it is the tier refusing.+ refusal = {"reason": "refused", "retry_after": 0, "alternates": [], "upgrade_url": ""}+ return _v(_R.auth_permanent, retryable=False, should_fallback=True,+ error_context={"welcome_refusal": refusal})if status == 429:- refusal = parse_welcome_refusal(c.body)- if refusal is None:- return None+ # Every free-tier 429 is the allowance talking, so even one without a ``reason`` (header-only,+ # quota words) is a refusal; otherwise it would fall to billing or the generic rate-limit copy.+ from agent.nous_rate_guard import welcome_refusal_from_headers+ refusal = parse_welcome_refusal(c.body) or welcome_refusal_from_headers(+ c.headers, body_wait=_rate_limit_reset_seconds(c.msg, c.body, c.headers))ctx = {"welcome_refusal": refusal}if refusal["reason"] in WELCOME_TIER_GATE_REASONS:return _v(_R.model_not_found, retryable=False, should_fallback=True, error_context=ctx)diff --git a/agent/nous_rate_guard.py b/agent/nous_rate_guard.pyindex 1f80a66785e..d6c2729b8a8 100644--- a/agent/nous_rate_guard.py+++ b/agent/nous_rate_guard.py@@ -152,6 +152,20 @@ def is_long_welcome_rate_limit(error_context: Any) -> bool:return _safe_float(refusal.get("retry_after"), 0.0) >= WELCOME_LONG_WAIT_SECONDS+def welcome_refusal_from_headers(+ headers: Optional[Mapping[str, str]], *, body_wait: Optional[float] = None,+) -> dict[str, Any]:+ """A free-tier 429 that carried no structured ``reason``, read from its headers (else the wait+ its body named) into the ``parse_welcome_refusal`` shape. Long wait or an empty bucket =+ ``rate_limited``; a short or unexplained one = ``at_capacity``. A missing wait stays 0 so the+ breaker never trips on a guess."""+ wait = _parse_reset_seconds(headers) or body_wait or 0.0+ empty = any(remaining is not None and remaining <= 0+ for remaining, _reset in _parse_buckets_from_headers(headers).values())+ reason = "rate_limited" if wait >= WELCOME_LONG_WAIT_SECONDS or empty else "at_capacity"+ return {"reason": reason, "retry_after": max(0, int(wait)), "alternates": [], "upgrade_url": ""}++def _parse_buckets_from_headers(headers: Optional[Mapping[str, str]],) -> dict[str, tuple[Optional[int], Optional[float]]]:diff --git a/tests/agent/test_error_classifier.py b/tests/agent/test_error_classifier.pyindex c8838d0c9e6..41039e8b24f 100644--- a/tests/agent/test_error_classifier.py+++ b/tests/agent/test_error_classifier.py@@ -2080,12 +2080,6 @@ class TestNousWelcomeTier: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", 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)diff --git a/tests/agent/test_free_tier_rate_limit_class.py b/tests/agent/test_free_tier_rate_limit_class.pynew file mode 100644index 00000000000..e40fadcb5d3--- /dev/null+++ b/tests/agent/test_free_tier_rate_limit_class.py@@ -0,0 +1,89 @@+"""Every free-tier refusal offers sign-in: any anonymous 429 (reason or not) and a 402 from the+welcome host classify as a welcome refusal; a signed-in account's identical response does not."""++from types import SimpleNamespace++import httpx+import openai+import pytest++from agent.error_classifier import classify_api_error+from agent.error_surface import build_error_surface_from_result+from agent.nous_rate_guard import is_long_welcome_rate_limit+from agent.turn_recovery import max_retries_exhausted_result, nonretryable_client_error_result+from tests.hermes_cli.anon_portal import make_jwt++WELCOME = "https://welcome-api.nousresearch.com/v1"+MODEL = "nous/welcome"+++def _agent(api_key):+ noop = lambda *a, **kw: None # noqa: E731+ return SimpleNamespace(+ provider="nous", api_key=api_key, base_url=WELCOME, model=MODEL, log_prefix="",+ _rate_limit_state=None, _has_pending_fallback=lambda: False, _dump_api_request_debug=noop,+ _flush_status_buffer=noop, _summarize_api_error=lambda e: str(e), _emit_status=noop,+ _persist_session=noop, _plines=noop, _vprint=noop, _buffer_status=noop, _buffer_vprint=noop,+ _emit_diagnostic_status=noop, _buffer_diagnostic_status=noop, _try_activate_fallback=lambda: False)+++def _error(status, body, headers=None):+ request = httpx.Request("POST", f"{WELCOME}/chat/completions")+ response = httpx.Response(status, json=body, headers=headers or {}, request=request)+ message = (body.get("error") or {}).get("message") if isinstance(body.get("error"), dict) else body.get("message")+ message = message or "refused"+ if status == 429:+ return openai.RateLimitError(message, response=response, body=body)+ return openai.APIStatusError(message, response=response, body=body)+++# (id, status, body, headers, expected free-tier kind, breaker trips)+CASES = [+ ("reason-long", 429, {"reason": "rate_limited", "retry_after": 3600}, None, "rate_limited", True),+ ("reason-short", 429, {"reason": "rate_limited", "retry_after": 5}, None, "rate_limited", False),+ ("retry-after-only", 429, {}, {"Retry-After": "900"}, "rate_limited", True),+ ("bucket-empty", 429, {}, {"x-ratelimit-remaining-requests-1h": "0",+ "x-ratelimit-reset-requests-1h": "3000"}, "rate_limited", True),+ ("short-header", 429, {}, {"Retry-After": "4"}, "at_capacity", False),+ ("bare", 429, {}, None, "at_capacity", False),+ ("unknown-reason", 429, {"reason": "something_else", "retry_after": 5}, None, "at_capacity", False),+ ("quota-words", 429, {"error": {"message": "quota exceeded"}}, None, "at_capacity", False),+ ("payment-402", 402, {"error": {"message": "payment required"}}, None, "refused", False),+]+++def _result(agent, error, classified, status):+ common = dict(api_kwargs=None, api_messages=[], messages=[], conversation_history=[], api_call_count=1,+ approx_tokens=10, provider="nous", base_url=WELCOME, model=MODEL)+ if status == 429:+ return max_retries_exhausted_result(agent, error, classified, attempts=3, is_rate_limited=True,+ error_msg=str(error), **common)+ return nonretryable_client_error_result(agent, error, classified, status_code=status, **common)++[email protected]("case_id,status,body,headers,kind,breaker", CASES, ids=[c[0] for c in CASES])+def test_anonymous_refusals_all_offer_sign_in(case_id, status, body, headers, kind, breaker):+ agent = _agent(make_jwt())+ error = _error(status, body, headers)+ classified = classify_api_error(error, provider="nous", model=MODEL, base_url=WELCOME, api_key=agent.api_key)+ assert classified.error_context["welcome_refusal"]["reason"] == (+ "refused" if status == 402 else kind)+ # A guessed (missing) wait never trips the cross-session breaker.+ assert is_long_welcome_rate_limit(classified.error_context) is breaker+ result = _result(agent, error, classified, status)+ assert result["free_tier"]["kind"] == kind+ assert result["final_response"].endswith("To sign in: /login.")+ assert "fallback add" not in result["final_response"]+ surface = build_error_surface_from_result(result, provider="nous", model=MODEL)+ assert surface["code"] == f"free_tier_{kind}"++[email protected]("case_id,status,body,headers,kind,breaker", CASES, ids=[c[0] for c in CASES])+def test_named_account_same_response_is_not_a_free_tier_refusal(case_id, status, body, headers, kind, breaker):+ agent = _agent(make_jwt(account_tier="free", client_id="hermes-cli"))+ error = _error(status, body, headers)+ classified = classify_api_error(error, provider="nous", model=MODEL, base_url=WELCOME, api_key=agent.api_key)+ assert "welcome_refusal" not in classified.error_context+ result = _result(agent, error, classified, status)+ assert "free_tier" not in result+ assert "To sign in: /login." not in result["final_response"]diff --git a/tests/agent/test_welcome_tier_recovery.py b/tests/agent/test_welcome_tier_recovery.pyindex 431f209d5da..40ba2e11012 100644--- a/tests/agent/test_welcome_tier_recovery.py+++ b/tests/agent/test_welcome_tier_recovery.py@@ -292,7 +292,8 @@ class TestFreeTierCooldownCutoff:is_rate_limited=True, error_msg="429", api_kwargs=None, api_messages=[], messages=[],conversation_history=[], api_call_count=1, approx_tokens=10, provider="nous", base_url=WELCOME,model="nous/welcome")- assert "resets in ~2 min" in result["final_response"]+ assert "refreshes in about 2 minutes" in result["final_response"]+ assert result["free_tier"]["kind"] == "rate_limited"def test_a_subagent_of_a_desktop_session_keeps_waiting(self):"""The child runs in a copy of the parent's context, so it reads the parent's source."""