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.

feat(google): central AI-Studio-vs-Vertex-express key routing resolver

rubenluetke10-beep9f03dfc610bc
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 526f79fedd..ef89d08473 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -3455,6 +3455,25 @@ class AgenticIdeConfig(BaseModel):
return text if text.replace("-", "").replace("_", "").isalnum() else "auto"
+class GoogleAuthConfig(BaseModel):
+ """Google credential routing: AI Studio vs Vertex AI express mode.
+
+ Google serves the same Gemini models behind two API-key families. Classic
+ AI Studio keys (``AIza...``) talk to ``generativelanguage.googleapis.com``;
+ Vertex AI *express mode* keys (``AQ....``) are only accepted when the
+ google-genai client is built with ``vertexai=True``. Newer AI Studio keys
+ ALSO start with ``AQ.``, so the prefix alone cannot decide. ``auto`` (the
+ default) probes an ambiguous key once per process and remembers the
+ answer; ``always``/``never`` force the route for installs where the probe
+ guesses wrong or the network blocks it. Read exclusively by
+ ``jarvis.core.google_genai`` (AP-31: no unread switch).
+ """
+
+ model_config = ConfigDict(extra="allow")
+
+ vertex_mode: Literal["auto", "always", "never"] = "auto"
+
+
class JarvisConfig(BaseModel):
"""Root config model."""
# populate_by_name=True lets callers use Python field names alongside
@@ -3467,6 +3486,8 @@ class JarvisConfig(BaseModel):
stt: STTConfig = Field(default_factory=STTConfig)
tts: TTSConfig = Field(default_factory=TTSConfig)
brain: BrainConfig = Field(default_factory=BrainConfig)
+ # Google key routing (AI Studio vs Vertex express) — see GoogleAuthConfig.
+ google: GoogleAuthConfig = Field(default_factory=GoogleAuthConfig)
memory: MemoryConfig = Field(default_factory=MemoryConfig)
safety: SafetyConfig = Field(default_factory=SafetyConfig)
skills: SkillsConfig = Field(default_factory=SkillsConfig)
diff --git a/jarvis/core/google_genai.py b/jarvis/core/google_genai.py
new file mode 100644
index 0000000000..ce7311aa10
--- /dev/null
+++ b/jarvis/core/google_genai.py
@@ -0,0 +1,288 @@
+"""Google GenAI client construction with AI-Studio-vs-Vertex key routing.
+
+Google ships two API-key families for the same Gemini models:
+
+* **Google AI Studio** keys — classic ``AIza...`` and newer ``AQ....`` —
+ served by ``generativelanguage.googleapis.com``.
+* **Vertex AI express mode** keys — also ``AQ....`` — served by
+ ``aiplatform.googleapis.com`` and only accepted when the google-genai
+ client is built with ``vertexai=True``.
+
+The prefix alone cannot distinguish the two ``AQ.`` families, and a key sent
+to the wrong endpoint fails with an auth error ("API key not valid"). This
+module is the single source of truth for picking the route, shared by every
+surface that builds a Gemini client (brain, tool model, realtime, STT, TTS,
+dictation polish, computer use, ack brain):
+
+* ``AIza...`` keys route straight to AI Studio — zero added latency, the
+ exact behaviour every install had before this module existed.
+* Ambiguous ``AQ....`` keys are probed ONCE per process: one cheap
+ ``models.list`` GET against AI Studio. Accepted → AI Studio; rejected with
+ an auth error → the key must be a Vertex express key. The verdict is
+ cached by key fingerprint, so realtime session opens and per-turn calls
+ never pay the probe again.
+* ``[google].vertex_mode`` in jarvis.toml overrides the probe: ``always``
+ forces Vertex for ambiguous keys, ``never`` restores the pre-Vertex
+ behaviour. ``auto`` (default) probes. Read only here (AP-31).
+
+An explicitly configured ``base_url`` (team proxy, W2) must bypass routing
+entirely — the proxy speaks the AI Studio wire format — which callers get by
+passing ``route="aistudio"`` to :func:`build_genai_client`.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import threading
+from typing import Any, Literal
+
+log = logging.getLogger("jarvis.google_genai")
+
+KeyRoute = Literal["aistudio", "vertex"]
+
+#: AI Studio model-list endpoint used as the routing probe. A GET here is the
+#: cheapest documented call that authenticates the key without generating
+#: tokens; the key travels in the ``x-goog-api-key`` header, never the URL,
+#: so it cannot leak into access logs.
+_AISTUDIO_PROBE_URL = "https://generativelanguage.googleapis.com/v1beta/models"
+
+#: HTTP statuses that mean "this key is not an AI Studio key" (as opposed to
+#: "the service hiccuped"). 400 is what generativelanguage actually returns
+#: for a foreign key (API_KEY_INVALID); 401/403 are kept for robustness.
+_AUTH_REJECT_STATUSES = frozenset({400, 401, 403})
+
+#: Probe budget. The probe runs once per process per key, off the boot
+#: critical path (clients are built lazily on first use), so a short budget
+#: only has to beat transient network stalls.
+_PROBE_TIMEOUT_S = 5.0
+
+_ROUTE_CACHE: dict[str, KeyRoute] = {}
+_CACHE_LOCK = threading.Lock()
+
+
+def _fingerprint(api_key: str) -> str:
+ """Non-reversible cache/log identity for a key (first 12 hex of SHA-256)."""
+ return hashlib.sha256(api_key.encode("utf-8")).hexdigest()[:12]
+
+
+def classify_google_key(api_key: str) -> KeyRoute | None:
+ """Classify a key by shape alone; ``None`` means "ambiguous, probe it".
+
+ ``AIza`` is the classic AI Studio / GCP API-key prefix and is never issued
+ for Vertex express, so it short-circuits with no probe. ``AQ.`` is issued
+ by BOTH AI Studio and Vertex express — undecidable by shape. Anything else
+ (wrong-provider paste, garbage) routes to AI Studio so it fails with the
+ same honest upstream error it always did.
+ """
+ key = api_key.strip()
+ if key.startswith("AQ."):
+ return None
+ return "aistudio"
+
+
+def _configured_mode() -> str:
+ """``[google].vertex_mode`` with a hard fallback to ``auto``.
+
+ Lazy import + broad fallback: this module must stay importable (and
+ behave sanely) even while the config system is mid-boot or the section
+ is absent in an older jarvis.toml.
+ """
+ try:
+ from jarvis.core.config import load_config
+
+ mode = str(load_config().google.vertex_mode or "auto").strip().lower()
+ except Exception: # noqa: BLE001 — config trouble must never break clients
+ return "auto"
+ return mode if mode in ("auto", "always", "never") else "auto"
+
+
+def _interpret_probe_status(status_code: int) -> KeyRoute | None:
+ """Map the AI Studio probe's HTTP status to a route (``None`` = unknown).
+
+ 2xx proves the key is an AI Studio key. An auth-reject status proves it is
+ NOT one — and the only other family sharing the ``AQ.`` shape is Vertex
+ express, so that is the verdict; if the key is invalid everywhere, the
+ first real call surfaces the same upstream error either way. Anything else
+ (5xx, 429) proves nothing and must not be cached.
+ """
+ if 200 <= status_code < 300:
+ return "aistudio"
+ if status_code in _AUTH_REJECT_STATUSES:
+ return "vertex"
+ return None
+
+
+def _cached_route(fp: str) -> KeyRoute | None:
+ with _CACHE_LOCK:
+ return _ROUTE_CACHE.get(fp)
+
+
+def _remember_route(fp: str, route: KeyRoute, *, source: str) -> KeyRoute:
+ with _CACHE_LOCK:
+ _ROUTE_CACHE[fp] = route
+ log.info("Google key %s routes via %s (%s).", fp, route, source)
+ return route
+
+
+def _resolve_preamble(api_key: str) -> tuple[str, KeyRoute | None]:
+ """Shared sync/async front half: cache, config override, shape.
+
+ Returns ``(fingerprint, route)`` where a non-``None`` route is final and
+ the probe is skipped.
+ """
+ fp = _fingerprint(api_key)
+ cached = _cached_route(fp)
+ if cached is not None:
+ return fp, cached
+ shape = classify_google_key(api_key)
+ if shape is not None:
+ # Unambiguous shape — cache without logging chatter: this is the
+ # unchanged historical path taken by every AIza key on every boot.
+ with _CACHE_LOCK:
+ _ROUTE_CACHE[fp] = shape
+ return fp, shape
+ mode = _configured_mode()
+ if mode == "always":
+ return fp, _remember_route(fp, "vertex", source="vertex_mode=always")
+ if mode == "never":
+ return fp, _remember_route(fp, "aistudio", source="vertex_mode=never")
+ return fp, None
+
+
+def resolve_google_key_route(api_key: str, *, transport: Any | None = None) -> KeyRoute:
+ """Decide the route for ``api_key`` (sync). Probes at most once per key.
+
+ ``transport`` is a test seam: an ``httpx.MockTransport`` makes the probe
+ fully offline. On network trouble the verdict defaults to ``aistudio``
+ WITHOUT caching, so a flaky network cannot pin a wrong route for the
+ process lifetime.
+ """
+ fp, decided = _resolve_preamble(api_key)
+ if decided is not None:
+ return decided
+ try:
+ import httpx
+
+ with httpx.Client(timeout=_PROBE_TIMEOUT_S, transport=transport) as client:
+ response = client.get(
+ _AISTUDIO_PROBE_URL,
+ params={"pageSize": 1},
+ headers={"x-goog-api-key": api_key},
+ )
+ route = _interpret_probe_status(response.status_code)
+ except Exception as exc: # noqa: BLE001 — probe failure must not break calls
+ log.warning(
+ "Google key %s: routing probe failed (%s: %s) — defaulting to "
+ "AI Studio without caching.",
+ fp,
+ type(exc).__name__,
+ exc,
+ )
+ return "aistudio"
+ if route is None:
+ log.warning(
+ "Google key %s: routing probe returned HTTP %s — defaulting to "
+ "AI Studio without caching.",
+ fp,
+ response.status_code,
+ )
+ return "aistudio"
+ return _remember_route(fp, route, source=f"probe HTTP {response.status_code}")
+
+
+async def resolve_google_key_route_async(api_key: str, *, transport: Any | None = None) -> KeyRoute:
+ """Async twin of :func:`resolve_google_key_route`; shares its cache."""
+ fp, decided = _resolve_preamble(api_key)
+ if decided is not None:
+ return decided
+ try:
+ import httpx
+
+ async with httpx.AsyncClient(timeout=_PROBE_TIMEOUT_S, transport=transport) as client:
+ response = await client.get(
+ _AISTUDIO_PROBE_URL,
+ params={"pageSize": 1},
+ headers={"x-goog-api-key": api_key},
+ )
+ route = _interpret_probe_status(response.status_code)
+ except Exception as exc: # noqa: BLE001 — probe failure must not break calls
+ log.warning(
+ "Google key %s: routing probe failed (%s: %s) — defaulting to "
+ "AI Studio without caching.",
+ fp,
+ type(exc).__name__,
+ exc,
+ )
+ return "aistudio"
+ if route is None:
+ log.warning(
+ "Google key %s: routing probe returned HTTP %s — defaulting to "
+ "AI Studio without caching.",
+ fp,
+ response.status_code,
+ )
+ return "aistudio"
+ return _remember_route(fp, route, source=f"probe HTTP {response.status_code}")
+
+
+def _client_kwargs(api_key: str, route: KeyRoute, http_options: Any | None) -> dict[str, Any]:
+ """Pure kwargs assembly for ``genai.Client`` — unit-testable sans SDK.
+
+ Express mode is exactly ``vertexai=True`` plus the key; no project or
+ location — the express endpoint infers the trial/billing project from the
+ key itself. The explicit ``api_key`` argument outranks any ambient
+ ``GOOGLE_API_KEY``/``GEMINI_API_KEY`` env, so no env-stripping is needed
+ here (unlike the TTS service-account path, which authenticates via env).
+ """
+ kwargs: dict[str, Any] = {"api_key": api_key}
+ if route == "vertex":
+ kwargs["vertexai"] = True
+ if http_options is not None:
+ kwargs["http_options"] = http_options
+ return kwargs
+
+
+def build_genai_client(
+ api_key: str,
+ *,
+ http_options: Any | None = None,
+ route: KeyRoute | None = None,
+) -> Any:
+ """Build a ``google.genai.Client`` on the right endpoint for this key.
+
+ Drop-in replacement for the bare ``genai.Client(api_key=...)`` calls that
+ predate Vertex support. ``route`` pins the endpoint when the caller
+ already knows it (team proxy → ``"aistudio"``); ``None`` resolves it via
+ :func:`resolve_google_key_route`. The SDK import stays inside the
+ function so headless installs without google-genai import this module
+ cleanly (AP-26).
+ """
+ from google import genai
+
+ resolved = route or resolve_google_key_route(api_key)
+ return genai.Client(**_client_kwargs(api_key, resolved, http_options))
+
+
+async def build_genai_client_async(
+ api_key: str,
+ *,
+ http_options: Any | None = None,
+ route: KeyRoute | None = None,
+) -> Any:
+ """Async twin of :func:`build_genai_client` for event-loop callers.
+
+ The realtime surface opens sessions inside the loop; resolving the route
+ with the async probe keeps a first-ever ``AQ.`` key from blocking the
+ loop for the probe round-trip.
+ """
+ from google import genai
+
+ resolved = route or await resolve_google_key_route_async(api_key)
+ return genai.Client(**_client_kwargs(api_key, resolved, http_options))
+
+
+def reset_route_cache() -> None:
+ """Forget every probed verdict (tests; key rotation edge cases)."""
+ with _CACHE_LOCK:
+ _ROUTE_CACHE.clear()
diff --git a/tests/unit/core/test_google_genai.py b/tests/unit/core/test_google_genai.py
new file mode 100644
index 0000000000..6acccc5199
--- /dev/null
+++ b/tests/unit/core/test_google_genai.py
@@ -0,0 +1,164 @@
+"""Route resolution for Google keys: AI Studio vs Vertex AI express mode.
+
+The prefix ``AQ.`` is issued by BOTH Google AI Studio and Vertex express, so
+the resolver may only trust shape for ``AIza`` keys and must probe the rest —
+once, with the verdict cached, and never caching a network hiccup. These tests
+drive the probe through ``httpx.MockTransport`` (a real transport, no network)
+so every branch is exercised offline.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import httpx
+import pytest
+
+from jarvis.core import google_genai as gg
+
+
[email protected](autouse=True)
+def _fresh_cache():
+ gg.reset_route_cache()
+ yield
+ gg.reset_route_cache()
+
+
+def _transport(status_code: int, counter: list[int]) -> httpx.MockTransport:
+ def handler(request: httpx.Request) -> httpx.Response:
+ counter[0] += 1
+ # The key must travel in the header, never the URL (log safety).
+ assert "key" not in request.url.params
+ assert request.headers.get("x-goog-api-key")
+ return httpx.Response(status_code, json={})
+
+ return httpx.MockTransport(handler)
+
+
+# ── shape classification ─────────────────────────────────────────────────────
+
+
+def test_aiza_keys_are_aistudio_by_shape():
+ assert gg.classify_google_key("AIzaSyFakeKey123") == "aistudio"
+
+
+def test_aq_keys_are_ambiguous():
+ assert gg.classify_google_key("AQ.fake-express-or-studio") is None
+
+
+def test_foreign_shapes_fall_back_to_aistudio():
+ # A wrong-provider paste must fail with the same upstream error as before
+ # this module existed, not with a surprising Vertex error.
+ assert gg.classify_google_key("sk-ant-somekey") == "aistudio"
+
+
+# ── probe verdicts ───────────────────────────────────────────────────────────
+
+
+def test_probe_200_routes_aistudio_and_caches():
+ calls = [0]
+ t = _transport(200, calls)
+ assert gg.resolve_google_key_route("AQ.studio-key-1", transport=t) == "aistudio"
+ assert gg.resolve_google_key_route("AQ.studio-key-1", transport=t) == "aistudio"
+ assert calls[0] == 1, "second resolve must hit the cache, not the network"
+
+
+def test_probe_400_routes_vertex_and_caches():
+ calls = [0]
+ t = _transport(400, calls)
+ assert gg.resolve_google_key_route("AQ.express-key-1", transport=t) == "vertex"
+ assert gg.resolve_google_key_route("AQ.express-key-1", transport=t) == "vertex"
+ assert calls[0] == 1
+
+
+def test_probe_5xx_defaults_aistudio_without_caching():
+ calls = [0]
+ t = _transport(503, calls)
+ assert gg.resolve_google_key_route("AQ.flaky-key-1", transport=t) == "aistudio"
+ assert gg.resolve_google_key_route("AQ.flaky-key-1", transport=t) == "aistudio"
+ assert calls[0] == 2, "an outage verdict must not be pinned for the process"
+
+
+def test_probe_network_error_defaults_aistudio_without_caching():
+ calls = [0]
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ calls[0] += 1
+ raise httpx.ConnectError("no route to host", request=request)
+
+ t = httpx.MockTransport(handler)
+ assert gg.resolve_google_key_route("AQ.offline-key-1", transport=t) == "aistudio"
+ assert gg.resolve_google_key_route("AQ.offline-key-1", transport=t) == "aistudio"
+ assert calls[0] == 2
+
+
+def test_async_resolver_shares_the_sync_cache():
+ calls = [0]
+ t = _transport(400, calls)
+ assert gg.resolve_google_key_route("AQ.shared-key-1", transport=t) == "vertex"
+ verdict = asyncio.run(gg.resolve_google_key_route_async("AQ.shared-key-1", transport=t))
+ assert verdict == "vertex"
+ assert calls[0] == 1, "the async twin must reuse the sync verdict"
+
+
+def test_async_probe_works_standalone():
+ calls = [0]
+ t = _transport(200, calls)
+ verdict = asyncio.run(gg.resolve_google_key_route_async("AQ.async-key-1", transport=t))
+ assert verdict == "aistudio"
+ assert calls[0] == 1
+
+
+# ── config override ──────────────────────────────────────────────────────────
+
+
+def test_vertex_mode_always_skips_the_probe(monkeypatch):
+ monkeypatch.setattr(gg, "_configured_mode", lambda: "always")
+ calls = [0]
+ t = _transport(200, calls)
+ assert gg.resolve_google_key_route("AQ.forced-key-1", transport=t) == "vertex"
+ assert calls[0] == 0
+
+
+def test_vertex_mode_never_skips_the_probe(monkeypatch):
+ monkeypatch.setattr(gg, "_configured_mode", lambda: "never")
+ calls = [0]
+ t = _transport(400, calls)
+ assert gg.resolve_google_key_route("AQ.forced-key-2", transport=t) == "aistudio"
+ assert calls[0] == 0
+
+
+def test_vertex_mode_never_leaves_aiza_untouched(monkeypatch):
+ monkeypatch.setattr(gg, "_configured_mode", lambda: "always")
+ # ``always`` governs AMBIGUOUS keys only; an AIza key stays AI Studio —
+ # forcing it through Vertex could never work (wrong key family).
+ assert gg.resolve_google_key_route("AIzaSyClassic") == "aistudio"
+
+
+def test_google_config_defaults_to_auto():
+ from jarvis.core.config import JarvisConfig
+
+ assert JarvisConfig().google.vertex_mode == "auto"
+
+
+# ── client kwargs assembly ───────────────────────────────────────────────────
+
+
+def test_client_kwargs_aistudio_matches_the_historical_call():
+ assert gg._client_kwargs("k", "aistudio", None) == {"api_key": "k"}
+
+
+def test_client_kwargs_vertex_sets_the_express_flag_only():
+ assert gg._client_kwargs("k", "vertex", None) == {
+ "api_key": "k",
+ "vertexai": True,
+ }
+
+
+def test_client_kwargs_pass_http_options_through():
+ opts = {"timeout": 1500}
+ assert gg._client_kwargs("k", "vertex", opts) == {
+ "api_key": "k",
+ "vertexai": True,
+ "http_options": opts,
+ }