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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(missions): per-API-family quota/auth cooldown so the family walk crosses past a depleted key (BUG-042 defect 4)
Ruben Lütke484719970383
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 5a3ead82da..c40d4b5474 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -3021,9 +3021,9 @@ OAuth login was dead (nothing refreshes `~/.claude` on this host). A healthyOpenRouter key was configured the whole time — the Brain chatted over ithappily — but no mission ever reached it.-**Root cause — three AP-22 violations in the worker chain** (the third only-became visible once the first two were fixed and the live verify mission-019f3d01 reached the API-key walk):+**Root cause — four AP-22 violations in the worker chain** (each next one+only became visible once the previous was fixed and a live verify mission+— 019f3d01, then 019f3d0f — walked one family further):1. *No memory of the codex cap.* `claude_quota_state` existed for the Claudedirection, but a usage-capped codex was deliberately NOT flagged ("thenext mission retries codex automatically"), so@@ -3044,6 +3044,12 @@ became visible once the first two were fixed and the live verify mission`ApiAgentWorker('claude-api')`, which 401'd ("invalid x-api-key") onevery retry while the healthy openrouter key sat ONE slot further in theSAME loop.+4. *No memory of a failing API family.* With defect 3 fixed, the walk+ reached gemini — whose prepaid credits were DEPLETED (429+ RESOURCE_EXHAUSTED, mission 019f3d0f). `ApiAgentWorker` recorded nothing+ about the failure, so every retry deterministically re-picked gemini;+ openrouter was never reached. The claude/codex directions had quota+ cooldowns, the API families had none.**Fix.** `jarvis/codex_quota_state.py` (new, mirror of`claude_quota_state`): a time-based, self-expiring cooldown armed by a@@ -3059,7 +3065,12 @@ claude→codex fallbacks all skip codex while the cooldown is armed.`get_provider_secret(prov)` gate everywhere the factory walks API-keyfamilies: for `claude-api` an `sk-ant-oat` bearer never counts, and aclassic key a worker fingerprint-flagged dead this session is skipped until-it changes.+it changes. `jarvis/api_family_quota_state.py` (new, generic per-provider+mirror of the claude/codex cooldowns): `ApiAgentWorker` arms it when a run+dies on a quota/auth provider error and clears it on success;+`_api_key_family_viable` consults it. FINGERPRINT-bound: saving a new key in+the API-Keys view lifts the block instantly (in-app recovery, §3), while the+same dead key stays skipped until the cooldown self-expires.**Guards.** `tests/missions/workers/test_codex_quota_state.py`;`tests/missions/workers/test_codex_auth_fallback.py` (cap arms cooldown +diff --git a/jarvis/api_family_quota_state.py b/jarvis/api_family_quota_state.pynew file mode 100644index 0000000000..f2c1df40fe--- /dev/null+++ b/jarvis/api_family_quota_state.py@@ -0,0 +1,103 @@+"""Process-local per-API-family quota/auth cooldown (time-based, fingerprinted).++Why this exists: the mission worker's API-key family walk+(``claude-api → gemini → openrouter → openai``) picked the FIRST family with a+stored key — with no memory of that family failing. Mission 019f3d0f+(2026-07-07, the verify run of the BUG-042 fixes): gemini's prepaid credits+were DEPLETED (429 RESOURCE_EXHAUSTED), yet every retry re-picked gemini; the+healthy openrouter key one slot further in the SAME loop was never reached+(AP-22). Same shape as the stale claude-api bearer that 401'd every retry in+mission 019f3d01.++This is the generic API-family mirror of ``claude_quota_state`` /+``codex_quota_state``, keyed by provider slug. When an ``ApiAgentWorker`` run+dies on a quota or auth provider error, it arms this cooldown; while armed the+family walk (``_api_key_family_viable``) skips the family. A successful run+clears it immediately, and the cooldown self-expires so a reset cap is+re-probed.++Fingerprint binding (in-app recoverability, CLAUDE.md §3): the cooldown is+bound to the credential that failed. Saving a NEW key in the API-Keys view+changes the fingerprint and lifts the block instantly — no restart, no wait.+A check without a current fingerprint is conservative: the cooldown holds.++Process-local + in-memory like its siblings: the live app is one process, a+module global suffices, and it resets on restart (then re-detected on the next+failing spawn). Monotonic clock; ``now_fn`` injectable for deterministic tests.+"""+from __future__ import annotations++import threading+import time+from collections.abc import Callable++# Same middle ground as the claude/codex cooldowns: at most one wasted re-probe+# per ~20 min of continuous mission activity, back in rotation soon after a+# top-up / cap reset.+_DEFAULT_COOLDOWN_S: float = 20 * 60.0++_lock = threading.Lock()+# provider slug -> (monotonic deadline, fingerprint-at-mark-time or None)+_cooldowns: dict[str, tuple[float, str | None]] = {}+++def _norm(provider: str | None) -> str:+ return (provider or "").strip().lower()+++def mark_api_family_cooldown(+ provider: str,+ *,+ fingerprint: str | None = None,+ now_fn: Callable[[], float] = time.monotonic,+ cooldown_s: float = _DEFAULT_COOLDOWN_S,+) -> None:+ """Arm the cooldown after a worker proved *provider*'s key unusable+ (quota depleted / rate-capped / auth-dead)."""+ key = _norm(provider)+ if not key:+ return+ with _lock:+ _cooldowns[key] = (now_fn() + cooldown_s, fingerprint)+++def clear_api_family_cooldown(provider: str) -> None:+ """Clear the cooldown immediately (a worker on *provider* just succeeded)."""+ with _lock:+ _cooldowns.pop(_norm(provider), None)+++def api_family_in_cooldown(+ provider: str,+ *,+ current_fingerprint: str | None = None,+ now_fn: Callable[[], float] = time.monotonic,+) -> bool:+ """True while *provider*'s key is presumed unusable.++ A ``current_fingerprint`` differing from the one recorded at mark time+ means the user saved a NEW credential — the cooldown does not apply to it.+ """+ key = _norm(provider)+ with _lock:+ entry = _cooldowns.get(key)+ if entry is None:+ return False+ deadline, marked_fp = entry+ if now_fn() >= deadline:+ _cooldowns.pop(key, None)+ return False+ if (+ marked_fp is not None+ and current_fingerprint is not None+ and current_fingerprint != marked_fp+ ):+ return False+ return True+++__all__ = [+ "api_family_in_cooldown",+ "clear_api_family_cooldown",+ "mark_api_family_cooldown",+]diff --git a/jarvis/missions/init.py b/jarvis/missions/init.pyindex c44e4100d7..31bdb77a48 100644--- a/jarvis/missions/init.py+++ b/jarvis/missions/init.py@@ -512,14 +512,20 @@ def _api_key_family_viable(provider: str) -> bool:key = get_provider_secret(provider)if not key:return False+ # A family a worker just proved quota-depleted / auth-dead is skipped+ # until its cooldown self-expires — fingerprinted, so saving a NEW key in+ # the API-Keys view lifts the block instantly (mission 019f3d0f: gemini's+ # depleted prepaid credits were re-picked on every retry, BUG-042).+ from jarvis.api_family_quota_state import api_family_in_cooldown+ from jarvis.claude_auth_state import claude_auth_dead, credential_fingerprint++ if api_family_in_cooldown(+ provider, current_fingerprint=credential_fingerprint(key)+ ):+ return Falseif provider == "claude-api":if key.startswith("sk-ant-oat"):return False- from jarvis.claude_auth_state import (- claude_auth_dead,- credential_fingerprint,- )-return not claude_auth_dead(current_fingerprint=credential_fingerprint(key))return Truediff --git a/jarvis/missions/workers/api_agent_worker.py b/jarvis/missions/workers/api_agent_worker.pyindex 9c94eecaec..83879429f6 100644--- a/jarvis/missions/workers/api_agent_worker.py+++ b/jarvis/missions/workers/api_agent_worker.py@@ -44,6 +44,40 @@ from .stream_consumer import (logger = logging.getLogger(__name__)+# Provider errors that mean the FAMILY's key is unusable right now — quota+# depleted / rate-capped ("Your prepayment credits are depleted", 429+# RESOURCE_EXHAUSTED) or auth-dead ("invalid x-api-key", 401). Either way,+# retrying the same family is a guaranteed repeat; the per-family cooldown+# tells the factory's family walk to cross to the next key (missions+# 019f3d01 + 019f3d0f, 2026-07-07 / BUG-042).+_FAMILY_UNUSABLE_MARKERS: tuple[str, ...] = (+ # quota / rate / billing+ "429",+ "quota",+ "rate limit",+ "rate_limit",+ "too many requests",+ "resource_exhausted",+ "depleted",+ "credit",+ "billing",+ "insufficient",+ # auth+ "401",+ "unauthorized",+ "authentication",+ "invalid x-api-key",+ "invalid api key",+ "invalid_api_key",+)+++def _error_means_family_unusable(text: str) -> bool:+ """True when a provider error proves the key itself cannot run right now."""+ low = (text or "").lower()+ return any(marker in low for marker in _FAMILY_UNUSABLE_MARKERS)++# Provider slug -> (module, class). Lazy-imported so a worker for one provider# never imports another's SDK path. Slugs match jarvis provider ids._BRAIN_BY_PROVIDER: dict[str, tuple[str, str]] = {@@ -380,6 +414,10 @@ class ApiAgentWorker:subtype="success", is_error=False, session_id=session_id,num_turns=turns, duration_ms=wall_ms, result=summary[:4000],)+ # This family's key works — lift any armed cooldown immediately.+ from jarvis.api_family_quota_state import clear_api_family_cooldown++ clear_api_family_cooldown(self.provider)_emit_line(res)yield resexcept asyncio.CancelledError:@@ -387,6 +425,28 @@ class ApiAgentWorker:except Exception as exc: # noqa: BLE001wall_ms = int((time.perf_counter() - t0) * 1000)logger.warning("ApiAgentWorker[%s] failed: %s", worker_id, exc, exc_info=True)+ if _error_means_family_unusable(str(exc)):+ # Remember that THIS key cannot run right now, fingerprinted so+ # a freshly saved key lifts the block instantly. The factory's+ # family walk skips the family on the retry and crosses to the+ # user's next healthy key (AP-22, BUG-042).+ from jarvis.api_family_quota_state import mark_api_family_cooldown+ from jarvis.claude_auth_state import credential_fingerprint++ fp: str | None = None+ try:+ from jarvis.core.config import get_provider_secret++ fp = credential_fingerprint(get_provider_secret(self.provider))+ except Exception: # noqa: BLE001 — unreadable store => unbound cooldown+ fp = None+ mark_api_family_cooldown(self.provider, fingerprint=fp)+ logger.warning(+ "ApiAgentWorker[%s]: provider %r key is unusable (quota/auth) "+ "— arming the family cooldown so the worker factory crosses "+ "to the next reachable key family on the retry.",+ worker_id, self.provider,+ )res = ClaudeResult(subtype="error_during_execution", is_error=True, session_id=session_id,num_turns=turns, duration_ms=wall_ms,diff --git a/tests/missions/test_worker_cross_family_fallback.py b/tests/missions/test_worker_cross_family_fallback.pyindex 1819d37b8a..e51851829b 100644--- a/tests/missions/test_worker_cross_family_fallback.py+++ b/tests/missions/test_worker_cross_family_fallback.py@@ -196,6 +196,31 @@ def test_claude_binary_with_dead_auth_crosses_to_api_key(assert worker.provider == "openrouter"+def test_quota_depleted_family_is_skipped_in_the_walk(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Mission 019f3d0f (2026-07-07): gemini's prepaid credits were depleted+ (429) and every retry re-picked gemini — openrouter, one slot further in+ the SAME loop, was never reached. A family in quota cooldown must be+ walked past."""+ from jarvis.api_family_quota_state import (+ clear_api_family_cooldown,+ mark_api_family_cooldown,+ )+ from jarvis.claude_auth_state import credential_fingerprint++ _patch_env(monkeypatch, keys=("gemini", "openrouter"))+ mark_api_family_cooldown(+ "gemini", fingerprint=credential_fingerprint("KEY")+ )+ try:+ worker = mi._cross_family_last_resort_worker("t")+ assert isinstance(worker, ApiAgentWorker)+ assert worker.provider == "openrouter"+ finally:+ clear_api_family_cooldown("gemini")++def test_claude_binary_with_live_auth_stays_preferred(monkeypatch: pytest.MonkeyPatch,) -> None:diff --git a/tests/missions/workers/test_api_agent_worker.py b/tests/missions/workers/test_api_agent_worker.pyindex f2eeed3cf1..d001b73be5 100644--- a/tests/missions/workers/test_api_agent_worker.py+++ b/tests/missions/workers/test_api_agent_worker.py@@ -48,6 +48,18 @@ async def _drain(worker: ApiAgentWorker, **kw): # noqa: ANN003return events[email protected](autouse=True)+def _reset_family_cooldowns() -> None:+ """The per-family cooldown is a process global — reset around every test."""+ from jarvis.api_family_quota_state import clear_api_family_cooldown++ for prov in ("openai", "openrouter", "gemini", "claude-api"):+ clear_api_family_cooldown(prov)+ yield+ for prov in ("openai", "openrouter", "gemini", "claude-api"):+ clear_api_family_cooldown(prov)++def test_supports_api_agent_worker() -> None:assert supports_api_agent_worker("openai")assert supports_api_agent_worker("openrouter")@@ -101,6 +113,137 @@ async def test_worker_writes_file_and_emits_critic_readable_stream(assert "out.txt" in extract_write_targets(stream_text)+class _RaisingBrain:+ """A brain whose complete() dies with a provider error (429/401/...)."""++ def __init__(self, exc: Exception) -> None:+ self._exc = exc++ def can_call_tools(self) -> bool:+ return True++ async def complete(self, req): # noqa: ANN001, ANN201+ raise self._exc+ yield # pragma: no cover — makes this an async generator+++async def test_quota_depleted_error_arms_family_cooldown(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """Mission 019f3d0f (2026-07-07): gemini's prepaid credits were depleted+ (429 RESOURCE_EXHAUSTED) and every retry re-picked gemini. A quota/auth+ provider error must arm the per-family cooldown so the factory's family+ walk skips this family on the retry and reaches the next healthy key."""+ from jarvis.api_family_quota_state import api_family_in_cooldown++ monkeypatch.setattr(+ "jarvis.missions.workers.api_agent_worker._build_brain",+ lambda provider, model: _RaisingBrain(+ RuntimeError(+ "429 Too Many Requests. Your prepayment credits are depleted. "+ "RESOURCE_EXHAUSTED"+ )+ ),+ )+ monkeypatch.setattr(+ "jarvis.core.config.get_provider_secret", lambda p: "DEAD-GEMINI-KEY"+ )+ worker = ApiAgentWorker("gemini")++ events = await _drain(+ worker, prompt="t", worktree=tmp_path, env={}, job=None,+ worker_id="m::0", log_dir=tmp_path / "_logs", model="gemini-3.5-flash",+ )++ assert events[-1].is_error is True+ from jarvis.claude_auth_state import credential_fingerprint++ assert (+ api_family_in_cooldown(+ "gemini", current_fingerprint=credential_fingerprint("DEAD-GEMINI-KEY")+ )+ is True+ )+++async def test_dead_key_401_arms_family_cooldown(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """Mission 019f3d01: a stale claude-api credential 401'd on every retry.+ An auth error is family-unusable just like a quota error — arm the cooldown."""+ from jarvis.api_family_quota_state import api_family_in_cooldown++ monkeypatch.setattr(+ "jarvis.missions.workers.api_agent_worker._build_brain",+ lambda provider, model: _RaisingBrain(+ RuntimeError(+ "Error code: 401 - {'type': 'error', 'error': {'type': "+ "'authentication_error', 'message': 'invalid x-api-key'}}"+ )+ ),+ )+ monkeypatch.setattr(+ "jarvis.core.config.get_provider_secret", lambda p: "STALE-KEY"+ )+ worker = ApiAgentWorker("claude-api")++ events = await _drain(+ worker, prompt="t", worktree=tmp_path, env={}, job=None,+ worker_id="m::0", log_dir=tmp_path / "_logs", model="claude-opus-4-8",+ )++ assert events[-1].is_error is True+ assert api_family_in_cooldown("claude-api") is True+++async def test_plain_worker_error_does_not_arm_cooldown(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """A non-quota, non-auth crash must NOT block the family — the key is fine."""+ from jarvis.api_family_quota_state import api_family_in_cooldown++ monkeypatch.setattr(+ "jarvis.missions.workers.api_agent_worker._build_brain",+ lambda provider, model: _RaisingBrain(RuntimeError("kaboom: flaky socket")),+ )+ worker = ApiAgentWorker("openrouter")++ events = await _drain(+ worker, prompt="t", worktree=tmp_path, env={}, job=None,+ worker_id="m::0", log_dir=tmp_path / "_logs", model="m",+ )++ assert events[-1].is_error is True+ assert api_family_in_cooldown("openrouter") is False+++async def test_success_clears_family_cooldown(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """A successful run proves the key works again — the cooldown must clear."""+ from jarvis.api_family_quota_state import (+ api_family_in_cooldown,+ mark_api_family_cooldown,+ )++ mark_api_family_cooldown("openai")+ turns = [[BrainDelta(content="done"), BrainDelta(finish_reason="end_turn")]]+ _patch_brain(monkeypatch, FakeBrain(turns))+ worker = ApiAgentWorker("openai")++ events = await _drain(+ worker, prompt="t", worktree=tmp_path, env={}, job=None,+ worker_id="m::0", log_dir=tmp_path / "_logs", model="gpt-5.5",+ )++ assert events[-1].is_error is False+ assert api_family_in_cooldown("openai") is False++@pytest.mark.asyncioasync def test_worker_tool_error_is_fed_back_not_fatal(monkeypatch: pytest.MonkeyPatch, tmp_path: Pathdiff --git a/tests/missions/workers/test_api_family_quota_state.py b/tests/missions/workers/test_api_family_quota_state.pynew file mode 100644index 0000000000..147fa25c1b--- /dev/null+++ b/tests/missions/workers/test_api_family_quota_state.py@@ -0,0 +1,82 @@+"""Process-local per-API-family quota/auth cooldown.++Live pattern (mission 019f3d0f, 2026-07-07 — the verify run of the BUG-042+fixes): with both subscription workers down, the API-key family walk picked+gemini, whose prepaid credits were DEPLETED (429 RESOURCE_EXHAUSTED). Nothing+remembered that, so every retry re-picked gemini — the healthy openrouter key+one slot further in the SAME loop was never reached. This is the generic+API-family mirror of ``claude_quota_state`` / ``codex_quota_state``, keyed by+provider slug and FINGERPRINTED: saving a NEW key in the API-Keys view lifts+the cooldown instantly (in-app recoverability, CLAUDE.md §3), while the same+dead key stays skipped until the cooldown self-expires.+"""+from __future__ import annotations++import pytest++import jarvis.api_family_quota_state as qs++[email protected](autouse=True)+def _reset() -> None:+ qs.clear_api_family_cooldown("gemini")+ qs.clear_api_family_cooldown("openrouter")+ yield+ qs.clear_api_family_cooldown("gemini")+ qs.clear_api_family_cooldown("openrouter")+++def test_default_not_in_cooldown() -> None:+ assert qs.api_family_in_cooldown("gemini") is False+++def test_mark_sets_cooldown_per_family() -> None:+ clock = [1000.0]+ qs.mark_api_family_cooldown("gemini", now_fn=lambda: clock[0], cooldown_s=600.0)+ assert qs.api_family_in_cooldown("gemini", now_fn=lambda: clock[0]) is True+ # Only the marked family is affected.+ assert qs.api_family_in_cooldown("openrouter", now_fn=lambda: clock[0]) is False+++def test_cooldown_expires_after_window() -> None:+ qs.mark_api_family_cooldown("gemini", now_fn=lambda: 1000.0, cooldown_s=600.0)+ assert qs.api_family_in_cooldown("gemini", now_fn=lambda: 1300.0) is True+ assert qs.api_family_in_cooldown("gemini", now_fn=lambda: 1601.0) is False+++def test_clear_resets_immediately() -> None:+ qs.mark_api_family_cooldown("gemini", now_fn=lambda: 1000.0, cooldown_s=600.0)+ qs.clear_api_family_cooldown("gemini")+ assert qs.api_family_in_cooldown("gemini", now_fn=lambda: 1000.0) is False+++def test_new_key_lifts_cooldown_instantly() -> None:+ """In-app recovery: the cooldown is bound to the credential that failed.+ A DIFFERENT current fingerprint (user saved a fresh key) is not blocked."""+ qs.mark_api_family_cooldown(+ "gemini", fingerprint="dead-key-fp", now_fn=lambda: 1000.0, cooldown_s=600.0+ )+ assert (+ qs.api_family_in_cooldown(+ "gemini", current_fingerprint="dead-key-fp", now_fn=lambda: 1000.0+ )+ is True+ )+ assert (+ qs.api_family_in_cooldown(+ "gemini", current_fingerprint="FRESH-key-fp", now_fn=lambda: 1000.0+ )+ is False+ )+++def test_unknown_current_fingerprint_stays_blocked() -> None:+ """No fingerprint available at check time → conservative: cooldown holds."""+ qs.mark_api_family_cooldown(+ "gemini", fingerprint="dead-key-fp", now_fn=lambda: 1000.0, cooldown_s=600.0+ )+ assert qs.api_family_in_cooldown("gemini", now_fn=lambda: 1000.0) is True+++def test_default_cooldown_is_twenty_minutes() -> None:+ assert qs._DEFAULT_COOLDOWN_S == 20 * 60.0