Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(agent-runtimes): name the real cause when a provider refuses an agent call

rubenluetke10-beep0a25c2446b10
diff --git a/docs/agent-runtimes.md b/docs/agent-runtimes.md
index 21e2e591b9..bc4d5f703d 100644
--- a/docs/agent-runtimes.md
+++ b/docs/agent-runtimes.md
@@ -71,7 +71,12 @@ call with its own provider plugins (`gateway.py`,
- **Failures.** A provider error before the first token becomes an HTTP
status the runtime backs off on (429 rate limit, 401 refused key, 502
otherwise); after streaming began it is an `error` chunk. Either way the
- message is Jarvis' own, never the provider's body.
+ message is Jarvis' own, never the provider's body. Refusals no retry can
+ fix are told apart first (`provider_errors.py`): an empty balance or zero
+ quota is 402 `billing` even when the provider sent 429 (OpenAI does), a
+ provider that cannot be reached (a stopped local server) is 503
+ `provider_unreachable`. Hermes treats 402 as billing and stops instead of
+ retrying.
- **Costs.** Every call goes through the plugin, so it lands in the cost
ledger (caller `agent-runtime`).
- **ChatGPT subscription.** Handing the login to the runtime would make a
@@ -88,6 +93,13 @@ call with its own provider plugins (`gateway.py`,
limits, so the model picker labels that seat "billed as extra usage"
(`login_providers` on `/api/agent-runtimes`). A Claude login (`sk-ant-oat…`)
saved in the Anthropic API-key slot is never sent as an API key.
+ Measured 2026-10-07: with Extra Usage turned off on the account, Haiku
+ still answers from the plan, while Sonnet, Opus and Fable get a bare 429
+ `rate_limit_error` although the plan has room. The gateway then reads the
+ account's usage report (`/api/oauth/usage`, no inference) and says why:
+ Extra Usage off or its monthly limit spent (402), or a plan window really
+ used up (429 until its reset). The gateway sends Anthropic the agent's own
+ request; it never presents itself as Claude Code.
`scripts/spikes/agent_runtimes_gateway_e2e.py <runtime> <provider> [model]`
runs two real turns through the gateway (route built by `route_for`, the real
diff --git a/jarvis/agent_runtimes/gateway.py b/jarvis/agent_runtimes/gateway.py
index 8da2740009..c40749db97 100644
--- a/jarvis/agent_runtimes/gateway.py
+++ b/jarvis/agent_runtimes/gateway.py
@@ -225,10 +225,17 @@ async def complete_response(grant: Grant, args: dict[str, Any]) -> dict[str, Any
from jarvis.live.subscription_reasoning import SubscriptionReasoningError
try:
+ items: list[dict[str, Any]] = []
async for event in _client(grant.account_id).stream(**args):
finished = event.get("response")
+ if event.get("type") == "response.output_item.done" and isinstance(
+ event.get("item"), dict
+ ):
+ items.append(event["item"])
if event.get("type") == "response.completed" and isinstance(finished, dict):
- return dict(finished)
+ # ChatGPT's backend streams the output items and sends the
+ # completed response with an empty ``output``.
+ return {**finished, "output": finished.get("output") or items}
except (SubscriptionReasoningError, SubscriptionAuthError) as exc:
raise GatewayError(str(exc), status=502, code="subscription_unavailable") from exc
raise GatewayError("ChatGPT ended without an answer.", status=502, code="incomplete")
@@ -400,6 +407,14 @@ def chat_request(body: Any) -> tuple[str, Any]:
def _failure(provider: str, exc: Exception) -> GatewayError:
"""A provider error as a status the runtime can back off on, and a plain
message — never the provider's own response body."""
+ from jarvis.agent_runtimes.provider_errors import classify
+
+ if (refusal := classify(provider, exc)) is not None:
+ # No credits, provider unreachable, Claude Extra Usage off: a retry
+ # cannot help, so the runtime must not read it as a rate limit.
+ failure = GatewayError(refusal.message, status=refusal.status, code=refusal.code)
+ failure.retry_after = refusal.retry_after
+ return failure
status = getattr(exc, "status_code", None) or getattr(exc, "status", None)
if not isinstance(status, int):
response = getattr(exc, "response", None)
@@ -442,6 +457,7 @@ async def _deltas(grant: Grant, model: str, request: Any) -> AsyncIterator[Any]:
queue: asyncio.Queue[Any] = asyncio.Queue(maxsize=256)
async def pump() -> None:
+ login: str | None = None
try:
secret = get_jarvis_agent_secret(grant.provider)
overrides = {grant.provider: secret} if secret else {}
@@ -459,6 +475,12 @@ async def _deltas(grant: Grant, model: str, request: Any) -> AsyncIterator[Any]:
await queue.put(delta)
await queue.put(_DONE)
except Exception as exc: # noqa: BLE001 — handed to the reader, which reports it
+ if login:
+ # Anthropic answers a Claude login it will not serve with a
+ # bare 429; the account's usage report says why.
+ from jarvis.agent_runtimes.provider_errors import explain_login_refusal
+
+ exc = await explain_login_refusal(exc, login, model)
await queue.put(exc)
task = asyncio.get_running_loop().create_task(pump())
diff --git a/jarvis/agent_runtimes/provider_errors.py b/jarvis/agent_runtimes/provider_errors.py
new file mode 100644
index 0000000000..46d8bf06ce
--- /dev/null
+++ b/jarvis/agent_runtimes/provider_errors.py
@@ -0,0 +1,279 @@
+"""Why a provider refused a Hermes / OpenClaw model call, in words a person can act on.
+
+A provider's HTTP status alone misleads: OpenAI answers an empty credit
+balance with 429, OpenRouter with 402, and Anthropic refuses a Claude
+subscription used outside Claude Code with a bare 429 ``rate_limit_error``
+while the plan still has room. Each of those reads as "rate limited, try
+again in 30 s" — and no retry will ever succeed. This module tells them apart:
+
+* **No credits / no quota** on a key -> 402 ``billing`` (a runtime does not
+ retry it; Hermes classifies 402 as billing and stops).
+* **Provider not reachable** (a local model server that is not running, no
+ network) -> 503 ``provider_unreachable``.
+* **Claude subscription**: Anthropic serves a subscription outside Claude Code
+ only through the account's Extra Usage for most models. A 429 on the login
+ is explained from the account's own usage report (``/api/oauth/usage``, the
+ endpoint Claude Code reads; it spends no inference): the plan window really
+ is used up, or Extra Usage is turned off / its monthly limit is spent.
+
+Messages never copy the provider's response body; the body is only matched.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from typing import Any, Final
+
+from jarvis.core.http_pool import SyncHttpClientPool
+
+log = logging.getLogger(__name__)
+
+#: Error codes providers use for an empty balance or a spent quota.
+_BILLING_CODES: Final[frozenset[str]] = frozenset(
+ {
+ "insufficient_quota",
+ "insufficient_credits",
+ "billing_not_active",
+ "billing_hard_limit_reached",
+ "credit_balance_exhausted",
+ "payment_required",
+ }
+)
+
+#: Wording of the same, for providers that send no structured code. Matched in
+#: lower case. Gemini's "limit: 0" means the key has no quota at all for the
+#: model (free tier without access), which no wait fixes.
+_BILLING_PHRASES: Final[tuple[str, ...]] = (
+ "no credits",
+ "insufficient credits",
+ "insufficient balance",
+ "credit balance is too low",
+ "out of credits",
+ "add more credits",
+ "limit: 0,",
+)
+
+#: Transport failures, by class name across the SDKs (openai, anthropic,
+#: httpx): the name is the stable capability signal, a class import is not.
+_UNREACHABLE_ERRORS: Final[frozenset[str]] = frozenset(
+ {"APIConnectionError", "APITimeoutError", "ConnectError", "ConnectTimeout"}
+)
+
+_HTTP_POOL: Final = SyncHttpClientPool(timeout_s=8.0)
+
+_CLAUDE_USAGE_URL: Final[str] = "https://api.anthropic.com/api/oauth/usage"
+_CLAUDE_OAUTH_BETA: Final[str] = "oauth-2025-04-20"
+
+#: The plan windows in the usage report, named the way a person reads them.
+_CLAUDE_WINDOWS: Final[tuple[tuple[str, str], ...]] = (
+ ("five_hour", "5-hour"),
+ ("seven_day", "weekly"),
+ ("seven_day_opus", "weekly Opus"),
+ ("seven_day_sonnet", "weekly Sonnet"),
+)
+
+
+@dataclass(frozen=True, slots=True)
+class Refusal:
+ """What the runtime is told: HTTP status, machine code, plain message."""
+
+ status: int
+ code: str
+ message: str
+ #: Seconds until the refusal lifts, when the provider says so.
+ retry_after: float | None = None
+
+
+class ProviderRefusal(Exception):
+ """A refusal already explained where its context was known (the login)."""
+
+ def __init__(self, refusal: Refusal) -> None:
+ super().__init__(refusal.message)
+ self.refusal = refusal
+
+
+def _status(exc: BaseException) -> int | None:
+ status = getattr(exc, "status_code", None) or getattr(exc, "status", None)
+ if not isinstance(status, int):
+ status = getattr(getattr(exc, "response", None), "status_code", None)
+ return status if isinstance(status, int) else None
+
+
+def _codes_and_text(exc: BaseException) -> tuple[set[str], str]:
+ """The structured error codes and the lower-cased text, for matching only."""
+ codes: set[str] = set()
+ body = getattr(exc, "body", None)
+ error = body.get("error", body) if isinstance(body, dict) else None
+ for source in (exc, error if isinstance(error, dict) else None):
+ if source is None:
+ continue
+ for field in ("code", "type"):
+ value = source.get(field) if isinstance(source, dict) else getattr(source, field, None)
+ if isinstance(value, str) and value:
+ codes.add(value.lower())
+ return codes, f"{exc} {body if body is not None else ''}".lower()
+
+
+def _chain(exc: BaseException) -> list[BaseException]:
+ seen: list[BaseException] = []
+ current: BaseException | None = exc
+ while current is not None and current not in seen and len(seen) < 5:
+ seen.append(current)
+ current = current.__cause__ or current.__context__
+ return seen
+
+
+#: How the gateway's providers are named in a message (the id otherwise).
+_LABELS: Final[dict[str, str]] = {
+ "claude-api": "Anthropic",
+ "openai": "OpenAI",
+ "openai-codex": "The ChatGPT subscription",
+ "grok": "xAI (Grok)",
+ "openrouter": "OpenRouter",
+ "nvidia": "NVIDIA",
+ "gemini": "Google Gemini",
+ "ollama": "Ollama",
+ "local-openai": "The local model server",
+}
+
+
+def _label(provider: str) -> str:
+ return _LABELS.get(provider, provider)
+
+
+def classify(provider: str, exc: BaseException) -> Refusal | None:
+ """The actionable refusal behind ``exc``, or ``None`` for an ordinary error."""
+ if isinstance(exc, ProviderRefusal):
+ return exc.refusal
+ status = _status(exc)
+ codes, text = _codes_and_text(exc)
+ if status == 402 or (
+ status in (400, 403, 429)
+ and (codes & _BILLING_CODES or any(phrase in text for phrase in _BILLING_PHRASES))
+ ):
+ return Refusal(
+ 402,
+ "billing",
+ f"{_label(provider)} has no credits or quota left on this key, so retrying "
+ "will not help. Top it up with the provider, or choose another connected "
+ "model in the agent's settings.",
+ )
+ if status is None and any(
+ cls.__name__ in _UNREACHABLE_ERRORS for err in _chain(exc) for cls in type(err).__mro__
+ ):
+ return Refusal(
+ 503,
+ "provider_unreachable",
+ f"{_label(provider)} is not reachable. If it is a model server on this "
+ "computer, start it; otherwise check the connection, or choose another "
+ "model in the agent's settings.",
+ )
+ return None
+
+
+# ------------------------------------------------------------ Claude login
+
+
+def _reset(raw: Any) -> datetime | None:
+ if not isinstance(raw, str) or not raw:
+ return None
+ try:
+ when = datetime.fromisoformat(raw.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ return when if when.tzinfo else when.replace(tzinfo=UTC)
+
+
+def login_refusal(usage: Any, model: str, *, now: datetime | None = None) -> Refusal | None:
+ """Why Anthropic refused a Claude-login call, from the account's usage report.
+
+ ``None`` when the report explains nothing (then it was an ordinary rate
+ limit). Pure, so it is tested without the network.
+ """
+ if not isinstance(usage, dict):
+ return None
+ now = now or datetime.now(UTC)
+ for field, name in _CLAUDE_WINDOWS:
+ window = usage.get(field)
+ if not isinstance(window, dict):
+ continue
+ utilization = window.get("utilization")
+ if not isinstance(utilization, int | float) or utilization < 100:
+ continue
+ reset = _reset(window.get("resets_at"))
+ wait = max(0.0, (reset - now).total_seconds()) if reset else None
+ when = ""
+ if reset is not None:
+ local = reset.astimezone()
+ when = f" It resets at {local:%H:%M} on {local:%d.%m.}"
+ return Refusal(
+ 429,
+ "rate_limited",
+ f"Your Claude plan's {name} limit is used up.{when}. Choose another "
+ "connected model in the agent's settings to keep working now.",
+ retry_after=wait,
+ )
+ extra = usage.get("extra_usage")
+ if not isinstance(extra, dict):
+ return None
+ shown = model or "This Claude model"
+ if extra.get("is_enabled") is False:
+ return Refusal(
+ 402,
+ "extra_usage_off",
+ f"Anthropic runs {shown} for Hermes and OpenClaw on your Claude "
+ "subscription only as Extra Usage (paid on top of the plan), and Extra "
+ "Usage is turned off for your Claude account, so retrying will not help. "
+ "Turn it on at claude.ai under Settings → Usage, run this agent on a "
+ "Claude Haiku model (covered by your plan), connect an Anthropic API key, "
+ "or choose another provider in the agent's settings.",
+ )
+ if extra.get("spend_limit_reached") is True:
+ return Refusal(
+ 402,
+ "extra_usage_spent",
+ f"Your Claude Extra Usage limit for this month is spent, and Anthropic runs "
+ f"{shown} for Hermes and OpenClaw only as Extra Usage. Raise the limit at "
+ "claude.ai under Settings → Usage, or choose another provider in the "
+ "agent's settings.",
+ )
+ return None
+
+
+def _claude_usage(token: str) -> Any:
+ """The login's usage report, or ``None``. Blocking; never logs the token."""
+ try:
+ response = _HTTP_POOL.client().get(
+ _CLAUDE_USAGE_URL,
+ headers={
+ "Authorization": f"Bearer {token}",
+ "anthropic-beta": _CLAUDE_OAUTH_BETA,
+ "Accept": "application/json",
+ },
+ )
+ except Exception as exc: # noqa: BLE001 — no report means "no explanation", logged
+ log.info("runtime gateway: Claude usage report unavailable (%s)", type(exc).__name__)
+ return None
+ if response.status_code != 200:
+ log.info("runtime gateway: Claude usage report answered %s", response.status_code)
+ return None
+ try:
+ return response.json()
+ except ValueError:
+ log.info("runtime gateway: Claude usage report was not JSON")
+ return None
+
+
+async def explain_login_refusal(exc: BaseException, token: str, model: str) -> BaseException:
+ """``exc`` replaced by a :class:`ProviderRefusal` when the account explains it."""
+ if _status(exc) != 429:
+ return exc
+ usage = await asyncio.to_thread(_claude_usage, token)
+ refusal = login_refusal(usage, model)
+ if refusal is None:
+ return exc
+ log.info("runtime gateway: Claude login refused %s (%s)", model, refusal.code)
+ return ProviderRefusal(refusal)
diff --git a/tests/unit/agent_runtimes/test_provider_errors.py b/tests/unit/agent_runtimes/test_provider_errors.py
new file mode 100644
index 0000000000..09b1f7c5a9
--- /dev/null
+++ b/tests/unit/agent_runtimes/test_provider_errors.py
@@ -0,0 +1,184 @@
+"""Provider refusals a retry cannot fix reach Hermes / OpenClaw as what they are.
+
+Measured live 2026-10-07: an empty OpenAI balance answers 429, OpenRouter 402,
+a stopped local server times out, and Anthropic refuses a Claude subscription
+outside Claude Code with a bare 429 while the plan has room (Extra Usage off).
+All of them used to read as "rate limited, try again in 30 s".
+"""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+
+from jarvis.agent_runtimes import gateway, provider_errors
+from jarvis.agent_runtimes.provider_errors import classify, login_refusal
+
+
+class ProviderStatusError(Exception):
+ """The shape the openai / anthropic SDKs raise: a status and a parsed body."""
+
+ def __init__(self, status: int, body: Any = None, message: str = "Error") -> None:
+ super().__init__(message)
+ self.status_code = status
+ self.body = body
+
+
+class APITimeoutError(Exception):
+ """Named like the SDKs' transport error; the name is the signal."""
+
+
+#: A stand-in Claude login bearer (not a credential).
+_BEARER = "login-bearer"
+
+_USAGE_ROOM = {
+ "five_hour": {"utilization": 21.0, "resets_at": "2026-10-07T11:09:59+00:00"},
+ "seven_day": {"utilization": 54.0, "resets_at": "2026-10-12T12:59:59+00:00"},
+}
+
+
+def test_an_empty_openai_balance_is_billing_not_a_rate_limit() -> None:
+ exc = ProviderStatusError(
+ 429,
+ {"error": {"message": "You have no credits remaining.", "code": "insufficient_quota"}},
+ )
+ refusal = classify("openai", exc)
+ assert refusal is not None
+ assert (refusal.status, refusal.code) == (402, "billing")
+ assert "OpenAI" in refusal.message
+ assert "no credits remaining" not in refusal.message # never the provider's body
+
+
+def test_payment_required_is_billing() -> None:
+ refusal = classify("openrouter", ProviderStatusError(402, {"error": {"code": 402}}))
+ assert refusal is not None and refusal.status == 402
+
+
+def test_a_zero_quota_is_billing() -> None:
+ body = {"error": {"message": "Quota exceeded for metric: x, limit: 0, model: m"}}
+ refusal = classify("gemini", ProviderStatusError(429, body))
+ assert refusal is not None and refusal.code == "billing"
+
+
+def test_an_ordinary_rate_limit_stays_unclassified() -> None:
+ body = {"error": {"type": "rate_limit_error", "message": "Error"}}
+ assert classify("claude-api", ProviderStatusError(429, body)) is None
+ assert classify("openai", ProviderStatusError(500)) is None
+
+
+def test_a_stopped_local_server_is_unreachable() -> None:
+ refusal = classify("local-openai", APITimeoutError("Request timed out."))
+ assert refusal is not None
+ assert (refusal.status, refusal.code) == (503, "provider_unreachable")
+
+
+def test_a_wrapped_transport_error_is_found_in_the_chain() -> None:
+ try:
+ try:
+ raise APITimeoutError("timed out")
+ except APITimeoutError as inner:
+ raise RuntimeError("stream failed") from inner
+ except RuntimeError as outer:
+ refusal = classify("ollama", outer)
+ assert refusal is not None and refusal.code == "provider_unreachable"
+
+
+def test_extra_usage_off_explains_a_claude_login_refusal() -> None:
+ usage = {**_USAGE_ROOM, "extra_usage": {"is_enabled": False, "user_disabled": True}}
+ refusal = login_refusal(usage, "claude-sonnet-5-5")
+ assert refusal is not None
+ assert (refusal.status, refusal.code) == (402, "extra_usage_off")
+ assert "claude-sonnet-5-5" in refusal.message
+ assert "Extra Usage" in refusal.message
+
+
+def test_a_spent_extra_usage_limit_is_named() -> None:
+ usage = {**_USAGE_ROOM, "extra_usage": {"is_enabled": True, "spend_limit_reached": True}}
+ refusal = login_refusal(usage, "claude-opus-5-5")
+ assert refusal is not None and refusal.code == "extra_usage_spent"
+
+
+def test_a_used_up_plan_window_waits_until_its_reset() -> None:
+ usage = {
+ "five_hour": {"utilization": 100.0, "resets_at": "2026-10-07T12:00:00+00:00"},
+ "extra_usage": {"is_enabled": False},
+ }
+ now = datetime(2026, 10, 7, 11, 0, tzinfo=UTC)
+ refusal = login_refusal(usage, "claude-sonnet-5-5", now=now)
+ assert refusal is not None
+ assert refusal.status == 429
+ assert refusal.retry_after == pytest.approx(3600)
+ assert "5-hour" in refusal.message
+
+
+def test_a_report_without_an_explanation_changes_nothing() -> None:
+ usage = {**_USAGE_ROOM, "extra_usage": {"is_enabled": True, "spend_limit_reached": False}}
+ assert login_refusal(usage, "claude-sonnet-5-5") is None
+ assert login_refusal(None, "claude-sonnet-5-5") is None
+
+
+def test_the_gateway_reports_the_refusal_not_a_rate_limit() -> None:
+ failure = gateway._failure(
+ "openai", ProviderStatusError(429, {"error": {"code": "insufficient_quota"}})
+ )
+ assert (failure.status, failure.code) == (402, "billing")
+
+
+async def test_a_claude_login_429_is_explained_from_the_usage_report(monkeypatch) -> None:
+ """The gateway's own plugin path: login answers, Anthropic says 429."""
+ import jarvis.agent_runtimes.model_map as model_map
+ import jarvis.core.config as config
+ import jarvis.plugins.brain.claude_api as claude_api
+ from jarvis.core.protocols import BrainMessage, BrainRequest
+
+ class RefusingBrain:
+ def __init__(self, model: str | None = None, *, auth_token: str | None = None) -> None:
+ assert auth_token == _BEARER
+
+ async def complete(self, request: Any) -> AsyncIterator[Any]:
+ raise ProviderStatusError(429, {"error": {"type": "rate_limit_error"}})
+ yield # pragma: no cover — makes this an async generator
+
+ seen: list[str] = []
+
+ def usage(token: str) -> dict[str, Any]:
+ seen.append(token)
+ return {**_USAGE_ROOM, "extra_usage": {"is_enabled": False}}
+
+ monkeypatch.setattr(model_map, "login_token_for", lambda provider, account: _BEARER)
+ monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: None)
+ monkeypatch.setattr(claude_api, "ClaudeAPIBrain", RefusingBrain)
+ monkeypatch.setattr(provider_errors, "_claude_usage", usage)
+ grant = gateway.Grant("agent-1", "claude-api", "subscription")
+ request = BrainRequest(messages=(BrainMessage("user", "Hi"),), max_tokens=16)
+
+ with pytest.raises(provider_errors.ProviderRefusal) as caught:
+ async for _ in gateway._deltas(grant, "claude-sonnet-5-5", request):
+ pass
+ assert seen == [_BEARER]
+ failure = gateway._failure("claude-api", caught.value)
+ assert (failure.status, failure.code) == (402, "extra_usage_off")
+
+
+async def test_a_non_streaming_subscription_answer_keeps_its_output(monkeypatch) -> None:
+ """ChatGPT's backend streams the items and completes with an empty output."""
+ item = {"type": "message", "content": [{"type": "output_text", "text": "ok"}]}
+
+ class Subscription:
+ async def stream(self, **kwargs: Any) -> AsyncIterator[dict[str, Any]]:
+ yield {"type": "response.output_item.done", "item": item}
+ yield {"type": "response.completed", "response": {"id": "r1", "output": []}}
+
+ gateway.reset()
+ monkeypatch.setattr(gateway, "_client", lambda account_id: Subscription())
+ try:
+ answer = await gateway.complete_response(
+ gateway.Grant("agent-1", "openai-codex"),
+ {"model": "gpt-5.6-sol", "input": [], "instructions": "", "tools": []},
+ )
+ finally:
+ gateway.reset()
+ assert answer["output"] == [item]