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
feat(local-realtime): size the voice brain's context from this machine's memory
rubenluetke10-beepd5cac7e40173
diff --git a/jarvis/brain/ollama_inventory.py b/jarvis/brain/ollama_inventory.pyindex 727a03478b..daa22c53f2 100644--- a/jarvis/brain/ollama_inventory.py+++ b/jarvis/brain/ollama_inventory.py@@ -20,7 +20,7 @@ Two families of download are Jarvis's own bookkeeping, not the user'schoice, and are hidden from every user-facing list by :func:`is_hidden_alias`:the per-model option profiles (``<base>-jarvis-<8 hex>``, created via``/api/create`` so ``num_ctx`` & co. can ride the OpenAI-compatible ``/v1``-path) and the voice brain's ``-voice-8k`` alias. Aliases share their weights+path) and the voice brain's ``-voice-<N>k`` alias. Aliases share their weightswith the base model, so hiding them also keeps :func:`disk_usage` honest.Every function takes the server ``root`` explicitly (see@@ -50,6 +50,7 @@ __all__ = ["OllamaModelNotFound","PROFILE_ALIAS_SUFFIX_RE","VOICE_ALIAS_SUFFIX",+ "VOICE_ALIAS_RE","is_hidden_alias","native_context_length","same_model",@@ -66,8 +67,11 @@ __all__ = [#: of the baked option dict.PROFILE_ALIAS_SUFFIX_RE = re.compile(r"-jarvis-[0-9a-f]{8}$")-#: The managed voice brain's fixed-context alias (``supervisor.py``).+#: The managed voice brain's bounded-context alias (``supervisor.py``):+#: ``<base>-voice-<N>k`` where ``N`` is the ``num_ctx`` this machine's memory+#: allowed. ``VOICE_ALIAS_SUFFIX`` is the historical fixed-size spelling.VOICE_ALIAS_SUFFIX = "-voice-8k"+VOICE_ALIAS_RE = re.compile(r"-voice-\d+k$")#: ``/api/show`` is one round-trip per download; eight in flight keeps a#: 40-model host under a second on localhost without hammering a LAN box.@@ -150,7 +154,7 @@ def is_hidden_alias(name: str) -> bool:return Falseif PROFILE_ALIAS_SUFFIX_RE.search(bare):return True- return bare.endswith(VOICE_ALIAS_SUFFIX)+ return VOICE_ALIAS_RE.search(bare) is not None# ── HTTP ─────────────────────────────────────────────────────────────────diff --git a/jarvis/brain/ollama_profiles.py b/jarvis/brain/ollama_profiles.pyindex 6a47f7373f..ae64d40901 100644--- a/jarvis/brain/ollama_profiles.py+++ b/jarvis/brain/ollama_profiles.py@@ -272,6 +272,29 @@ def to_v1_kwargs(opts: OllamaModelOptions | None) -> dict[str, Any]:return kwargs+def largest_context_for(+ *, size_gb: float, native_context: int | None, budget_gb: float | None+) -> int:+ """The largest ladder rung whose weights + KV cache fit ``budget_gb``.++ ``native_context`` caps the ladder at the model's own window; ``None``+ budget (memory unreadable) returns the smallest rung. Shared by the+ per-model profile suggester and the managed voice brain so one machine+ never gets two different answers to "how much context fits here?".+ """+ kv_per_1k = max(size_gb, 0.5) * _KV_GB_PER_1K_PER_MODEL_GB+ ladder = [+ rung for rung in _CONTEXT_LADDER if native_context is None or rung <= native_context+ ] or [_CONTEXT_LADDER[0]]+ chosen = ladder[0]+ if budget_gb is not None:+ for rung in ladder:+ needed = size_gb + _OVERHEAD_GB + kv_per_1k * (rung / 1000)+ if needed <= budget_gb:+ chosen = rung+ return chosen++def suggest_options(*,size_gb: float,@@ -316,15 +339,8 @@ def suggest_options(# Context: the largest rung whose weights + KV cache fit the budget.kv_per_1k = max(size_gb, 0.5) * _KV_GB_PER_1K_PER_MODEL_GB- ladder = [- rung for rung in _CONTEXT_LADDER if native_context is None or rung <= native_context- ] or [_CONTEXT_LADDER[0]]- chosen = ladder[0]+ chosen = largest_context_for(size_gb=size_gb, native_context=native_context, budget_gb=budget)if budget is not None:- for rung in ladder:- needed = size_gb + _OVERHEAD_GB + kv_per_1k * (rung / 1000)- if needed <= budget:- chosen = rungestimate = size_gb + _OVERHEAD_GB + kv_per_1k * (chosen / 1000)reasons.append(f"num_ctx {chosen:,}: weights plus a {chosen // 1024}k context need "diff --git a/jarvis/realtime/local_server/supervisor.py b/jarvis/realtime/local_server/supervisor.pyindex 68c3d9a48d..5013b711aa 100644--- a/jarvis/realtime/local_server/supervisor.py+++ b/jarvis/realtime/local_server/supervisor.py@@ -106,12 +106,20 @@ BRAIN_REWARM_INTERVAL_S = 45 * 60.0# Ollama's OpenAI-compatible endpoints cannot accept a per-request context# size. Current long-context models can therefore reserve their full native# window (qwen3.5:4b used 262,144 tokens and spilled 5+ GiB into shared GPU-# memory on a 16 GiB card). The managed voice stack needs only a compact turn-# history, so it runs through a deterministic Ollama profile with an explicit-# bounded context. This leaves room for local TTS and prevents system-wide-# WDDM paging while preserving the user's chosen base model.-VOICE_BRAIN_CONTEXT_TOKENS = 8192-_VOICE_MODEL_SUFFIX = "-voice-8k"+# memory on a 16 GiB card). The managed voice stack therefore runs through a+# deterministic Ollama profile with an explicit ``num_ctx`` — sized from THIS+# machine's memory (maintainer mandate 2026-08-24: the context is not a cost+# lever; it is as large as the hardware allows). The brain shares the card+# with local STT and TTS, so a fixed reserve stays free for them; the rest+# goes to weights + KV cache on the shared context ladder+# (``jarvis.brain.ollama_profiles.largest_context_for``).+#: Context used when the machine's memory or the model's size cannot be read.+VOICE_BRAIN_CONTEXT_TOKENS_FLOOR = 8192+#: Accelerator memory kept free for the local STT + TTS models beside the brain.+VOICE_STACK_RESERVE_GB = 4.0+#: Historical name of the floor; readers that only need "some bound" keep it.+VOICE_BRAIN_CONTEXT_TOKENS = VOICE_BRAIN_CONTEXT_TOKENS_FLOOR+_VOICE_MODEL_SUFFIX_RE = re.compile(r"-voice-(\d+)k$")_VOICE_MODEL_PREPARE_LOCK = threading.Lock()_prepared_voice_models: set[tuple[str, str, str]] = set()@@ -2123,15 +2131,18 @@ def prepare_voice_brain_command(launch_command: str, *, timeout: float = 30.0) -if not root.startswith(("http://", "https://")):return launch_command- source_model, voice_model = _voice_context_models(model)+ source_model, _ = _voice_context_models(model)+ context_tokens, why = voice_brain_context_tokens(root, source_model, timeout=timeout)+ _, voice_model = _voice_context_models(source_model, context_tokens)cache_key = (root, source_model, voice_model)with _VOICE_MODEL_PREPARE_LOCK:if cache_key not in _prepared_voice_models:+ log.info("local-realtime supervisor: voice brain context %s — %s", context_tokens, why)payload = json.dumps({"model": voice_model,"from": source_model,- "parameters": {"num_ctx": VOICE_BRAIN_CONTEXT_TOKENS},+ "parameters": {"num_ctx": context_tokens},"stream": False,}).encode("utf-8")@@ -2147,7 +2158,7 @@ def prepare_voice_brain_command(launch_command: str, *, timeout: float = 30.0) -passexcept (urllib.error.URLError, OSError, ValueError) as exc:raise RuntimeError(- f"could not create the {VOICE_BRAIN_CONTEXT_TOKENS}-token "+ f"could not create the {context_tokens}-token "f"Ollama voice profile for {source_model}: {exc}") from exc_prepared_voice_models.add(cache_key)@@ -2155,21 +2166,116 @@ def prepare_voice_brain_command(launch_command: str, *, timeout: float = 30.0) -"local-realtime supervisor: prepared bounded Ollama model %s from %s (num_ctx=%s)",voice_model,source_model,- VOICE_BRAIN_CONTEXT_TOKENS,+ context_tokens,)return _replace_brain_model(launch_command, voice_model)-def _voice_context_models(model: str) -> tuple[str, str]:- """Return ``(base, bounded_alias)`` for an Ollama model tag."""+def _ollama_model_facts(+ root: str, model: str, *, timeout: float+) -> tuple[float | None, int | None]:+ """``(size_gb, native_context)`` of an installed Ollama model, or ``None``s.++ Two cheap local round-trips (``/api/tags`` for the on-disk size,+ ``/api/show`` for the architecture's context window). Any failure is a+ ``None`` — the caller then falls back to the floor and says so.+ """+ import urllib.error+ import urllib.request++ size_gb: float | None = None+ native: int | None = None+ try:+ with urllib.request.urlopen(f"{root}/api/tags", timeout=timeout) as resp: # noqa: S310+ rows = json.loads(resp.read().decode("utf-8")).get("models") or []+ from jarvis.brain.ollama_inventory import same_model++ for row in rows:+ name = str(row.get("name") or row.get("model") or "")+ if same_model(name, model):+ size = int(row.get("size") or 0)+ size_gb = size / (1024**3) if size > 0 else None+ break+ except (urllib.error.URLError, OSError, ValueError, TypeError):+ log.debug("supervisor: /api/tags lookup failed for %s", model, exc_info=True)+ try:+ request = urllib.request.Request( # noqa: S310 - scheme checked by the caller+ f"{root}/api/show",+ data=json.dumps({"model": model}).encode("utf-8"),+ headers={"Content-Type": "application/json"},+ )+ with urllib.request.urlopen(request, timeout=timeout) as resp: # noqa: S310+ show = json.loads(resp.read().decode("utf-8"))+ from jarvis.brain.ollama_inventory import native_context_length++ native = native_context_length(show.get("model_info"))+ except (urllib.error.URLError, OSError, ValueError, TypeError):+ log.debug("supervisor: /api/show lookup failed for %s", model, exc_info=True)+ return size_gb, native+++def voice_brain_context_tokens(root: str, model: str, *, timeout: float = 10.0) -> tuple[int, str]:+ """``(num_ctx, reason)`` for the managed voice brain on THIS machine.++ Budget = usable accelerator memory (dedicated VRAM, or unified memory on+ Apple Silicon) minus :data:`VOICE_STACK_RESERVE_GB` for the local STT and+ TTS models; without a readable accelerator the RAM rule from+ ``ollama_profiles`` applies. The largest rung of the shared context ladder+ whose weights + KV cache fit that budget wins, capped at the model's own+ window. Unknown size or unknown memory -> the floor, stated honestly.+ """+ from jarvis.brain.ollama_profiles import _RAM_SHARE, largest_context_for+ from jarvis.hardware.detection import system_ram_gb, usable_accelerator_gb++ floor = VOICE_BRAIN_CONTEXT_TOKENS_FLOOR+ size_gb, native = _ollama_model_facts(root, model, timeout=timeout)+ if size_gb is None:+ return floor, f"{model}: size unreadable from Ollama, using the {floor}-token floor"+ accelerator_gb, source = usable_accelerator_gb()+ if accelerator_gb > 0:+ budget = accelerator_gb - VOICE_STACK_RESERVE_GB+ where = "unified memory" if source == "apple-unified" else "accelerator memory"+ budget_sentence = (+ f"{accelerator_gb:.1f} GB {where} minus {VOICE_STACK_RESERVE_GB:.0f} GB "+ "reserved for local STT/TTS"+ )+ else:+ ram_gb = system_ram_gb()+ if ram_gb is None:+ return floor, f"{model}: no readable accelerator or RAM, using the {floor}-token floor"+ budget = ram_gb * _RAM_SHARE - VOICE_STACK_RESERVE_GB+ budget_sentence = (+ f"no accelerator this probe can vouch for, so {_RAM_SHARE:.0%} of "+ f"{ram_gb:g} GB RAM minus {VOICE_STACK_RESERVE_GB:.0f} GB for local STT/TTS"+ )+ chosen = largest_context_for(size_gb=size_gb, native_context=native, budget_gb=max(budget, 0.0))+ chosen = max(chosen, min(floor, native or floor))+ native_note = f", native window {native:,}" if native else ""+ return (+ chosen,+ f"{model} ({size_gb:.1f} GB{native_note}): {budget_sentence} -> num_ctx {chosen:,}",+ )+++def _voice_context_models(+ model: str, context_tokens: int = VOICE_BRAIN_CONTEXT_TOKENS_FLOOR+) -> tuple[str, str]:+ """Return ``(base, bounded_alias)`` for an Ollama model tag.++ The alias encodes its context (``<base>-voice-<N>k``), so a machine whose+ memory changed gets a fresh alias instead of a stale one; an alias passed+ in is folded back to its base first.+ """cleaned = model.strip()if ":" in cleaned:name, tag = cleaned.rsplit(":", 1)else:name, tag = cleaned, "latest"- if tag.endswith(_VOICE_MODEL_SUFFIX):- return f"{name}:{tag[: -len(_VOICE_MODEL_SUFFIX)]}", cleaned- return cleaned, f"{name}:{tag}{_VOICE_MODEL_SUFFIX}"+ match = _VOICE_MODEL_SUFFIX_RE.search(tag)+ if match:+ tag = tag[: match.start()]+ base = f"{name}:{tag}"+ return base, f"{base}-voice-{max(int(context_tokens), 1024) // 1024}k"_MODEL_NAME_FLAG = re.compile(diff --git a/tests/unit/realtime/local_server/test_supervisor.py b/tests/unit/realtime/local_server/test_supervisor.pyindex 1e4f04fc18..0bf9a6213e 100644--- a/tests/unit/realtime/local_server/test_supervisor.py+++ b/tests/unit/realtime/local_server/test_supervisor.py@@ -1630,9 +1630,15 @@ def test_brain_endpoint_is_parsed_from_the_command() -> None:assert base == "http://127.0.0.1:11434/v1"-def test_voice_brain_command_creates_an_8k_ollama_profile(monkeypatch) -> None:+def test_voice_brain_command_creates_a_bounded_ollama_profile(monkeypatch) -> None:import urllib.request+ # The size itself follows the machine (test_voice_brain_context.py); here+ # the create round-trip is under test, so the choice is pinned.+ monkeypatch.setattr(+ supervisor, "voice_brain_context_tokens", lambda *a, **k: (8192, "pinned")+ )+requests: list[tuple[str, dict[str, Any]]] = []class _Response:@@ -1667,6 +1673,10 @@ def test_voice_brain_command_creates_an_8k_ollama_profile(monkeypatch) -> None:def test_voice_brain_profile_is_idempotent_across_restarts(monkeypatch) -> None:import urllib.request+ monkeypatch.setattr(+ supervisor, "voice_brain_context_tokens", lambda *a, **k: (8192, "pinned")+ )+payloads: list[dict[str, Any]] = []class _Response:diff --git a/tests/unit/realtime/local_server/test_voice_brain_context.py b/tests/unit/realtime/local_server/test_voice_brain_context.pynew file mode 100644index 0000000000..71b12d0b1c--- /dev/null+++ b/tests/unit/realtime/local_server/test_voice_brain_context.py@@ -0,0 +1,140 @@+"""The managed voice brain's ``num_ctx`` follows the machine's memory.++Maintainer mandate 2026-08-24: the context is not a cost lever. The old fixed+8k profile is now the floor; the real size is the largest rung of the shared+context ladder whose weights + KV cache fit the accelerator (minus the reserve+for local STT/TTS), capped at the model's native window.+"""++from __future__ import annotations++import json+from typing import Any++import pytest++from jarvis.brain import ollama_inventory+from jarvis.brain.ollama_profiles import largest_context_for+from jarvis.realtime.local_server import supervisor+++class _FakeResponse:+ def __init__(self, payload: dict[str, Any]) -> None:+ self._body = json.dumps(payload).encode("utf-8")++ def read(self) -> bytes:+ return self._body++ def __enter__(self) -> _FakeResponse:+ return self++ def __exit__(self, *exc: object) -> None:+ return None+++def _fake_ollama(monkeypatch, *, size_bytes: int, native: int | None, created: list[dict]):+ """Serve ``/api/tags`` + ``/api/show`` for one model and record ``/api/create``."""+ import urllib.request++ def urlopen(request, timeout=None): # noqa: ANN001+ url = request if isinstance(request, str) else request.full_url+ if url.endswith("/api/tags"):+ return _FakeResponse({"models": [{"name": "qwen3.5:4b", "size": size_bytes}]})+ if url.endswith("/api/show"):+ info = {"general.architecture": "qwen3"}+ if native is not None:+ info["qwen3.context_length"] = native+ return _FakeResponse({"model_info": info})+ if url.endswith("/api/create"):+ created.append(json.loads(request.data.decode("utf-8")))+ return _FakeResponse({"status": "success"})+ raise AssertionError(f"unexpected url {url}")++ monkeypatch.setattr(urllib.request, "urlopen", urlopen)++[email protected](autouse=True)+def _fresh_memo() -> None:+ supervisor._prepared_voice_models.clear()+++def test_ladder_helper_is_capped_by_native_window_and_budget() -> None:+ # 3.4 GB model, unlimited budget, native 32k -> the 32k rung, not 128k.+ assert largest_context_for(size_gb=3.4, native_context=32_768, budget_gb=500.0) == 32_768+ # Unknown budget -> the smallest rung.+ assert largest_context_for(size_gb=3.4, native_context=None, budget_gb=None) == 4096+++def test_a_16gb_card_gets_a_64k_voice_context(monkeypatch) -> None:+ _fake_ollama(monkeypatch, size_bytes=3_400_000_000, native=262_144, created=[])+ monkeypatch.setattr(+ "jarvis.hardware.detection.usable_accelerator_gb", lambda: (15.9, "nvidia-smi")+ )+ tokens, why = supervisor.voice_brain_context_tokens("http://127.0.0.1:11434", "qwen3.5:4b")+ assert tokens == 65_536+ assert "reserved for local STT/TTS" in why+++def test_a_128gb_box_climbs_to_the_top_rung_within_the_native_window(monkeypatch) -> None:+ _fake_ollama(monkeypatch, size_bytes=3_400_000_000, native=262_144, created=[])+ monkeypatch.setattr(+ "jarvis.hardware.detection.usable_accelerator_gb", lambda: (128.0, "apple-unified")+ )+ tokens, why = supervisor.voice_brain_context_tokens("http://127.0.0.1:11434", "qwen3.5:4b")+ assert tokens == 131_072+ assert "unified memory" in why+++def test_unreadable_hardware_falls_back_to_the_floor_and_says_so(monkeypatch) -> None:+ _fake_ollama(monkeypatch, size_bytes=3_400_000_000, native=262_144, created=[])+ monkeypatch.setattr("jarvis.hardware.detection.usable_accelerator_gb", lambda: (0.0, "none"))+ monkeypatch.setattr("jarvis.hardware.detection.system_ram_gb", lambda: None)+ tokens, why = supervisor.voice_brain_context_tokens("http://127.0.0.1:11434", "qwen3.5:4b")+ assert tokens == supervisor.VOICE_BRAIN_CONTEXT_TOKENS_FLOOR+ assert "floor" in why+++def test_no_accelerator_uses_the_ram_rule(monkeypatch) -> None:+ _fake_ollama(monkeypatch, size_bytes=3_400_000_000, native=262_144, created=[])+ monkeypatch.setattr("jarvis.hardware.detection.usable_accelerator_gb", lambda: (0.0, "none"))+ monkeypatch.setattr("jarvis.hardware.detection.system_ram_gb", lambda: 32.0)+ tokens, why = supervisor.voice_brain_context_tokens("http://127.0.0.1:11434", "qwen3.5:4b")+ # 60 % of 32 GB minus the 4 GB reserve = 15.2 GB -> the 64k rung fits (11.1 GB).+ assert tokens == 65_536+ assert "RAM" in why+++def test_prepare_creates_an_alias_named_after_the_chosen_context(monkeypatch) -> None:+ created: list[dict] = []+ _fake_ollama(monkeypatch, size_bytes=3_400_000_000, native=262_144, created=created)+ monkeypatch.setattr(+ "jarvis.hardware.detection.usable_accelerator_gb", lambda: (15.9, "nvidia-smi")+ )+ command = (+ "python -m server --model_name qwen3.5:4b "+ "--responses_api_base_url http://127.0.0.1:11434/v1 --responses_api_api_key ollama"+ )+ out = supervisor.prepare_voice_brain_command(command)+ assert "qwen3.5:4b-voice-64k" in out+ assert created and created[0]["parameters"] == {"num_ctx": 65_536}+ assert created[0]["from"] == "qwen3.5:4b"+++def test_alias_round_trip_folds_any_context_size_back_to_the_base() -> None:+ assert supervisor._voice_context_models("qwen3.5:4b-voice-64k") == (+ "qwen3.5:4b",+ "qwen3.5:4b-voice-8k",+ )+ assert supervisor._voice_context_models("qwen3.5:4b", 32_768) == (+ "qwen3.5:4b",+ "qwen3.5:4b-voice-32k",+ )+ assert supervisor._voice_context_models("qwen3.5:4b-voice-8k", 131_072)[1] == (+ "qwen3.5:4b-voice-128k"+ )+++def test_inventory_hides_every_voice_alias_size() -> None:+ assert ollama_inventory.is_hidden_alias("qwen3.5:4b-voice-8k")+ assert ollama_inventory.is_hidden_alias("qwen3.5:4b-voice-64k:latest")+ assert not ollama_inventory.is_hidden_alias("qwen3.5:4b")