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(google): confirm the Vertex route with a countTokens counter-probe

rubenluetke10-beepfd08d34f5002
diff --git a/jarvis/core/google_genai.py b/jarvis/core/google_genai.py
index ce7311aa10..9d50152573 100644
--- a/jarvis/core/google_genai.py
+++ b/jarvis/core/google_genai.py
@@ -16,11 +16,14 @@ 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.
+* Ambiguous ``AQ....`` keys are probed ONCE per process, in two steps: a
+ cheap ``models.list`` GET against AI Studio, and — only if AI Studio
+ rejects the key — a free Vertex ``countTokens`` counter-probe. Accepted by
+ AI Studio → AI Studio; accepted by Vertex → express key; rejected by BOTH
+ → the key is simply invalid, so the historical AI Studio path surfaces
+ Google's own error and nothing is cached. A confirmed 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).
@@ -41,15 +44,38 @@ 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.
+#: AI Studio model-list endpoint used as the first 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
+#: Vertex express counter-probe. An AI Studio rejection alone does NOT prove
+#: the key is a Vertex express key — an invalid/expired ``AQ.`` key is
+#: rejected by BOTH endpoints (measured 2026-08-12: 401
+#: ACCESS_TOKEN_TYPE_UNSUPPORTED on either host). Only a successful
+#: ``countTokens`` — one of exactly three methods officially in scope for
+#: express mode, and free (it counts, it does not generate) — confirms the
+#: Vertex route. Express uses the GLOBAL aiplatform host: no project, no
+#: location, key in the same header.
+_VERTEX_PROBE_URL_TMPL = (
+ "https://aiplatform.googleapis.com/v1/publishers/google/models/{model}:countTokens"
+)
+
+#: Models tried for the counter-probe, in order. The probe needs SOME model id
+#: in the URL (there is no model-free express call in the documented set); a
+#: 404 means "this model id is gone", not an auth verdict, so the next
+#: candidate is tried. Auth semantics do not depend on which model answers
+#: (never a behavioural pin, AP-21).
+_VERTEX_PROBE_MODELS = ("gemini-2.5-flash", "gemini-2.5-flash-lite")
+
+#: Minimal countTokens body — one character to count, zero generation.
+_VERTEX_PROBE_BODY = {"contents": [{"role": "user", "parts": [{"text": "x"}]}]}
+
+#: HTTP statuses that mean "this endpoint rejects this 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.
+#: for a foreign/invalid key (API_KEY_INVALID); 401 is what both hosts return
+#: for a bad authorization key; 403 is kept for robustness.
_AUTH_REJECT_STATUSES = frozenset({400, 401, 403})
#: Probe budget. The probe runs once per process per key, off the boot
@@ -97,20 +123,31 @@ def _configured_mode() -> str:
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).
+def _probe_verdict(
+ aistudio_status: int, vertex_statuses: tuple[int, ...]
+) -> tuple[KeyRoute | None, str]:
+ """Combine both probe answers into ``(route, detail)``.
- 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.
+ * AI Studio 2xx → the key IS an AI Studio key (an authorization key valid
+ for both services deterministically picks AI Studio; ``vertex_mode =
+ "always"`` overrides).
+ * AI Studio reject + Vertex ``countTokens`` 2xx → proven express key.
+ * Rejected by BOTH → the key is simply invalid; route ``None`` so the
+ caller defaults to the historical AI Studio path WITHOUT caching and
+ the first real call surfaces Google's own error message.
+ * Anything else (5xx, 429, network) proves nothing → ``None``.
"""
- if 200 <= status_code < 300:
- return "aistudio"
- if status_code in _AUTH_REJECT_STATUSES:
- return "vertex"
- return None
+ if 200 <= aistudio_status < 300:
+ return "aistudio", f"AI Studio probe HTTP {aistudio_status}"
+ if aistudio_status not in _AUTH_REJECT_STATUSES:
+ return None, f"AI Studio probe HTTP {aistudio_status}"
+ for status in vertex_statuses:
+ if 200 <= status < 300:
+ return "vertex", (f"AI Studio {aistudio_status}, Vertex countTokens {status}")
+ return None, (
+ f"rejected by both endpoints (AI Studio {aistudio_status}, "
+ f"Vertex {list(vertex_statuses) or 'unprobed'}) — key likely invalid"
+ )
def _cached_route(fp: str) -> KeyRoute | None:
@@ -150,27 +187,69 @@ def _resolve_preamble(api_key: str) -> tuple[str, KeyRoute | None]:
return fp, None
+def _run_probe_sync(api_key: str, transport: Any | None) -> tuple[KeyRoute | None, str]:
+ """Two-step probe (sync): AI Studio GET, then the Vertex counter-probe.
+
+ The counter-probe runs ONLY after an AI Studio auth-reject. A Vertex 404
+ means "this model id is gone", not an auth verdict, so the next candidate
+ model is tried; any other answer is decisive and the loop stops.
+ """
+ import httpx
+
+ headers = {"x-goog-api-key": api_key}
+ with httpx.Client(timeout=_PROBE_TIMEOUT_S, transport=transport) as client:
+ aistudio = client.get(_AISTUDIO_PROBE_URL, params={"pageSize": 1}, headers=headers)
+ if aistudio.status_code not in _AUTH_REJECT_STATUSES:
+ return _probe_verdict(aistudio.status_code, ())
+ statuses: list[int] = []
+ for model in _VERTEX_PROBE_MODELS:
+ vertex = client.post(
+ _VERTEX_PROBE_URL_TMPL.format(model=model),
+ json=_VERTEX_PROBE_BODY,
+ headers=headers,
+ )
+ statuses.append(vertex.status_code)
+ if vertex.status_code != 404:
+ break
+ return _probe_verdict(aistudio.status_code, tuple(statuses))
+
+
+async def _run_probe_async(api_key: str, transport: Any | None) -> tuple[KeyRoute | None, str]:
+ """Async twin of :func:`_run_probe_sync` — same two-step semantics."""
+ import httpx
+
+ headers = {"x-goog-api-key": api_key}
+ async with httpx.AsyncClient(timeout=_PROBE_TIMEOUT_S, transport=transport) as client:
+ aistudio = await client.get(_AISTUDIO_PROBE_URL, params={"pageSize": 1}, headers=headers)
+ if aistudio.status_code not in _AUTH_REJECT_STATUSES:
+ return _probe_verdict(aistudio.status_code, ())
+ statuses: list[int] = []
+ for model in _VERTEX_PROBE_MODELS:
+ vertex = await client.post(
+ _VERTEX_PROBE_URL_TMPL.format(model=model),
+ json=_VERTEX_PROBE_BODY,
+ headers=headers,
+ )
+ statuses.append(vertex.status_code)
+ if vertex.status_code != 404:
+ break
+ return _probe_verdict(aistudio.status_code, tuple(statuses))
+
+
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.
+ fully offline. On network trouble — or when both endpoints reject the key
+ (an invalid key, not a routing signal) — the verdict defaults to
+ ``aistudio`` WITHOUT caching, so neither a flaky network nor a typo can
+ 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)
+ route, detail = _run_probe_sync(api_key, transport)
except Exception as exc: # noqa: BLE001 — probe failure must not break calls
log.warning(
"Google key %s: routing probe failed (%s: %s) — defaulting to "
@@ -182,13 +261,12 @@ def resolve_google_key_route(api_key: str, *, transport: Any | None = None) -> K
return "aistudio"
if route is None:
log.warning(
- "Google key %s: routing probe returned HTTP %s — defaulting to "
- "AI Studio without caching.",
+ "Google key %s: %s — defaulting to AI Studio without caching.",
fp,
- response.status_code,
+ detail,
)
return "aistudio"
- return _remember_route(fp, route, source=f"probe HTTP {response.status_code}")
+ return _remember_route(fp, route, source=detail)
async def resolve_google_key_route_async(api_key: str, *, transport: Any | None = None) -> KeyRoute:
@@ -197,15 +275,7 @@ async def resolve_google_key_route_async(api_key: str, *, transport: Any | None
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)
+ route, detail = await _run_probe_async(api_key, transport)
except Exception as exc: # noqa: BLE001 — probe failure must not break calls
log.warning(
"Google key %s: routing probe failed (%s: %s) — defaulting to "
@@ -217,13 +287,12 @@ async def resolve_google_key_route_async(api_key: str, *, transport: Any | None
return "aistudio"
if route is None:
log.warning(
- "Google key %s: routing probe returned HTTP %s — defaulting to "
- "AI Studio without caching.",
+ "Google key %s: %s — defaulting to AI Studio without caching.",
fp,
- response.status_code,
+ detail,
)
return "aistudio"
- return _remember_route(fp, route, source=f"probe HTTP {response.status_code}")
+ return _remember_route(fp, route, source=detail)
def _client_kwargs(api_key: str, route: KeyRoute, http_options: Any | None) -> dict[str, Any]:
diff --git a/tests/unit/core/test_google_genai.py b/tests/unit/core/test_google_genai.py
index 6acccc5199..43ce7e12dd 100644
--- a/tests/unit/core/test_google_genai.py
+++ b/tests/unit/core/test_google_genai.py
@@ -1,10 +1,13 @@
"""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.
+the resolver may only trust shape for ``AIza`` keys and must probe the rest.
+The probe is two-step (verified against live endpoint behaviour, 2026-08-12):
+an AI Studio rejection alone does NOT prove a Vertex key — an invalid ``AQ.``
+key is rejected by both hosts — so only a successful Vertex ``countTokens``
+counter-probe confirms the Vertex route. Verdicts are cached once per key;
+network trouble and both-rejected keys are never cached. These tests drive
+the probe through ``httpx.MockTransport`` (a real transport, no network).
"""
from __future__ import annotations
@@ -24,15 +27,41 @@ def _fresh_cache():
gg.reset_route_cache()
-def _transport(status_code: int, counter: list[int]) -> httpx.MockTransport:
- def handler(request: httpx.Request) -> httpx.Response:
- counter[0] += 1
+class _FakeGoogle:
+ """Offline stand-in for both Google hosts, with per-endpoint call counts.
+
+ ``vertex_statuses`` maps a probe-model id to its countTokens answer, so a
+ test can retire one candidate model (404) and serve the next.
+ """
+
+ def __init__(
+ self,
+ aistudio_status: int,
+ vertex_statuses: dict[str, int] | int = 401,
+ ) -> None:
+ self.aistudio_status = aistudio_status
+ if isinstance(vertex_statuses, int):
+ vertex_statuses = dict.fromkeys(gg._VERTEX_PROBE_MODELS, vertex_statuses)
+ self.vertex_statuses = vertex_statuses
+ self.aistudio_calls = 0
+ self.vertex_calls: list[str] = []
+
+ def handler(self, request: httpx.Request) -> httpx.Response:
# 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={})
+ if request.url.host == "generativelanguage.googleapis.com":
+ self.aistudio_calls += 1
+ return httpx.Response(self.aistudio_status, json={})
+ assert request.url.host == "aiplatform.googleapis.com"
+ assert request.method == "POST"
+ model = request.url.path.split("/")[-1].removesuffix(":countTokens")
+ self.vertex_calls.append(model)
+ return httpx.Response(self.vertex_statuses[model], json={})
- return httpx.MockTransport(handler)
+ @property
+ def transport(self) -> httpx.MockTransport:
+ return httpx.MockTransport(self.handler)
# ── shape classification ─────────────────────────────────────────────────────
@@ -55,28 +84,47 @@ def test_foreign_shapes_fall_back_to_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_aistudio_200_routes_aistudio_without_vertex_probe():
+ fake = _FakeGoogle(200)
+ assert gg.resolve_google_key_route("AQ.studio-key-1", transport=fake.transport) == "aistudio"
+ assert gg.resolve_google_key_route("AQ.studio-key-1", transport=fake.transport) == "aistudio"
+ assert fake.aistudio_calls == 1, "second resolve must hit the cache"
+ assert fake.vertex_calls == [], "an accepted key needs no counter-probe"
-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_aistudio_reject_plus_vertex_ok_routes_vertex_and_caches():
+ fake = _FakeGoogle(401, {gg._VERTEX_PROBE_MODELS[0]: 200})
+ assert gg.resolve_google_key_route("AQ.express-key-1", transport=fake.transport) == "vertex"
+ assert gg.resolve_google_key_route("AQ.express-key-1", transport=fake.transport) == "vertex"
+ assert fake.aistudio_calls == 1
+ assert fake.vertex_calls == [gg._VERTEX_PROBE_MODELS[0]]
-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_rejected_by_both_defaults_aistudio_without_caching():
+ # Measured live: an invalid AQ. key gets 401 from BOTH hosts. That is a
+ # key error, not a routing signal — the honest upstream error must come
+ # from the historical endpoint, and nothing may be cached.
+ fake = _FakeGoogle(401, 401)
+ assert gg.resolve_google_key_route("AQ.broken-key-1", transport=fake.transport) == "aistudio"
+ assert gg.resolve_google_key_route("AQ.broken-key-1", transport=fake.transport) == "aistudio"
+ assert fake.aistudio_calls == 2, "a both-rejected verdict must not be pinned"
+
+
+def test_vertex_404_tries_the_next_probe_model():
+ # A retired probe model answers 404 — that is "model gone", not an auth
+ # verdict, so the next candidate decides.
+ first, second = gg._VERTEX_PROBE_MODELS
+ fake = _FakeGoogle(401, {first: 404, second: 200})
+ assert gg.resolve_google_key_route("AQ.express-key-2", transport=fake.transport) == "vertex"
+ assert fake.vertex_calls == [first, second]
+
+
+def test_aistudio_5xx_defaults_aistudio_without_caching():
+ fake = _FakeGoogle(503)
+ assert gg.resolve_google_key_route("AQ.flaky-key-1", transport=fake.transport) == "aistudio"
+ assert gg.resolve_google_key_route("AQ.flaky-key-1", transport=fake.transport) == "aistudio"
+ assert fake.aistudio_calls == 2, "an outage verdict must not be pinned"
+ assert fake.vertex_calls == [], "a 5xx is not an auth reject — no counter-probe"
def test_probe_network_error_defaults_aistudio_without_caching():
@@ -93,20 +141,23 @@ def test_probe_network_error_defaults_aistudio_without_caching():
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))
+ fake = _FakeGoogle(401, {gg._VERTEX_PROBE_MODELS[0]: 200})
+ assert gg.resolve_google_key_route("AQ.shared-key-1", transport=fake.transport) == "vertex"
+ verdict = asyncio.run(
+ gg.resolve_google_key_route_async("AQ.shared-key-1", transport=fake.transport)
+ )
assert verdict == "vertex"
- assert calls[0] == 1, "the async twin must reuse the sync verdict"
+ assert fake.aistudio_calls == 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
+ fake = _FakeGoogle(401, {gg._VERTEX_PROBE_MODELS[0]: 200})
+ verdict = asyncio.run(
+ gg.resolve_google_key_route_async("AQ.async-key-1", transport=fake.transport)
+ )
+ assert verdict == "vertex"
+ assert fake.aistudio_calls == 1
+ assert fake.vertex_calls == [gg._VERTEX_PROBE_MODELS[0]]
# ── config override ──────────────────────────────────────────────────────────
@@ -114,24 +165,23 @@ def test_async_probe_works_standalone():
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
+ fake = _FakeGoogle(200)
+ assert gg.resolve_google_key_route("AQ.forced-key-1", transport=fake.transport) == "vertex"
+ assert fake.aistudio_calls == 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
+ fake = _FakeGoogle(401, 200)
+ assert gg.resolve_google_key_route("AQ.forced-key-2", transport=fake.transport) == "aistudio"
+ assert fake.aistudio_calls == 0
-def test_vertex_mode_never_leaves_aiza_untouched(monkeypatch):
+def test_vertex_mode_always_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).
+ # a standard key can never authenticate against Vertex (measured: 401
+ # CREDENTIALS_MISSING), so forcing it would only break a working setup.
assert gg.resolve_google_key_route("AIzaSyClassic") == "aistudio"
@@ -149,6 +199,8 @@ def test_client_kwargs_aistudio_matches_the_historical_call():
def test_client_kwargs_vertex_sets_the_express_flag_only():
+ # Express mode is exactly vertexai=True + the key: no project, no location
+ # (officially documented; the key alone satisfies the SDK's auth gate).
assert gg._client_kwargs("k", "vertex", None) == {
"api_key": "k",
"vertexai": True,