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(vision): cut screenshot-turn wait by leading with a fast vision model
rubenluetke10-beepb6f9cc106423
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex dea2e5911a..e483a2ceb5 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -3402,6 +3402,73 @@ class BrainManager:log.warning("No credential-ready, tool-capable Tool Model is available.")return ready+ def _lead_vision_chain(+ self, chain: list[tuple[str, str | None]]+ ) -> list[tuple[str, str | None]]:+ """On an image turn, put a live vision FAST model first.++ Live 2026-08-31 17:06: a realtime screenshot delegated through+ ``prefer_tool_model`` led with Vertex ``gemini-3.7-flash`` (the Tool+ Model). Five providers then failed — Gemini schema, OpenRouter 402,+ Claude 401, Gemini schema again, OpenAI 429 retries — and grok-4.6+ answered after 20 s. The router already has a fast vision model+ (grok-4.20 non-reasoning). A look turn must not walk the Tool-Model+ chain first.+ """+ if not chain:+ return chain+ active = self._active_name+ vision: list[tuple[str, str | None]] = []+ rest: list[tuple[str, str | None]] = []+ seen: set[str] = set()+ for provider, model in chain:+ if provider in seen:+ continue+ seen.add(provider)+ pick_model = self._vision_look_model(provider) or model+ if self._provider_advertises_vision(provider, pick_model):+ vision.append((provider, pick_model))+ else:+ rest.append((provider, model))+ if not vision:+ return chain+ preferred = [item for item in vision if item[0] == active]+ others = [item for item in vision if item[0] != active]+ led = preferred + others + rest+ log.info(+ "screen-turn vision lead: %s(%s) — %d vision-capable, %d others",+ led[0][0],+ led[0][1],+ len(vision),+ len(rest),+ )+ return led++ def _vision_look_model(self, provider: str) -> str | None:+ """The fast look-at-screen model for ``provider``, never the CU/tool slot.++ Computer-Use and the Tool Model pick heavy siblings (grok-4.6). A+ screenshot narration wants the router-tier fast id when this is the+ routing provider.+ """+ router = getattr(getattr(self._config, "brain", None), "router", None)+ if (+ router is not None+ and getattr(router, "provider", None) == provider+ and getattr(router, "model", None)+ ):+ return str(router.model)+ return self._fast_model(provider)++ def _provider_advertises_vision(+ self, provider: str, model: str | None+ ) -> bool:+ try:+ brain = self._get_brain(provider, model)+ except Exception: # noqa: BLE001 — unready provider stays in the tail+ return False+ return getattr(brain, "supports_vision", False) is True+def _get_brain(self, name: str, model: str | None = None, *, scope: str | None = None) -> Brain:@@ -6437,8 +6504,15 @@ class BrainManager:"""keep = self._evidence_required_tool or ""return {- n: t for n, t in self._tools.items()- if n not in _SCREEN_TURN_HIDDEN_TOOL_NAMES or n == keep+ n: t+ for n, t in self._tools.items()+ if (n not in _SCREEN_TURN_HIDDEN_TOOL_NAMES or n == keep)+ # MCP tools are namespaced ``server/tool``. Their JSON-Schema+ # unions brick Gemini (live 2026-08-31: Linear+ # ``issue_fields.value.type = [string, number, boolean]``) and+ # they bloat a look-at-screen prompt for every other provider.+ # A mandated tool still survives.+ and ("/" not in n or n == keep)}def _gate_screen_tool(@@ -11566,6 +11640,9 @@ class BrainManager:)vision_capable_seen = False+ if images:+ chain = self._lead_vision_chain(chain)+ screen_turn_t0 = time.perf_counter() if images else Nonefor idx, (prov_name, model) in enumerate(chain):# Skip providers already marked dead in THIS turn.@@ -12043,6 +12120,14 @@ class BrainManager:"Fallback-Hit: %s(%s) — %d provider übersprungen",prov_name, model, idx,)+ if screen_turn_t0 is not None:+ log.info(+ "screen-turn answered by %s(%s) in %d ms (skipped=%d)",+ prov_name,+ model,+ int((time.perf_counter() - screen_turn_t0) * 1000),+ idx,+ )# Under an override the pick answering after its router# lead is the plan, not a fallback: the sidebar and its# "Brain -> X" toast follow this event, and the live braindiff --git a/jarvis/plugins/brain/gemini.py b/jarvis/plugins/brain/gemini.pyindex 786e948fca..e40b319346 100644--- a/jarvis/plugins/brain/gemini.py+++ b/jarvis/plugins/brain/gemini.py@@ -10,6 +10,7 @@ uses Google's official OpenAI-compatible HTTPS endpoint. The fallback keepscore text, vision, streaming, and function-calling available on platformswhere the Google SDK dependency graph has no installable wheel."""+from __future__ import annotationsimport asyncio@@ -118,9 +119,8 @@ def _is_stale_context_cache_error(exc: Exception) -> bool:if "cached_content" in msg and "not found" in msg:return Trueif (- ("403" in msg or "permission_denied" in msg or "permission denied" in msg)- and "cache" in msg- ):+ "403" in msg or "permission_denied" in msg or "permission denied" in msg+ ) and "cache" in msg:return Truereturn False@@ -146,10 +146,7 @@ def _thinking_config_for(from google.genai import types as _genai_typesdef _budget_cfg(value: int) -> Any | None:- if (- value in rejected_budgets- or (model, value) in _REJECTED_THINKING_BUDGETS- ):+ if value in rejected_budgets or (model, value) in _REJECTED_THINKING_BUDGETS:return Nonetry:return _genai_types.ThinkingConfig(thinking_budget=value)@@ -266,22 +263,23 @@ def _to_gemini_contents(for part in payloadif isinstance(part, dict) and part.get("type") == "tool_result"]- result_text = (- "\n".join(t for t in inner if t)- or json.dumps(payload, default=str)- )+ result_text = "\n".join(t for t in inner if t) or json.dumps(payload, default=str)else:result_text = str(payload)tool_name = m.name or ""- contents.append({- "role": "user",- "parts": [{- "functionResponse": {- "name": name_map.get(tool_name, tool_name),- "response": {"result": result_text},- }- }],- })+ contents.append(+ {+ "role": "user",+ "parts": [+ {+ "functionResponse": {+ "name": name_map.get(tool_name, tool_name),+ "response": {"result": result_text},+ }+ }+ ],+ }+ )continue# `getattr` for backwards-compat (Protocol pre-Wave-1-B1 had no images).@@ -310,24 +308,28 @@ def _to_gemini_contents(# covers all Gemini-originated calls.call_name = str(part.get("name", ""))call_args = part.get("input")- parts.append({- "functionCall": {- "name": name_map.get(call_name, call_name),- "args": call_args if isinstance(call_args, dict) else {},- },- "thought_signature": part["thought_signature"],- })+ parts.append(+ {+ "functionCall": {+ "name": name_map.get(call_name, call_name),+ "args": call_args if isinstance(call_args, dict) else {},+ },+ "thought_signature": part["thought_signature"],+ }+ )else:# Unknown block type: keep the previous lossless behavior.parts.append({"text": json.dumps(part, default=str)})if m.role == "user" and images:for img in images:- parts.append({- "inline_data": {- "mime_type": img.mime,- "data": img.data_b64,+ parts.append(+ {+ "inline_data": {+ "mime_type": img.mime,+ "data": img.data_b64,+ }}- })+ )if not parts:# Defensive: a Gemini content must not be empty.parts.append({"text": ""})@@ -340,44 +342,46 @@ def _to_gemini_contents(# `strict=True` + `input_examples=[...]` at the schema root. Without this# cleanup, Gemini rejects the request with GenerateContentConfig validation errors# (Bug #API-1, 2026-04-29).-_GEMINI_FORBIDDEN_SCHEMA_KEYS: frozenset[str] = frozenset({- "strict", # OpenAI strict-mode flag- "input_examples", # Phase 7.3 SelfMod input_examples- "additionalProperties", # OpenAI 2024-08 strict-mode marker- "additional_properties", # google-genai may receive pydantic's snake_case form- "$schema", # JSON-Schema meta- "$id",- # JSON-schema keywords the google-genai Schema model (extra="forbid")- # rejects. The Schema model accepts only its documented subset — verified- # 2026-06-01 against google-genai 1.67 (types.Schema.model_fields). The- # ``exclusive*`` bounds below are first CONVERTED to ``minimum``/``maximum``- # in ``_sanitize_for_gemini`` (constraint-preserving) and only then dropped- # here; the rest are simply not part of Gemini's schema dialect.- "exclusiveMinimum", # Pydantic Field(gt=N) — converted to ``minimum``- "exclusiveMaximum", # Pydantic Field(lt=N) — converted to ``maximum``- "exclusive_minimum", # snake_case variant- "exclusive_maximum", # snake_case variant- "$defs", # Pydantic emits these for nested models / refs- "definitions", # draft-07 definitions block- "examples", # plural — Gemini only accepts singular ``example``- "const", # not in Gemini's subset- # JSON-schema object-key constraints Gemini's Schema model (extra="forbid")- # rejects. A connected MCP/plugin tool can ship these on a free-form object- # parameter; left in, ONE such tool schema fails the WHOLE GenerateContent- # request with a Pydantic "extra_forbidden" validation error, so the primary- # brain (Gemini) dies and the turn falls through the whole provider chain- # (live forensic 2026-07-23: functionDeclarations[105].parameters.properties.- # anchor.propertyNames → 5 validation errors → gemini down → claude 401 →- # openrouter 400 → openai 429 → anti-silence fallback). Dropping the- # constraint keeps the tool callable; only the key-name restriction is lost.- "propertyNames", # restricts allowed property names — not in Gemini's subset- "patternProperties", # per-pattern property schemas — not in Gemini's subset- "unevaluatedProperties",- "minProperties", # object size bounds — not in Gemini's subset- "maxProperties",- "dependentRequired",- "dependentSchemas",-})+_GEMINI_FORBIDDEN_SCHEMA_KEYS: frozenset[str] = frozenset(+ {+ "strict", # OpenAI strict-mode flag+ "input_examples", # Phase 7.3 SelfMod input_examples+ "additionalProperties", # OpenAI 2024-08 strict-mode marker+ "additional_properties", # google-genai may receive pydantic's snake_case form+ "$schema", # JSON-Schema meta+ "$id",+ # JSON-schema keywords the google-genai Schema model (extra="forbid")+ # rejects. The Schema model accepts only its documented subset — verified+ # 2026-06-01 against google-genai 1.67 (types.Schema.model_fields). The+ # ``exclusive*`` bounds below are first CONVERTED to ``minimum``/``maximum``+ # in ``_sanitize_for_gemini`` (constraint-preserving) and only then dropped+ # here; the rest are simply not part of Gemini's schema dialect.+ "exclusiveMinimum", # Pydantic Field(gt=N) — converted to ``minimum``+ "exclusiveMaximum", # Pydantic Field(lt=N) — converted to ``maximum``+ "exclusive_minimum", # snake_case variant+ "exclusive_maximum", # snake_case variant+ "$defs", # Pydantic emits these for nested models / refs+ "definitions", # draft-07 definitions block+ "examples", # plural — Gemini only accepts singular ``example``+ "const", # not in Gemini's subset+ # JSON-schema object-key constraints Gemini's Schema model (extra="forbid")+ # rejects. A connected MCP/plugin tool can ship these on a free-form object+ # parameter; left in, ONE such tool schema fails the WHOLE GenerateContent+ # request with a Pydantic "extra_forbidden" validation error, so the primary+ # brain (Gemini) dies and the turn falls through the whole provider chain+ # (live forensic 2026-07-23: functionDeclarations[105].parameters.properties.+ # anchor.propertyNames → 5 validation errors → gemini down → claude 401 →+ # openrouter 400 → openai 429 → anti-silence fallback). Dropping the+ # constraint keeps the tool callable; only the key-name restriction is lost.+ "propertyNames", # restricts allowed property names — not in Gemini's subset+ "patternProperties", # per-pattern property schemas — not in Gemini's subset+ "unevaluatedProperties",+ "minProperties", # object size bounds — not in Gemini's subset+ "maxProperties",+ "dependentRequired",+ "dependentSchemas",+ }+)def _convert_exclusive_bounds(schema: dict[str, Any]) -> dict[str, Any]:@@ -414,15 +418,44 @@ def _convert_exclusive_bounds(schema: dict[str, Any]) -> dict[str, Any]:# The documented Gemini schema subset, used when the installed google-genai# cannot be introspected. Field names AND their JSON aliases, because a tool# schema arrives in either spelling.-_GEMINI_SCHEMA_KEYS_FALLBACK: frozenset[str] = frozenset({- "additionalProperties", "additional_properties", "anyOf", "any_of",- "default", "defs", "description", "enum", "example", "format", "items",- "maxItems", "max_items", "maxLength", "max_length", "maxProperties",- "max_properties", "maximum", "minItems", "min_items", "minLength",- "min_length", "minProperties", "min_properties", "minimum", "nullable",- "pattern", "properties", "propertyOrdering", "property_ordering", "ref",- "required", "title", "type",-})+_GEMINI_SCHEMA_KEYS_FALLBACK: frozenset[str] = frozenset(+ {+ "additionalProperties",+ "additional_properties",+ "anyOf",+ "any_of",+ "default",+ "defs",+ "description",+ "enum",+ "example",+ "format",+ "items",+ "maxItems",+ "max_items",+ "maxLength",+ "max_length",+ "maxProperties",+ "max_properties",+ "maximum",+ "minItems",+ "min_items",+ "minLength",+ "min_length",+ "minProperties",+ "min_properties",+ "minimum",+ "nullable",+ "pattern",+ "properties",+ "propertyOrdering",+ "property_ordering",+ "ref",+ "required",+ "title",+ "type",+ }+)@lru_cache(maxsize=1)@@ -502,11 +535,45 @@ def _sanitize_for_gemini(schema: dict[str, Any]) -> dict[str, Any]:out[k] = [_sanitize_for_gemini(sub) if isinstance(sub, dict) else sub for sub in v]elif k in _GEMINI_SCHEMA_VALUED and isinstance(v, dict):out[k] = _sanitize_for_gemini(v)+ elif k == "type":+ # JSON Schema allows ``type: ["string", "number"]``. Gemini's+ # Schema.type is a single enum. A Linear MCP tool shipped a union+ # on ``issue_fields.items.properties.value.type``; left as a list+ # it 400s the WHOLE GenerateContentConfig, so Vertex/Gemini die+ # and a screenshot turn walks five other providers (live+ # 2026-08-31 17:06, 20 s to grok-4.6). Flatten to one type.+ out[k] = _gemini_single_type(v)else:out[k] = vreturn out+_GEMINI_TYPE_NAMES: tuple[str, ...] = (+ "string",+ "number",+ "integer",+ "boolean",+ "array",+ "object",+ "null",+)+++def _gemini_single_type(value: Any) -> Any:+ """Collapse a JSON-Schema union ``type`` list to one Gemini enum value."""+ if not isinstance(value, list):+ return value+ names = [str(item).strip().lower() for item in value if item is not None]+ if not names:+ return "string"+ if "null" in names:+ names = [n for n in names if n != "null"] or ["string"]+ for preferred in _GEMINI_TYPE_NAMES:+ if preferred in names:+ return preferred+ return names[0]++# Gemini function-name rule (live forensic 2026-06-01, data/jarvis_desktop.log# 23:34:57): names must match ^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$. Connected# MCP/marketplace plugin tools (the "plugin-tools" virtual loader) carry names@@ -583,11 +650,13 @@ def _build_gemini_tool_declarations(raw_schema = t.get("input_schema") or t.get("parameters") or t.get("schema") or {}schema = _sanitize_for_gemini(raw_schema) if raw_schema else {}original = t.get("name", "")- declarations.append({- "name": name_map.get(original, original),- "description": t.get("description", ""),- "parameters": schema if schema else {"type": "object", "properties": {}},- })+ declarations.append(+ {+ "name": name_map.get(original, original),+ "description": t.get("description", ""),+ "parameters": schema if schema else {"type": "object", "properties": {}},+ }+ )return [{"functionDeclarations": declarations}], name_map@@ -642,9 +711,7 @@ def _create_native_client(endpoint: Any, *, pinned_route: str | None = None) ->http_options = genai_types.HttpOptions(base_url=endpoint.base_url)route = "aistudio"- return build_genai_client(- endpoint.credential, http_options=http_options, route=route- )+ return build_genai_client(endpoint.credential, http_options=http_options, route=route)def _reject_compat_fallback_for_vertex(@@ -718,16 +785,9 @@ def _openai_compat_request(req: BrainRequest) -> BrainRequest:sanitized_tools: list[dict[str, Any]] = []for tool in req.tools:copied = dict(tool)- raw_schema = (- tool.get("input_schema")- or tool.get("parameters")- or tool.get("schema")- or {}- )+ raw_schema = tool.get("input_schema") or tool.get("parameters") or tool.get("schema") or {}copied["input_schema"] = (- _sanitize_for_gemini(raw_schema)- if raw_schema- else {"type": "object", "properties": {}}+ _sanitize_for_gemini(raw_schema) if raw_schema else {"type": "object", "properties": {}})sanitized_tools.append(copied)return BrainRequest(@@ -830,12 +890,9 @@ class GeminiBrain:# documented HTTPS compatibility API. Log only the exception# class: dependency messages can contain local paths, and the# credential must never enter logs.- _reject_compat_fallback_for_vertex(- ep, exc, pinned_route=self.pinned_route- )+ _reject_compat_fallback_for_vertex(ep, exc, pinned_route=self.pinned_route)log.info(- "Gemini native SDK unavailable (%s); using the "- "OpenAI-compatible transport",+ "Gemini native SDK unavailable (%s); using the OpenAI-compatible transport",type(exc).__name__,)self._client = _create_openai_compat_client(ep)@@ -843,7 +900,9 @@ class GeminiBrain:return self._clientasync def _ensure_cache(- self, system_text: str, tools_payload: list[dict[str, Any]] | None,+ self,+ system_text: str,+ tools_payload: list[dict[str, Any]] | None,) -> str | None:"""Latency-Sprint-2: lazy init of the context cache.@@ -877,7 +936,8 @@ class GeminiBrain:if approx_tokens < _MIN_CACHE_TOKENS:log.debug("Gemini cache skipped (prefix ~%d tokens < %d minimum size)",- approx_tokens, _MIN_CACHE_TOKENS,+ approx_tokens,+ _MIN_CACHE_TOKENS,)return Noneremaining = self._cache_create_blocked_until - time.monotonic()@@ -891,6 +951,7 @@ class GeminiBrain:try:from google.genai import types as _genai_types+cache = await self._client.aio.caches.create(model=self._model,config=_genai_types.CreateCachedContentConfig(@@ -905,16 +966,16 @@ class GeminiBrain:self._cache_slots[sig] = self._cached_content_namewhile len(self._cache_slots) > _MAX_CACHE_SLOTS:self._cache_slots.pop(next(iter(self._cache_slots)))- log.info("Gemini context cache created: %s (tokens ~%d)",- self._cached_content_name, approx_tokens)+ log.info(+ "Gemini context cache created: %s (tokens ~%d)",+ self._cached_content_name,+ approx_tokens,+ )return self._cached_content_nameexcept Exception as exc: # noqa: BLE001- self._cache_create_blocked_until = (- time.monotonic() + _CACHE_CREATE_RETRY_AFTER_S- )+ self._cache_create_blocked_until = time.monotonic() + _CACHE_CREATE_RETRY_AFTER_Slog.warning(- "Gemini cache create failed, falling back to direct for the next "- "%.0fs: %s",+ "Gemini cache create failed, falling back to direct for the next %.0fs: %s",_CACHE_CREATE_RETRY_AFTER_S,exc,)@@ -958,8 +1019,9 @@ class GeminiBrain:yield deltareturn- system_parts: list[str] = [m.content for m in req.messages- if m.role == "system" and isinstance(m.content, str)]+ system_parts: list[str] = [+ m.content for m in req.messages if m.role == "system" and isinstance(m.content, str)+ ]if req.system:system_parts.append(req.system)@@ -1009,8 +1071,9 @@ class GeminiBrain:# the call (it just keeps the slower legacy behavior).try:from google.genai import types as _genai_types- config_dict["automatic_function_calling"] = (- _genai_types.AutomaticFunctionCallingConfig(disable=True)++ config_dict["automatic_function_calling"] = _genai_types.AutomaticFunctionCallingConfig(+ disable=True)except Exception: # noqa: BLE001 — never break the brain call over an SDK shape changelog.debug("could not disable Gemini automatic_function_calling", exc_info=True)@@ -1203,18 +1266,10 @@ class GeminiBrain:# deltas. Emitting every snapshot makes the shared# aggregator sum the same prompt repeatedly. Retain the# latest snapshot and emit it once after the stream.- prompt_tokens = int(- getattr(usage, "prompt_token_count", 0) or 0- )- cache_hit_tokens = int(- getattr(usage, "cached_content_token_count", 0) or 0- )- candidate_tokens = int(- getattr(usage, "candidates_token_count", 0) or 0- )- thought_tokens = int(- getattr(usage, "thoughts_token_count", 0) or 0- )+ prompt_tokens = int(getattr(usage, "prompt_token_count", 0) or 0)+ cache_hit_tokens = int(getattr(usage, "cached_content_token_count", 0) or 0)+ candidate_tokens = int(getattr(usage, "candidates_token_count", 0) or 0)+ thought_tokens = int(getattr(usage, "thoughts_token_count", 0) or 0)tool_result_tokens = int(getattr(usage, "tool_use_prompt_token_count", 0) or 0)@@ -1224,7 +1279,8 @@ class GeminiBrain:"input_tokens": max(prompt_tokens - cache_hit_tokens,0,- ) + tool_result_tokens,+ )+ + tool_result_tokens,"output_tokens": candidate_tokens + thought_tokens,"cache_hit_tokens": cache_hit_tokens,}@@ -1236,25 +1292,19 @@ class GeminiBrain:# on this instance skip that budget (and the extra 400)# entirely.self._rejected_thinking_budgets.add(pending_rejected_budget)- _REJECTED_THINKING_BUDGETS.add(- (self._model, pending_rejected_budget)- )+ _REJECTED_THINKING_BUDGETS.add((self._model, pending_rejected_budget))log.info(- "Gemini model %s rejects thinking_budget=%d — "- "omitting it from now on",+ "Gemini model %s rejects thinking_budget=%d — omitting it from now on",self._model,pending_rejected_budget,)returnexcept Exception as exc: # noqa: BLE001 — BUG-019 stale-cache recovery- if (- attempt == 1- and cache_name- and _is_stale_context_cache_error(exc)- ):+ if attempt == 1 and cache_name and _is_stale_context_cache_error(exc):log.warning("Gemini stale context-cache (BUG-019) — invalidating "- "and retrying once without cache: %s", exc,+ "and retrying once without cache: %s",+ exc,)self.invalidate_cache()config_dict.pop("cached_content", None)@@ -1267,10 +1317,7 @@ class GeminiBrain:if (not yielded_deltaand "thinking_config" in config_dict- and (- thinking_config_blamed- or _is_generic_invalid_argument_error(exc)- )+ and (thinking_config_blamed or _is_generic_invalid_argument_error(exc))):# Some models REQUIRE thinking mode and 400 on budget=0# ("Budget 0 is invalid. This model only works in thinking@@ -1284,8 +1331,9 @@ class GeminiBrain:# the error still propagates — one extra round trip, no# behavior change.log.info(- "Gemini model %s rejected thinking_config — retrying "- "once without it: %s", self._model, exc,+ "Gemini model %s rejected thinking_config — retrying once without it: %s",+ self._model,+ exc,)rejected_budget = getattr(config_dict.get("thinking_config"),@@ -1293,9 +1341,8 @@ class GeminiBrain:None,)cache_on_wire = bool(cache_name and "cached_content" in config_dict)- if (- thinking_kind == "level"- and not (not thinking_config_blamed and cache_on_wire)+ if thinking_kind == "level" and not (+ not thinking_config_blamed and cache_on_wire):# Gemini 2.5 400s on thinking_level. Fall through to# the budget path instead of dropping the knob —@@ -1306,15 +1353,14 @@ class GeminiBrain:# the two-variable retry must not blame either._REJECTED_THINKING_LEVELS.add(self._model)from google.genai import types as _retry_types+fallback = Noneif (0 not in self._rejected_thinking_budgetsand (self._model, 0) not in _REJECTED_THINKING_BUDGETS):try:- fallback = _retry_types.ThinkingConfig(- thinking_budget=0- )+ fallback = _retry_types.ThinkingConfig(thinking_budget=0)except (TypeError, AttributeError, ValueError):# Last rung of the same ladder, on the retry# path: no usable config means the request is@@ -1351,9 +1397,7 @@ class GeminiBrain:# The message names the thinking config — no# further evidence needed.self._rejected_thinking_budgets.add(rejected_budget)- _REJECTED_THINKING_BUDGETS.add(- (self._model, rejected_budget)- )+ _REJECTED_THINKING_BUDGETS.add((self._model, rejected_budget))elif not dropped_cache:pending_rejected_budget = rejected_budgetcontinue@@ -1369,9 +1413,7 @@ class GeminiBrain:ep = self._resolve_endpoint()if not self._credential_is_sufficient(ep):raise- _reject_compat_fallback_for_vertex(- ep, exc, pinned_route=self.pinned_route- )+ _reject_compat_fallback_for_vertex(ep, exc, pinned_route=self.pinned_route)log.info("Gemini native stream dependency unavailable (%s); ""using the OpenAI-compatible transport",diff --git a/jarvis/plugins/brain/grok.py b/jarvis/plugins/brain/grok.pyindex 7088d8ed09..8f8649eeb3 100644--- a/jarvis/plugins/brain/grok.py+++ b/jarvis/plugins/brain/grok.py@@ -49,6 +49,7 @@ class GrokBrain:api_key=ep.credential,base_url=ep.base_url,timeout=CLIENT_TIMEOUT,+ max_retries=0,)return self._clientdiff --git a/jarvis/plugins/brain/openai.py b/jarvis/plugins/brain/openai.pyindex 762391b0c1..eb797b96f2 100644--- a/jarvis/plugins/brain/openai.py+++ b/jarvis/plugins/brain/openai.py@@ -1,4 +1,5 @@"""OpenAI GPT Brain (direct API)."""+from __future__ import annotationsimport asyncio@@ -29,7 +30,16 @@ class OpenAIBrain:if not ep.credential:raise RuntimeError("No OpenAI API key found (openai_api_key / OPENAI_API_KEY).")from openai import AsyncOpenAI- kwargs: dict[str, Any] = {"api_key": ep.credential, "timeout": CLIENT_TIMEOUT}++ kwargs: dict[str, Any] = {+ "api_key": ep.credential,+ "timeout": CLIENT_TIMEOUT,+ # Live 2026-08-31 17:06: a screenshot turn spent 3.7 s on+ # three SDK retries of ``insufficient_quota`` 429 before the+ # chain reached Grok. Quota exhaustion is terminal; retrying+ # it is pure wait.+ "max_retries": 0,+ }if ep.base_url:kwargs["base_url"] = ep.base_urlself._client = AsyncOpenAI(**kwargs)diff --git a/jarvis/plugins/tool/screen_snapshot.py b/jarvis/plugins/tool/screen_snapshot.pyindex b171180668..14164b2dc2 100644--- a/jarvis/plugins/tool/screen_snapshot.py+++ b/jarvis/plugins/tool/screen_snapshot.py@@ -43,13 +43,10 @@ from jarvis.vision.screenshot import (_MAX_BYTES = 500_000_DEFAULT_JPEG_QUALITY = 85_MIN_JPEG_QUALITY = 50-# Vision LLMs (Claude/Gemini/GPT) internally downscale to ~1568 px on the-# longest side for token accounting. 4K captures (3840x2160) are pure-# waste — they cost ~3x the bytes and tokens with no visible vision benefit.-# 2048 px on the longest side is the sweet spot: noticeably larger than the-# internal LLM resampling target (no detail loss), but tight enough to-# reliably hit the _MAX_BYTES budget on 4K multi-monitor captures.-_MAX_DIMENSION = 2048+# Vision LLMs internally downscale to ~1568 px. Sending 2048 px costs+# tokens and grok/Gemini time with no extra UI-text reading+# (live 2026-08-31 17:06: 2048x1152 + grok-4.6 = 13 s of streaming).+_MAX_DIMENSION = 1280def _resize_for_budget(image: Any, max_dim: int) -> Any:diff --git a/jarvis/screen_context/service.py b/jarvis/screen_context/service.pyindex 484acc705e..c8c7c2e9fd 100644--- a/jarvis/screen_context/service.py+++ b/jarvis/screen_context/service.py@@ -21,6 +21,7 @@ feature whose promise is that the picture does not stick around. That is alsowhy this module uses the stateless ``capture_region``-style grab through theport rather than reusing ``ScreenshotSource``."""+from __future__ import annotationsimport asyncio@@ -66,7 +67,10 @@ log = logging.getLogger(__name__)#: Vision models downscale to roughly this on the long edge for token#: accounting, so anything larger costs bytes and latency for no added detail.#: Same value the existing screenshot tool settled on.-_MAX_DIMENSION = 2048+# Live 2026-08-31 17:06: a 2048x1152 JPEG plus grok-4.6 streamed 13 s.+# Vision models internally resample to ~1568 px; sending more costs tokens+# and time with no extra reading of on-screen text.+_MAX_DIMENSION = 1280_JPEG_QUALITY = 85_MAX_IMAGE_BYTES = 500_000_MIN_JPEG_QUALITY = 50@@ -252,9 +256,7 @@ class ScreenContextService:if self._bus is None:self._bus = buselif self._bus is not bus:- log.warning(- "screen_context: ignored an attempt to bind a second EventBus"- )+ log.warning("screen_context: ignored an attempt to bind a second EventBus")returnif hasattr(bus, "subscribe"):from jarvis.audio.effects import attach_audio_effects # noqa: PLC0415@@ -305,10 +307,7 @@ class ScreenContextService:status="refused",verdict=verdict,reason_kind="policy",- message=(- "Screen context is switched off. You can turn it back on in "- "Settings."- ),+ message=("Screen context is switched off. You can turn it back on in Settings."),)if verdict.intent is VisualIntent.AMBIGUOUS:@@ -364,22 +363,14 @@ class ScreenContextService:# The cursor is sampled ONCE, here, and threaded through. See# targeting.resolve_target for why re-reading it later is a race.cursor_point = await asyncio.to_thread(self.cursor.position)- bar_point = (- await asyncio.to_thread(self.bar.position)- if cursor_point is None- else None- )+ bar_point = await asyncio.to_thread(self.bar.position) if cursor_point is None else None# Facts and native handle must describe the SAME foreground window.# Reading them separately lets a focus switch route a denylist verdict# for window A into a native capture of window B (especially on macOS).window_handle = Nonewindow_probe = self.window_probesnapshot_getter = getattr(window_probe, "foreground_snapshot", None)- snapshot = (- await asyncio.to_thread(snapshot_getter)- if callable(snapshot_getter)- else None- )+ snapshot = await asyncio.to_thread(snapshot_getter) if callable(snapshot_getter) else Noneif snapshot is not None:window_facts = snapshot.factswindow_handle = snapshot.handle@@ -413,13 +404,9 @@ class ScreenContextService:"denylist."),)- blocked_by = redaction.blocked_by_denylist(- window_facts, self._settings.denylist- )+ blocked_by = redaction.blocked_by_denylist(window_facts, self._settings.denylist)if blocked_by:- log.info(- "screen_context: capture blocked by denylist entry %r", blocked_by- )+ log.info("screen_context: capture blocked by denylist entry %r", blocked_by)return CaptureOutcome(status="refused",verdict=verdict,@@ -463,9 +450,7 @@ class ScreenContextService:# that monitor before any pixels exist. Unknown window geometry counts# as intersecting (fail closed), and an unavailable enumeration blocks# monitor scope rather than silently weakening the privacy rule.- monitor_privacy_error = await asyncio.to_thread(- self._monitor_privacy_error, target- )+ monitor_privacy_error = await asyncio.to_thread(self._monitor_privacy_error, target)if monitor_privacy_error:return CaptureOutcome(status="refused",@@ -514,9 +499,7 @@ class ScreenContextService:"when the intended window is in front."),)- monitor_privacy_error = await asyncio.to_thread(- self._monitor_privacy_error, target- )+ monitor_privacy_error = await asyncio.to_thread(self._monitor_privacy_error, target)if monitor_privacy_error:return CaptureOutcome(status="refused",@@ -546,8 +529,7 @@ class ScreenContextService:verdict=verdict,reason_kind="failure",message=(- "The screen could not be captured because the capture "- "backend failed."+ "The screen could not be captured because the capture backend failed."),)@@ -574,9 +556,7 @@ class ScreenContextService:"window is stable."),)- monitor_privacy_error = await asyncio.to_thread(- self._monitor_privacy_error, target- )+ monitor_privacy_error = await asyncio.to_thread(self._monitor_privacy_error, target)if monitor_privacy_error:return CaptureOutcome(status="refused",@@ -655,12 +635,8 @@ class ScreenContextService:"application could not be identified for your privacy ""denylist. Ask for the active window instead.")- blocked_by = redaction.blocked_by_denylist(- candidate, self._settings.denylist- )- if blocked_by and _rects_intersect_or_unknown(- candidate.frame_rect, target.bbox- ):+ blocked_by = redaction.blocked_by_denylist(candidate, self._settings.denylist)+ if blocked_by and _rects_intersect_or_unknown(candidate.frame_rect, target.bbox):return ("I did not capture the monitor because a visible window "f"matches your privacy rule '{blocked_by}'."@@ -690,9 +666,7 @@ class ScreenContextService:text, text_source, nodes, text_degradations = "", "none", (), ()access_error = await asyncio.to_thread(accessibility_permission_error)if access_error:- degradations.append(- Degradation(code=DegradationCode.NO_UI_TEXT, message=access_error)- )+ degradations.append(Degradation(code=DegradationCode.NO_UI_TEXT, message=access_error))else:try:text, text_source, nodes, text_degradations = await asyncio.wait_for(@@ -702,9 +676,7 @@ class ScreenContextService:max_chars=self._settings.max_text_chars,keep_unbounded_nodes=target.kind is TargetKind.WINDOW,window_title_filter=(- target.window.title- if target.kind is TargetKind.WINDOW- else None+ target.window.title if target.kind is TargetKind.WINDOW else None),expected_pid=target.window.pid,expected_window_title=target.window.title,@@ -723,8 +695,7 @@ class ScreenContextService:))log.warning(- "screen_context: accessibility read exceeded %.1fs; "- "continuing image-only",+ "screen_context: accessibility read exceeded %.1fs; continuing image-only",_UI_TEXT_TIMEOUT_S,)degradations.extend(text_degradations)@@ -794,9 +765,7 @@ class ScreenContextService:else ocr_scrubbed)text_hits = text_hits + ocr_hits- text_source = (- "ocr" if text_source == "none" else "accessibility+ocr"- )+ text_source = "ocr" if text_source == "none" else "accessibility+ocr"image_bytes, encoded_size = _encode(image)@@ -836,9 +805,7 @@ class ScreenContextService:if expected.pid and current.facts.pid:comparisons.append(int(expected.pid) == int(current.facts.pid))expected_title = " ".join(str(expected.title or "").casefold().split())- current_title = " ".join(- str(current.facts.title or "").casefold().split()- )+ current_title = " ".join(str(current.facts.title or "").casefold().split())if expected_title and current_title:comparisons.append(expected_title == current_title)return all(comparisons) if comparisons else not expected.is_known@@ -852,9 +819,7 @@ class ScreenContextService:raise RuntimeError("Screen Context service is closed")self.sweep()handle_id = secrets.token_urlsafe(12)- expires_at_ns = self._clock() + int(- self._settings.ttl_s * 1_000_000_000- )+ expires_at_ns = self._clock() + int(self._settings.ttl_s * 1_000_000_000)self._handles[handle_id] = _Handle(context=context,expires_at_ns=expires_at_ns,@@ -893,11 +858,7 @@ class ScreenContextService:"""Drop expired handles. Returns how many were dropped."""with self._handle_lock:now = self._clock()- expired = [- key- for key, handle in self._handles.items()- if handle.expires_at_ns <= now- ]+ expired = [key for key, handle in self._handles.items() if handle.expires_at_ns <= now]for key in expired:self._handles.pop(key, None)self._cancel_expiry(key)@@ -1043,9 +1004,7 @@ class ScreenContextService:if not truthful_ack:return Trueassert waiter is not None- return await asyncio.wait_for(- asyncio.shield(waiter), timeout=_ANNOUNCE_TIMEOUT_S- )+ return await asyncio.wait_for(asyncio.shield(waiter), timeout=_ANNOUNCE_TIMEOUT_S)except TimeoutError:log.warning("screen_context: capture indicator did not acknowledge within "@@ -1068,18 +1027,14 @@ class ScreenContextService:ScreenCaptureIndicatorDismissed,)- await self._bus.publish(- ScreenCaptureIndicatorDismissed(trace_id=trace_id)- )+ await self._bus.publish(ScreenCaptureIndicatorDismissed(trace_id=trace_id))except Exception: # noqa: BLE001 - hiding is best effort but observablelog.warning("screen_context: capture indicator dismissal failed",exc_info=True,)- async def _publish_completed(- self, context: ScreenContext, *, trace_id: UUID- ) -> None:+ async def _publish_completed(self, context: ScreenContext, *, trace_id: UUID) -> None:if self._bus is None:returntry:@@ -1104,9 +1059,7 @@ class ScreenContextService:exc_info=True,)- async def _publish_grabbed(- self, size: tuple[int, int], *, trace_id: UUID- ) -> None:+ async def _publish_grabbed(self, size: tuple[int, int], *, trace_id: UUID) -> None:if self._bus is None:returntry:@@ -1204,9 +1157,7 @@ def settings_from_config(cfg: Any) -> ScreenContextSettings:enabled=bool(getattr(block, "enabled", True)),denylist=tuple(getattr(block, "denylist", ()) or ()),extra_patterns=tuple(getattr(block, "sensitive_patterns", ()) or ()),- include_default_patterns=bool(- getattr(block, "include_default_patterns", True)- ),+ include_default_patterns=bool(getattr(block, "include_default_patterns", True)),max_text_chars=int(getattr(block, "max_text_chars", 4000)),ttl_s=float(getattr(block, "ttl_s", 120.0)),deck_preview_s=float(getattr(block, "deck_preview_s", 120.0)),diff --git a/tests/unit/brain/test_gemini_schema_sanitize.py b/tests/unit/brain/test_gemini_schema_sanitize.pyindex 9ed1d07064..780dd67d49 100644--- a/tests/unit/brain/test_gemini_schema_sanitize.py+++ b/tests/unit/brain/test_gemini_schema_sanitize.py@@ -77,6 +77,26 @@ def test_sanitizer_recurses_into_nested_and_lists():assert clean["properties"]["outer"]["items"]["type"] == "object"+def test_json_schema_union_type_flattens_to_one_gemini_enum() -> None:+ """Linear MCP shipped ``type: [string, number, boolean]`` (live 2026-08-31 17:06)."""+ bad = {+ "type": "object",+ "properties": {+ "issue_fields": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "value": {"type": ["string", "number", "boolean"]},+ },+ },+ }+ },+ }+ clean = _sanitize_for_gemini(bad)+ assert clean["properties"]["issue_fields"]["items"]["properties"]["value"]["type"] == ("string")++def test_an_unknown_extension_key_is_dropped_whatever_it_is_called():"""The 2026-08-26 outage: the GitHub MCP server tags parameters with``x-mcp-header``. It was on no block-list, so 81 validation errors killeddiff --git a/tests/unit/brain/test_grok_provider_wiring.py b/tests/unit/brain/test_grok_provider_wiring.pyindex f7e6c03a62..d1a17a955e 100644--- a/tests/unit/brain/test_grok_provider_wiring.py+++ b/tests/unit/brain/test_grok_provider_wiring.py@@ -140,6 +140,7 @@ def test_grok_uses_xai_openai_compatible_endpoint(GrokBrain()._ensure_client()assert _FakeOpenAI.last_kwargs["api_key"] == "xai-test"assert _FakeOpenAI.last_kwargs["base_url"] == BASE_URL+ assert _FakeOpenAI.last_kwargs["max_retries"] == 0@pytest.mark.asynciodiff --git a/tests/unit/brain/test_image_turn_tool_override.py b/tests/unit/brain/test_image_turn_tool_override.pyindex e378a96229..1c5cef18e6 100644--- a/tests/unit/brain/test_image_turn_tool_override.py+++ b/tests/unit/brain/test_image_turn_tool_override.py@@ -31,17 +31,18 @@ def _mgr(tools: dict, *, required: str = "", is_write: bool = False) -> BrainMandef _surface() -> dict:return {- "screenshot": object(), # read — must stay- "search_web": object(), # read — must stay- "computer_use": object(), # the action vehicle a screen turn may need- "run_shell": object(), # write mandate target (2026-08-08)- "spawn_worker": object(), # unattended background agent — hidden- "multi_spawn": object(), # ditto- "contact-upsert": object(), # silent record write — hidden- "wiki-ingest": object(), # ditto+ "screenshot": object(), # read — must stay+ "search_web": object(), # read — must stay+ "computer_use": object(), # the action vehicle a screen turn may need+ "run_shell": object(), # write mandate target (2026-08-08)+ "spawn_worker": object(), # unattended background agent — hidden+ "multi_spawn": object(), # ditto+ "contact-upsert": object(), # silent record write — hidden+ "wiki-ingest": object(), # ditto"google_calendar": object(), # ditto- "call-contact": object(), # ditto- "update_profile": object(), # ditto+ "call-contact": object(), # ditto+ "update_profile": object(), # ditto+ "linear/save_issue": object(), # MCP — union types brick Gemini}@@ -57,8 +58,14 @@ def test_screen_turn_hides_the_unattended_vehicles() -> None:# record behind the user's back.out = _mgr(_surface())._image_turn_tool_override()for hidden in (- "spawn_worker", "multi_spawn", "contact-upsert", "wiki-ingest",- "google_calendar", "call-contact", "update_profile",+ "spawn_worker",+ "multi_spawn",+ "contact-upsert",+ "wiki-ingest",+ "google_calendar",+ "call-contact",+ "update_profile",+ "linear/save_issue",):assert hidden not in out, hiddendiff --git a/tests/unit/brain/test_vision_lead_chain.py b/tests/unit/brain/test_vision_lead_chain.pynew file mode 100644index 0000000000..4d1d10a0b9--- /dev/null+++ b/tests/unit/brain/test_vision_lead_chain.py@@ -0,0 +1,71 @@+"""Image turns must lead with a live vision FAST model, not the Tool Model.++Live 2026-08-31 17:06: prefer_tool_model hoisted Vertex gemini-3.7-flash.+Five providers failed (schema / 402 / 401 / 429 retries) and grok-4.6+answered after 20 s. A look turn leads with the router-tier vision model.+"""++from __future__ import annotations++from types import SimpleNamespace++from jarvis.brain.manager import BrainManager+++class _Vision:+ supports_vision = True+++class _Blind:+ supports_vision = False+++def _mgr(*, active: str = "grok") -> BrainManager:+ m = BrainManager.__new__(BrainManager)+ m._active_name = active+ m._dead_providers = set()+ m._brain_cache = {}+ m._config = SimpleNamespace(+ brain=SimpleNamespace(+ router=SimpleNamespace(+ provider="grok",+ model="grok-4.20-0309-non-reasoning",+ )+ )+ )+ brains = {+ "grok": _Vision(),+ "vertex": _Vision(),+ "openrouter": _Vision(),+ "claude-api": _Vision(),+ "codex": _Blind(),+ }++ def _get_brain(provider: str, model: str | None = None, **kwargs: object) -> object:+ return brains[provider]++ def _fast_model(provider: str) -> str:+ return {"grok": "grok-4.3", "vertex": "gemini-3.5-flash"}.get(provider, "fast")++ m._get_brain = _get_brain # type: ignore[method-assign]+ m._fast_model = _fast_model # type: ignore[method-assign]+ return m+++def test_image_turn_leads_with_the_router_vision_model() -> None:+ m = _mgr()+ chain = [+ ("vertex", "gemini-3.7-flash"),+ ("openrouter", "google/gemini-3.5-flash"),+ ("claude-api", "claude-opus-4-8"),+ ("grok", "grok-4.6"),+ ]+ led = m._lead_vision_chain(chain)+ assert led[0] == ("grok", "grok-4.20-0309-non-reasoning")+++def test_blind_providers_stay_in_the_tail() -> None:+ m = _mgr(active="codex")+ led = m._lead_vision_chain([("codex", "gpt-5.5"), ("grok", "grok-4.6")])+ assert led[0][0] == "grok"+ assert led[-1][0] == "codex"