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 realtime quota-family fallback
Ruben Lütke957a0de0d6a7
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 071d4cd776..4f9123d377 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -6757,3 +6757,83 @@ any in-flight stream-open operation. Stopping only the current device handle isnot cancellation: an async producer or worker thread can recreate it after thesurface has already changed state. Playback grace begins at physical playback,not at intent to play.++---++## BUG-098: one exhausted Google project breaks both Gemini Live and the Tool Model mid-call, then reconnects the same dead account (CRITICAL, FIXED IN CODE 2026-07-20; LIVE DEPLOYMENT PENDING)++**Symptom.** Realtime session `bfd8a2f1-9b0f-4aae-8108-eca925acc79b`+ran normally for almost four minutes, then two consecutive public-knowledge+questions received improvised connection-error apologies. The API-Keys view+subsequently showed both of these failures:++- Google Gemini REST: HTTP `429`, `RESOURCE_EXHAUSTED`, project monthly+ spending cap exceeded.+- Gemini Live: WebSocket close `1011`, with the same project monthly spending+ cap message.++The two cards did not identify two integration defects. They exercised two+Google transports backed by the same account/quota family after one project+budget became unavailable.++**Reconstruction.** The Live WebSocket opened successfully at 08:51:01 CEST+and remained open until the user ended the call at 08:54:52. The session itself+did not receive a `1011`. Five earlier public-fact turns were unnecessarily+delegated to the Gemini Tool Model and succeeded, consuming 95,957 input tokens+plus 606 output tokens. At 08:54:34 the next delegated REST request returned the+monthly-cap `429`; the Brain chain correctly dead-listed Gemini but had no+second credential-ready, tool-capable API family. At 08:54:44 the retry found+an empty Tool Model chain, and Gemini TTS also returned `429`. A concurrent+API-Keys health sweep then opened a new Gemini Live probe, which Google rejected+with `1011`; that probe produced the second card message.++**Root causes.** Four independent gaps amplified one legitimate provider+account state:++1. The canonical billing classifier recognized qualified limits and quotas but+ not Google's exact `spending cap` wording, especially when the Live close had+ no HTTP status code.+2. Runtime transport recovery treated any exception from a rebuild-capable+ Gemini session as a transient wire death. It reopened the provider chain+ from candidate zero without retiring the failed credential family, so a+ terminal account failure could spend all three reconnect attempts on the+ same account.+3. The realtime model called `jarvis_action` for ordinary public facts despite+ its tool directive. The handler trusted that optional model decision even+ when both the local transcript and normalized request were provably native+ factual questions.+4. A non-empty Brain provider-down apology was counted as a successful+ delegated action result. The realtime model then re-rendered that failure as+ free-form speech, hiding the structured failure state.++**Fix.** `spending cap` and `spend cap` now classify as `no_credits`. First-party+realtime adapters expose optional `credential_family` metadata; the shared+session keeps call-local blocked provider/family sets, overrides misleading+recoverable flags for auth/billing failures, and crosses to the next viable+family without ending the call. Unknown `1006` transport failures retain the+existing same-provider rebuild, while a terminal account failure with no+alternate fails once instead of reconnecting three times. Rebuilds preserve the+existing bounded history seed, output-language decision, surface turn boundary,+and fresh `audio_ready` contract.++The delegate handler now rejects only narrowly proven public factual questions+when both the transcript and the provider-normalized request remain native.+Ambiguous actions, advice, current/private/local evidence, voice confirmations,+and the vague-follow-up recovery path still reach the Brain. Finally,+`_last_turn_all_failed` makes a non-empty outage phrase an honest failed tool+result rather than a successful action.++**Guards and parity.** Tests pin the exact REST `429` and Live `1011` messages,+Gemini-to-OpenAI and OpenAI-to-Gemini mid-call crossings, one terminal failure+when no alternate exists, preservation of generic `1006` reconnect behavior,+the public-knowledge rejection, the vague-Wiki counterexample, and truthful+delegate failure payloads. The logic is transport-neutral Python with no OS+branch. A user still needs an independently funded API key from another family+for automatic crossing; ChatGPT/Codex subscription OAuth remains correctly+limited to Jarvis-Agent workers and is not presented as an OpenAI Realtime or+Tool Model API credential.++**Class rule.** Credential readiness is not account health. A runtime+auth/billing/quota failure retires its explicit credential family for that call+before recovery chooses another candidate; a UI health probe must never be+mistaken for evidence that the active voice transport died.diff --git a/jarvis/brain/provider_test.py b/jarvis/brain/provider_test.pyindex 76fbd66b2a..6884aa400a 100644--- a/jarvis/brain/provider_test.py+++ b/jarvis/brain/provider_test.py@@ -70,7 +70,9 @@ _HTTP_CODE_RE = re.compile(r"\b([45]\d\d)\b")BILLING_LIMIT_MARKERS = ("credit", # "credit balance too low", "used all available credits""spending limit",+ "spending cap","spend limit",+ "spend cap","key limit", # OpenRouter per-key cap: "Key limit exceeded (total limit)""total limit", # OpenRouter per-key cap (the parenthetical)"credit limit",diff --git a/jarvis/plugins/realtime/gemini_live.py b/jarvis/plugins/realtime/gemini_live.pyindex 5e54fc9b3e..6d2154d7c1 100644--- a/jarvis/plugins/realtime/gemini_live.py+++ b/jarvis/plugins/realtime/gemini_live.py@@ -384,6 +384,11 @@ class GeminiLiveProvider:"""Structural provider entry point for the Gemini Live family."""name = "gemini-live"+ # Optional provider capability consumed by the shared session fallback.+ # Every adapter that draws from the same account quota must expose the+ # same value so a terminal billing/auth failure is not retried through an+ # alias backed by the very same credential family (AP-22).+ credential_family = "gemini"supports_realtime = Trueinput_sample_rate = _INPUT_RATEoutput_sample_rate = _OUTPUT_RATEdiff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.pyindex deedcd3a2f..a1ae421289 100644--- a/jarvis/plugins/realtime/openai_realtime.py+++ b/jarvis/plugins/realtime/openai_realtime.py@@ -1024,6 +1024,9 @@ class OpenAIRealtimeProvider:"""Structural provider entry point for the OpenAI Realtime family."""name = "openai-realtime"+ # Optional provider capability consumed by the shared session fallback.+ # This is account/quota metadata, not a provider-name feature gate.+ credential_family = "openai"supports_realtime = Trueinput_sample_rate = _INPUT_RATEoutput_sample_rate = _OUTPUT_RATEdiff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex de49f43c2b..f3f9f9899b 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -24,6 +24,15 @@ from jarvis.brain.action_honesty import (has_deferred_action_claim,)from jarvis.brain.output_filter import scrub_for_voice+from jarvis.brain.provider_test import (+ BAD_KEY,+ MODEL_UNAVAILABLE,+ NO_CREDITS,+ NOT_CONFIGURED,+ RATE_LIMITED,+ UNREACHABLE,+ classify_provider_error,+)from jarvis.brain.turn_planner import TurnPlan, plan_turnfrom jarvis.core.protocols import AudioChunk, BrainMessagefrom jarvis.core.redact import safe_preview@@ -129,6 +138,30 @@ _EMBEDDED_SILENCE_PEAK = 200# of reconnect-storming._TRANSPORT_REBUILD_WINDOW_S = 120.0_TRANSPORT_REBUILD_MAX_PER_WINDOW = 3+_CREDENTIAL_TERMINAL_STATUSES = frozenset(+ {BAD_KEY, NO_CREDITS, NOT_CONFIGURED}+)+_PROVIDER_FAILOVER_STATUSES = frozenset(+ {MODEL_UNAVAILABLE, RATE_LIMITED, UNREACHABLE}+)+# Narrow proof that a native turn is an ordinary factual question. This is+# intentionally not a generic "planner said native" check: advice, deictic+# follow-ups, and ambiguous action phrases also stay native so the realtime+# model can disambiguate them with a tool call. The multilingual tokens are+# literal speech-input matching data. # i18n-allow: supported input vocabulary+_PUBLIC_KNOWLEDGE_QUESTION_RE = re.compile(+ r"^\s*(?:"+ r"who\b|where\b|when\b|which\b|"+ r"what\s+(?:is|are|was|were|did|does|has|have)\b|"+ r"how\s+(?:many|much|old|large|big|far)\b|"+ r"wer\b|wo\b|wann\b|welch\w*\b|"+ r"was\s+(?:ist|sind|war|waren|hat|haben|macht|machte)\b|" # i18n-allow: input+ r"wie\s+(?:viel|viele|alt|gross|groß|weit)\b|" # i18n-allow: input+ r"quien\b|donde\b|cuando\b|cual\w*\b|cuant\w*\b|"+ r"que\s+(?:es|son|fue|eran|hizo|hace|tiene|tienen)\b"+ r")",+ re.IGNORECASE,+)def _pcm16_peak(pcm: bytes) -> int:@@ -139,6 +172,12 @@ def _pcm16_peak(pcm: bytes) -> int:samples = array.array("h")samples.frombytes(pcm[:usable])return max(max(samples), -min(samples))+++def _is_public_knowledge_question(text: str) -> bool:+ return bool(_PUBLIC_KNOWLEDGE_QUESTION_RE.search(str(text or "").strip()))++# A realtime bridge is useful only for a genuinely long delegated turn. Starting# a second provider response after two seconds made ordinary 5-7 second searches# slower: the trusted result had to wait for the interim response lifecycle to@@ -782,6 +821,11 @@ class RealtimeVoiceSession:self._ended = Falseself._browser_session_started = Falseself._provider_errors: list[str] = []+ # Session-local only: a quota/auth failure must immediately cross to a+ # different credential family, but it must not mutate the process-wide+ # plugin registry or leak one user's account state into another call.+ self._blocked_provider_ids: set[str] = set()+ self._blocked_credential_families: set[str] = set()self._failed = asyncio.Event()self._failure_detail = ""self._active_model = ""@@ -956,10 +1000,72 @@ class RealtimeVoiceSession:)return model, voice+ @staticmethod+ def _provider_id(provider: Any) -> str:+ return str(getattr(provider, "name", "") or "unknown").strip().casefold()++ def _credential_family(self, provider: Any) -> str:+ """Return optional account/quota metadata without name-based gating.++ First-party adapters declare ``credential_family`` explicitly. An+ older third-party adapter remains compatible and is isolated under its+ own provider id, so a failure cannot accidentally suppress an unrelated+ plugin merely because their names look similar (AP-21/AP-22).+ """+ explicit = str(+ getattr(provider, "credential_family", "") or ""+ ).strip().casefold()+ return explicit or f"provider:{self._provider_id(provider)}"++ def _provider_is_available(self, provider: Any) -> bool:+ return (+ self._provider_id(provider) not in self._blocked_provider_ids+ and self._credential_family(provider)+ not in self._blocked_credential_families+ )++ def _has_viable_alternate(self, current: Any) -> bool:+ return any(+ candidate is not current and self._provider_is_available(candidate)+ for candidate in self._providers+ )++ def _prepare_cross_provider_fallback(+ self,+ provider: Any,+ message: str,+ *,+ terminal: bool,+ ) -> tuple[str, bool]:+ """Retire a failed candidate and report whether another one remains.++ Billing, quota, and authentication failures retire the explicit+ credential family for the rest of this call. Transient provider/model+ failures cross only when an alternate is already available; otherwise+ a rebuild-capable adapter retains its existing same-provider recovery.+ A terminal provider event always retires that provider because replaying+ a terminal event through the same session cannot make it healthy.+ """+ status = classify_provider_error(message)+ if status in _CREDENTIAL_TERMINAL_STATUSES:+ self._blocked_credential_families.add(+ self._credential_family(provider)+ )+ elif terminal or (+ status in _PROVIDER_FAILOVER_STATUSES+ and self._has_viable_alternate(provider)+ ):+ self._blocked_provider_ids.add(self._provider_id(provider))+ else:+ return status, False+ return status, self._has_viable_alternate(provider)+async def _open(self) -> None:loop = asyncio.get_running_loop()deadline = loop.time() + _PROVIDER_HANDSHAKE_TOTAL_TIMEOUT_S- for index, provider in enumerate(self._providers):+ for provider in self._providers:+ if not self._provider_is_available(provider):+ continuemodel, voice = self._active_provider_selection(provider)input_rate = int(getattr(provider, "input_sample_rate", 16_000) or 16_000)output_rate = int(getattr(provider, "output_sample_rate", 24_000) or 24_000)@@ -990,7 +1096,11 @@ class RealtimeVoiceSession:history=self._history_seed(),)try:- providers_left = len(self._providers) - index+ providers_left = sum(+ 1+ for candidate in self._providers+ if self._provider_is_available(candidate)+ )remaining = max(0.0, deadline - loop.time())if remaining <= 0:raise TimeoutError("realtime handshake budget exhausted")@@ -1021,6 +1131,11 @@ class RealtimeVoiceSession:provider_id = str(getattr(provider, "name", "unknown") or "unknown")detail = f"{type(exc).__name__}: {safe_preview(exc, max_chars=700)}"self._provider_errors.append(f"{provider_id}: {detail}")+ status, _alternate_ready = self._prepare_cross_provider_fallback(+ provider,+ detail,+ terminal=True,+ )log.warning("Realtime provider %s handshake failed: %s", provider_id, detail)try:await self._send_json(@@ -1028,6 +1143,7 @@ class RealtimeVoiceSession:"type": "provider_fallback","provider": provider_id,"error": detail,+ "status": status,})except Exception: # noqa: BLE001, S110 — status is best-effort@@ -2015,15 +2131,41 @@ class RealtimeVoiceSession:message = safe_preview(event.error or "provider error", max_chars=800)- recoverable = bool(getattr(event, "recoverable", False))+ declared_recoverable = bool(+ getattr(event, "recoverable", False)+ )+ status = classify_provider_error(message)+ # A provider may label a failed response as recoverable+ # even though its account says there is no money/quota or+ # the key is invalid. Retrying that same credential family+ # cannot recover and caused the live 1011 reconnect storm.+ recoverable = (+ declared_recoverable+ and status not in _CREDENTIAL_TERMINAL_STATUSES+ )+ failover_ready = False+ if not recoverable:+ status, failover_ready = (+ self._prepare_cross_provider_fallback(+ self._provider,+ message,+ terminal=True,+ )+ )log.warning("realtime[%s] %s provider error: %s",self.session_id,- "recoverable" if recoverable else "terminal",+ (+ "recoverable"+ if recoverable or failover_ready+ else "terminal"+ ),message,)await self._publish_error(- "RealtimeProviderError", message, recoverable=recoverable+ "RealtimeProviderError",+ message,+ recoverable=recoverable or failover_ready,)if recoverable:await self._send_json(@@ -2046,6 +2188,26 @@ class RealtimeVoiceSession:for chunk in final_chunks:await self._emit_audio(chunk)self._gate.drain()+ if failover_ready:+ provider_id = str(+ getattr(self._provider, "name", "unknown")+ or "unknown"+ )+ self._provider_errors.append(+ f"{provider_id}: {message}"+ )+ await self._send_json(+ {+ "type": "provider_fallback",+ "provider": provider_id,+ "error": message,+ "status": status,+ }+ )+ return (+ f"{provider_id} became unavailable ({status}); "+ "switching realtime provider"+ )self._failure_detail = messageself._failed.set()await self._send_json(@@ -2096,12 +2258,42 @@ class RealtimeVoiceSession:except Exception as exc: # noqa: BLE001 — AP-20: never re-read a dead transportmessage = safe_preview(exc, max_chars=800) or "Realtime receive loop ended"log.warning("realtime[%s] pump ended", self.session_id, exc_info=True)+ same_provider_rebuild = self._transport_death_is_rebuildable()+ status, failover_ready = self._prepare_cross_provider_fallback(+ self._provider,+ message,+ terminal=not same_provider_rebuild,+ )+ credential_terminal = status in _CREDENTIAL_TERMINAL_STATUSES+ can_recover = failover_ready or (+ same_provider_rebuild and not credential_terminal+ )await self._publish_error(type(exc).__name__,message,- recoverable=True,+ recoverable=can_recover,)- if self._transport_death_is_rebuildable():+ if failover_ready:+ provider_id = str(+ getattr(self._provider, "name", "unknown") or "unknown"+ )+ self._provider_errors.append(f"{provider_id}: {message}")+ try:+ await self._send_json(+ {+ "type": "provider_fallback",+ "provider": provider_id,+ "error": message,+ "status": status,+ }+ )+ except Exception: # noqa: BLE001, S110 — status is best-effort+ pass+ return (+ f"{provider_id} transport failed ({status}); "+ "switching realtime provider"+ )+ if same_provider_rebuild and not credential_terminal:return messageself._failure_detail = messageself._failed.set()@@ -3445,6 +3637,44 @@ class RealtimeVoiceSession:and call_idand wire_name == str(_DELEGATE_DECLARATION["name"])):+ provider_request = str(arguments.get("request", "") or "").strip()+ local_plan = self._plan_turn(self._last_user_text)+ provider_plan = self._plan_turn(provider_request)+ if (+ not self._delegate_required_for_turn+ and not local_plan.requires_orchestrator+ and not provider_plan.requires_orchestrator+ and _is_public_knowledge_question(self._last_user_text)+ and _is_public_knowledge_question(+ provider_request or self._last_user_text+ )+ ):+ # Provider prompt compliance is not a correctness boundary.+ # Gemini called jarvis_action for ordinary public-knowledge+ # questions in the 2026-07-20 live run, consuming ~96k Tool+ # Model input tokens before the shared Google cap stopped the+ # call. Reject the unnecessary action and keep the answer in+ # the already-open realtime model. A provider that adds real+ # private/current/local intent to its normalized request still+ # reaches the orchestrator (the vague-Wiki gate-miss path).+ log.info(+ "realtime[%s] rejected unnecessary delegate call for a "+ "native realtime turn",+ self.session_id,+ )+ await self._session.send_tool_result(+ call_id,+ wire_name,+ {+ "success": False,+ "error": (+ "No Jarvis action is needed. Answer the user's "+ "general-knowledge request directly in this "+ "realtime response."+ ),+ },+ )+ returnturn_id = self._turn_idturn_state = self._delegate_turns.setdefault(turn_id,@@ -3477,8 +3707,7 @@ class RealtimeVoiceSession:returnturn_state.pending_tool_calls.append((call_id, wire_name))if not turn_state.user_text:- request = str(arguments.get("request", "") or "")- turn_state.user_text = self._last_user_text or request+ turn_state.user_text = self._last_user_text or provider_requestif not turn_state.dispatch_started:self._start_delegate(turn_id, turn_state)await self._coalesce_ready_delegate_result(turn_state)@@ -3802,7 +4031,10 @@ class RealtimeVoiceSession:)or "").strip()- if reply:+ brain_chain_failed = bool(+ getattr(self._brain, "_last_turn_all_failed", False)+ )+ if reply and not brain_chain_failed:turn_state.last_reply = replyresult: dict[str, Any] = {"success": True,@@ -3812,7 +4044,11 @@ class RealtimeVoiceSession:else:result = {"success": False,- "error": "The delegated action returned no grounded result.",+ "error": (+ "No configured Tool Model completed the delegated turn."+ if brain_chain_failed+ else "The delegated action returned no grounded result."+ ),}succeeded = Falseexcept TimeoutError:@@ -4010,14 +4246,21 @@ class RealtimeVoiceSession:)or "").strip()- if reply:+ brain_chain_failed = bool(+ getattr(self._brain, "_last_turn_all_failed", False)+ )+ if reply and not brain_chain_failed:turn_state.last_reply = replyresult: dict[str, Any] = {"success": True, "spoken_reply": reply}succeeded = Trueelse:result = {"success": False,- "error": "The delegated action returned no grounded result.",+ "error": (+ "No configured Tool Model completed the delegated turn."+ if brain_chain_failed+ else "The delegated action returned no grounded result."+ ),}if self._delegate_turns.get(turn_id) is turn_state:if succeeded:diff --git a/tests/unit/brain/test_provider_test.py b/tests/unit/brain/test_provider_test.pyindex 03b76cfc94..4efd6ae78d 100644--- a/tests/unit/brain/test_provider_test.py+++ b/tests/unit/brain/test_provider_test.py@@ -93,6 +93,24 @@ def test_openai_insufficient_quota_429_is_no_credits() -> None:assert classify_provider_error(msg) == "no_credits"+ "msg",+ (+ (+ "ClientError: 429 Too Many Requests. Your project has exceeded "+ "its monthly spending cap. status: RESOURCE_EXHAUSTED"+ ),+ (+ "APIError: 1011 None. Your project has exceeded its monthly "+ "spending cap. Please go to AI Studio to manage your project"+ ),+ ),+)+def test_gemini_monthly_spending_cap_is_no_credits(msg: str) -> None:+ """REST 429 and Live 1011 are the same terminal account state."""+ assert classify_provider_error(msg) == "no_credits"++def test_plain_429_rate_limit_is_rate_limited() -> None:msg = "RateLimitError: Error code: 429 - rate limit exceeded, please slow down"assert classify_provider_error(msg) == "rate_limited"diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex 137a8855f2..6de898fafc 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -3417,6 +3417,82 @@ async def test_gate_miss_lets_the_model_reach_the_wiki_through_jarvis_action():await sess.end(reason="test")+async def test_native_knowledge_turn_rejects_unnecessary_jarvis_action():+ """A realtime model cannot spend Tool Model quota on public knowledge."""+ from jarvis.brain.turn_planner import plan_turn++ utterance = "Where does Aliko Dangote live?"+ assert plan_turn(utterance).requires_orchestrator is False++ brain = FakeBrain(replies=("This must not be called.",))+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text=utterance,+ is_final=True,+ ),+ RealtimeEvent(+ type="tool_call",+ call_id="c-native",+ tool_name="jarvis_action",+ tool_args={"request": utterance},+ ),+ RealtimeEvent(+ type="output_transcript_delta",+ text="He lives in Lagos.",+ is_final=True,+ ),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ sess = _session(provider, brain=brain)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()++ assert brain.calls == []+ result = provider.session.tool_results[0][2]+ assert result["success"] is False+ assert "Answer" in result["error"]+ await sess.end(reason="test")+++async def test_provider_down_apology_is_not_reported_as_delegate_success():+ """A non-empty Brain outage phrase is still a failed Tool Model turn."""+ brain = FakeBrain(replies=("The model connection is unavailable.",))+ brain._last_turn_all_failed = True+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="input_transcript",+ text="What is there?",+ is_final=True,+ ),+ RealtimeEvent(+ type="tool_call",+ call_id="c-down",+ tool_name="jarvis_action",+ tool_args={"request": "What is in my wiki?"},+ ),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ sess = _session(provider, brain=brain)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await asyncio.sleep(0.02)++ result = provider.session.tool_results[0][2]+ assert result["success"] is False+ assert "Tool Model" in result["error"]+ assert result["spoken_reply"] != "The model connection is unavailable."+ await sess.end(reason="test")++@pytest.mark.asyncioasync def test_garbled_wiki_follow_up_inherits_session_context_and_delegates():"""The exact forensic STT output must not depend on model tool discretion."""@@ -4693,6 +4769,131 @@ async def test_transport_death_rebuilds_the_session_in_place():await sess.end(reason="test")+async def test_gemini_live_spending_cap_crosses_family_without_retrying():+ """The live 1011 spending-cap close must cross from Gemini to OpenAI."""+ gemini = RebuildingProvider(+ [+ lambda: DyingSession(+ [],+ error=(+ "1011 None. Your project has exceeded its monthly "+ "spending cap. Please go to AI Studio to manage your project"+ ),+ )+ ]+ )+ gemini.name = "gemini-live"+ gemini.credential_family = "gemini"+ openai = RebuildingProvider([lambda: StayOpenSession([])])+ openai.name = "openai-realtime"+ openai.credential_family = "openai"+ jsons = []+ sess = RealtimeVoiceSession(+ session_id="gemini-cap-cross-family",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda message: jsons.append(message) or asyncio.sleep(0),+ providers=[gemini, openai],+ config=_cfg(),+ bus=None,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await _wait_until(lambda: openai.open_calls == 1)++ assert gemini.open_calls == 1+ assert sess.active_provider == "openai-realtime"+ assert not sess.failed+ assert [m for m in jsons if m.get("type") == "provider_error"] == []+ fallback = next(+ m+ for m in jsons+ if m.get("type") == "provider_fallback"+ and m.get("provider") == "gemini-live"+ )+ assert fallback["status"] == "no_credits"+ await sess.end(reason="test")+++async def test_openai_insufficient_quota_event_crosses_to_gemini():+ """A failed response.done can be account-terminal despite recoverable=True."""+ openai = RebuildingProvider(+ [+ lambda: FakeSession(+ [+ RealtimeEvent(+ type="error",+ error=(+ "RateLimitError: 429 insufficient_quota; check your "+ "plan and billing details"+ ),+ recoverable=True,+ )+ ]+ )+ ]+ )+ openai.name = "openai-realtime"+ openai.credential_family = "openai"+ gemini = RebuildingProvider([lambda: StayOpenSession([])])+ gemini.name = "gemini-live"+ gemini.credential_family = "gemini"+ jsons = []+ sess = RealtimeVoiceSession(+ session_id="openai-quota-cross-family",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda message: jsons.append(message) or asyncio.sleep(0),+ providers=[openai, gemini],+ config=_cfg(),+ bus=None,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await _wait_until(lambda: gemini.open_calls == 1)++ assert openai.open_calls == 1+ assert sess.active_provider == "gemini-live"+ assert not sess.failed+ assert [m for m in jsons if m.get("type") == "provider_error"] == []+ await sess.end(reason="test")+++async def test_terminal_account_failure_without_alternate_does_not_reconnect():+ """No alternate means one honest failure, not three futile reconnects."""+ gemini = RebuildingProvider(+ [+ lambda: DyingSession(+ [],+ error=(+ "1011 None. Your project has exceeded its monthly "+ "spending cap"+ ),+ )+ ]+ )+ gemini.name = "gemini-live"+ gemini.credential_family = "gemini"+ jsons = []+ sess = RealtimeVoiceSession(+ session_id="gemini-cap-no-alternate",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda message: jsons.append(message) or asyncio.sleep(0),+ provider=gemini,+ config=_cfg(),+ bus=None,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(sess.wait_finished(), timeout=2)++ assert sess.failed+ assert gemini.open_calls == 1+ assert len([m for m in jsons if m.get("type") == "provider_error"]) == 1+ await sess.end(reason="test")++@pytest.mark.asyncioasync def test_audio_send_timeout_rebuilds_without_ending_the_call(monkeypatch):"""A write-only stall and a later stale timeout preserve the live call."""