The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: credit-wall 404 is one billing table row; billing fallback warns with profile + remedy
teknium11cd2c45fcbf3
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex b4b96c611bf..68692c4e288 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -1825,6 +1825,23 @@ def _rebind_fallback_credential_pool(agent, fb_provider: str, fb_model: str) ->logger.debug("Fallback to %s/%s: could not attach credential pool: %s", fb_provider, fb_model, exc)+def _log_fallback_activated(agent, reason, old_model, old_provider, fb_model, fb_provider) -> None:+ """A billing switch is a WARNING naming the profile, both models and the remedy: the gateway+ persists the turn as a transient failure otherwise, and nothing in the log says the paid+ model was refused for credits or how to fix it (#115702). Other reasons stay INFO."""+ if reason != FailoverReason.billing:+ logger.info("Fallback activated: %s → %s (%s)", old_model, fb_model, fb_provider)+ return+ from hermes_constants import get_hermes_home, profile_name_for_home+ profile = profile_name_for_home(get_hermes_home()) or "default"+ remedy = "hermes model" if profile == "default" else f"hermes -p {profile} model"+ logger.warning(+ "Profile %s: %s via %s refused for billing/credits — using fallback %s via %s. "+ "Top up credits, or run `%s` to pick a model this account can use.",+ profile, old_model, old_provider, fb_model, fb_provider, remedy,+ )++def _fallback_chain_exhausted(agent, reason: "FailoverReason | None") -> bool:"""Chain exhausted (always False). A non-empty chain walked on a non-rate-limit failure arms ashort cooldown so next turn's restore_primary_runtime stays gated instead of replaying the whole@@ -2071,7 +2088,7 @@ def try_activate_fallback(agent, reason: "FailoverReason | None" = None) -> bool# provenance so the restore path only emits a recovery notice after a real fallback.agent._provider_fallback_active = Trueagent._provider_fallback_route = (str(fb_model), str(fb_provider))- logger.info("Fallback activated: %s → %s (%s)", old_model, fb_model, fb_provider)+ _log_fallback_activated(agent, reason, old_model, old_provider, fb_model, fb_provider)# The stale-call streak measured the OLD provider; carrying it over would# short-circuit the fresh fallback before its first stream attempt._reset_stale_streak(agent)diff --git a/agent/error_classifier.py b/agent/error_classifier.pyindex b90801d1613..293b6c42bcb 100644--- a/agent/error_classifier.py+++ b/agent/error_classifier.py@@ -136,8 +136,7 @@ _BILLING_ERROR_CODES = frozenset({# terminal for this credential until limits are raised."credit_balance_exhausted", "organization_spend_limit_exceeded","organization_usage_limit_exceeded", "project_spend_limit_exceeded",- # Paid-model credit wall arriving as a 404 (the paid model "vanishes"- # without credits): also matched explicitly by _status_404. (#115702)+ # Nous paid model behind an empty credit balance arrives as a 404 (#115702)."insufficient_credits_for_paid_model",})@@ -588,10 +587,6 @@ _OVERFLOW_AS_5XX_RULES = ((_CONTEXT_OVERFLOW_PATTERNS, _V_CONTEXT_OVERFLOW),)-# 404 credit-exhaustion code (paid model without credits): matched as a-# structured code AND in flattened SDK error text by _status_404. (#115702)-_CREDIT_EXHAUSTION_404_CODES = frozenset({"insufficient_credits_for_paid_model"})-# 404: Nous API surfaces credit depletion as a paid model vanishing from the# Free Tier (billing, not missing model); policy block before model_not_found._404_RULES = (@@ -1003,17 +998,10 @@ def _status_403(c: _Ctx) -> Verdict:def _status_404(c: _Ctx) -> Verdict:- # Paid-model credit wall: route like 429-exhaustion (billing with the- # fallback chain armed). A structured billing code is decisive here, mirroring- # _status_429 — the status handler always returns, so _by_error_code never- # sees it. The marker lets the fallback switch log an actionable ERROR- # naming the credits and the fallback target.- credit_code = c.code if c.code in _CREDIT_EXHAUSTION_404_CODES else next(- (code for code in _CREDIT_EXHAUSTION_404_CODES if code in c.msg), None,- )- if credit_code is not None:- return _v(_R.billing, retryable=False, **_ROTATE_FALLBACK,- error_context={"credit_exhaustion_code": credit_code})+ # Structured billing code first, as in _status_429: this handler always returns,+ # so _by_error_code never sees it; a bare "Not Found" message has nothing to match.+ if c.code in _BILLING_ERROR_CODES:+ return _V_BILLINGverdict = _first_match(c.msg, _404_RULES)if verdict is not None:return verdictdiff --git a/agent/turn_api_error.py b/agent/turn_api_error.pyindex 8fdf475ade0..464801c0cc5 100644--- a/agent/turn_api_error.py+++ b/agent/turn_api_error.py@@ -19,7 +19,7 @@ from agent.error_classifier import FailoverReason, classify_api_errorfrom agent.turn_overflow import recover_from_overflowfrom agent.turn_recovery import (_NONRETRYABLE_LABELS, abort_turn_on_interrupt, compute_error_backoff, interruptible_backoff_sleep,- log_api_error_attempt, log_credit_exhaustion_fallback,+ log_api_error_attempt,max_retries_exhausted_result, nonretryable_client_error_result, recover_after_classification,recover_before_classification, route_classified_error,)@@ -339,7 +339,6 @@ def settle_unrecovered_error(_label = _NONRETRYABLE_LABELS.get(classified.reason, f"Non-retryable error (HTTP {status_code})")agent._buffer_diagnostic_status(f"⚠️ {_label} — trying fallback...")if agent._try_activate_fallback():- log_credit_exhaustion_fallback(agent, classified)# Direct ``return _verdict("break")`` is load-bearing: the restart handler# re-runs the pre-API preflight against the fallback's context window.active_system_prompt = _arm_fallback_restart(agent, api_messages, active_system_prompt, _retry)diff --git a/agent/turn_recovery.py b/agent/turn_recovery.pyindex 34b0a53d518..32324ecd792 100644--- a/agent/turn_recovery.py+++ b/agent/turn_recovery.py@@ -1603,24 +1603,6 @@ def activate_codex_app_server_fallback(agent: Any, result: Dict[str, Any]) -> boreturn bool(agent._try_activate_fallback(reason=classified.reason))-def log_credit_exhaustion_fallback(agent: Any, classified: Any) -> None:- """ERROR naming a 404 credit-exhaustion fallback switch and its target.-- Narrow (#115702): only fires when the classifier marked the verdict with- ``credit_exhaustion_code`` -- every other fallback keeps its existing copy.- """- code = (getattr(classified, "error_context", None) or {}).get("credit_exhaustion_code")- if not code:- return- logger.error(- "%sInsufficient credits for paid model (404 %s on %s via %s) -- "- "using fallback %s via %s. Top up credits or pick a free model.",- getattr(agent, "log_prefix", ""),- code, getattr(classified, "model", None), getattr(classified, "provider", None),- getattr(agent, "model", None), getattr(agent, "provider", None),- )--def _is_genuine_nous_rate_limit(agent: Any, api_error: Exception, error_context: Any, classified: Any = None) -> bool:"""Record a genuine account-level Nous 429 to the cross-session breaker; upstreamcapacity 429s (no exhausted bucket in headers or last-known state) are left alone.@@ -1797,7 +1779,6 @@ def route_classified_error(if not pool_may_recover:agent._buffer_diagnostic_status(_eager_fallback_status(classified, _is_upstream, _is_transport_failure))if agent._try_activate_fallback(reason=classified.reason):- log_credit_exhaustion_fallback(agent, classified)return _fallback_break()# A 401/403 surviving credential refresh means a broken credential or endpoint:diff --git a/tests/agent/test_credit_404_fallback.py b/tests/agent/test_credit_404_fallback.pyindex ea4fbdb9252..bcbd9c61f18 100644--- a/tests/agent/test_credit_404_fallback.py+++ b/tests/agent/test_credit_404_fallback.py@@ -1,94 +1,59 @@-"""404 'insufficient_credits_for_paid_model' triggers the fallback chain (#115702)."""+"""Regression for #115702: a paid Nous model behind an empty credit balance answers HTTP 404+``insufficient_credits_for_paid_model``. The code must classify as billing (fallback chain armed,+no retry burn) and the resulting switch must be a WARNING naming the failing profile and remedy.+"""import logging-from types import SimpleNamespace+from agent.chat_completion_helpers import _log_fallback_activatedfrom agent.error_classifier import FailoverReason, classify_api_error-from agent.turn_recovery import log_credit_exhaustion_fallback, route_classified_error-from agent.turn_retry_state import TurnRetryState+from hermes_constants import reset_hermes_home_override, set_hermes_home_override-class MockAPIError(Exception):- """Simulates an OpenAI SDK APIStatusError."""-- def __init__(self, message, status_code=None, body=None):+class _StatusError(Exception):+ def __init__(self, message, status_code, body):super().__init__(message)self.status_code = status_code- self.body = body or {}+ self.body = body-def _classified_credit_404():- e = MockAPIError(- "Not Found",- status_code=404,- body={"error": {"code": "insufficient_credits_for_paid_model", "message": "Not Found"}},+def test_404_insufficient_credits_code_is_billing_with_fallback():+ # Structured code only, message carries no billing wording (message-pattern rules cannot save it).+ err = _StatusError(+ "Not Found", 404, {"error": {"code": "insufficient_credits_for_paid_model", "message": "Not Found"}},)- return classify_api_error(e, provider="nous", model="openai/gpt-5.5-pro")---def test_credit_404_classifies_like_429_exhaustion():- result = _classified_credit_404()- assert result.reason == FailoverReason.billing- assert result.retryable is False- assert result.should_fallback is True---def test_credit_404_fallback_logs_actionable_error_naming_credits_and_target(caplog):- agent = SimpleNamespace(model="openai/gpt-5.5-free", provider="nous", log_prefix="")- with caplog.at_level(logging.ERROR, logger="agent.conversation_loop"):- log_credit_exhaustion_fallback(agent, _classified_credit_404())- errors = [r for r in caplog.records if r.levelno >= logging.ERROR]- assert len(errors) == 1- text = errors[0].getMessage().lower()- assert "credit" in text- assert "insufficient_credits_for_paid_model" in text- assert "openai/gpt-5.5-free" in text---def test_credit_404_fallback_log_silent_without_marker(caplog):- agent = SimpleNamespace(model="x", provider="nous", log_prefix="")- classified = SimpleNamespace(reason=FailoverReason.billing, error_context={})- with caplog.at_level(logging.ERROR, logger="agent.conversation_loop"):- log_credit_exhaustion_fallback(agent, classified)- assert [r for r in caplog.records if r.levelno >= logging.ERROR] == []---def test_credit_404_routes_to_fallback_chain(caplog):- """End to end through the classifier + eager-fallback routing: the 404- credit error attempts the fallback_model chain and logs the ERROR."""- classified = _classified_credit_404()- calls = []-- agent = SimpleNamespace(- model="openai/gpt-5.5-pro",- provider="nous",- log_prefix="",- _fallback_index=0,- _fallback_chain=[{"provider": "nous", "model": "openai/gpt-5.5-free"}],- _credential_pool=None,+ verdict = classify_api_error(err, provider="nous", model="z-ai/glm-5.2")+ assert verdict.reason == FailoverReason.billing+ assert verdict.should_fallback and not verdict.retryable+ # Control: an unrelated 404 body keeps its generic verdict — nothing to fall back for.+ other = classify_api_error(+ _StatusError("Not Found", 404, {"error": {"code": "route_not_found", "message": "Not Found"}}),+ provider="nous", model="z-ai/glm-5.2",)-- def _activate(reason=None):- calls.append(reason)- agent.model = "openai/gpt-5.5-free"- return True-- agent._try_activate_fallback = _activate- agent._buffer_diagnostic_status = lambda msg: calls.append(msg)-- with caplog.at_level(logging.ERROR, logger="agent.conversation_loop"):- verdict = route_classified_error(- agent, MockAPIError("Not Found", 404), classified, TurnRetryState(),- error_msg="Not Found", error_context={}, recovered_with_pool=False,- base_url="", model="openai/gpt-5.5-pro", messages=[], api_messages=[],- system_message=None, active_system_prompt="sys", conversation_history=[],- retry_count=0, max_retries=3, compression_attempts=0,- max_compression_attempts=2, api_call_count=1, effective_task_id=None,- )- assert verdict.action == "break"- assert FailoverReason.billing in calls- assert agent.model == "openai/gpt-5.5-free"- errors = [r for r in caplog.records if r.levelno >= logging.ERROR]- assert len(errors) == 1- text = errors[0].getMessage().lower()- assert "credit" in text and "openai/gpt-5.5-free" in text+ assert other.reason == FailoverReason.unknown+++def test_billing_fallback_warning_names_failing_profile_and_remedy(tmp_path, caplog):+ """Under multiplex the log runs in the failing profile's home scope: A then B name themselves,+ never the launch profile; a non-billing switch stays INFO."""+ seen = {}+ for name in ("alpha", "beta"):+ token = set_hermes_home_override(tmp_path / ".hermes" / "profiles" / name)+ try:+ caplog.clear()+ with caplog.at_level(logging.INFO, logger="agent.chat_completion_helpers"):+ _log_fallback_activated(None, FailoverReason.billing, "z-ai/glm-5.2", "nous", "free/model", "nous")+ finally:+ reset_hermes_home_override(token)+ warnings = [r for r in caplog.records if r.levelno == logging.WARNING]+ assert len(warnings) == 1+ seen[name] = warnings[0].getMessage()+ assert "Profile alpha:" in seen["alpha"] and "hermes -p alpha model" in seen["alpha"]+ assert "Profile beta:" in seen["beta"] and "alpha" not in seen["beta"]+ for text in seen.values():+ assert "z-ai/glm-5.2" in text and "free/model" in text++ caplog.clear()+ with caplog.at_level(logging.INFO, logger="agent.chat_completion_helpers"):+ _log_fallback_activated(None, FailoverReason.server_error, "a", "p", "b", "q")+ assert [r.levelno for r in caplog.records] == [logging.INFO]diff --git a/tests/agent/test_error_classifier.py b/tests/agent/test_error_classifier.pyindex 66588810817..5c0f941b150 100644--- a/tests/agent/test_error_classifier.py+++ b/tests/agent/test_error_classifier.py@@ -270,43 +270,6 @@ class TestClassifyApiError:assert result.retryable is Falseassert result.should_fallback is True- def test_404_insufficient_credits_for_paid_model_code_is_billing(self):- # A 404 carrying the structured 'insufficient_credits_for_paid_model'- # code (paid model ungated by credits) must route like 429-exhaustion:- # billing with the fallback chain armed -- not 'unknown' burning- # retries and never falling back. (#115702)- e = MockAPIError(- "Not Found",- status_code=404,- body={- "error": {- "code": "insufficient_credits_for_paid_model",- "message": "Not Found",- },- },- )- result = classify_api_error(e, provider="nous", model="openai/gpt-5.5-pro")- assert result.reason == FailoverReason.billing- assert result.retryable is False- assert result.should_rotate_credential is True- assert result.should_fallback is True- assert result.error_context.get("credit_exhaustion_code") == "insufficient_credits_for_paid_model"-- def test_404_insufficient_credits_for_paid_model_in_message_is_billing(self):- # Same code embedded in the exception text (the SDK str() flattens the- # body) with no billing wording in the message -- still billing.- e = MockAPIError(- "Error code: 404 - {'error': {'code': 'insufficient_credits_for_paid_model', "- "'message': 'request failed'}}",- status_code=404,- )- result = classify_api_error(e, provider="nous", model="openai/gpt-5.5-pro")- assert result.reason == FailoverReason.billing- assert result.retryable is False- assert result.should_fallback is True- assert result.error_context.get("credit_exhaustion_code") == "insufficient_credits_for_paid_model"--def test_wrapped_402_uses_nested_body_message(self):inner = MockAPIError("inner",