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
perf(brain): keep Gemini context caches per tool-set variant and teach delegated turns the speed contract
Ruben Lütkee9e4ffe7e5b1
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex c285187ac6..b9f88c21f8 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -394,6 +394,21 @@ _DELEGATE_DEADLINE_S: float = 20.0# Computer-Use calls (jarvis/cu/brain_call.py); providers without a# reasoning knob ignore the hint (AP-21: capability hint, no provider pin)._DELEGATE_REASONING_EFFORT: Literal["none"] = "none"+# Appended to the system prompt of DELEGATED voice turns only. Live 2026-07-17+# (turn af736681): the tool loop spent 5 sequential rounds on one question —+# three near-identical wiki-recall calls, then wiki-list, then wiki-page-read —+# and ran the 20 s deadline out. Every round is a full provider round-trip, so+# round count IS the latency. Static text (byte-stable across turns) so the+# delegated prefix keeps its own provider prompt-cache entry.+_DELEGATE_VOICE_DIRECTIVE = (+ "DELEGATED VOICE TURN — SPEED CONTRACT: the user is waiting in a live "+ "voice call, and every model round costs seconds. Finish in as few "+ "rounds as possible: batch ALL independent lookups as multiple function "+ "calls in ONE round instead of one per round; never re-issue a tool call "+ "(or a rephrasing of it) whose result you already have; as soon as the "+ "gathered evidence answers the question, stop calling tools and answer. "+ "Keep the final answer concise and speakable."+)def _resolve_tier_model(@@ -2643,6 +2658,7 @@ class BrainManager:max_turns: int | None = None,deadline_s: float | None = None,reasoning_effort: Literal["none"] | None = None,+ delegated_voice: bool = False,) -> BrainDispatcher:"""Builds the dispatcher with an optional tool override.@@ -2659,6 +2675,11 @@ class BrainManager:of the turn. Delegated realtime voice turns pass ``"none"`` so athinking-by-default model never burns seconds of internal reasoningper tool-loop round — see ``_DELEGATE_REASONING_EFFORT``.++ ``delegated_voice`` (2026-07-17): appends the static speed contract+ (``_DELEGATE_VOICE_DIRECTIVE``) — batch lookups, no repeats, answer+ as soon as evidence suffices — to the system prompt of delegated+ voice turns only, so classic chat prompts stay byte-identical."""tools = tools_override if tools_override is not None else self._toolssystem_prompt = self._build_system_prompt()@@ -2668,6 +2689,8 @@ class BrainManager:cards = self._plugin_usage_cards_block(tools)if cards:system_prompt = f"{system_prompt}\n\n{cards}"+ if delegated_voice:+ system_prompt = f"{system_prompt}\n\n{_DELEGATE_VOICE_DIRECTIVE}"kwargs: dict[str, Any] = {}if max_turns is not None:kwargs["max_turns"] = max_turns@@ -7965,6 +7988,7 @@ class BrainManager:"max_turns": _DELEGATE_MAX_TURNS,"deadline_s": _DELEGATE_DEADLINE_S,"reasoning_effort": _DELEGATE_REASONING_EFFORT,+ "delegated_voice": True,}if prefer_tool_modelelse {}diff --git a/jarvis/plugins/brain/gemini.py b/jarvis/plugins/brain/gemini.pyindex 94831066c4..350ffbffc9 100644--- a/jarvis/plugins/brain/gemini.py+++ b/jarvis/plugins/brain/gemini.py@@ -50,6 +50,10 @@ _TOOL_HISTORY_EXTRA_CONTENT = {# when ``[performance].gemini_context_cache = true``. The cache holds the# system prompt + tools; vision frames stay non-cached (they vary per turn)._ENV_CONTEXT_CACHE = "JARVIS_GEMINI_CONTEXT_CACHE"+# How many distinct (system, tools) cache variants one brain instance keeps.+# The voice manager produces a small recurring set per session (full tool set,+# screen-tool-gated set, tools-stripped deadline round) — 4 covers them all.+_MAX_CACHE_SLOTS = 4# Minimum cache size: Gemini caches have a token floor (>= ~4096 tokens# depending on the model). For smaller prefixes the API either rejects it or# the cache isn't worth it — then we skip it and fall back to the direct path.@@ -444,11 +448,18 @@ class GeminiBrain:self._thinking_budget = thinking_budget# Latency-Sprint-2: context-cache name (lazily created on the first# call with system+tools). Key: (system_hash, tools_hash) → cache_name.- # Only one entry per instance, because system+tools are constant for- # a running voice session. On change (e.g. a tool reload), the cache- # is discarded via ``invalidate_cache()``.+ # ``_cached_content_name``/``_cache_signature`` hold the most recently+ # used slot (BUG-019 recovery pokes exactly these two attributes).self._cached_content_name: str | None = Noneself._cache_signature: tuple[str, str] | None = None+ # 2026-07-17: a single slot re-created the (expensive, ~1.5 s) server+ # cache on EVERY delegated voice turn, because the manager legitimately+ # varies the tool set per utterance (screen-tool gating) and the+ # deadline-forced final round strips tools entirely — two or three+ # recurring (system, tools) variants kept evicting each other. A small+ # multi-slot map lets each recurring variant keep its own server-side+ # cache; insertion-ordered, oldest evicted beyond the cap.+ self._cache_slots: dict[tuple[str, str], str] = {}def _ensure_client(self) -> Any:if self._client is None:@@ -499,6 +510,13 @@ class GeminiBrain:)if self._cache_signature == sig and self._cached_content_name:return self._cached_content_name+ slot_hit = self._cache_slots.get(sig)+ if slot_hit:+ # A recurring (system, tools) variant — reuse its server cache and+ # promote it to the most-recently-used marker pair.+ self._cached_content_name = slot_hit+ self._cache_signature = sig+ return slot_hit# Estimate the minimum size (heuristic: 1 token ~ 4 chars).approx_tokens = (len(system_text) + len(json.dumps(tools_payload or []))) // 4@@ -521,6 +539,10 @@ class GeminiBrain:)self._cached_content_name = getattr(cache, "name", None)self._cache_signature = sig+ if self._cached_content_name:+ self._cache_slots[sig] = self._cached_content_name+ while 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)return self._cached_content_name@@ -546,6 +568,10 @@ class GeminiBrain:"""self._cached_content_name = Noneself._cache_signature = None+ # A stale-cache 403 usually means the server evicted by TTL — sibling+ # slots created around the same time are just as dead. Dropping them+ # all trades a few lazy re-creations for never re-sending a dead id.+ self._cache_slots.clear()async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:client = self._ensure_client()diff --git a/tests/unit/brain/test_delegate_voice_directive.py b/tests/unit/brain/test_delegate_voice_directive.pynew file mode 100644index 0000000000..923747ebbe--- /dev/null+++ b/tests/unit/brain/test_delegate_voice_directive.py@@ -0,0 +1,49 @@+"""Delegated-voice speed contract in the dispatcher system prompt.++Live forensic 2026-07-17 (turn af736681): a delegated voice turn burned five+sequential tool-loop rounds — three near-identical wiki-recall calls, then+wiki-list, then wiki-page-read — into the 20 s deadline. Round count is the+dominant latency on the delegated path, so delegated turns get an explicit+static directive: batch independent lookups into one round, never repeat a+call, answer as soon as the evidence suffices.++Contract under test:+ 1. ``_build_dispatcher(delegated_voice=True)`` appends the directive.+ 2. Classic dispatchers (default) stay byte-identical — no directive.+"""+from __future__ import annotations++from typing import Any++from jarvis.brain.manager import _DELEGATE_VOICE_DIRECTIVE, BrainManager+++def _bare_manager() -> Any:+ """A BrainManager shell sufficient for _build_dispatcher."""+ manager = BrainManager.__new__(BrainManager)+ manager._tools = {}+ manager._tool_executor = None+ manager._config = type(+ "Cfg", (), {"brain": type("BrainCfg", (), {"max_tokens": 1024})()}+ )()+ manager._build_system_prompt = lambda: "BASE PROMPT" # type: ignore[method-assign]+ manager._plugin_usage_cards_block = lambda tools: "" # type: ignore[method-assign]+ return manager+++def test_delegated_voice_dispatcher_carries_the_speed_contract() -> None:+ manager = _bare_manager()++ dispatcher = manager._build_dispatcher(object(), delegated_voice=True)++ assert dispatcher._system_prompt.startswith("BASE PROMPT")+ assert _DELEGATE_VOICE_DIRECTIVE in dispatcher._system_prompt+++def test_classic_dispatcher_prompt_stays_unchanged() -> None:+ manager = _bare_manager()++ dispatcher = manager._build_dispatcher(object())++ assert dispatcher._system_prompt == "BASE PROMPT"+ assert _DELEGATE_VOICE_DIRECTIVE not in dispatcher._system_promptdiff --git a/tests/unit/brain/test_gemini_cache_slots.py b/tests/unit/brain/test_gemini_cache_slots.pynew file mode 100644index 0000000000..433fceae2e--- /dev/null+++ b/tests/unit/brain/test_gemini_cache_slots.py@@ -0,0 +1,93 @@+"""Multi-slot Gemini context cache (per-turn re-creation fix, 2026-07-17).++Live forensic: the voice manager legitimately varies the tool set per+utterance (screen-tool gating) and the deadline-forced final round strips+tools entirely. With a single cache slot, every flap between those recurring+(system, tools) variants re-created the server-side cache (~1.5 s + billed+storage) — observed as one "Gemini context cache created" per delegated turn+plus a second one inside deadline turns.++Contract under test:+ 1. Two alternating (system, tools) variants each create their cache ONCE;+ revisiting a variant reuses its slot (no third create).+ 2. The slot map is bounded (oldest evicted beyond _MAX_CACHE_SLOTS).+ 3. ``invalidate_cache()`` clears the slots too — after a stale-cache 403+ no dead id can be served from a sibling slot.+"""+from __future__ import annotations++from types import SimpleNamespace+from typing import Any++import pytest++from jarvis.plugins.brain.gemini import _MAX_CACHE_SLOTS, GeminiBrain++_BIG = "X" * (4096 * 4 + 100) # clears the _MIN_CACHE_TOKENS floor+++class _FakeCaches:+ def __init__(self) -> None:+ self.creates = 0++ async def create(self, *, model: str, config: Any) -> Any:+ self.creates += 1+ return SimpleNamespace(name=f"cachedContents/slot-{self.creates}")+++def _provider() -> tuple[GeminiBrain, _FakeCaches]:+ provider = GeminiBrain(model="gemini-3.5-flash")+ caches = _FakeCaches()+ provider._client = SimpleNamespace(aio=SimpleNamespace(caches=caches))+ return provider, caches+++def _tools(marker: str) -> list[dict[str, Any]]:+ # Shape mirrors _build_gemini_tool_declarations output: genai Tool dicts+ # (CreateCachedContentConfig validates them — raw Anthropic-format tool+ # dicts would fail validation and silently skip the cache).+ return [{"function_declarations": [{"name": marker, "description": _BIG}]}]+++async def test_alternating_variants_reuse_their_slots() -> None:+ provider, caches = _provider()++ name_a1 = await provider._ensure_cache(_BIG, _tools("full-set"))+ name_b1 = await provider._ensure_cache(_BIG, None) # deadline round: no tools+ name_a2 = await provider._ensure_cache(_BIG, _tools("full-set"))+ name_b2 = await provider._ensure_cache(_BIG, None)++ assert caches.creates == 2, "each recurring variant must be created once"+ assert name_a1 == name_a2+ assert name_b1 == name_b2+ assert name_a1 != name_b1+++async def test_slot_map_is_bounded() -> None:+ provider, caches = _provider()++ for index in range(_MAX_CACHE_SLOTS + 2):+ await provider._ensure_cache(_BIG, _tools(f"variant-{index}"))++ assert caches.creates == _MAX_CACHE_SLOTS + 2+ assert len(provider._cache_slots) == _MAX_CACHE_SLOTS+++async def test_invalidate_cache_drops_all_slots() -> None:+ provider, caches = _provider()++ await provider._ensure_cache(_BIG, _tools("full-set"))+ await provider._ensure_cache(_BIG, None)+ assert provider._cache_slots++ provider.invalidate_cache()++ assert provider._cached_content_name is None+ assert provider._cache_signature is None+ assert not provider._cache_slots+ # The next call must CREATE again, never serve a dead id from a slot.+ await provider._ensure_cache(_BIG, _tools("full-set"))+ assert caches.creates == 3