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.

perf(realtime): size the local card's per-turn prompt from the machine, not a price list

rubenluetke10-beep9c1cccb3ab28
diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.py
index d1fbe098ba..31317b6bf8 100644
--- a/jarvis/plugins/realtime/openai_realtime.py
+++ b/jarvis/plugins/realtime/openai_realtime.py
@@ -1487,6 +1487,37 @@ _LOCAL_MANAGED_INTERACTIVE_OPEN_S = 3.0
_LOCAL_LAUNCH_MIN_INTERVAL_S = 60.0
+def _local_declaration_budget(launch_command: str) -> int:
+ """Declaration tokens THIS machine's own voice brain can carry (ADR-0035 §4).
+
+ A hosted model reads a big declaration block off a server-side cache; a
+ self-hosted one re-sends it into a window it shares with the persona, the
+ transcript and the answer, and re-prefills it whenever the local prefix
+ cache misses. So the bound belongs to the machine, not to a price list —
+ it is derived from the num_ctx the supervisor already sized from this
+ host's VRAM, and is therefore right on an 8 GB laptop and a 48 GB
+ workstation alike. Tools over it stay reachable through ``jarvis_action``.
+
+ 0 (unbounded) for an endpoint we cannot measure: a box on the LAN may be
+ far bigger than this one, and ``[voice].realtime_tool_declaration_budget_tokens``
+ stays the user's own lever there.
+ """
+ if not launch_command:
+ return 0
+ try:
+ import importlib # lazy (AP-26)
+
+ supervisor = importlib.import_module("jarvis.realtime.local_server.supervisor")
+ return max(int(supervisor.voice_brain_declaration_budget_tokens(launch_command)), 0)
+ except Exception: # noqa: BLE001 — an unbounded set still works, just slower
+ log.debug(
+ "local-realtime: declaration budget unreadable; leaving the "
+ "native tool set unbounded",
+ exc_info=True,
+ )
+ return 0
+
+
def _launch_command_target_state(command: str) -> str:
"""Whether the program a launch command names still exists on this machine.
@@ -1603,8 +1634,10 @@ class LocalRealtimeProvider:
name = "local-realtime"
supports_realtime = True
- # Same OpenAI-protocol wire, same per-response context billing model —
- # and a self-hosted model is usually the smaller one (ADR-0035 §4).
+ # Class-level floor for the declaration budget (ADR-0035 §4). The real
+ # number is per-instance and comes from the brain this machine actually
+ # runs — see the property below; this literal only keeps the attribute
+ # present for the runtime protocol check on the CLASS.
tool_declaration_budget_tokens = 0
# Never an implicit stand-in: a self-hosted endpoint is a deliberate choice,
# and quietly routing a call into one the user did not pick is the opposite
@@ -1685,6 +1718,9 @@ class LocalRealtimeProvider:
self._launch_command = (launch_command or "").strip()
self._managed_interactive_preflight = False
self._duplex_unavailable_reason = ""
+ self.tool_declaration_budget_tokens = _local_declaration_budget(
+ self._launch_command
+ )
# -- factory wiring ----------------------------------------------------
diff --git a/jarvis/realtime/local_server/supervisor.py b/jarvis/realtime/local_server/supervisor.py
index bfc06a41dc..fb714c8252 100644
--- a/jarvis/realtime/local_server/supervisor.py
+++ b/jarvis/realtime/local_server/supervisor.py
@@ -159,6 +159,17 @@ def _brain_keep_alive(release_s: float) -> str:
# (``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
+
+#: Share of the voice brain's context window that native tool declarations may
+#: claim. Small local brains re-send the whole declaration block on every turn,
+#: and llama.cpp only keeps it free by caching that unchanged prefix — a cache
+#: that dies the moment declarations plus the growing transcript overflow
+#: num_ctx and the context starts shifting. Measured on an RTX 5070 Ti with
+#: ornith:9b at 32k (2026-08-27): a stable 8k-token block costs 2.4 s once and
+#: 0.16 s on every later turn, while a set that overflows the window costs the
+#: full 4.2 s prefill EVERY turn. A quarter leaves three quarters for the
+#: instructions, the transcript and the answer, so the cache survives the call.
+VOICE_BRAIN_DECLARATION_SHARE = 0.25
#: 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.
@@ -2461,6 +2472,35 @@ def voice_brain_context_tokens(
)
+def voice_brain_declaration_budget_tokens(launch_command: str) -> int:
+ """Native tool declarations THIS machine's voice brain can carry, in tokens.
+
+ A hardware bound, not a cost one (the 2026-08-24 mandate retires cost caps
+ but keeps hardware limits): a hosted model reads a 60k-token declaration
+ block off a cached, server-side prefix, while a 9B brain in a 32k window
+ has to fit that block, the persona, the whole transcript AND the answer
+ into the same window — and pays a full prefill on every turn once it does
+ not. Live 2026-08-27 that was 4.2 s of silence per answer instead of 0.2 s.
+
+ Derived from the context window the machine actually got, so it scales with
+ the box: :func:`voice_brain_context_tokens` already sizes num_ctx from this
+ host's VRAM (or RAM), and the bounded alias carries the result in its name.
+ A command with no readable window falls back to the floor, which is the
+ smallest window any managed brain is ever given.
+
+ Nothing becomes unreachable: declarations over the budget are dropped from
+ the NATIVE set in a deterministic order and stay callable through
+ ``jarvis_action`` (ADR-0035 §4).
+ """
+ model, _brain_url = _brain_endpoint(launch_command)
+ if not model:
+ return 0
+ tag = model.rsplit(":", 1)[-1] if ":" in model else ""
+ match = _VOICE_MODEL_SUFFIX_RE.search(tag)
+ context_tokens = int(match.group(1)) * 1024 if match else VOICE_BRAIN_CONTEXT_TOKENS_FLOOR
+ return max(int(context_tokens * VOICE_BRAIN_DECLARATION_SHARE), 512)
+
+
def _voice_context_models(
model: str, context_tokens: int = VOICE_BRAIN_CONTEXT_TOKENS_FLOOR
) -> tuple[str, str]:
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 334e11dfed..d692cacc91 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -2127,6 +2127,16 @@ _COMPLETE_THE_REQUEST_DIRECTIVE = (
# a few hundred characters and pass through untouched.
_PREFERENCES_MAX_CHARS = 64_000
+#: The same block for a brain that re-reads it on every turn. Not a cost
+#: window — the cap above was retired as one (2026-08-24), but its own comment
+#: names this hot path, and a self-hosted model has no server-side prompt cache
+#: to hide behind: it re-prefills whatever it is handed whenever the local
+#: prefix cache misses. Live 2026-08-27 the per-turn prompt on the local card
+#: had grown from a 3,060-token median to 16,386, and the call stopped feeling
+#: live. Providers that declare ``prefers_compact_instructions`` get this one;
+#: everyone else keeps the full block.
+_PREFERENCES_MAX_CHARS_COMPACT = 4_000
+
#: Cap on a skill body injected straight into the live session. Tighter than the
#: preferences cap above by precedent, not by guess: that block is the user's own
#: standing file and carries the comment that a pathologically large one must not
@@ -2149,7 +2159,7 @@ _REALTIME_SKILL_TOOL_WORD_RE = re.compile(
)
-def _preferences_block(config: Any) -> str:
+def _preferences_block(config: Any, *, compact: bool = False) -> str:
"""The user's standing-instructions block (``Ruben.md`` equivalent).
The realtime engine speaks directly to the user, so it must honor the same
@@ -2163,7 +2173,10 @@ def _preferences_block(config: Any) -> str:
from jarvis.brain import agent_instructions
return agent_instructions.render_for_prompt(
- config, max_chars=_PREFERENCES_MAX_CHARS
+ config,
+ max_chars=(
+ _PREFERENCES_MAX_CHARS_COMPACT if compact else _PREFERENCES_MAX_CHARS
+ ),
)
except Exception: # noqa: BLE001 — never break the voice session on a prefs fault
return ""
@@ -3731,7 +3744,12 @@ class RealtimeVoiceSession:
model=model,
language_is_pinned=self._language_is_pinned,
tool_directive=self._tool_directive(provider=provider),
- preferences=_preferences_block(self._config),
+ preferences=_preferences_block(
+ self._config,
+ compact=bool(
+ getattr(provider, "prefers_compact_instructions", False)
+ ),
+ ),
workspace_directive=self._workspace_directive(),
skills_directive=self._skills_directive(
compact=bool(
@@ -5283,7 +5301,12 @@ class RealtimeVoiceSession:
model=self._active_model,
language_is_pinned=True,
tool_directive=turn_tool_directive,
- preferences=_preferences_block(self._config),
+ preferences=_preferences_block(
+ self._config,
+ compact=getattr(
+ self, "_compact_instructions", False
+ ),
+ ),
# Zero extra round trips: this update already
# fires on every final transcript, so a
# qualifying skill rides along instead of paying
@@ -7175,7 +7198,10 @@ class RealtimeVoiceSession:
delegate_required=False,
delegate_discouraged=True,
),
- preferences=_preferences_block(self._config),
+ preferences=_preferences_block(
+ self._config,
+ compact=getattr(self, "_compact_instructions", False),
+ ),
workspace_directive=self._workspace_directive(),
skills_directive=self._skills_directive(),
compact=getattr(self, "_compact_instructions", False),
diff --git a/tests/unit/realtime/local_server/test_supervisor.py b/tests/unit/realtime/local_server/test_supervisor.py
index b59fb18fb9..31731b97de 100644
--- a/tests/unit/realtime/local_server/test_supervisor.py
+++ b/tests/unit/realtime/local_server/test_supervisor.py
@@ -1733,6 +1733,39 @@ def test_warm_brain_pings_ollama_with_keep_alive(monkeypatch) -> None:
assert payload["keep_alive"] == supervisor.BRAIN_KEEP_ALIVE
+def test_the_declaration_budget_follows_this_machine_s_context_window() -> None:
+ """The bound is the hardware's, so it has to move with the box: the same
+ code must give a 8 GB laptop and a big workstation different numbers."""
+ def command(model: str) -> str:
+ return (
+ '"C:\tree\venv\Scripts\speech-to-speech.exe" --mode realtime '
+ f"--model_name {model} "
+ "--responses_api_base_url http://127.0.0.1:11434/v1 "
+ "--responses_api_api_key ollama"
+ )
+
+ small = supervisor.voice_brain_declaration_budget_tokens(command("qwen3.5:4b-voice-8k"))
+ medium = supervisor.voice_brain_declaration_budget_tokens(command("ornith:9b-voice-32k"))
+ large = supervisor.voice_brain_declaration_budget_tokens(command("m:14b-voice-64k"))
+
+ assert (small, medium, large) == (2048, 8192, 16384)
+ assert small < medium < large
+
+
+def test_a_brain_without_a_sized_alias_falls_back_to_the_floor() -> None:
+ """Never unbounded on a local brain we cannot measure: the floor is the
+ smallest window a managed brain is ever given."""
+ budget = supervisor.voice_brain_declaration_budget_tokens(_COMMAND)
+ expected = int(
+ supervisor.VOICE_BRAIN_CONTEXT_TOKENS_FLOOR * supervisor.VOICE_BRAIN_DECLARATION_SHARE
+ )
+ assert budget == expected
+
+
+def test_a_command_without_a_brain_declares_no_budget() -> None:
+ assert supervisor.voice_brain_declaration_budget_tokens("serve --mode realtime") == 0
+
+
def test_anchor_brain_load_outlives_the_caller(monkeypatch) -> None:
"""Ollama drops a model load the moment its LAST client hangs up, so the
request that carries a cold load must not be one the spawn path waits on
diff --git a/tests/unit/realtime/test_declaration_budget_per_provider.py b/tests/unit/realtime/test_declaration_budget_per_provider.py
index 4a1b41ed3f..62529aaeb1 100644
--- a/tests/unit/realtime/test_declaration_budget_per_provider.py
+++ b/tests/unit/realtime/test_declaration_budget_per_provider.py
@@ -140,3 +140,97 @@ def test_a_bridge_without_refit_or_a_non_hybrid_session_is_left_alone() -> None:
sess._tool_mode = "delegate"
sess._fit_declaration_budget(gemini)
assert bridge.budgets == []
+
+
+def test_the_real_local_card_bounds_itself_to_its_own_context_window() -> None:
+ """The whole chain, with the shipped provider rather than a stand-in.
+
+ Live 2026-08-27 this card declared no budget at all, so a 220-tool set
+ (~62k tokens) went to a 9B brain in a 32k window: the declarations plus
+ the transcript overflowed it, llama.cpp shifted the context, the cached
+ prefix died and every answer paid a 4.2 s prefill instead of 0.2 s.
+ """
+ from jarvis.plugins.realtime.openai_realtime import LocalRealtimeProvider
+
+ command = (
+ '"C:\tree\venv\Scripts\speech-to-speech.exe" --mode realtime '
+ "--model_name ornith:9b-voice-32k "
+ "--responses_api_base_url http://127.0.0.1:11434/v1 "
+ "--responses_api_api_key ollama"
+ )
+ card = LocalRealtimeProvider(
+ base_url="http://127.0.0.1:8765", launch_command=command
+ )
+ sess = _build([card], budget_tokens=0)
+
+ # A quarter of the 32k window this machine's brain actually runs.
+ assert card.tool_declaration_budget_tokens == 8_192
+ assert sess._declaration_budget_chars(card) == 8_192 * 4
+
+
+def test_the_local_card_scales_with_the_machine_it_runs_on() -> None:
+ """The same code has to give a small laptop and a big box different room."""
+ from jarvis.plugins.realtime.openai_realtime import LocalRealtimeProvider
+
+ def card(model: str) -> object:
+ return LocalRealtimeProvider(
+ base_url="http://127.0.0.1:8765",
+ launch_command=(
+ f'"s.exe" --mode realtime --model_name {model} '
+ "--responses_api_base_url http://127.0.0.1:11434/v1 "
+ "--responses_api_api_key ollama"
+ ),
+ )
+
+ laptop = card("qwen3.5:4b-voice-8k").tool_declaration_budget_tokens
+ workstation = card("m:14b-voice-64k").tool_declaration_budget_tokens
+ assert laptop == 2_048
+ assert workstation == 16_384
+
+
+def test_an_unmanaged_endpoint_is_not_bounded_by_a_guess() -> None:
+ """Without a launch command there is no machine to read, and a LAN box may
+ be far bigger than this one — the config bound stays the user's lever."""
+ from jarvis.plugins.realtime.openai_realtime import LocalRealtimeProvider
+
+ card = LocalRealtimeProvider(base_url="http://192.168.1.9:8765")
+ assert card.tool_declaration_budget_tokens == 0
+
+
+def test_a_small_local_brain_gets_a_compact_standing_instructions_block(
+ monkeypatch,
+) -> None:
+ """That block is re-sent on EVERY turn and a self-hosted model has no
+ server-side prompt cache to hide behind.
+
+ Live 2026-08-27 the per-turn prompt on the local card had grown from a
+ 3,060-token median to 16,386 and the call stopped feeling live. Cloud
+ wires keep the full block — the 2026-08-24 mandate retired that cap as a
+ COST lever, and on those wires it is one.
+ """
+ from types import SimpleNamespace as NS
+
+ from jarvis.brain import agent_instructions
+ from jarvis.realtime import session as sess_mod
+
+ seen: list[int] = []
+ monkeypatch.setattr(
+ agent_instructions,
+ "render_for_prompt",
+ lambda config, *, max_chars: (seen.append(max_chars) or "x" * 10),
+ )
+
+ sess_mod._preferences_block(NS(), compact=True)
+ sess_mod._preferences_block(NS(), compact=False)
+
+ compact, full = seen
+ assert compact == sess_mod._PREFERENCES_MAX_CHARS_COMPACT == 4_000
+ assert full == sess_mod._PREFERENCES_MAX_CHARS
+ assert compact < full
+
+
+def test_the_local_card_is_the_one_asking_for_that_profile() -> None:
+ """The bound follows a declared capability, never a provider name (AP-21)."""
+ from jarvis.plugins.realtime.openai_realtime import LocalRealtimeProvider
+
+ assert LocalRealtimeProvider.prefers_compact_instructions is True